File size: 10,686 Bytes
e2c1f2e
 
 
 
 
 
 
c9b5d14
 
e2c1f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a6f7ad
e2c1f2e
 
 
 
 
 
 
 
 
 
1a6f7ad
 
e2c1f2e
 
 
 
1a6f7ad
 
e2c1f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9b5d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c1f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e721060
 
 
 
 
 
 
 
 
e2c1f2e
e721060
e2c1f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e721060
e2c1f2e
 
e721060
1a6f7ad
e2c1f2e
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
from flask import Blueprint, request, jsonify, current_app, render_template, send_from_directory
from werkzeug.utils import secure_filename
import os
from pathlib import Path
import logging
import json
from datetime import datetime
import requests
from urllib.parse import urlparse

from app.services.encoder_service import encoder_service

logger = logging.getLogger(__name__)

# Create blueprints
main_bp = Blueprint('main', __name__)
api_bp = Blueprint('api', __name__)

@main_bp.route('/')
def index():
    """Render the main page"""
    return render_template('index.html')

@main_bp.route('/files')
def files_page():
    """Render the files page"""
    return render_template('files.html')

@api_bp.route('/files')
def list_files():
    """List all quality files that have been encoded (even if the overall job isn’t finished)"""
    try:
        encoded_dir = Path(current_app.config['ENCODED_FOLDER'])
        files = []
        
        if encoded_dir.exists():
            for job_dir in encoded_dir.iterdir():
                if job_dir.is_dir():
                    job_id = job_dir.name
                    job_info = encoder_service.get_job_info(job_id)
                    
                    # If there are any quality files available, include this job.
                    if job_info and job_info.get('files'):
                        files.append({
                            'job_id': job_id,
                            'output_name': job_info.get('output_name', ''),
                            'created_at': job_info.get('start_time'),
                            'completed_at': job_info.get('completion_time', None),
                            'status': job_info.get('status'),
                            'qualities': {
                                file['quality']: file['size'] 
                                for file in job_info.get('files', [])
                            }
                        })
        
        return jsonify({
            'files': sorted(files, key=lambda x: x['created_at'], reverse=True)
        })
    except Exception as e:
        logger.error(f"Failed to list files: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to list files'
        }), 500

@api_bp.route('/upload', methods=['POST'])
def upload_video():
    """Handle video file upload and start encoding process"""
    try:
        if 'video' not in request.files:
            return jsonify({
                'error': True,
                'message': 'No video file provided'
            }), 400

        file = request.files['video']
        output_name = request.form.get('output_name')
        
        if file.filename == '':
            return jsonify({
                'error': True,
                'message': 'No file selected'
            }), 400

        if not allowed_file(file.filename):
            return jsonify({
                'error': True,
                'message': 'Invalid file type'
            }), 400

        filename = secure_filename(file.filename)
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        
        # Save the file
        file.save(file_path)
        
        # Get custom encoding settings if provided
        settings = request.form.get('settings')
        
        # Generate job ID and start encoding
        job_id = generate_job_id()
        result = encoder_service.start_encode_job(
            filename=filename,
            job_id=job_id,
            output_name=output_name,
            settings=settings
        )
        
        return jsonify({
            'job_id': job_id,
            'message': 'Video upload successful',
            'status': result['status']
        }), 202

    except Exception as e:
        logger.error(f"Upload failed: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to process upload'
        }), 500

