[ie/youtube] Add age-gate workaround for some embeddable videos (#11821)
[yt-dlp.git] / yt_dlp / downloader / common.py
blobe8dcb37cc3145786ae8578910f6f7332e0efa369
1 import contextlib
2 import errno
3 import functools
4 import os
5 import random
6 import re
7 import threading
8 import time
10 from ..minicurses import (
11 BreaklineStatusPrinter,
12 MultilineLogger,
13 MultilinePrinter,
14 QuietMultilinePrinter,
16 from ..utils import (
17 IDENTITY,
18 NO_DEFAULT,
19 LockingUnsupportedError,
20 Namespace,
21 RetryManager,
22 classproperty,
23 deprecation_warning,
24 format_bytes,
25 join_nonempty,
26 parse_bytes,
27 remove_start,
28 sanitize_open,
29 shell_quote,
30 timeconvert,
31 timetuple_from_msec,
32 try_call,
36 class FileDownloader:
37 """File Downloader class.
39 File downloader objects are the ones responsible of downloading the
40 actual video file and writing it to disk.
42 File downloaders accept a lot of parameters. In order not to saturate
43 the object constructor with arguments, it receives a dictionary of
44 options instead.
46 Available options:
48 verbose: Print additional info to stdout.
49 quiet: Do not print messages to stdout.
50 ratelimit: Download speed limit, in bytes/sec.
51 throttledratelimit: Assume the download is being throttled below this speed (bytes/sec)
52 retries: Number of times to retry for expected network errors.
53 Default is 0 for API, but 10 for CLI
54 file_access_retries: Number of times to retry on file access error (default: 3)
55 buffersize: Size of download buffer in bytes.
56 noresizebuffer: Do not automatically resize the download buffer.
57 continuedl: Try to continue downloads if possible.
58 noprogress: Do not print the progress bar.
59 nopart: Do not use temporary .part files.
60 updatetime: Use the Last-modified header to set output file timestamps.
61 test: Download only first bytes to test the downloader.
62 min_filesize: Skip files smaller than this size
63 max_filesize: Skip files larger than this size
64 xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
65 progress_delta: The minimum time between progress output, in seconds
66 external_downloader_args: A dictionary of downloader keys (in lower case)
67 and a list of additional command-line arguments for the
68 executable. Use 'default' as the name for arguments to be
69 passed to all downloaders. For compatibility with youtube-dl,
70 a single list of args can also be used
71 hls_use_mpegts: Use the mpegts container for HLS videos.
72 http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be
73 useful for bypassing bandwidth throttling imposed by
74 a webserver (experimental)
75 progress_template: See YoutubeDL.py
76 retry_sleep_functions: See YoutubeDL.py
78 Subclasses of this one must re-define the real_download method.
79 """
81 _TEST_FILE_SIZE = 10241
82 params = None
84 def __init__(self, ydl, params):
85 """Create a FileDownloader object with the given options."""
86 self._set_ydl(ydl)
87 self._progress_hooks = []
88 self.params = params
89 self._prepare_multiline_status()
90 self.add_progress_hook(self.report_progress)
91 if self.params.get('progress_delta'):
92 self._progress_delta_lock = threading.Lock()
93 self._progress_delta_time = time.monotonic()
95 def _set_ydl(self, ydl):
96 self.ydl = ydl
98 for func in (
99 'deprecation_warning',
100 'deprecated_feature',
101 'report_error',
102 'report_file_already_downloaded',
103 'report_warning',
104 'to_console_title',
105 'to_stderr',
106 'trouble',
107 'write_debug',
109 if not hasattr(self, func):
110 setattr(self, func, getattr(ydl, func))
112 def to_screen(self, *args, **kargs):
113 self.ydl.to_screen(*args, quiet=self.params.get('quiet'), **kargs)
115 __to_screen = to_screen
117 @classproperty
118 def FD_NAME(cls):
119 return re.sub(r'(?<=[a-z])(?=[A-Z])', '_', cls.__name__[:-2]).lower()
121 @staticmethod
122 def format_seconds(seconds):
123 if seconds is None:
124 return ' Unknown'
125 time = timetuple_from_msec(seconds * 1000)
126 if time.hours > 99:
127 return '--:--:--'
128 return '%02d:%02d:%02d' % time[:-1]
130 @classmethod
131 def format_eta(cls, seconds):
132 return f'{remove_start(cls.format_seconds(seconds), "00:"):>8s}'
134 @staticmethod
135 def calc_percent(byte_counter, data_len):
136 if data_len is None:
137 return None
138 return float(byte_counter) / float(data_len) * 100.0
140 @staticmethod
141 def format_percent(percent):
142 return ' N/A%' if percent is None else f'{percent:>5.1f}%'
144 @classmethod
145 def calc_eta(cls, start_or_rate, now_or_remaining, total=NO_DEFAULT, current=NO_DEFAULT):
146 if total is NO_DEFAULT:
147 rate, remaining = start_or_rate, now_or_remaining
148 if None in (rate, remaining):
149 return None
150 return int(float(remaining) / rate)
152 start, now = start_or_rate, now_or_remaining
153 if total is None:
154 return None
155 if now is None:
156 now = time.time()
157 rate = cls.calc_speed(start, now, current)
158 return rate and int((float(total) - float(current)) / rate)
160 @staticmethod
161 def calc_speed(start, now, bytes):
162 dif = now - start
163 if bytes == 0 or dif < 0.001: # One millisecond
164 return None
165 return float(bytes) / dif
167 @staticmethod
168 def format_speed(speed):
169 return ' Unknown B/s' if speed is None else f'{format_bytes(speed):>10s}/s'
171 @staticmethod
172 def format_retries(retries):
173 return 'inf' if retries == float('inf') else int(retries)
175 @staticmethod
176 def filesize_or_none(unencoded_filename):
177 if os.path.isfile(unencoded_filename):
178 return os.path.getsize(unencoded_filename)
179 return 0
181 @staticmethod
182 def best_block_size(elapsed_time, bytes):
183 new_min = max(bytes / 2.0, 1.0)
184 new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
185 if elapsed_time < 0.001:
186 return int(new_max)
187 rate = bytes / elapsed_time
188 if rate > new_max:
189 return int(new_max)
190 if rate < new_min:
191 return int(new_min)
192 return int(rate)
194 @staticmethod
195 def parse_bytes(bytestr):
196 """Parse a string indicating a byte quantity into an integer."""
197 deprecation_warning('yt_dlp.FileDownloader.parse_bytes is deprecated and '
198 'may be removed in the future. Use yt_dlp.utils.parse_bytes instead')
199 return parse_bytes(bytestr)
201 def slow_down(self, start_time, now, byte_counter):
202 """Sleep if the download speed is over the rate limit."""
203 rate_limit = self.params.get('ratelimit')
204 if rate_limit is None or byte_counter == 0:
205 return
206 if now is None:
207 now = time.time()
208 elapsed = now - start_time
209 if elapsed <= 0.0:
210 return
211 speed = float(byte_counter) / elapsed
212 if speed > rate_limit:
213 sleep_time = float(byte_counter) / rate_limit - elapsed
214 if sleep_time > 0:
215 time.sleep(sleep_time)
217 def temp_name(self, filename):
218 """Returns a temporary filename for the given filename."""
219 if self.params.get('nopart', False) or filename == '-' or \
220 (os.path.exists(filename) and not os.path.isfile(filename)):
221 return filename
222 return filename + '.part'
224 def undo_temp_name(self, filename):
225 if filename.endswith('.part'):
226 return filename[:-len('.part')]
227 return filename
229 def ytdl_filename(self, filename):
230 return filename + '.ytdl'
232 def wrap_file_access(action, *, fatal=False):
233 def error_callback(err, count, retries, *, fd):
234 return RetryManager.report_retry(
235 err, count, retries, info=fd.__to_screen,
236 warn=lambda e: (time.sleep(0.01), fd.to_screen(f'[download] Unable to {action} file: {e}')),
237 error=None if fatal else lambda e: fd.report_error(f'Unable to {action} file: {e}'),
238 sleep_func=fd.params.get('retry_sleep_functions', {}).get('file_access'))
240 def wrapper(self, func, *args, **kwargs):
241 for retry in RetryManager(self.params.get('file_access_retries', 3), error_callback, fd=self):
242 try:
243 return func(self, *args, **kwargs)
244 except OSError as err:
245 if err.errno in (errno.EACCES, errno.EINVAL):
246 retry.error = err
247 continue
248 retry.error_callback(err, 1, 0)
250 return functools.partial(functools.partialmethod, wrapper)
252 @wrap_file_access('open', fatal=True)
253 def sanitize_open(self, filename, open_mode):
254 f, filename = sanitize_open(filename, open_mode)
255 if not getattr(f, 'locked', None):
256 self.write_debug(f'{LockingUnsupportedError.msg}. Proceeding without locking', only_once=True)
257 return f, filename
259 @wrap_file_access('remove')
260 def try_remove(self, filename):
261 if os.path.isfile(filename):
262 os.remove(filename)
264 @wrap_file_access('rename')
265 def try_rename(self, old_filename, new_filename):
266 if old_filename == new_filename:
267 return
268 os.replace(old_filename, new_filename)
270 def try_utime(self, filename, last_modified_hdr):
271 """Try to set the last-modified time of the given file."""
272 if last_modified_hdr is None:
273 return
274 if not os.path.isfile(filename):
275 return
276 timestr = last_modified_hdr
277 if timestr is None:
278 return
279 filetime = timeconvert(timestr)
280 if filetime is None:
281 return filetime
282 # Ignore obviously invalid dates
283 if filetime == 0:
284 return
285 with contextlib.suppress(Exception):
286 os.utime(filename, (time.time(), filetime))
287 return filetime
289 def report_destination(self, filename):
290 """Report destination filename."""
291 self.to_screen('[download] Destination: ' + filename)
293 def _prepare_multiline_status(self, lines=1):
294 if self.params.get('noprogress'):
295 self._multiline = QuietMultilinePrinter()
296 elif self.ydl.params.get('logger'):
297 self._multiline = MultilineLogger(self.ydl.params['logger'], lines)
298 elif self.params.get('progress_with_newline'):
299 self._multiline = BreaklineStatusPrinter(self.ydl._out_files.out, lines)
300 else:
301 self._multiline = MultilinePrinter(self.ydl._out_files.out, lines, not self.params.get('quiet'))
302 self._multiline.allow_colors = self.ydl._allow_colors.out and self.ydl._allow_colors.out != 'no_color'
303 self._multiline._HAVE_FULLCAP = self.ydl._allow_colors.out
305 def _finish_multiline_status(self):
306 self._multiline.end()
308 ProgressStyles = Namespace(
309 downloaded_bytes='light blue',
310 percent='light blue',
311 eta='yellow',
312 speed='green',
313 elapsed='bold white',
314 total_bytes='',
315 total_bytes_estimate='',
318 def _report_progress_status(self, s, default_template):
319 for name, style in self.ProgressStyles.items_:
320 name = f'_{name}_str'
321 if name not in s:
322 continue
323 s[name] = self._format_progress(s[name], style)
324 s['_default_template'] = default_template % s
326 progress_dict = s.copy()
327 progress_dict.pop('info_dict')
328 progress_dict = {'info': s['info_dict'], 'progress': progress_dict}
330 progress_template = self.params.get('progress_template', {})
331 self._multiline.print_at_line(self.ydl.evaluate_outtmpl(
332 progress_template.get('download') or '[download] %(progress._default_template)s',
333 progress_dict), s.get('progress_idx') or 0)
334 self.to_console_title(self.ydl.evaluate_outtmpl(
335 progress_template.get('download-title') or 'yt-dlp %(progress._default_template)s',
336 progress_dict))
338 def _format_progress(self, *args, **kwargs):
339 return self.ydl._format_text(
340 self._multiline.stream, self._multiline.allow_colors, *args, **kwargs)
342 def report_progress(self, s):
343 def with_fields(*tups, default=''):
344 for *fields, tmpl in tups:
345 if all(s.get(f) is not None for f in fields):
346 return tmpl
347 return default
349 _format_bytes = lambda k: f'{format_bytes(s.get(k)):>10s}'
351 if s['status'] == 'finished':
352 if self.params.get('noprogress'):
353 self.to_screen('[download] Download completed')
354 speed = try_call(lambda: s['total_bytes'] / s['elapsed'])
355 s.update({
356 'speed': speed,
357 '_speed_str': self.format_speed(speed).strip(),
358 '_total_bytes_str': _format_bytes('total_bytes'),
359 '_elapsed_str': self.format_seconds(s.get('elapsed')),
360 '_percent_str': self.format_percent(100),
362 self._report_progress_status(s, join_nonempty(
363 '100%%',
364 with_fields(('total_bytes', 'of %(_total_bytes_str)s')),
365 with_fields(('elapsed', 'in %(_elapsed_str)s')),
366 with_fields(('speed', 'at %(_speed_str)s')),
367 delim=' '))
369 if s['status'] != 'downloading':
370 return
372 if update_delta := self.params.get('progress_delta'):
373 with self._progress_delta_lock:
374 if time.monotonic() < self._progress_delta_time:
375 return
376 self._progress_delta_time += update_delta
378 s.update({
379 '_eta_str': self.format_eta(s.get('eta')).strip(),
380 '_speed_str': self.format_speed(s.get('speed')),
381 '_percent_str': self.format_percent(try_call(
382 lambda: 100 * s['downloaded_bytes'] / s['total_bytes'],
383 lambda: 100 * s['downloaded_bytes'] / s['total_bytes_estimate'],
384 lambda: s['downloaded_bytes'] == 0 and 0)),
385 '_total_bytes_str': _format_bytes('total_bytes'),
386 '_total_bytes_estimate_str': _format_bytes('total_bytes_estimate'),
387 '_downloaded_bytes_str': _format_bytes('downloaded_bytes'),
388 '_elapsed_str': self.format_seconds(s.get('elapsed')),
391 msg_template = with_fields(
392 ('total_bytes', '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'),
393 ('total_bytes_estimate', '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'),
394 ('downloaded_bytes', 'elapsed', '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'),
395 ('downloaded_bytes', '%(_downloaded_bytes_str)s at %(_speed_str)s'),
396 default='%(_percent_str)s at %(_speed_str)s ETA %(_eta_str)s')
398 msg_template += with_fields(
399 ('fragment_index', 'fragment_count', ' (frag %(fragment_index)s/%(fragment_count)s)'),
400 ('fragment_index', ' (frag %(fragment_index)s)'))
401 self._report_progress_status(s, msg_template)
403 def report_resuming_byte(self, resume_len):
404 """Report attempt to resume at given byte."""
405 self.to_screen(f'[download] Resuming download at byte {resume_len}')
407 def report_retry(self, err, count, retries, frag_index=NO_DEFAULT, fatal=True):
408 """Report retry"""
409 is_frag = False if frag_index is NO_DEFAULT else 'fragment'
410 RetryManager.report_retry(
411 err, count, retries, info=self.__to_screen,
412 warn=lambda msg: self.__to_screen(f'[download] Got error: {msg}'),
413 error=IDENTITY if not fatal else lambda e: self.report_error(f'\r[download] Got error: {e}'),
414 sleep_func=self.params.get('retry_sleep_functions', {}).get(is_frag or 'http'),
415 suffix=f'fragment{"s" if frag_index is None else f" {frag_index}"}' if is_frag else None)
417 def report_unable_to_resume(self):
418 """Report it was impossible to resume download."""
419 self.to_screen('[download] Unable to resume')
421 @staticmethod
422 def supports_manifest(manifest):
423 """ Whether the downloader can download the fragments from the manifest.
424 Redefine in subclasses if needed. """
425 pass
427 def download(self, filename, info_dict, subtitle=False):
428 """Download to a filename using the info from info_dict
429 Return True on success and False otherwise
431 nooverwrites_and_exists = (
432 not self.params.get('overwrites', True)
433 and os.path.exists(filename)
436 if not hasattr(filename, 'write'):
437 continuedl_and_exists = (
438 self.params.get('continuedl', True)
439 and os.path.isfile(filename)
440 and not self.params.get('nopart', False)
443 # Check file already present
444 if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
445 self.report_file_already_downloaded(filename)
446 self._hook_progress({
447 'filename': filename,
448 'status': 'finished',
449 'total_bytes': os.path.getsize(filename),
450 }, info_dict)
451 self._finish_multiline_status()
452 return True, False
454 if subtitle:
455 sleep_interval = self.params.get('sleep_interval_subtitles') or 0
456 else:
457 min_sleep_interval = self.params.get('sleep_interval') or 0
458 sleep_interval = random.uniform(
459 min_sleep_interval, self.params.get('max_sleep_interval') or min_sleep_interval)
460 if sleep_interval > 0:
461 self.to_screen(f'[download] Sleeping {sleep_interval:.2f} seconds ...')
462 time.sleep(sleep_interval)
464 ret = self.real_download(filename, info_dict)
465 self._finish_multiline_status()
466 return ret, True
468 def real_download(self, filename, info_dict):
469 """Real download process. Redefine in subclasses."""
470 raise NotImplementedError('This method must be implemented by subclasses')
472 def _hook_progress(self, status, info_dict):
473 # Ideally we want to make a copy of the dict, but that is too slow
474 status['info_dict'] = info_dict
475 # youtube-dl passes the same status object to all the hooks.
476 # Some third party scripts seems to be relying on this.
477 # So keep this behavior if possible
478 for ph in self._progress_hooks:
479 ph(status)
481 def add_progress_hook(self, ph):
482 # See YoutubeDl.py (search for progress_hooks) for a description of
483 # this interface
484 self._progress_hooks.append(ph)
486 def _debug_cmd(self, args, exe=None):
487 if not self.params.get('verbose', False):
488 return
490 if exe is None:
491 exe = os.path.basename(args[0])
493 self.write_debug(f'{exe} command line: {shell_quote(args)}')