Debian Codegraph @

gallery_dl/downloader/ytdl.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Downloader module for URLs requiring youtube-dl support"""
10
11 from .common import DownloaderBase
12 from .. import ytdl, text, util
13 from xml.etree import ElementTree
14 from http.cookiejar import Cookie
15 import os
16 FLAGS = util.FLAGS
17
18
19 class YoutubeDLDownloader(DownloaderBase):
20 scheme = "ytdl"
21
22 def __init__(self, job):
23 DownloaderBase.__init__(self, job)
24
25 extractor = job.extractor
26 self.retries = self.config("retries", extractor._retries)
27 self.ytdl_opts = {
28 "retries": self.retries+1 if self.retries >= 0 else float("inf"),
29 "socket_timeout": self.config("timeout", extractor._timeout),
30 "nocheckcertificate": not self.config("verify", extractor._verify),
31 "proxy": self.proxies.get("http") if self.proxies else None,
32 "ignoreerrors": True,
33 }
34
35 self.ytdl_instance = None
36 self.rate_dyn = None
37 self.forward_cookies = self.config("forward-cookies", True)
38 self.progress = self.config("progress", 3.0)
39 self.outtmpl = self.config("outtmpl")
40
41 def download(self, url, pathfmt):
42 kwdict = pathfmt.kwdict
43 tries = 0
44
45 kwdict["_mtime_http"] = None
46 if ytdl_instance := kwdict.pop("_ytdl_instance", None):
47 # 'ytdl' extractor
48 self._prepare(ytdl_instance)
49 info_dict = kwdict.pop("_ytdl_info_dict")
50 else:
51 # other extractors
52 ytdl_instance = self.ytdl_instance
53 if not ytdl_instance:
54 try:
55 module = ytdl.import_module(self.config("module"))
56 except (ImportError, SyntaxError) as exc:
57 if exc.__context__:
58 self.log.error("Cannot import yt-dlp or youtube-dl")
59 else:
60 self.log.error("Cannot import module '%s'",
61 getattr(exc, "name", ""))
62 self.log.traceback(exc)
63 self.download = lambda u, p: False
64 return False
65
66 try:
67 ytdl_version = module.version.__version__
68 except Exception:
69 ytdl_version = ""
70 self.log.debug("Using %s version %s", module, ytdl_version)
71
72 self.ytdl_instance = ytdl_instance = ytdl.construct_YoutubeDL(
73 module, self, self.ytdl_opts, kwdict.get("_ytdl_params"))
74 self.ytdl_pp = module.postprocessor
75 if self.outtmpl == "default":
76 self.outtmpl = module.DEFAULT_OUTTMPL
77 self._prepare(ytdl_instance)
78
79 if self.forward_cookies:
80 self.log.debug("Forwarding cookies to %s",
81 ytdl_instance.__module__)
82 set_cookie = ytdl_instance.cookiejar.set_cookie
83 for cookie in self.session.cookies:
84 set_cookie(cookie)
85
86 url = url[5:]
87 manifest = kwdict.get("_ytdl_manifest")
88 while True:
89 if FLAGS.DOWNLOAD is not None:
90 return FLAGS.process("DOWNLOAD")
91
92 tries += 1
93 self.error = None
94 try:
95 if manifest is None:
96 info_dict = self._extract_url(
97 ytdl_instance, url)
98 else:
99 info_dict = self._extract_manifest(
100 ytdl_instance, url, kwdict)
101 except Exception as exc:
102 self.log.traceback(exc)
103 cls = exc.__class__
104 if cls.__module__ == "builtins":
105 tries = False
106 msg = f"{cls.__name__}: {exc}"
107 else:
108 if self.error is not None:
109 msg = self.error
110 elif not info_dict:
111 msg = "Empty 'info_dict' data"
112 else:
113 break
114
115 if tries:
116 self.log.error("%s (%s/%s)", msg, tries, self.retries+1)
117 else:
118 self.log.error(msg)
119 return False
120 if tries > self.retries:
121 return False
122
123 if extra := kwdict.get("_ytdl_extra"):
124 info_dict.update(extra)
125
126 while True:
127 if FLAGS.DOWNLOAD is not None:
128 return FLAGS.process("DOWNLOAD")
129
130 tries += 1
131 self.error = None
132 try:
133 if "entries" in info_dict:
134 success = self._download_playlist(
135 ytdl_instance, pathfmt, info_dict)
136 else:
137 success = self._download_video(
138 ytdl_instance, pathfmt, info_dict)
139 except Exception as exc:
140 self.log.traceback(exc)
141 cls = exc.__class__
142 if cls.__module__ == "builtins":
143 tries = False
144 msg = f"{cls.__name__}: {exc}"
145 else:
146 if self.error is not None:
147 msg = self.error
148 elif not success:
149 msg = "Error"
150 else:
151 break
152
153 if tries:
154 self.log.error("%s (%s/%s)", msg, tries, self.retries+1)
155 else:
156 self.log.error(msg)
157 return False
158 if tries > self.retries:
159 return False
160 return True
161
162 def _extract_url(self, ytdl, url):
163 return ytdl.extract_info(url, download=False)
164
165 def _extract_manifest(self, ytdl, url, kwdict):
166 extr = ytdl.get_info_extractor("Generic")
167 video_id = extr._generic_id(url)
168
169 if cookies := kwdict.get("_ytdl_manifest_cookies"):
170 if isinstance(cookies, dict):
171 cookies = cookies.items()
172 set_cookie = ytdl.cookiejar.set_cookie
173 for name, value in cookies:
174 set_cookie(Cookie(
175 0, name, value, None, False,
176 "", False, False, "/", False,
177 False, None, False, None, None, {},
178 ))
179
180 type = kwdict["_ytdl_manifest"]
181 data = kwdict.get("_ytdl_manifest_data")
182 remux = kwdict.get("_ytdl_manifest_remux")
183 headers = kwdict.get("_ytdl_manifest_headers")
184 if type == "hls":
185 ext = "ytdl" if remux else "mp4"
186 protocol = "m3u8_native"
187
188 if data is None:
189 try:
190 fmts, subs = extr._extract_m3u8_formats_and_subtitles(
191 url, video_id, ext, protocol, headers=headers)
192 except AttributeError:
193 fmts = extr._extract_m3u8_formats(
194 url, video_id, ext, protocol, headers=headers)
195 subs = None
196 else:
197 try:
198 fmts, subs = extr._parse_m3u8_formats_and_subtitles(
199 data, url, ext, protocol, headers=headers)
200 except AttributeError:
201 fmts = extr._parse_m3u8_formats(
202 data, url, ext, protocol, headers=headers)
203 subs = None
204
205 elif type == "dash":
206 if data is None:
207 try:
208 fmts, subs = extr._extract_mpd_formats_and_subtitles(
209 url, video_id, headers=headers)
210 except AttributeError:
211 fmts = extr._extract_mpd_formats(
212 url, video_id, headers=headers)
213 subs = None
214 else:
215 if isinstance(data, str):
216 data = ElementTree.fromstring(data)
217 try:
218 fmts, subs = extr._parse_mpd_formats_and_subtitles(
219 data, mpd_id="dash")
220 except AttributeError:
221 fmts = extr._parse_mpd_formats(
222 data, mpd_id="dash")
223 subs = None
224
225 else:
226 raise ValueError(f"Unsupported manifest type '{type}'")
227
228 if headers:
229 for fmt in fmts:
230 fmt["http_headers"] = headers
231
232 info_dict = {
233 "extractor": "",
234 "id" : video_id,
235 "title" : video_id,
236 "formats" : fmts,
237 "subtitles": subs,
238 }
239 info_dict = ytdl.process_ie_result(info_dict, download=False)
240
241 if remux:
242 info_dict["__postprocessors"] = [
243 self.ytdl_pp.FFmpegVideoRemuxerPP(self.ytdl_instance, remux)]
244
245 return info_dict
246
247 def _download_video(self, ytdl_instance, pathfmt, info_dict):
248 if "url" in info_dict:
249 if "filename" in pathfmt.kwdict:
250 pathfmt.kwdict["extension"] = \
251 text.ext_from_url(info_dict["url"])
252 else:
253 text.nameext_from_url(info_dict["url"], pathfmt.kwdict)
254
255 formats = info_dict.get("requested_formats")
256 if formats and not compatible_formats(formats):
257 info_dict["ext"] = "mkv"
258 elif "ext" not in info_dict:
259 try:
260 info_dict["ext"] = info_dict["formats"][0]["ext"]
261 except LookupError:
262 info_dict["ext"] = "mp4"
263
264 if self.outtmpl:
265 self._set_outtmpl(ytdl_instance, self.outtmpl)
266 pathfmt.filename = filename = \
267 ytdl_instance.prepare_filename(info_dict)
268 pathfmt.extension = info_dict["ext"]
269 pathfmt.path = pathfmt.directory + filename
270 pathfmt.realpath = pathfmt.temppath = (
271 pathfmt.realdirectory + filename)
272 elif info_dict["ext"] != "ytdl":
273 pathfmt.set_extension(info_dict["ext"])
274 pathfmt.build_path()
275
276 if pathfmt.exists():
277 pathfmt.temppath = ""
278 return True
279
280 if self.rate_dyn is not None:
281 # static ratelimits are set in ytdl.construct_YoutubeDL
282 ytdl_instance.params["ratelimit"] = self.rate_dyn()
283
284 self.out.start(pathfmt.path)
285 if self.part:
286 pathfmt.kwdict["extension"] = pathfmt.prefix
287 filename = pathfmt.build_filename(pathfmt.kwdict)
288 pathfmt.kwdict["extension"] = info_dict["ext"]
289 if self.partdir:
290 path = os.path.join(self.partdir, filename)
291 else:
292 path = pathfmt.realdirectory + filename
293 path = path.replace("%", "%%") + "%(ext)s"
294 else:
295 path = pathfmt.realpath.replace("%", "%%")
296
297 self._set_outtmpl(ytdl_instance, path)
298 ytdl_instance.process_info(info_dict)
299 pathfmt.temppath = info_dict.get("filepath") or info_dict["_filename"]
300 return True
301
302 def _download_playlist(self, ytdl_instance, pathfmt, info_dict):
303 pathfmt.kwdict["extension"] = pathfmt.prefix
304 filename = pathfmt.build_filename(pathfmt.kwdict)
305 pathfmt.kwdict["extension"] = pathfmt.extension
306 path = pathfmt.realdirectory + filename
307 path = path.replace("%", "%%") + "%(playlist_index)s.%(ext)s"
308 self._set_outtmpl(ytdl_instance, path)
309
310 status = False
311 for entry in info_dict["entries"]:
312 if not entry:
313 continue
314 if self.rate_dyn is not None:
315 ytdl_instance.params["ratelimit"] = self.rate_dyn()
316 try:
317 ytdl_instance.process_info(entry)
318 status = True
319 except Exception as exc:
320 self.log.traceback(exc)
321 self.log.error("%s: %s", exc.__class__.__name__, exc)
322 return status
323
324 def _prepare(self, ytdl_instance):
325 if "__gdl_initialize" not in ytdl_instance.params:
326 return
327
328 del ytdl_instance.params["__gdl_initialize"]
329 if self.progress is not None:
330 ytdl_instance.add_progress_hook(self._progress_hook)
331 if rlf := ytdl_instance.params.pop("__gdl_ratelimit_func", False):
332 self.rate_dyn = rlf
333 ytdl_instance.params["logger"] = LoggerAdapter(self, ytdl_instance)
334
335 def _progress_hook(self, info):
336 if info["status"] == "downloading" and \
337 info["elapsed"] >= self.progress:
338 total = info.get("total_bytes") or info.get("total_bytes_estimate")
339 speed = info.get("speed")
340 self.out.progress(
341 None if total is None else int(total),
342 info["downloaded_bytes"],
343 int(speed) if speed else 0,
344 )
345
346 def _set_outtmpl(self, ytdl_instance, outtmpl):
347 try:
348 ytdl_instance._parse_outtmpl
349 except AttributeError:
350 try:
351 ytdl_instance.outtmpl_dict["default"] = outtmpl
352 except AttributeError:
353 ytdl_instance.params["outtmpl"] = outtmpl
354 else:
355 ytdl_instance.params["outtmpl"] = {"default": outtmpl}
356
357
358 class LoggerAdapter():
359 __slots__ = ("obj", "log")
360
361 def __init__(self, obj, ytdl_instance):
362 self.obj = obj
363 self.log = ytdl_instance.params.get("logger")
364
365 def debug(self, msg):
366 if self.log is not None:
367 if msg[0] == "[":
368 msg = msg[msg.find("]")+2:]
369 self.log.debug(msg)
370
371 def warning(self, msg):
372 if self.log is not None:
373 if "WARNING:" in msg:
374 msg = msg[msg.find(" ")+1:]
375 self.log.warning(msg)
376
377 def error(self, msg):
378 if "ERROR:" in msg:
379 msg = msg[msg.find(" ")+1:]
380 self.obj.error = msg
381
382
383 def compatible_formats(formats):
384 """Returns True if 'formats' are compatible for merge"""
385 video_ext = formats[0].get("ext")
386 audio_ext = formats[1].get("ext")
387
388 if video_ext == "webm" and audio_ext == "webm":
389 return True
390
391 exts = ("mp3", "mp4", "m4a", "m4p", "m4b", "m4r", "m4v", "ismv", "isma")
392 return video_ext in exts and audio_ext in exts
393
394
395 __downloader__ = YoutubeDLDownloader