9 from ..minicurses
import (
10 BreaklineStatusPrinter
,
13 QuietMultilinePrinter
,
19 LockingUnsupportedError
,
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
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
77 Subclasses of this one must re-define the real_download method.
80 _TEST_FILE_SIZE
= 10241
83 def __init__(self
, ydl
, params
):
84 """Create a FileDownloader object with the given options."""
86 self
._progress
_hooks
= []
88 self
._prepare
_multiline
_status
()
89 self
.add_progress_hook(self
.report_progress
)
91 def _set_ydl(self
, ydl
):
95 'deprecation_warning',
98 'report_file_already_downloaded',
105 if not hasattr(self
, func
):
106 setattr(self
, func
, getattr(ydl
, func
))
108 def to_screen(self
, *args
, **kargs
):
109 self
.ydl
.to_screen(*args
, quiet
=self
.params
.get('quiet'), **kargs
)
111 __to_screen
= to_screen
115 return re
.sub(r
'(?<=[a-z])(?=[A-Z])', '_', cls
.__name
__[:-2]).lower()
118 def format_seconds(seconds
):
121 time
= timetuple_from_msec(seconds
* 1000)
124 return '%02d:%02d:%02d' % time
[:-1]
127 def format_eta(cls
, seconds
):
128 return f
'{remove_start(cls.format_seconds(seconds), "00:"):>8s}'
131 def calc_percent(byte_counter
, data_len
):
134 return float(byte_counter
) / float(data_len
) * 100.0
137 def format_percent(percent
):
138 return ' N/A%' if percent
is None else f
'{percent:>5.1f}%'
141 def calc_eta(start
, now
, total
, current
):
147 if current
== 0 or dif
< 0.001: # One millisecond
149 rate
= float(current
) / dif
150 return int((float(total
) - float(current
)) / rate
)
153 def calc_speed(start
, now
, bytes):
155 if bytes == 0 or dif
< 0.001: # One millisecond
157 return float(bytes) / dif
160 def format_speed(speed
):
161 return ' Unknown B/s' if speed
is None else f
'{format_bytes(speed):>10s}/s'
164 def format_retries(retries
):
165 return 'inf' if retries
== float('inf') else int(retries
)
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:
173 rate
= bytes / elapsed_time
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
)
186 number
= float(matchobj
.group(1))
187 multiplier
= 1024.0 ** 'bkmgtpezy'.index(matchobj
.group(2).lower())
188 return int(round(number
* multiplier
))
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:
197 elapsed
= now
- start_time
200 speed
= float(byte_counter
) / elapsed
201 if speed
> rate_limit
:
202 sleep_time
= float(byte_counter
) / rate_limit
- elapsed
204 time
.sleep(sleep_time
)
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
))):
211 return filename
+ '.part'
213 def undo_temp_name(self
, filename
):
214 if filename
.endswith('.part'):
215 return filename
[:-len('.part')]
218 def ytdl_filename(self
, filename
):
219 return filename
+ '.ytdl'
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'))
229 def wrapper(self
, func
, *args
, **kwargs
):
230 for retry
in RetryManager(self
.params
.get('file_access_retries'), error_callback
, fd
=self
):
232 return func(self
, *args
, **kwargs
)
233 except OSError as err
:
234 if err
.errno
in (errno
.EACCES
, errno
.EINVAL
):
237 retry
.error_callback(err
, 1, 0)
239 return functools
.partial(functools
.partialmethod
, wrapper
)
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)
248 @wrap_file_access('remove')
249 def try_remove(self
, filename
):
252 @wrap_file_access('rename')
253 def try_rename(self
, old_filename
, new_filename
):
254 if old_filename
== new_filename
:
256 os
.replace(old_filename
, new_filename
)
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:
262 if not os
.path
.isfile(encodeFilename(filename
)):
264 timestr
= last_modified_hdr
267 filetime
= timeconvert(timestr
)
270 # Ignore obviously invalid dates
273 with contextlib
.suppress(Exception):
274 os
.utime(filename
, (time
.time(), filetime
))
277 def report_destination(self
, filename
):
278 """Report destination filename."""
279 self
.to_screen('[download] Destination: ' + filename
)
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
)
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')
292 def _finish_multiline_status(self
):
293 self
._multiline
.end()
295 ProgressStyles
= Namespace(
296 downloaded_bytes
='light blue',
297 percent
='light blue',
300 elapsed
='bold white',
302 total_bytes_estimate
='',
305 def _report_progress_status(self
, s
, default_template
):
306 for name
, style
in self
.ProgressStyles
.items_
:
307 name
= f
'_{name}_str'
310 s
[name
] = self
._format
_progress
(s
[name
], style
)
311 s
['_default_template'] = default_template
% s
313 progress_dict
= s
.copy()
314 progress_dict
.pop('info_dict')
315 progress_dict
= {'info': s['info_dict'], 'progress': progress_dict}
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',
325 def _format_progress(self
, *args
, **kwargs
):
326 return self
.ydl
._format
_text
(
327 self
._multiline
.stream
, self
._multiline
.allow_colors
, *args
, **kwargs
)
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
):
336 _formats_bytes
= lambda k
: f
'{format_bytes(s.get(k)):>10s}'
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'])
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),
349 self
._report
_progress
_status
(s
, join_nonempty(
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')),
356 if s
['status'] != 'downloading':
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')),
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')
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
)
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
)
388 def report_retry(self
, err
, count
, retries
, frag_index
=NO_DEFAULT
, fatal
=True):
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)
398 def report_unable_to_resume(self
):
399 """Report it was impossible to resume download."""
400 self
.to_screen('[download] Unable to resume')
403 def supports_manifest(manifest
):
404 """ Whether the downloader can download the fragments from the manifest.
405 Redefine in subclasses if needed. """
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
413 nooverwrites_and_exists
= (
414 not self
.params
.get('overwrites', True)
415 and os
.path
.exists(encodeFilename(filename
))
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)
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
)),
433 self
._finish
_multiline
_status
()
437 sleep_interval
= self
.params
.get('sleep_interval_subtitles') or 0
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
)
446 ret
= self
.real_download(filename
, info_dict
)
447 self
._finish
_multiline
_status
()
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')
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
:
463 def add_progress_hook(self
, ph
):
464 # See YoutubeDl.py (search for progress_hooks) for a description of
466 self
._progress
_hooks
.append(ph
)
468 def _debug_cmd(self
, args
, exe
=None):
469 if not self
.params
.get('verbose', False):
472 str_args
= [decodeArgument(a
) for a
in args
]
475 exe
= os
.path
.basename(str_args
[0])
477 self
.write_debug(f
'{exe} command line: {shell_quote(str_args)}')