-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
710 lines (580 loc) · 25.6 KB
/
Copy pathserver.py
File metadata and controls
710 lines (580 loc) · 25.6 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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
import os
import mimetypes
import subprocess
import cv2
import numpy as np
import json
import shutil
import requests
import uuid
import time
from urllib.parse import urlparse
from typing import List, Optional
from fastapi import FastAPI, Request, Response, HTTPException, Depends, Query, File, UploadFile, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, StreamingResponse, JSONResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from werkzeug.utils import secure_filename
from auth import verify_token
from services.essential_checker import create_thumbnails_for_videos
from services.video_services import stream_mkv_to_mp4, serve_video_file_with_range
load_dotenv() # take environment variables from .env.
app = FastAPI(title="Video Manager API")
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://localhost:4000", "https://stream.akaigen.site/"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
SECRET_TOKEN = os.environ.get("SECRET_TOKEN")
PORT = os.environ.get("PORT")
# Set the root directory (adjust this as needed or make it dynamic)
ROOT_DIR = os.path.realpath(os.environ.get("ROOT_DIR", "root_dir"))
def get_safe_path(base_dir, relative_or_absolute_path):
"""
Resolves target path and ensures it remains strictly within the base_dir directory.
Returns the absolute canonical path if safe, otherwise raises a PermissionError.
"""
real_base = os.path.realpath(base_dir)
sanitized_target = relative_or_absolute_path.lstrip('/')
joined_path = os.path.join(real_base, sanitized_target)
real_target = os.path.realpath(joined_path)
try:
common_path = os.path.commonpath([real_base, real_target])
except ValueError:
raise PermissionError("Path traversal detected")
if common_path != real_base:
raise PermissionError("Path traversal attempt blocked")
return real_target
# Define allowed media types
MEDIA_TYPES = {
'video': ['video/mp4', 'video/x-matroska', 'video/avi', 'video/webm', 'video/quicktime'],
'audio': ['audio/mpeg', 'audio/wav'],
'image': ['image/jpeg', 'image/png', 'image/gif'],
'document': ['application/pdf', 'text/plain', 'application/msword'],
'archive': ['application/zip', 'application/x-tar'],
'subtitle': ['text/vtt', 'text/srt', 'application/x-subrip'],
}
def get_file_type(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
for media_type, mime_list in MEDIA_TYPES.items():
if mime_type in mime_list:
return media_type
return 'other'
def get_video_duration(file_path):
try:
# cache check
duration_path = f"{os.path.dirname(file_path)}/.essentials/{os.path.basename(file_path)}.duration"
if os.path.exists(duration_path):
with open(duration_path, 'r') as f:
return float(f.read().strip())
cmd = [
"ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", file_path
]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=2)
duration = float(result.stdout.strip())
# save to cache
os.makedirs(os.path.dirname(duration_path), exist_ok=True)
with open(duration_path, 'w') as f:
f.write(str(duration))
return duration
except Exception:
return 0.0
def get_video_tracks(file_path):
try:
# cache check
tracks_path = f"{os.path.dirname(file_path)}/.essentials/{os.path.basename(file_path)}.tracks.json"
if os.path.exists(tracks_path):
with open(tracks_path, 'r') as f:
return json.loads(f.read())
cmd = [
"ffprobe", "-v", "error", "-print_format", "json",
"-show_entries", "stream=index,codec_type,tags", file_path
]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=5)
data = json.loads(result.stdout)
audio_tracks = []
subtitle_tracks = []
for stream in data.get('streams', []):
if stream.get('codec_type') == 'audio':
tags = stream.get('tags', {})
title = tags.get('title') or tags.get('TITLE') or f"Audio Track {len(audio_tracks) + 1}"
lang = tags.get('language') or tags.get('LANGUAGE') or 'und'
audio_tracks.append({"index": stream['index'], "title": title, "language": lang})
elif stream.get('codec_type') == 'subtitle':
tags = stream.get('tags', {})
title = tags.get('title') or tags.get('TITLE') or f"Subtitle {len(subtitle_tracks) + 1}"
lang = tags.get('language') or tags.get('LANGUAGE') or 'und'
subtitle_tracks.append({"index": stream['index'], "title": title, "language": lang})
tracks = {"audio": audio_tracks, "subtitles": subtitle_tracks}
os.makedirs(os.path.dirname(tracks_path), exist_ok=True)
with open(tracks_path, 'w') as f:
f.write(json.dumps(tracks))
return tracks
except Exception:
return {"audio": [], "subtitles": []}
# --- Request/Response Models ---
class PathsPayload(BaseModel):
paths: List[str]
class RenamePayload(BaseModel):
path: str
new_name: str
class MoveCopyPayload(BaseModel):
paths: List[str]
destination: str = ""
class RemoteUploadPayload(BaseModel):
url: str
path: Optional[str] = ""
filename: Optional[str] = ""
headers: Optional[str] = ""
cookies: Optional[str] = ""
verify_ssl: Optional[bool] = True
# --- API Routes ---
@app.get('/browse')
def browse_folder(background_tasks: BackgroundTasks, path: str = "", _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(abs_path):
raise HTTPException(status_code=400, detail="Invalid path")
background_tasks.add_task(create_thumbnails_for_videos, abs_path)
contents = {"directories": [], "files": []}
for item in os.listdir(abs_path):
item_path = os.path.join(abs_path, item)
if os.path.isdir(item_path):
if not item.startswith('.'):
contents["directories"].append({
"name": item,
"last_modified": os.path.getmtime(item_path)
})
else:
file_type = get_file_type(item_path)
duration = None
if file_type == 'video':
duration = get_video_duration(item_path)
if not item.startswith('.'):
contents["files"].append({
"name": item,
"type": file_type,
"actual_type": mimetypes.guess_type(item_path)[0],
"size": os.path.getsize(item_path),
"duration": duration,
"last_modified": os.path.getmtime(item_path)
})
return contents
@app.get('/tree')
def get_tree(_=Depends(verify_token)):
def build_tree(dir_path):
tree = []
try:
for item in os.listdir(dir_path):
if item.startswith('.') or item == '.essentials':
continue
item_path = os.path.join(dir_path, item)
if os.path.isdir(item_path):
rel_path = os.path.relpath(item_path, ROOT_DIR)
if rel_path == '.':
rel_path = ''
tree.append({
"name": item,
"path": rel_path,
"children": build_tree(item_path),
"is_dir": True
})
else:
rel_path = os.path.relpath(item_path, ROOT_DIR)
tree.append({
"name": item,
"path": rel_path,
"is_dir": False
})
except Exception:
pass
return sorted(tree, key=lambda x: (not x.get("is_dir", False), x["name"].lower()))
return [{"name": "Home", "path": "", "children": build_tree(ROOT_DIR), "is_dir": True}]
@app.post('/file/delete')
def delete_items(payload: PathsPayload, _=Depends(verify_token)):
for p in payload.paths:
try:
abs_p = get_safe_path(ROOT_DIR, p)
if os.path.exists(abs_p):
if os.path.isdir(abs_p):
shutil.rmtree(abs_p)
else:
os.remove(abs_p)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
return {"success": True}
@app.post('/file/rename')
def rename_item(payload: RenamePayload, _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, payload.path)
if os.path.exists(abs_path):
sanitized_new_name = os.path.basename(payload.new_name)
new_abs_path = get_safe_path(os.path.dirname(abs_path), sanitized_new_name)
os.rename(abs_path, new_abs_path)
return {"success": True, "new_path": os.path.relpath(new_abs_path, ROOT_DIR)}
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
raise HTTPException(status_code=400, detail="Invalid path")
@app.post('/file/move')
def move_items(payload: MoveCopyPayload, _=Depends(verify_token)):
try:
abs_dest = get_safe_path(ROOT_DIR, payload.destination)
if not os.path.exists(abs_dest):
raise HTTPException(status_code=400, detail="Invalid destination")
for p in payload.paths:
abs_p = get_safe_path(ROOT_DIR, p)
if os.path.exists(abs_p):
shutil.move(abs_p, abs_dest)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
return {"success": True}
@app.post('/file/copy')
def copy_items(payload: MoveCopyPayload, _=Depends(verify_token)):
try:
abs_dest = get_safe_path(ROOT_DIR, payload.destination)
if not os.path.exists(abs_dest):
raise HTTPException(status_code=400, detail="Invalid destination")
for p in payload.paths:
abs_p = get_safe_path(ROOT_DIR, p)
if os.path.exists(abs_p):
if os.path.isdir(abs_p):
shutil.copytree(abs_p, os.path.join(abs_dest, os.path.basename(abs_p)))
else:
shutil.copy2(abs_p, abs_dest)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
return {"success": True}
@app.get('/file/info')
def file_info(path: str = "", _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(abs_path):
raise HTTPException(status_code=400, detail="Invalid path or file does not exist")
if os.path.isdir(abs_path):
raise HTTPException(status_code=400, detail="The path points to a directory, not a file")
file_type = get_file_type(abs_path)
file_size = os.path.getsize(abs_path)
file_mtime = os.path.getmtime(abs_path)
duration = None
tracks = {"audio": [], "subtitles": []}
if file_type == 'video':
duration = get_video_duration(abs_path)
tracks = get_video_tracks(abs_path)
return {
"name": os.path.basename(abs_path),
"type": file_type,
"actual_type": mimetypes.guess_type(abs_path)[0],
"size": file_size,
"last_modified": file_mtime,
"duration": duration,
"tracks": tracks,
}
@app.get('/stream')
def serve_video(request: Request, path: str = "", _=Depends(verify_token)):
try:
file_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.isfile(file_path):
raise HTTPException(status_code=404, detail="File not found")
range_header = request.headers.get('Range', None)
return serve_video_file_with_range(file_path, range_header)
@app.get('/subtitle')
def serve_subtitle(path: str = "", track: str = "", _=Depends(verify_token)):
try:
file_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.isfile(file_path) or not track:
raise HTTPException(status_code=404, detail="File or track not found")
def generate_vtt():
cmd = [
"ffmpeg", "-v", "error", "-i", file_path,
"-map", f"0:{track}", "-f", "webvtt", "pipe:1"
]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
try:
while True:
data = process.stdout.read(4096)
if not data:
break
yield data
finally:
process.terminate()
return StreamingResponse(generate_vtt(), media_type="text/vtt")
@app.get('/storyboard.jpg')
def generate_storyboard(path: str = "", _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(abs_path):
raise HTTPException(status_code=400, detail="Invalid video path")
storyboard_path = f"{os.path.dirname(abs_path)}/.essentials/{os.path.basename(abs_path)}-storyboard.jpg"
if os.path.exists(storyboard_path):
return FileResponse(storyboard_path, media_type='image/jpeg')
grid_cols, grid_rows = 10, 5
thumbnail_width, thumbnail_height = 180, 101
cap = cv2.VideoCapture(abs_path)
if not cap.isOpened():
raise HTTPException(status_code=400, detail="Unable to open video file")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_interval = total_frames // (grid_cols * grid_rows)
storyboard = np.zeros((grid_rows * thumbnail_height, grid_cols * thumbnail_width, 3), dtype=np.uint8)
frame_idx = 0
for row in range(grid_rows):
for col in range(grid_cols):
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ret, frame = cap.read()
if not ret:
break
thumbnail = cv2.resize(frame, (thumbnail_width, thumbnail_height))
y1 = row * thumbnail_height
y2 = y1 + thumbnail_height
x1 = col * thumbnail_width
x2 = x1 + thumbnail_width
storyboard[y1:y2, x1:x2] = thumbnail
frame_idx += frame_interval
cap.release()
os.makedirs(os.path.dirname(storyboard_path), exist_ok=True)
cv2.imwrite(storyboard_path, storyboard)
return FileResponse(storyboard_path, media_type='image/jpeg')
def format_time(seconds):
"""Format time in seconds to VTT timestamp format (hh:mm:ss.mmm)."""
ms = int((seconds % 1) * 1000)
seconds = int(seconds)
s = seconds % 60
minutes = (seconds // 60) % 60
hours = seconds // 3600
return f"{hours:02}:{minutes:02}:{s:02}.{ms:03}"
@app.get('/thumbnails.vtt')
def generate_thumbnails_vtt(path: str = "", token: str = Query(None), _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(abs_path):
raise HTTPException(status_code=400, detail="Invalid video path")
grid_cols, grid_rows = 10, 5
thumbnail_width, thumbnail_height = 180, 101
cap = cv2.VideoCapture(abs_path)
if not cap.isOpened():
raise HTTPException(status_code=400, detail="Unable to open video file")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_rate = cap.get(cv2.CAP_PROP_FPS)
video_duration = total_frames / frame_rate
frame_interval = video_duration / (grid_cols * grid_rows)
vtt_content = ["WEBVTT\n"]
for i in range(grid_rows):
for j in range(grid_cols):
start_time = (i * grid_cols + j) * frame_interval
end_time = start_time + frame_interval
start_time_str = format_time(start_time)
end_time_str = format_time(end_time)
x = j * thumbnail_width
y = i * thumbnail_height
vtt_content.append(f"{start_time_str} --> {end_time_str}")
token_param = f"&token={token}" if token else ""
vtt_content.append(
f"storyboard.jpg?path={path}{token_param}#xywh={x},{y},{thumbnail_width},{thumbnail_height}\n")
cap.release()
return Response("\n".join(vtt_content), media_type='text/vtt')
@app.get('/thumbnail')
def thumbnail_image(path: str = "", _=Depends(verify_token)):
try:
abs_path = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(abs_path):
raise HTTPException(status_code=400, detail="Invalid video path")
thumbnail_path = f"{os.path.dirname(abs_path)}/.essentials/{os.path.basename(abs_path)}-thumbnail.jpg"
if os.path.exists(thumbnail_path):
return FileResponse(thumbnail_path, media_type='image/jpeg')
raise HTTPException(status_code=404, detail="Thumbnail not found")
@app.post('/upload')
async def upload_video(
background_tasks: BackgroundTasks,
path: str = "",
files: List[UploadFile] = File(...),
_=Depends(verify_token)
):
try:
try:
target_dir = get_safe_path(ROOT_DIR, path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(target_dir):
raise HTTPException(status_code=400, detail="Invalid target directory")
uploaded_files = []
failed_files = []
ALLOWED_VIDEO_EXTENSIONS = {
'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp'}
for file in files:
if file and file.filename:
filename = secure_filename(file.filename)
file_ext = os.path.splitext(filename)[1].lower()
if file_ext not in ALLOWED_VIDEO_EXTENSIONS:
failed_files.append({
"name": filename,
"reason": f"Unsupported file type: {file_ext}"
})
continue
file_path = os.path.join(target_dir, filename)
counter = 1
base_name, ext = os.path.splitext(filename)
while os.path.exists(file_path):
filename = f"{base_name}_{counter}{ext}"
file_path = os.path.join(target_dir, filename)
counter += 1
try:
# Save the uploaded file
with open(file_path, 'wb') as f:
while chunk := await file.read(1024 * 1024): # 1MB chunks
f.write(chunk)
file_size = os.path.getsize(file_path)
file_type = get_file_type(file_path)
uploaded_files.append({
"name": filename,
"size": file_size,
"type": file_type,
"path": os.path.join(path, filename) if path else filename
})
except Exception as e:
failed_files.append({
"name": filename,
"reason": f"Failed to save file: {str(e)}"
})
# Start thumbnail generation in background
background_tasks.add_task(create_thumbnails_for_videos, target_dir)
response = {
"success": True,
"uploaded": len(uploaded_files),
"failed": len(failed_files),
"files": uploaded_files
}
if failed_files:
response["failed_files"] = failed_files
return response
except Exception as e:
raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
remote_downloads_status = {}
def download_remote_file(task_id, url, target_dir, filename, headers_str, cookies_str, verify_ssl):
try:
remote_downloads_status[task_id] = {
"status": "starting",
"progress": 0,
"total": 0,
"loaded": 0,
"speed": 0,
"filename": filename or "pending..."
}
headers = {}
if headers_str:
for line in headers_str.split('\n'):
if ':' in line:
k, v = line.split(':', 1)
headers[k.strip()] = v.strip()
cookies = {}
if cookies_str:
for line in cookies_str.split(';'):
if '=' in line:
k, v = line.split('=', 1)
cookies[k.strip()] = v.strip()
if not filename:
parsed = urlparse(url)
filename = os.path.basename(parsed.path)
if not filename:
filename = "downloaded_video.mp4"
filename = secure_filename(filename)
file_path = os.path.join(target_dir, filename)
counter = 1
base_name, ext = os.path.splitext(filename)
while os.path.exists(file_path):
filename = f"{base_name}_{counter}{ext}"
file_path = os.path.join(target_dir, filename)
counter += 1
remote_downloads_status[task_id]["filename"] = filename
with requests.get(url, headers=headers, cookies=cookies, stream=True, timeout=10, verify=verify_ssl) as r:
r.raise_for_status()
total_size = int(r.headers.get('content-length', 0))
remote_downloads_status[task_id]["total"] = total_size
remote_downloads_status[task_id]["status"] = "downloading"
loaded = 0
start_time = time.time()
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
loaded += len(chunk)
current_time = time.time()
elapsed = current_time - start_time
if elapsed > 0:
speed = loaded / elapsed
progress = round((loaded / total_size) * 100) if total_size > 0 else 0
remote_downloads_status[task_id]["loaded"] = loaded
remote_downloads_status[task_id]["progress"] = progress
remote_downloads_status[task_id]["speed"] = speed
remote_downloads_status[task_id]["status"] = "success"
remote_downloads_status[task_id]["progress"] = 100
# Build thumbnails
create_thumbnails_for_videos(target_dir)
except Exception as e:
print(f"Failed to download remote file: {e}")
remote_downloads_status[task_id] = {
"status": "error",
"error": str(e),
"progress": 0,
"filename": filename or "unknown"
}
@app.post('/upload/remote')
async def upload_remote(background_tasks: BackgroundTasks, payload: RemoteUploadPayload, _=Depends(verify_token)):
if not payload.url:
raise HTTPException(status_code=400, detail="No URL provided")
try:
target_dir = get_safe_path(ROOT_DIR, payload.path)
except PermissionError:
raise HTTPException(status_code=403, detail="Unauthorized path traversal detected")
if not os.path.exists(target_dir):
raise HTTPException(status_code=400, detail="Invalid target directory")
task_id = str(uuid.uuid4())
background_tasks.add_task(
download_remote_file,
task_id, payload.url, target_dir, payload.filename,
payload.headers, payload.cookies, payload.verify_ssl
)
return {"success": True, "message": "Download started in background", "task_id": task_id}
@app.get('/upload/remote/status/{task_id}')
def upload_remote_status(task_id: str, _=Depends(verify_token)):
status = remote_downloads_status.get(task_id)
if not status:
raise HTTPException(status_code=404, detail="Task not found")
return status
# SPA Fallback and Catch-all Route for Frontend serving
@app.get("/{path:path}")
def serve_frontend(path: str = ""):
static_folder = "frontend/dist"
# Serve from the static folder if it's a real file
if path and os.path.exists(os.path.join(static_folder, path)):
return FileResponse(os.path.join(static_folder, path))
# Fallback to SPA index.html
index_path = os.path.join(static_folder, 'index.html')
if os.path.exists(index_path):
return FileResponse(index_path)
# If build directory doesn't exist, return a generic friendly warning message
return JSONResponse(
status_code=404,
content={"message": "Frontend build files not found. Please compile the React bundle."}
)
if __name__ == '__main__':
import uvicorn
uvicorn.run("server:app", host='0.0.0.0', port=int(PORT or 4000), reload=True)