aria2c for downloading
Browse files- App/Youtube/youtubeRouter.py +53 -85
App/Youtube/youtubeRouter.py
CHANGED
@@ -2,10 +2,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks
|
|
2 |
import tempfile
|
3 |
import os
|
4 |
import logging
|
5 |
-
import aiohttp
|
6 |
import asyncio
|
7 |
-
import aiofiles
|
8 |
-
import subprocess
|
9 |
from .Schema import YouTubeUploadTask
|
10 |
|
11 |
# Configure logging
|
@@ -16,81 +13,48 @@ router = APIRouter(prefix="/youtube", tags=["youtube"])
|
|
16 |
|
17 |
|
18 |
async def download_file(url: str) -> str:
|
19 |
-
"""Download file from URL
|
20 |
try:
|
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 |
-
"error",
|
62 |
-
"-show_entries",
|
63 |
-
"format=format_name",
|
64 |
-
"-of",
|
65 |
-
"default=noprint_wrappers=1:nokey=1",
|
66 |
-
temp_path,
|
67 |
-
]
|
68 |
-
format_result = subprocess.run(
|
69 |
-
format_cmd, capture_output=True, text=True
|
70 |
-
)
|
71 |
-
format_name = format_result.stdout.strip().lower()
|
72 |
-
|
73 |
-
# Determine extension based on codec and container
|
74 |
-
if "mp4" in format_name or codec in ("h264", "aac"):
|
75 |
-
ext = ".mp4"
|
76 |
-
elif "webm" in format_name or codec == "vp9":
|
77 |
-
ext = ".webm"
|
78 |
-
elif "avi" in format_name:
|
79 |
-
ext = ".avi"
|
80 |
-
else:
|
81 |
-
# Fallback to content-type if metadata unavailable
|
82 |
-
content_type = response.headers.get("content-type", "")
|
83 |
-
ext = ".mp4" if "video" in content_type else ".tmp"
|
84 |
-
except Exception:
|
85 |
-
# Fallback if ffprobe fails
|
86 |
-
content_type = response.headers.get("content-type", "")
|
87 |
-
ext = ".mp4" if "video" in content_type else ".tmp"
|
88 |
-
|
89 |
-
# Rename file with correct extension
|
90 |
-
new_temp_path = f"{temp_path[:-4]}{ext}"
|
91 |
-
os.rename(temp_path, new_temp_path)
|
92 |
-
|
93 |
-
return new_temp_path
|
94 |
except Exception as e:
|
95 |
logger.error(f"Error downloading file: {str(e)}")
|
96 |
raise HTTPException(status_code=500, detail=f"File download failed: {str(e)}")
|
@@ -98,17 +62,18 @@ async def download_file(url: str) -> str:
|
|
98 |
|
99 |
async def upload_video_background(task: YouTubeUploadTask):
|
100 |
"""Background task to handle video upload."""
|
101 |
-
|
102 |
try:
|
103 |
logger.info(f"Starting download for video: {task.filename}")
|
104 |
-
|
105 |
-
|
|
|
106 |
|
107 |
# Build the command
|
108 |
command = [
|
109 |
"/srv/youtube/youtubeuploader",
|
110 |
"-filename",
|
111 |
-
|
112 |
"-title",
|
113 |
task.title,
|
114 |
"-description",
|
@@ -143,12 +108,15 @@ async def upload_video_background(task: YouTubeUploadTask):
|
|
143 |
logger.error(f"Error in upload process: {str(e)}")
|
144 |
raise
|
145 |
finally:
|
146 |
-
|
|
|
147 |
try:
|
148 |
-
os.
|
149 |
-
|
|
|
|
|
150 |
except Exception as e:
|
151 |
-
logger.error(f"Failed to clean up temp
|
152 |
|
153 |
|
154 |
@router.post("/upload")
|
|
|
2 |
import tempfile
|
3 |
import os
|
4 |
import logging
|
|
|
5 |
import asyncio
|
|
|
|
|
6 |
from .Schema import YouTubeUploadTask
|
7 |
|
8 |
# Configure logging
|
|
|
13 |
|
14 |
|
15 |
async def download_file(url: str) -> str:
|
16 |
+
"""Download file from URL using aria2c."""
|
17 |
try:
|
18 |
+
# Create temp directory for download
|
19 |
+
temp_dir = tempfile.mkdtemp()
|
20 |
+
temp_path = os.path.join(
|
21 |
+
temp_dir, "video"
|
22 |
+
) # aria2c will add extension automatically
|
23 |
+
|
24 |
+
# Build aria2c command
|
25 |
+
command = [
|
26 |
+
"aria2c",
|
27 |
+
"--allow-overwrite=true",
|
28 |
+
"--auto-file-renaming=false",
|
29 |
+
"--max-connection-per-server=16",
|
30 |
+
"--split=16",
|
31 |
+
"--dir",
|
32 |
+
temp_dir,
|
33 |
+
"--out",
|
34 |
+
"video",
|
35 |
+
url,
|
36 |
+
]
|
37 |
+
|
38 |
+
logger.info(f"Starting download with aria2c: {url}")
|
39 |
+
process = await asyncio.create_subprocess_exec(
|
40 |
+
*command,
|
41 |
+
stdout=asyncio.subprocess.PIPE,
|
42 |
+
stderr=asyncio.subprocess.PIPE,
|
43 |
+
)
|
44 |
+
stdout, stderr = await process.communicate()
|
45 |
+
|
46 |
+
if process.returncode != 0:
|
47 |
+
raise Exception(f"Download failed: {stderr.decode()}")
|
48 |
+
|
49 |
+
# Find the downloaded file (aria2c adds extension automatically)
|
50 |
+
downloaded_files = os.listdir(temp_dir)
|
51 |
+
if not downloaded_files:
|
52 |
+
raise Exception("No file downloaded")
|
53 |
+
|
54 |
+
downloaded_file = os.path.join(temp_dir, downloaded_files[0])
|
55 |
+
logger.info(f"Download completed: {downloaded_file}")
|
56 |
+
return downloaded_file
|
57 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
except Exception as e:
|
59 |
logger.error(f"Error downloading file: {str(e)}")
|
60 |
raise HTTPException(status_code=500, detail=f"File download failed: {str(e)}")
|
|
|
62 |
|
63 |
async def upload_video_background(task: YouTubeUploadTask):
|
64 |
"""Background task to handle video upload."""
|
65 |
+
temp_dir = None
|
66 |
try:
|
67 |
logger.info(f"Starting download for video: {task.filename}")
|
68 |
+
downloaded_file = await download_file(task.filename)
|
69 |
+
temp_dir = os.path.dirname(downloaded_file)
|
70 |
+
logger.info(f"Download complete. Saved to: {downloaded_file}")
|
71 |
|
72 |
# Build the command
|
73 |
command = [
|
74 |
"/srv/youtube/youtubeuploader",
|
75 |
"-filename",
|
76 |
+
downloaded_file,
|
77 |
"-title",
|
78 |
task.title,
|
79 |
"-description",
|
|
|
108 |
logger.error(f"Error in upload process: {str(e)}")
|
109 |
raise
|
110 |
finally:
|
111 |
+
# Clean up temp directory and its contents
|
112 |
+
if temp_dir and os.path.exists(temp_dir):
|
113 |
try:
|
114 |
+
for file in os.listdir(temp_dir):
|
115 |
+
os.remove(os.path.join(temp_dir, file))
|
116 |
+
os.rmdir(temp_dir)
|
117 |
+
logger.info(f"Cleaned up temporary directory: {temp_dir}")
|
118 |
except Exception as e:
|
119 |
+
logger.error(f"Failed to clean up temp directory: {str(e)}")
|
120 |
|
121 |
|
122 |
@router.post("/upload")
|