@api_bp.route('/upload-url', methods=['POST'])
def upload_video_from_url():
    """
    Handle video file upload from a provided URL and start the encoding process.
    Expects a JSON payload with:
        - url: The URL of the video file.
        - output_name: (optional) Desired output name without extension.
        - settings: (optional) Custom encoding settings.
    """
    try:
        data = request.get_json()
        if not data or 'url' not in data:
            return jsonify({
                'error': True,
                'message': 'No URL provided'
            }), 400
        
        video_url = data['url']
        output_name = data.get('output_name')
        settings = data.get('settings')
        
        # Download the video file from the URL
        response = requests.get(video_url, stream=True)
        if response.status_code != 200:
            return jsonify({
                'error': True,
                'message': 'Failed to download file from the provided URL'
            }), 400
        
        # Extract filename from URL
        parsed_url = urlparse(video_url)
        filename = os.path.basename(parsed_url.path)
        if not filename:
            # Fallback if filename is not present in the URL
            content_type = response.headers.get('content-type', '')
            extension = 'mp4'
            if 'mov' in content_type:
                extension = 'mov'
            elif 'avi' in content_type:
                extension = 'avi'
            elif 'mkv' in content_type:
                extension = 'mkv'
            filename = f"downloaded_video.{extension}"
        
        if not allowed_file(filename):
            return jsonify({
                'error': True,
                'message': 'Invalid file type from URL'
            }), 400

        filename = secure_filename(filename)
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        
        # Save the downloaded file in chunks
        with open(file_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        
        # Set default output name if not provided
        if not output_name:
            output_name = filename.rsplit('.', 1)[0]
        
        # Generate job ID and start encoding job
        job_id = generate_job_id()
        result = encoder_service.start_encode_job(
            filename=filename,
            job_id=job_id,
            output_name=output_name,
            settings=json.dumps(settings) if settings else None
        )
        
        return jsonify({
            'job_id': job_id,
            'message': 'Video download and encoding started',
            'status': result['status']
        }), 202

    except Exception as e:
        logger.error(f"Video download from URL failed: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to process video from URL'
        }), 500

@api_bp.route('/jobs', methods=['GET'])
def list_jobs():
    """List all encoding jobs"""
    try:
        return jsonify({
            'jobs': encoder_service.jobs
        }), 200
    except Exception as e:
        logger.error(f"Failed to list jobs: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to list jobs'
        }), 500

@api_bp.route('/jobs/<job_id>/stop', methods=['POST'])
def stop_job(job_id):
    """Stop an encoding job"""
    try:
        if encoder_service.stop_job(job_id):
            return jsonify({
                'message': 'Job stopped successfully'
            }), 200
        else:
            return jsonify({
                'error': True,
                'message': 'Job not found or already completed'
            }), 404
    except Exception as e:
        logger.error(f"Failed to stop job: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to stop job'
        }), 500

@api_bp.route('/jobs/<job_id>/clean', methods=['POST'])
def clean_job(job_id):
    """Clean up all files related to a job"""
    try:
        if encoder_service.clean_job(job_id):
            return jsonify({
                'message': 'Job cleaned successfully'
            }), 200
        else:
            return jsonify({
                'error': True,
                'message': 'Failed to clean job'
            }), 500
    except Exception as e:
        logger.error(f"Failed to clean job: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to clean job'
        }), 500

@api_bp.route('/status/<job_id>', methods=['GET'])
def get_job_status(job_id):
    """Get the status of an encoding job"""
    try:
        status = encoder_service.get_job_status(job_id)
        return jsonify(status), 200
    except Exception as e:
        logger.error(f"Failed to get status for job {job_id}: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to get job status'
        }), 500

@api_bp.route('/video/<job_id>/<quality>')
def serve_video(job_id, quality):
    """Serve encoded video files"""
    try:
        job_info = encoder_service.get_job_info(job_id)
        if not job_info:
            return jsonify({
                'error': True,
                'message': 'Job not found'
            }), 404

        # Retrieve the video file path based on quality from the job info
        video_file_path = None
        for file in job_info.get('files', []):
            if file['quality'] == quality:
                video_file_path = file['path']
                break

        if video_file_path and os.path.exists(video_file_path):
            directory, video_filename = os.path.split(video_file_path)
            return send_from_directory(
                directory,
                video_filename,
                mimetype='video/mp4',
                as_attachment=True,
                download_name=video_filename
            )
        else:
            return jsonify({
                'error': True,
                'message': 'Video not found'
            }), 404
    except Exception as e:
        logger.error(f"Failed to serve video: {str(e)}")
        return jsonify({
            'error': True,
            'message': 'Failed to serve video'
        }), 500


def allowed_file(filename):
    """Check if the file extension is allowed"""
    ALLOWED_EXTENSIONS = {'mp4', 'mov', 'avi', 'mkv', 'wmv', 'flv', 'webm', '3gp','ts','m4v', 'mpg', 'mpeg'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def generate_job_id():
    """Generate a unique job ID"""
    import uuid
    return str(uuid.uuid4())