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