]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/common.py
c48a2ff8ac7ac9bad863b6f3c19faaee7bd44d58
[yt-dlp.git] / yt_dlp / downloader / common.py
1 import contextlib
2 import errno
3 import functools
4 import os
5 import random
6 import re
7 import time
8
9 from ..minicurses import (
10 BreaklineStatusPrinter,
11 MultilineLogger,
12 MultilinePrinter,
13 QuietMultilinePrinter,
14 )
15 from ..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 )
35
36
37 class FileDownloader:
38 """File Downloader class.
39
40 File downloader objects are the ones responsible of downloading the
41 actual video file and writing it to disk.
42
43 File downloaders accept a lot of parameters. In order not to saturate
44 the object constructor with arguments, it receives a dictionary of
45 options instead.
46
47 Available options:
48
49 verbose: Print additional info to stdout.
50 quiet: Do not print messages to stdout.
51 ratelimit: Download speed limit, in bytes/sec.
52 continuedl: Attempt to continue downloads if possible
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 os.remove(filename)
260
261 @wrap_file_access('rename')
262 def try_rename(self, old_filename, new_filename):
263 if old_filename == new_filename:
264 return
265 os.replace(old_filename, new_filename)
266
267 def try_utime(self, filename, last_modified_hdr):
268 """Try to set the last-modified time of the given file."""
269 if last_modified_hdr is None:
270 return
271 if not os.path.isfile(encodeFilename(filename)):
272 return
273 timestr = last_modified_hdr
274 if timestr is None:
275 return
276 filetime = timeconvert(timestr)
277 if filetime is None:
278 return filetime
279 # Ignore obviously invalid dates
280 if filetime == 0:
281 return
282 with contextlib.suppress(Exception):
283 os.utime(filename, (time.time(), filetime))
284 return filetime
285
286 def report_destination(self, filename):
287 """Report destination filename."""
288 self.to_screen('[download] Destination: ' + filename)
289
290 def _prepare_multiline_status(self, lines=1):
291 if self.params.get('noprogress'):
292 self._multiline = QuietMultilinePrinter()
293 elif self.ydl.params.get('logger'):
294 self._multiline = MultilineLogger(self.ydl.params['logger'], lines)
295 elif self.params.get('progress_with_newline'):
296 self._multiline = BreaklineStatusPrinter(self.ydl._out_files.out, lines)
297 else:
298 self._multiline = MultilinePrinter(self.ydl._out_files.out, lines, not self.params.get('quiet'))
299 self._multiline.allow_colors = self._multiline._HAVE_FULLCAP and not self.params.get('no_color')
300
301 def _finish_multiline_status(self):
302 self._multiline.end()
303
304 ProgressStyles = Namespace(
305 downloaded_bytes='light blue',
306 percent='light blue',
307 eta='yellow',
308 speed='green',
309 elapsed='bold white',
310 total_bytes='',
311 total_bytes_estimate='',
312 )
313
314 def _report_progress_status(self, s, default_template):
315 for name, style in self.ProgressStyles.items_:
316 name = f'_{name}_str'
317 if name not in s:
318 continue
319 s[name] = self._format_progress(s[name], style)
320 s['_default_template'] = default_template % s
321
322 progress_dict = s.copy()
323 progress_dict.pop('info_dict')
324 progress_dict = {'info': s['info_dict'], 'progress': progress_dict}
325
326 progress_template = self.params.get('progress_template', {})
327 self._multiline.print_at_line(self.ydl.evaluate_outtmpl(
328 progress_template.get('download') or '[download] %(progress._default_template)s',
329 progress_dict), s.get('progress_idx') or 0)
330 self.to_console_title(self.ydl.evaluate_outtmpl(
331 progress_template.get('download-title') or 'yt-dlp %(progress._default_template)s',
332 progress_dict))
333
334 def _format_progress(self, *args, **kwargs):
335 return self.ydl._format_text(
336 self._multiline.stream, self._multiline.allow_colors, *args, **kwargs)
337
338 def report_progress(self, s):
339 def with_fields(*tups, default=''):
340 for *fields, tmpl in tups:
341 if all(s.get(f) is not None for f in fields):
342 return tmpl
343 return default
344
345 _format_bytes = lambda k: f'{format_bytes(s.get(k)):>10s}'
346
347 if s['status'] == 'finished':
348 if self.params.get('noprogress'):
349 self.to_screen('[download] Download completed')
350 speed = try_call(lambda: s['total_bytes'] / s['elapsed'])
351 s.update({
352 'speed': speed,
353 '_speed_str': self.format_speed(speed).strip(),
354 '_total_bytes_str': _format_bytes('total_bytes'),
355 '_elapsed_str': self.format_seconds(s.get('elapsed')),
356 '_percent_str': self.format_percent(100),
357 })
358 self._report_progress_status(s, join_nonempty(
359 '100%%',
360 with_fields(('total_bytes', 'of %(_total_bytes_str)s')),
361 with_fields(('elapsed', 'in %(_elapsed_str)s')),
362 with_fields(('speed', 'at %(_speed_str)s')),
363 delim=' '))
364
365 if s['status'] != 'downloading':
366 return
367
368 s.update({
369 '_eta_str': self.format_eta(s.get('eta')).strip(),
370 '_speed_str': self.format_speed(s.get('speed')),
371 '_percent_str': self.format_percent(try_call(
372 lambda: 100 * s['downloaded_bytes'] / s['total_bytes'],
373 lambda: 100 * s['downloaded_bytes'] / s['total_bytes_estimate'],
374 lambda: s['downloaded_bytes'] == 0 and 0)),
375 '_total_bytes_str': _format_bytes('total_bytes'),
376 '_total_bytes_estimate_str': _format_bytes('total_bytes_estimate'),
377 '_downloaded_bytes_str': _format_bytes('downloaded_bytes'),
378 '_elapsed_str': self.format_seconds(s.get('elapsed')),
379 })
380
381 msg_template = with_fields(
382 ('total_bytes', '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'),
383 ('total_bytes_estimate', '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'),
384 ('downloaded_bytes', 'elapsed', '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'),
385 ('downloaded_bytes', '%(_downloaded_bytes_str)s at %(_speed_str)s'),
386 default='%(_percent_str)s at %(_speed_str)s ETA %(_eta_str)s')
387
388 msg_template += with_fields(
389 ('fragment_index', 'fragment_count', ' (frag %(fragment_index)s/%(fragment_count)s)'),
390 ('fragment_index', ' (frag %(fragment_index)s)'))
391 self._report_progress_status(s, msg_template)
392
393 def report_resuming_byte(self, resume_len):
394 """Report attempt to resume at given byte."""
395 self.to_screen('[download] Resuming download at byte %s' % resume_len)
396
397 def report_retry(self, err, count, retries, frag_index=NO_DEFAULT, fatal=True):
398 """Report retry"""
399 is_frag = False if frag_index is NO_DEFAULT else 'fragment'
400 RetryManager.report_retry(
401 err, count, retries, info=self.__to_screen,
402 warn=lambda msg: self.__to_screen(f'[download] Got error: {msg}'),
403 error=IDENTITY if not fatal else lambda e: self.report_error(f'\r[download] Got error: {e}'),
404 sleep_func=self.params.get('retry_sleep_functions', {}).get(is_frag or 'http'),
405 suffix=f'fragment{"s" if frag_index is None else f" {frag_index}"}' if is_frag else None)
406
407 def report_unable_to_resume(self):
408 """Report it was impossible to resume download."""
409 self.to_screen('[download] Unable to resume')
410
411 @staticmethod
412 def supports_manifest(manifest):
413 """ Whether the downloader can download the fragments from the manifest.
414 Redefine in subclasses if needed. """
415 pass
416
417 def download(self, filename, info_dict, subtitle=False):
418 """Download to a filename using the info from info_dict
419 Return True on success and False otherwise
420 """
421
422 nooverwrites_and_exists = (
423 not self.params.get('overwrites', True)
424 and os.path.exists(encodeFilename(filename))
425 )
426
427 if not hasattr(filename, 'write'):
428 continuedl_and_exists = (
429 self.params.get('continuedl', True)
430 and os.path.isfile(encodeFilename(filename))
431 and not self.params.get('nopart', False)
432 )
433
434 # Check file already present
435 if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
436 self.report_file_already_downloaded(filename)
437 self._hook_progress({
438 'filename': filename,
439 'status': 'finished',
440 'total_bytes': os.path.getsize(encodeFilename(filename)),
441 }, info_dict)
442 self._finish_multiline_status()
443 return True, False
444
445 if subtitle:
446 sleep_interval = self.params.get('sleep_interval_subtitles') or 0
447 else:
448 min_sleep_interval = self.params.get('sleep_interval') or 0
449 sleep_interval = random.uniform(
450 min_sleep_interval, self.params.get('max_sleep_interval') or min_sleep_interval)
451 if sleep_interval > 0:
452 self.to_screen(f'[download] Sleeping {sleep_interval:.2f} seconds ...')
453 time.sleep(sleep_interval)
454
455 ret = self.real_download(filename, info_dict)
456 self._finish_multiline_status()
457 return ret, True
458
459 def real_download(self, filename, info_dict):
460 """Real download process. Redefine in subclasses."""
461 raise NotImplementedError('This method must be implemented by subclasses')
462
463 def _hook_progress(self, status, info_dict):
464 # Ideally we want to make a copy of the dict, but that is too slow
465 status['info_dict'] = info_dict
466 # youtube-dl passes the same status object to all the hooks.
467 # Some third party scripts seems to be relying on this.
468 # So keep this behavior if possible
469 for ph in self._progress_hooks:
470 ph(status)
471
472 def add_progress_hook(self, ph):
473 # See YoutubeDl.py (search for progress_hooks) for a description of
474 # this interface
475 self._progress_hooks.append(ph)
476
477 def _debug_cmd(self, args, exe=None):
478 if not self.params.get('verbose', False):
479 return
480
481 str_args = [decodeArgument(a) for a in args]
482
483 if exe is None:
484 exe = os.path.basename(str_args[0])
485
486 self.write_debug(f'{exe} command line: {shell_quote(str_args)}')