forked from manbearwiz/youtube-dl-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube-dl-server.py
151 lines (115 loc) · 4.7 KB
/
youtube-dl-server.py
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
import sys
import subprocess
import os
from starlette.status import HTTP_303_SEE_OTHER
from starlette.applications import Starlette
from starlette.config import Config
from starlette.staticfiles import StaticFiles
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Mount, Route
from starlette.templating import Jinja2Templates
from starlette.background import BackgroundTask
from yt_dlp import YoutubeDL, version
templates = Jinja2Templates(directory="templates")
config = Config(".env")
YDLS_OUTPUT_DIR = "/mnt/multimedia_nfs/youtube-dl/"
app_defaults = {
"YDL_FORMAT": config("YDL_FORMAT", cast=str, default="bestvideo+bestaudio/best"),
"YDL_EXTRACT_AUDIO_FORMAT": config("YDL_EXTRACT_AUDIO_FORMAT", default=None),
"YDL_EXTRACT_AUDIO_QUALITY": config("YDL_EXTRACT_AUDIO_QUALITY", cast=str, default="192"),
"YDL_RECODE_VIDEO_FORMAT": config("YDL_RECODE_VIDEO_FORMAT", default=None),
"YDL_OUTPUT_TEMPLATE": config("YDL_OUTPUT_TEMPLATE", cast=str, default="%(title).200s [%(id)s].%(ext)s"),
"YDL_ARCHIVE_FILE": config("YDL_ARCHIVE_FILE", default=None),
"YDL_UPDATE_TIME": config("YDL_UPDATE_TIME", cast=bool, default=False),
}
async def dl_queue_list(request):
return templates.TemplateResponse("index.html", {"request": request, "ytdlp_version": version.__version__})
async def redirect(request):
return RedirectResponse(url="/youtube-dl")
async def q_put(request):
form = await request.form()
url = form.get("url").strip()
ui = form.get("ui")
options = {"format": form.get("format")}
if not url:
return JSONResponse(
{"success": False, "error": "/q called without a 'url' in form data"}
)
task = BackgroundTask(download, url, options)
print("Added url " + url + " to the download queue")
if not ui:
return JSONResponse(
{"success": True, "url": url, "options": options}, background=task
)
return RedirectResponse(
url="/youtube-dl?added=" + url, status_code=HTTP_303_SEE_OTHER, background=task
)
async def update_route(scope, receive, send):
task = BackgroundTask(update)
return JSONResponse({"output": "Initiated package update"}, background=task)
def update():
try:
output = subprocess.check_output(
[sys.executable, "-m", "pip", "install", "--upgrade", "yt-dlp"]
)
print(output.decode("utf-8"))
except subprocess.CalledProcessError as e:
print(e.output)
def get_ydl_options(request_options):
request_vars = {
"YDL_EXTRACT_AUDIO_FORMAT": None,
"YDL_RECODE_VIDEO_FORMAT": None,
}
output_path = YDLS_OUTPUT_DIR
requested_format = request_options.get("format", "bestvideo")
if requested_format in ["aac", "flac", "mp3", "m4a", "opus", "vorbis", "wav"]:
request_vars["YDL_EXTRACT_AUDIO_FORMAT"] = requested_format
output_path += "audio/"
elif requested_format == "bestaudio":
request_vars["YDL_EXTRACT_AUDIO_FORMAT"] = "best"
output_path += "audio/"
elif requested_format in ["mp4", "flv", "webm", "ogg", "mkv", "avi"]:
request_vars["YDL_RECODE_VIDEO_FORMAT"] = requested_format
if not (os.path.exists(output_path)):
try:
os.mkdir(output_path)
except OSError as error:
print(error)
output_path = YDLS_OUTPUT_DIR
ydl_vars = app_defaults.copy()
ydl_vars.update(request_vars)
postprocessors = []
if ydl_vars["YDL_EXTRACT_AUDIO_FORMAT"]:
postprocessors.append(
{
"key": "FFmpegExtractAudio",
"preferredcodec": ydl_vars["YDL_EXTRACT_AUDIO_FORMAT"],
"preferredquality": ydl_vars["YDL_EXTRACT_AUDIO_QUALITY"],
}
)
if ydl_vars["YDL_RECODE_VIDEO_FORMAT"]:
postprocessors.append(
{
"key": "FFmpegVideoConvertor",
"preferedformat": ydl_vars["YDL_RECODE_VIDEO_FORMAT"],
}
)
return {
"format": ydl_vars["YDL_FORMAT"],
"postprocessors": postprocessors,
"outtmpl": output_path + ydl_vars["YDL_OUTPUT_TEMPLATE"],
"download_archive": ydl_vars["YDL_ARCHIVE_FILE"],
"updatetime": ydl_vars["YDL_UPDATE_TIME"] == "True",
}
def download(url, request_options):
with YoutubeDL(get_ydl_options(request_options)) as ydl:
ydl.download([url])
routes = [
Route("/", endpoint=redirect),
Route("/youtube-dl", endpoint=dl_queue_list),
Route("/youtube-dl/q", endpoint=q_put, methods=["POST"]),
Route("/youtube-dl/update", endpoint=update_route, methods=["PUT"]),
]
app = Starlette(debug=True, routes=routes)
print("Updating youtube-dl to the newest version")
update()