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