-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideos.py
More file actions
521 lines (450 loc) · 18.3 KB
/
Copy pathvideos.py
File metadata and controls
521 lines (450 loc) · 18.3 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, status, Query
from fastapi.responses import FileResponse, StreamingResponse
from typing import List
import os
import io
import zipfile
import logging
from datetime import datetime
from pathlib import Path
try:
import magic
except ImportError:
magic = None
from app.core.security import get_current_user
from app.core.database import get_supabase_client
from app.core.file_manager import file_manager, validate_file_path
from app.core.config import settings
from app.workers.tasks import process_single_image_task, process_dual_image_task
from app.schemas.video import PaginatedVideosResponse
from supabase import Client
router = APIRouter(tags=["video_processing"])
logger = logging.getLogger(__name__)
# Configuration
ALLOWED_MIME_TYPES = {"image/jpeg", "image/png", "image/webp"}
MAX_FILE_SIZE = 8 * 1024 * 1024 # 8MB in bytes
async def validate_image_file(file: UploadFile) -> bytes:
"""
Validate uploaded image file using magic bytes and size limits.
Args:
file: The uploaded file to validate
Returns:
The file content as bytes
Raises:
HTTPException: If file is invalid, wrong type, or too large
"""
content = await file.read()
# Check file size
if len(content) > MAX_FILE_SIZE:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="File too large. Maximum size is 8MB.",
)
# Validate MIME type using magic bytes if available
if magic:
mime_type = magic.from_buffer(content, mime=True)
if mime_type not in ALLOWED_MIME_TYPES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid file type. Only JPEG, PNG, and WebP images are allowed.",
)
else:
# Fallback: validate content-type header if magic is not available
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid file type. Only images are allowed.",
)
# Check against allowed MIME types from header
if file.content_type not in ALLOWED_MIME_TYPES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid file type. Only JPEG, PNG, and WebP images are allowed.",
)
return content
@router.post("/upload/single", response_model=dict)
async def upload_single_image(
file: UploadFile = File(...),
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
try:
# Validate file (size, MIME type using magic bytes)
file_content = await validate_image_file(file)
# Save file
file_path = file_manager.save_uploaded_file(
file_content, current_user["id"], file.filename
)
# Validate that the saved path is within the user's directory (path traversal protection)
user_dir = file_manager.get_user_upload_directory(current_user["id"])
validate_file_path(file_path, user_dir)
video_data = {
"user_id": current_user["id"],
"original_filename": file.filename,
"video_type": "single",
"status": "processing",
"original_image_path": file_path,
}
response = supabase.table("videos").insert(video_data).execute()
video_id = response.data[0]["id"]
# Queue worker task with hybrid parameters (context + clear names)
process_single_image_task.send(
video_id=video_id, user_id=current_user["id"], input_filepath=file_path
)
return {
"message": "File uploaded successfully",
"video_id": video_id,
"status": "processing",
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Single image upload failed for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Upload failed. Please contact support.",
)
@router.post("/upload/dual", response_model=dict)
async def upload_dual_images(
file1: UploadFile = File(...),
file2: UploadFile = File(...),
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
try:
# Validate both files (size, MIME type using magic bytes)
file1_content = await validate_image_file(file1)
file2_content = await validate_image_file(file2)
# Save files
file1_path = file_manager.save_uploaded_file(
file1_content, current_user["id"], file1.filename
)
file2_path = file_manager.save_uploaded_file(
file2_content, current_user["id"], file2.filename
)
# Validate that the saved paths are within the user's directory (path traversal protection)
user_dir = file_manager.get_user_upload_directory(current_user["id"])
validate_file_path(file1_path, user_dir)
validate_file_path(file2_path, user_dir)
video_data = {
"user_id": current_user["id"],
"original_filename": f"{file1.filename}, {file2.filename}",
"video_type": "dual",
"status": "processing",
"original_image_path": f"{file1_path},{file2_path}",
}
response = supabase.table("videos").insert(video_data).execute()
video_id = response.data[0]["id"]
# Queue worker task with hybrid parameters (context + clear names)
process_dual_image_task.send(
video_id=video_id,
user_id=current_user["id"],
front_image_path=file1_path,
back_image_path=file2_path,
)
return {
"message": "Files uploaded successfully",
"video_id": video_id,
"status": "processing",
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Dual image upload failed for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Upload failed. Please contact support.",
)
@router.get("/", response_model=PaginatedVideosResponse)
async def list_user_videos(
limit: int = Query(20, ge=1, le=100, description="Number of videos per page (default: 20, max: 100)"),
offset: int = Query(0, ge=0, description="Number of videos to skip (default: 0)"),
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
"""
List all videos for the authenticated user with pagination.
Query Parameters:
- limit: Number of videos to return (1-100, default: 20)
- offset: Number of videos to skip (default: 0)
Returns paginated list with total count and has_more flag for UI convenience.
"""
try:
# Get total count of videos for this user
count_response = (
supabase.table("videos")
.select("id", count="exact")
.eq("user_id", current_user["id"])
.execute()
)
total_count = count_response.count if count_response.count is not None else 0
# Fetch paginated videos
response = (
supabase.table("videos")
.select("*")
.eq("user_id", current_user["id"])
.order("created_at", desc=True)
.range(offset, offset + limit - 1)
.execute()
)
videos = response.data if response.data else []
has_more = (offset + limit) < total_count
return PaginatedVideosResponse(
items=videos,
total=total_count,
limit=limit,
offset=offset,
has_more=has_more
)
except Exception as e:
logger.error(f"Failed to fetch videos for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to fetch videos. Please try again later.",
)
@router.get("/export-all")
async def export_all_videos(
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
"""
Export all completed videos as a ZIP file.
Only includes videos that:
- Belong to the authenticated user (ownership check)
- Have status 'completed' (only completed videos)
- Have valid file paths that exist on disk
Returns a ZIP archive with all videos organized by upload date.
"""
try:
# Fetch all completed videos for this user
response = (
supabase.table("videos")
.select("id, user_id, status, final_video_path, original_filename, video_type, created_at")
.eq("user_id", current_user["id"])
.eq("status", "completed")
.order("created_at", desc=True)
.execute()
)
videos = response.data
if not videos:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No completed videos to export"
)
# Create ZIP file in memory
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for video in videos:
video_path = video.get("final_video_path")
# Skip if file path is missing or file doesn't exist
if not video_path or not os.path.exists(video_path):
continue
# Validate path traversal - ensure file is within output directory
try:
validate_file_path(video_path, Path(settings.OUTPUT_DIRECTORY))
except ValueError:
logger.error(f"Path traversal attempt detected for video {video['id']}")
continue
# Create a readable filename for the ZIP
video_type = video.get("video_type", "video")
if video_type == "dual":
filename = f"product_animation_dual_{video['id'][:8]}.mp4"
else:
filename = f"product_animation_single_{video['id'][:8]}.mp4"
# Add file to ZIP
try:
zip_file.write(video_path, arcname=filename)
except Exception as e:
# Log but continue if one file fails
logger.warning(f"Could not add {filename} to ZIP: {str(e)}")
continue
# Prepare the ZIP for download
zip_buffer.seek(0)
# Generate filename with current date
timestamp = datetime.now().strftime("%Y%m%d")
zip_filename = f"productmotion_videos_{timestamp}.zip"
return StreamingResponse(
iter([zip_buffer.getvalue()]),
media_type="application/zip",
headers={"Content-Disposition": f"attachment; filename={zip_filename}"}
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to export videos for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to export videos. Please try again later.",
)
@router.get("/{video_id}", response_model=dict)
async def get_video_details(
video_id: str,
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
try:
response = (
supabase.table("videos")
.select("*")
.eq("id", video_id)
.eq("user_id", current_user["id"])
.execute()
)
if not response.data:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Video not found"
)
return response.data[0]
except Exception as e:
logger.error(f"Failed to fetch video {video_id} for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to fetch video. Please try again later.",
)
@router.get("/download/{video_id}")
async def download_video(
video_id: str,
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
"""
Download a processed video file.
Only allows downloading if:
- Video belongs to the authenticated user (ownership check)
- Video status is 'completed' (only completed videos can be downloaded)
- File exists on disk
Returns the video file with appropriate Content-Disposition header for download.
"""
try:
# Fetch video metadata with ownership and status check
response = (
supabase.table("videos")
.select("id, user_id, status, final_video_path, original_filename, video_type")
.eq("id", video_id)
.eq("user_id", current_user["id"])
.execute()
)
if not response.data:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Video not found or you don't have permission to download it"
)
video = response.data[0]
# Only allow downloading completed videos
if video["status"] != "completed":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Video is still {video['status']}. Only completed videos can be downloaded."
)
# Verify the file path exists
video_path = video.get("final_video_path")
if not video_path:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Video file path not found in database"
)
# Validate path traversal - ensure file is within output directory
try:
validate_file_path(video_path, Path(settings.OUTPUT_DIRECTORY))
except ValueError:
logger.error(f"Path traversal attempt detected for video {video_id}")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Video file not found"
)
# Verify the file actually exists on disk
if not os.path.exists(video_path):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Video file not found on server"
)
# Generate a clean filename for download
# Use video_type to create appropriate name
video_type = video.get("video_type", "video")
# Create a simple, user-friendly filename
if video_type == "dual":
# For dual images, use simplified names
filename = f"product_animation_dual.mp4"
else:
# For single image, use simplified name
filename = f"product_animation_single.mp4"
# Return file with download disposition
return FileResponse(
path=video_path,
filename=filename,
media_type="video/mp4",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to download video {video_id} for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to download video. Please try again later.",
)
@router.delete("/clear-all")
async def clear_all_videos(
current_user=Depends(get_current_user),
supabase: Client = Depends(get_supabase_client),
):
"""
Delete all videos for the current user and clean up associated files.
This action is irreversible and will:
- Delete all video records from the database
- Delete all video files from disk storage
"""
try:
user_id = current_user["id"]
logger.info(f"Starting deletion of all videos for user {user_id}")
# Fetch all user's videos to get file paths for cleanup
response = (
supabase.table("videos")
.select("id, final_video_path, original_image_path")
.eq("user_id", user_id)
.execute()
)
videos = response.data
deleted_count = 0
logger.info(f"Found {len(videos)} videos to delete for user {user_id}")
# Delete files from disk
for video in videos:
# Delete final video file
video_path = video.get("final_video_path")
if video_path and os.path.exists(video_path):
try:
os.remove(video_path)
deleted_count += 1
logger.debug(f"Deleted video file: {video_path}")
except Exception as e:
logger.warning(f"Could not delete video file {video_path}: {str(e)}")
# Delete original image files
image_paths = video.get("original_image_path", "").split(",")
for image_path in image_paths:
image_path = image_path.strip()
if image_path and os.path.exists(image_path):
try:
os.remove(image_path)
logger.debug(f"Deleted image file: {image_path}")
except Exception as e:
logger.warning(f"Could not delete image file {image_path}: {str(e)}")
# Delete all video records from database
logger.info(f"Deleting {len(videos)} database records for user {user_id}")
delete_response = (
supabase.table("videos")
.delete()
.eq("user_id", user_id)
.execute()
)
logger.info(f"Successfully completed deletion of all videos for user {user_id}")
return {
"message": f"Successfully deleted all videos and freed storage",
"videos_deleted": len(videos),
"files_deleted": deleted_count
}
except Exception as e:
logger.error(f"Error deleting videos for user {current_user['id']}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to clear videos. Please contact support.",
)