2022-04-17 20:58:28 +00:00
|
|
|
import contextlib
|
2022-04-11 22:32:57 +00:00
|
|
|
import errno
|
2022-08-01 20:13:18 +00:00
|
|
|
import functools
|
2013-09-23 15:59:27 +00:00
|
|
|
import os
|
2022-04-11 22:32:57 +00:00
|
|
|
import random
|
2013-09-23 15:59:27 +00:00
|
|
|
import re
|
2024-04-08 20:47:38 +00:00
|
|
|
import threading
|
2013-09-23 15:59:27 +00:00
|
|
|
import time
|
|
|
|
|
2022-04-11 22:32:57 +00:00
|
|
|
from ..minicurses import (
|
|
|
|
BreaklineStatusPrinter,
|
|
|
|
MultilineLogger,
|
|
|
|
MultilinePrinter,
|
|
|
|
QuietMultilinePrinter,
|
|
|
|
)
|
2013-09-23 15:59:27 +00:00
|
|
|
from ..utils import (
|
2022-08-01 20:13:18 +00:00
|
|
|
IDENTITY,
|
|
|
|
NO_DEFAULT,
|
2022-04-11 22:32:57 +00:00
|
|
|
LockingUnsupportedError,
|
2022-04-17 20:58:28 +00:00
|
|
|
Namespace,
|
2022-08-01 20:13:18 +00:00
|
|
|
RetryManager,
|
2022-05-20 15:25:21 +00:00
|
|
|
classproperty,
|
2022-11-30 06:04:51 +00:00
|
|
|
deprecation_warning,
|
2013-09-23 15:59:27 +00:00
|
|
|
format_bytes,
|
2022-05-22 16:22:26 +00:00
|
|
|
join_nonempty,
|
2022-11-17 03:10:34 +00:00
|
|
|
parse_bytes,
|
2022-10-03 20:04:04 +00:00
|
|
|
remove_start,
|
2021-12-23 02:29:03 +00:00
|
|
|
sanitize_open,
|
2017-06-17 16:50:21 +00:00
|
|
|
shell_quote,
|
2014-04-04 12:59:11 +00:00
|
|
|
timeconvert,
|
2021-10-19 17:28:14 +00:00
|
|
|
timetuple_from_msec,
|
2022-05-22 16:22:26 +00:00
|
|
|
try_call,
|
2013-09-23 15:59:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-04-11 15:10:28 +00:00
|
|
|
class FileDownloader:
|
2013-09-23 15:59:27 +00:00
|
|
|
"""File Downloader class.
|
|
|
|
|
|
|
|
File downloader objects are the ones responsible of downloading the
|
|
|
|
actual video file and writing it to disk.
|
|
|
|
|
|
|
|
File downloaders accept a lot of parameters. In order not to saturate
|
|
|
|
the object constructor with arguments, it receives a dictionary of
|
|
|
|
options instead.
|
|
|
|
|
|
|
|
Available options:
|
|
|
|
|
2015-01-25 03:49:44 +00:00
|
|
|
verbose: Print additional info to stdout.
|
|
|
|
quiet: Do not print messages to stdout.
|
|
|
|
ratelimit: Download speed limit, in bytes/sec.
|
2021-06-22 23:11:09 +00:00
|
|
|
throttledratelimit: Assume the download is being throttled below this speed (bytes/sec)
|
2023-05-24 17:59:30 +00:00
|
|
|
retries: Number of times to retry for expected network errors.
|
|
|
|
Default is 0 for API, but 10 for CLI
|
|
|
|
file_access_retries: Number of times to retry on file access error (default: 3)
|
2015-01-25 03:49:44 +00:00
|
|
|
buffersize: Size of download buffer in bytes.
|
|
|
|
noresizebuffer: Do not automatically resize the download buffer.
|
|
|
|
continuedl: Try to continue downloads if possible.
|
|
|
|
noprogress: Do not print the progress bar.
|
|
|
|
nopart: Do not use temporary .part files.
|
|
|
|
updatetime: Use the Last-modified header to set output file timestamps.
|
|
|
|
test: Download only first bytes to test the downloader.
|
|
|
|
min_filesize: Skip files smaller than this size
|
|
|
|
max_filesize: Skip files larger than this size
|
|
|
|
xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
|
2024-04-08 20:47:38 +00:00
|
|
|
progress_delta: The minimum time between progress output, in seconds
|
2021-08-07 08:49:17 +00:00
|
|
|
external_downloader_args: A dictionary of downloader keys (in lower case)
|
|
|
|
and a list of additional command-line arguments for the
|
|
|
|
executable. Use 'default' as the name for arguments to be
|
|
|
|
passed to all downloaders. For compatibility with youtube-dl,
|
|
|
|
a single list of args can also be used
|
2016-01-30 11:26:40 +00:00
|
|
|
hls_use_mpegts: Use the mpegts container for HLS videos.
|
2018-02-17 12:10:12 +00:00
|
|
|
http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be
|
2018-02-03 19:53:50 +00:00
|
|
|
useful for bypassing bandwidth throttling imposed by
|
|
|
|
a webserver (experimental)
|
2021-10-08 19:11:59 +00:00
|
|
|
progress_template: See YoutubeDL.py
|
2022-05-19 14:30:31 +00:00
|
|
|
retry_sleep_functions: See YoutubeDL.py
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
Subclasses of this one must re-define the real_download method.
|
|
|
|
"""
|
|
|
|
|
2014-09-24 12:38:40 +00:00
|
|
|
_TEST_FILE_SIZE = 10241
|
2013-09-23 15:59:27 +00:00
|
|
|
params = None
|
|
|
|
|
|
|
|
def __init__(self, ydl, params):
|
|
|
|
"""Create a FileDownloader object with the given options."""
|
2022-04-17 20:58:28 +00:00
|
|
|
self._set_ydl(ydl)
|
2013-09-23 15:59:27 +00:00
|
|
|
self._progress_hooks = []
|
|
|
|
self.params = params
|
2021-10-08 19:11:59 +00:00
|
|
|
self._prepare_multiline_status()
|
2015-02-17 20:37:48 +00:00
|
|
|
self.add_progress_hook(self.report_progress)
|
2024-04-08 20:47:38 +00:00
|
|
|
if self.params.get('progress_delta'):
|
|
|
|
self._progress_delta_lock = threading.Lock()
|
|
|
|
self._progress_delta_time = time.monotonic()
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2022-04-17 20:58:28 +00:00
|
|
|
def _set_ydl(self, ydl):
|
|
|
|
self.ydl = ydl
|
|
|
|
|
|
|
|
for func in (
|
|
|
|
'deprecation_warning',
|
2022-08-30 15:28:28 +00:00
|
|
|
'deprecated_feature',
|
2022-04-17 20:58:28 +00:00
|
|
|
'report_error',
|
|
|
|
'report_file_already_downloaded',
|
|
|
|
'report_warning',
|
|
|
|
'to_console_title',
|
|
|
|
'to_stderr',
|
|
|
|
'trouble',
|
|
|
|
'write_debug',
|
|
|
|
):
|
2022-04-29 01:48:36 +00:00
|
|
|
if not hasattr(self, func):
|
|
|
|
setattr(self, func, getattr(ydl, func))
|
2022-04-17 20:58:28 +00:00
|
|
|
|
|
|
|
def to_screen(self, *args, **kargs):
|
|
|
|
self.ydl.to_screen(*args, quiet=self.params.get('quiet'), **kargs)
|
|
|
|
|
2022-05-19 14:30:31 +00:00
|
|
|
__to_screen = to_screen
|
|
|
|
|
2022-05-20 15:25:21 +00:00
|
|
|
@classproperty
|
|
|
|
def FD_NAME(cls):
|
2022-06-21 22:17:41 +00:00
|
|
|
return re.sub(r'(?<=[a-z])(?=[A-Z])', '_', cls.__name__[:-2]).lower()
|
2022-05-11 01:06:29 +00:00
|
|
|
|
2013-09-23 15:59:27 +00:00
|
|
|
@staticmethod
|
|
|
|
def format_seconds(seconds):
|
2022-05-22 16:22:26 +00:00
|
|
|
if seconds is None:
|
|
|
|
return ' Unknown'
|
2021-10-19 17:28:14 +00:00
|
|
|
time = timetuple_from_msec(seconds * 1000)
|
|
|
|
if time.hours > 99:
|
2013-09-23 15:59:27 +00:00
|
|
|
return '--:--:--'
|
2021-10-19 17:28:14 +00:00
|
|
|
return '%02d:%02d:%02d' % time[:-1]
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2022-10-03 20:04:04 +00:00
|
|
|
@classmethod
|
|
|
|
def format_eta(cls, seconds):
|
|
|
|
return f'{remove_start(cls.format_seconds(seconds), "00:"):>8s}'
|
2022-05-22 16:22:26 +00:00
|
|
|
|
2013-09-23 15:59:27 +00:00
|
|
|
@staticmethod
|
|
|
|
def calc_percent(byte_counter, data_len):
|
|
|
|
if data_len is None:
|
|
|
|
return None
|
|
|
|
return float(byte_counter) / float(data_len) * 100.0
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def format_percent(percent):
|
2022-05-22 16:22:26 +00:00
|
|
|
return ' N/A%' if percent is None else f'{percent:>5.1f}%'
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2023-05-24 18:00:43 +00:00
|
|
|
@classmethod
|
|
|
|
def calc_eta(cls, start_or_rate, now_or_remaining, total=NO_DEFAULT, current=NO_DEFAULT):
|
|
|
|
if total is NO_DEFAULT:
|
|
|
|
rate, remaining = start_or_rate, now_or_remaining
|
|
|
|
if None in (rate, remaining):
|
|
|
|
return None
|
|
|
|
return int(float(remaining) / rate)
|
|
|
|
|
|
|
|
start, now = start_or_rate, now_or_remaining
|
2013-09-23 15:59:27 +00:00
|
|
|
if total is None:
|
|
|
|
return None
|
2014-07-31 01:08:24 +00:00
|
|
|
if now is None:
|
|
|
|
now = time.time()
|
2023-05-24 18:00:43 +00:00
|
|
|
rate = cls.calc_speed(start, now, current)
|
|
|
|
return rate and int((float(total) - float(current)) / rate)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def calc_speed(start, now, bytes):
|
|
|
|
dif = now - start
|
2014-11-23 19:41:03 +00:00
|
|
|
if bytes == 0 or dif < 0.001: # One millisecond
|
2013-09-23 15:59:27 +00:00
|
|
|
return None
|
|
|
|
return float(bytes) / dif
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def format_speed(speed):
|
2022-05-22 16:22:26 +00:00
|
|
|
return ' Unknown B/s' if speed is None else f'{format_bytes(speed):>10s}/s'
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2016-03-19 14:51:30 +00:00
|
|
|
@staticmethod
|
|
|
|
def format_retries(retries):
|
2022-05-22 16:22:26 +00:00
|
|
|
return 'inf' if retries == float('inf') else int(retries)
|
2016-03-19 14:51:30 +00:00
|
|
|
|
2023-05-24 18:00:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def filesize_or_none(unencoded_filename):
|
|
|
|
if os.path.isfile(unencoded_filename):
|
|
|
|
return os.path.getsize(unencoded_filename)
|
|
|
|
return 0
|
|
|
|
|
2013-09-23 15:59:27 +00:00
|
|
|
@staticmethod
|
|
|
|
def best_block_size(elapsed_time, bytes):
|
|
|
|
new_min = max(bytes / 2.0, 1.0)
|
2014-11-23 19:41:03 +00:00
|
|
|
new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
|
2013-09-23 15:59:27 +00:00
|
|
|
if elapsed_time < 0.001:
|
|
|
|
return int(new_max)
|
|
|
|
rate = bytes / elapsed_time
|
|
|
|
if rate > new_max:
|
|
|
|
return int(new_max)
|
|
|
|
if rate < new_min:
|
|
|
|
return int(new_min)
|
|
|
|
return int(rate)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def parse_bytes(bytestr):
|
|
|
|
"""Parse a string indicating a byte quantity into an integer."""
|
2022-11-30 06:04:51 +00:00
|
|
|
deprecation_warning('yt_dlp.FileDownloader.parse_bytes is deprecated and '
|
|
|
|
'may be removed in the future. Use yt_dlp.utils.parse_bytes instead')
|
|
|
|
return parse_bytes(bytestr)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2014-07-31 01:08:24 +00:00
|
|
|
def slow_down(self, start_time, now, byte_counter):
|
2013-09-23 15:59:27 +00:00
|
|
|
"""Sleep if the download speed is over the rate limit."""
|
2016-02-14 08:25:04 +00:00
|
|
|
rate_limit = self.params.get('ratelimit')
|
2021-06-23 00:03:52 +00:00
|
|
|
if rate_limit is None or byte_counter == 0:
|
2013-09-23 15:59:27 +00:00
|
|
|
return
|
2014-07-31 01:08:24 +00:00
|
|
|
if now is None:
|
|
|
|
now = time.time()
|
2013-09-23 15:59:27 +00:00
|
|
|
elapsed = now - start_time
|
|
|
|
if elapsed <= 0.0:
|
|
|
|
return
|
|
|
|
speed = float(byte_counter) / elapsed
|
2021-06-23 00:03:52 +00:00
|
|
|
if speed > rate_limit:
|
2019-06-04 20:06:35 +00:00
|
|
|
sleep_time = float(byte_counter) / rate_limit - elapsed
|
|
|
|
if sleep_time > 0:
|
|
|
|
time.sleep(sleep_time)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def temp_name(self, filename):
|
|
|
|
"""Returns a temporary filename for the given filename."""
|
2014-11-16 14:06:59 +00:00
|
|
|
if self.params.get('nopart', False) or filename == '-' or \
|
2024-11-16 23:24:11 +00:00
|
|
|
(os.path.exists(filename) and not os.path.isfile(filename)):
|
2013-09-23 15:59:27 +00:00
|
|
|
return filename
|
2014-11-16 14:06:59 +00:00
|
|
|
return filename + '.part'
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def undo_temp_name(self, filename):
|
2014-11-16 14:06:59 +00:00
|
|
|
if filename.endswith('.part'):
|
|
|
|
return filename[:-len('.part')]
|
2013-09-23 15:59:27 +00:00
|
|
|
return filename
|
|
|
|
|
2017-04-19 17:34:25 +00:00
|
|
|
def ytdl_filename(self, filename):
|
|
|
|
return filename + '.ytdl'
|
|
|
|
|
2022-03-03 14:33:32 +00:00
|
|
|
def wrap_file_access(action, *, fatal=False):
|
2022-08-01 20:13:18 +00:00
|
|
|
def error_callback(err, count, retries, *, fd):
|
|
|
|
return RetryManager.report_retry(
|
|
|
|
err, count, retries, info=fd.__to_screen,
|
|
|
|
warn=lambda e: (time.sleep(0.01), fd.to_screen(f'[download] Unable to {action} file: {e}')),
|
|
|
|
error=None if fatal else lambda e: fd.report_error(f'Unable to {action} file: {e}'),
|
|
|
|
sleep_func=fd.params.get('retry_sleep_functions', {}).get('file_access'))
|
|
|
|
|
|
|
|
def wrapper(self, func, *args, **kwargs):
|
2023-05-24 17:59:30 +00:00
|
|
|
for retry in RetryManager(self.params.get('file_access_retries', 3), error_callback, fd=self):
|
2022-08-01 20:13:18 +00:00
|
|
|
try:
|
|
|
|
return func(self, *args, **kwargs)
|
|
|
|
except OSError as err:
|
|
|
|
if err.errno in (errno.EACCES, errno.EINVAL):
|
|
|
|
retry.error = err
|
|
|
|
continue
|
|
|
|
retry.error_callback(err, 1, 0)
|
|
|
|
|
|
|
|
return functools.partial(functools.partialmethod, wrapper)
|
2022-03-03 14:33:32 +00:00
|
|
|
|
|
|
|
@wrap_file_access('open', fatal=True)
|
2021-12-23 02:29:03 +00:00
|
|
|
def sanitize_open(self, filename, open_mode):
|
2022-04-05 17:38:18 +00:00
|
|
|
f, filename = sanitize_open(filename, open_mode)
|
|
|
|
if not getattr(f, 'locked', None):
|
|
|
|
self.write_debug(f'{LockingUnsupportedError.msg}. Proceeding without locking', only_once=True)
|
|
|
|
return f, filename
|
2021-12-23 02:29:03 +00:00
|
|
|
|
2022-03-03 14:33:32 +00:00
|
|
|
@wrap_file_access('remove')
|
|
|
|
def try_remove(self, filename):
|
2023-07-06 14:39:42 +00:00
|
|
|
if os.path.isfile(filename):
|
|
|
|
os.remove(filename)
|
2022-03-03 14:33:32 +00:00
|
|
|
|
|
|
|
@wrap_file_access('rename')
|
2013-09-23 15:59:27 +00:00
|
|
|
def try_rename(self, old_filename, new_filename):
|
2021-08-14 15:43:02 +00:00
|
|
|
if old_filename == new_filename:
|
|
|
|
return
|
2022-03-03 14:33:32 +00:00
|
|
|
os.replace(old_filename, new_filename)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def try_utime(self, filename, last_modified_hdr):
|
|
|
|
"""Try to set the last-modified time of the given file."""
|
|
|
|
if last_modified_hdr is None:
|
|
|
|
return
|
2024-11-16 23:24:11 +00:00
|
|
|
if not os.path.isfile(filename):
|
2013-09-23 15:59:27 +00:00
|
|
|
return
|
|
|
|
timestr = last_modified_hdr
|
|
|
|
if timestr is None:
|
|
|
|
return
|
|
|
|
filetime = timeconvert(timestr)
|
|
|
|
if filetime is None:
|
|
|
|
return filetime
|
|
|
|
# Ignore obviously invalid dates
|
|
|
|
if filetime == 0:
|
|
|
|
return
|
2022-04-17 20:58:28 +00:00
|
|
|
with contextlib.suppress(Exception):
|
2013-09-23 15:59:27 +00:00
|
|
|
os.utime(filename, (time.time(), filetime))
|
|
|
|
return filetime
|
|
|
|
|
|
|
|
def report_destination(self, filename):
|
|
|
|
"""Report destination filename."""
|
2014-11-16 14:06:59 +00:00
|
|
|
self.to_screen('[download] Destination: ' + filename)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2021-10-08 19:11:59 +00:00
|
|
|
def _prepare_multiline_status(self, lines=1):
|
|
|
|
if self.params.get('noprogress'):
|
2021-09-22 14:12:04 +00:00
|
|
|
self._multiline = QuietMultilinePrinter()
|
2021-10-08 19:11:59 +00:00
|
|
|
elif self.ydl.params.get('logger'):
|
|
|
|
self._multiline = MultilineLogger(self.ydl.params['logger'], lines)
|
|
|
|
elif self.params.get('progress_with_newline'):
|
2022-05-30 20:53:54 +00:00
|
|
|
self._multiline = BreaklineStatusPrinter(self.ydl._out_files.out, lines)
|
2021-09-22 14:12:04 +00:00
|
|
|
else:
|
2022-05-30 20:53:54 +00:00
|
|
|
self._multiline = MultilinePrinter(self.ydl._out_files.out, lines, not self.params.get('quiet'))
|
2023-05-24 18:35:07 +00:00
|
|
|
self._multiline.allow_colors = self.ydl._allow_colors.out and self.ydl._allow_colors.out != 'no_color'
|
|
|
|
self._multiline._HAVE_FULLCAP = self.ydl._allow_colors.out
|
2021-09-22 14:12:04 +00:00
|
|
|
|
|
|
|
def _finish_multiline_status(self):
|
2021-10-08 19:11:59 +00:00
|
|
|
self._multiline.end()
|
|
|
|
|
2022-04-17 20:58:28 +00:00
|
|
|
ProgressStyles = Namespace(
|
|
|
|
downloaded_bytes='light blue',
|
|
|
|
percent='light blue',
|
|
|
|
eta='yellow',
|
|
|
|
speed='green',
|
|
|
|
elapsed='bold white',
|
|
|
|
total_bytes='',
|
|
|
|
total_bytes_estimate='',
|
|
|
|
)
|
2021-11-28 21:25:37 +00:00
|
|
|
|
|
|
|
def _report_progress_status(self, s, default_template):
|
2022-05-25 12:23:46 +00:00
|
|
|
for name, style in self.ProgressStyles.items_:
|
2021-11-28 21:25:37 +00:00
|
|
|
name = f'_{name}_str'
|
|
|
|
if name not in s:
|
|
|
|
continue
|
|
|
|
s[name] = self._format_progress(s[name], style)
|
|
|
|
s['_default_template'] = default_template % s
|
|
|
|
|
2021-10-08 19:11:59 +00:00
|
|
|
progress_dict = s.copy()
|
|
|
|
progress_dict.pop('info_dict')
|
|
|
|
progress_dict = {'info': s['info_dict'], 'progress': progress_dict}
|
|
|
|
|
|
|
|
progress_template = self.params.get('progress_template', {})
|
|
|
|
self._multiline.print_at_line(self.ydl.evaluate_outtmpl(
|
|
|
|
progress_template.get('download') or '[download] %(progress._default_template)s',
|
|
|
|
progress_dict), s.get('progress_idx') or 0)
|
|
|
|
self.to_console_title(self.ydl.evaluate_outtmpl(
|
|
|
|
progress_template.get('download-title') or 'yt-dlp %(progress._default_template)s',
|
|
|
|
progress_dict))
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2021-11-28 21:25:37 +00:00
|
|
|
def _format_progress(self, *args, **kwargs):
|
|
|
|
return self.ydl._format_text(
|
|
|
|
self._multiline.stream, self._multiline.allow_colors, *args, **kwargs)
|
|
|
|
|
2015-02-17 20:37:48 +00:00
|
|
|
def report_progress(self, s):
|
2022-05-22 16:22:26 +00:00
|
|
|
def with_fields(*tups, default=''):
|
|
|
|
for *fields, tmpl in tups:
|
|
|
|
if all(s.get(f) is not None for f in fields):
|
|
|
|
return tmpl
|
|
|
|
return default
|
|
|
|
|
2022-10-18 17:58:57 +00:00
|
|
|
_format_bytes = lambda k: f'{format_bytes(s.get(k)):>10s}'
|
2022-10-03 20:04:04 +00:00
|
|
|
|
2015-02-17 20:37:48 +00:00
|
|
|
if s['status'] == 'finished':
|
2021-10-08 19:11:59 +00:00
|
|
|
if self.params.get('noprogress'):
|
2015-02-17 20:37:48 +00:00
|
|
|
self.to_screen('[download] Download completed')
|
2022-07-30 22:50:02 +00:00
|
|
|
speed = try_call(lambda: s['total_bytes'] / s['elapsed'])
|
2022-05-22 16:22:26 +00:00
|
|
|
s.update({
|
2022-07-30 22:50:02 +00:00
|
|
|
'speed': speed,
|
|
|
|
'_speed_str': self.format_speed(speed).strip(),
|
2022-10-18 17:58:57 +00:00
|
|
|
'_total_bytes_str': _format_bytes('total_bytes'),
|
2022-05-22 16:22:26 +00:00
|
|
|
'_elapsed_str': self.format_seconds(s.get('elapsed')),
|
|
|
|
'_percent_str': self.format_percent(100),
|
|
|
|
})
|
|
|
|
self._report_progress_status(s, join_nonempty(
|
|
|
|
'100%%',
|
|
|
|
with_fields(('total_bytes', 'of %(_total_bytes_str)s')),
|
|
|
|
with_fields(('elapsed', 'in %(_elapsed_str)s')),
|
2022-07-30 22:50:02 +00:00
|
|
|
with_fields(('speed', 'at %(_speed_str)s')),
|
2022-05-22 16:22:26 +00:00
|
|
|
delim=' '))
|
2015-02-17 20:37:48 +00:00
|
|
|
|
|
|
|
if s['status'] != 'downloading':
|
|
|
|
return
|
|
|
|
|
2024-04-08 20:47:38 +00:00
|
|
|
if update_delta := self.params.get('progress_delta'):
|
|
|
|
with self._progress_delta_lock:
|
|
|
|
if time.monotonic() < self._progress_delta_time:
|
|
|
|
return
|
|
|
|
self._progress_delta_time += update_delta
|
|
|
|
|
2022-05-22 16:22:26 +00:00
|
|
|
s.update({
|
2022-10-03 20:04:04 +00:00
|
|
|
'_eta_str': self.format_eta(s.get('eta')).strip(),
|
2022-05-22 16:22:26 +00:00
|
|
|
'_speed_str': self.format_speed(s.get('speed')),
|
|
|
|
'_percent_str': self.format_percent(try_call(
|
|
|
|
lambda: 100 * s['downloaded_bytes'] / s['total_bytes'],
|
|
|
|
lambda: 100 * s['downloaded_bytes'] / s['total_bytes_estimate'],
|
|
|
|
lambda: s['downloaded_bytes'] == 0 and 0)),
|
2022-10-18 17:58:57 +00:00
|
|
|
'_total_bytes_str': _format_bytes('total_bytes'),
|
|
|
|
'_total_bytes_estimate_str': _format_bytes('total_bytes_estimate'),
|
|
|
|
'_downloaded_bytes_str': _format_bytes('downloaded_bytes'),
|
2022-05-22 16:22:26 +00:00
|
|
|
'_elapsed_str': self.format_seconds(s.get('elapsed')),
|
|
|
|
})
|
|
|
|
|
|
|
|
msg_template = with_fields(
|
|
|
|
('total_bytes', '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'),
|
|
|
|
('total_bytes_estimate', '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'),
|
|
|
|
('downloaded_bytes', 'elapsed', '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'),
|
|
|
|
('downloaded_bytes', '%(_downloaded_bytes_str)s at %(_speed_str)s'),
|
|
|
|
default='%(_percent_str)s at %(_speed_str)s ETA %(_eta_str)s')
|
|
|
|
|
|
|
|
msg_template += with_fields(
|
|
|
|
('fragment_index', 'fragment_count', ' (frag %(fragment_index)s/%(fragment_count)s)'),
|
|
|
|
('fragment_index', ' (frag %(fragment_index)s)'))
|
2021-11-28 21:25:37 +00:00
|
|
|
self._report_progress_status(s, msg_template)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def report_resuming_byte(self, resume_len):
|
|
|
|
"""Report attempt to resume at given byte."""
|
2024-06-11 23:09:58 +00:00
|
|
|
self.to_screen(f'[download] Resuming download at byte {resume_len}')
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2022-08-01 20:13:18 +00:00
|
|
|
def report_retry(self, err, count, retries, frag_index=NO_DEFAULT, fatal=True):
|
|
|
|
"""Report retry"""
|
|
|
|
is_frag = False if frag_index is NO_DEFAULT else 'fragment'
|
|
|
|
RetryManager.report_retry(
|
|
|
|
err, count, retries, info=self.__to_screen,
|
|
|
|
warn=lambda msg: self.__to_screen(f'[download] Got error: {msg}'),
|
|
|
|
error=IDENTITY if not fatal else lambda e: self.report_error(f'\r[download] Got error: {e}'),
|
|
|
|
sleep_func=self.params.get('retry_sleep_functions', {}).get(is_frag or 'http'),
|
|
|
|
suffix=f'fragment{"s" if frag_index is None else f" {frag_index}"}' if is_frag else None)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def report_unable_to_resume(self):
|
|
|
|
"""Report it was impossible to resume download."""
|
2014-11-16 14:06:59 +00:00
|
|
|
self.to_screen('[download] Unable to resume')
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2021-03-10 15:26:24 +00:00
|
|
|
@staticmethod
|
|
|
|
def supports_manifest(manifest):
|
|
|
|
""" Whether the downloader can download the fragments from the manifest.
|
|
|
|
Redefine in subclasses if needed. """
|
|
|
|
pass
|
|
|
|
|
2020-10-31 04:46:51 +00:00
|
|
|
def download(self, filename, info_dict, subtitle=False):
|
2013-09-23 15:59:27 +00:00
|
|
|
"""Download to a filename using the info from info_dict
|
|
|
|
Return True on success and False otherwise
|
|
|
|
"""
|
2014-09-25 16:37:20 +00:00
|
|
|
nooverwrites_and_exists = (
|
2021-08-05 19:24:49 +00:00
|
|
|
not self.params.get('overwrites', True)
|
2024-11-16 23:24:11 +00:00
|
|
|
and os.path.exists(filename)
|
2014-09-25 16:37:20 +00:00
|
|
|
)
|
|
|
|
|
2016-06-28 17:07:50 +00:00
|
|
|
if not hasattr(filename, 'write'):
|
|
|
|
continuedl_and_exists = (
|
2019-05-10 20:56:22 +00:00
|
|
|
self.params.get('continuedl', True)
|
2024-11-16 23:24:11 +00:00
|
|
|
and os.path.isfile(filename)
|
2019-05-10 20:56:22 +00:00
|
|
|
and not self.params.get('nopart', False)
|
2016-06-28 17:07:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# Check file already present
|
|
|
|
if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
|
|
|
|
self.report_file_already_downloaded(filename)
|
|
|
|
self._hook_progress({
|
|
|
|
'filename': filename,
|
|
|
|
'status': 'finished',
|
2024-11-16 23:24:11 +00:00
|
|
|
'total_bytes': os.path.getsize(filename),
|
2021-07-21 17:28:43 +00:00
|
|
|
}, info_dict)
|
2021-12-23 01:42:26 +00:00
|
|
|
self._finish_multiline_status()
|
2020-11-15 00:28:41 +00:00
|
|
|
return True, False
|
2013-12-23 15:03:06 +00:00
|
|
|
|
2022-04-17 20:58:28 +00:00
|
|
|
if subtitle:
|
|
|
|
sleep_interval = self.params.get('sleep_interval_subtitles') or 0
|
2020-10-31 04:46:51 +00:00
|
|
|
else:
|
2022-04-17 20:58:28 +00:00
|
|
|
min_sleep_interval = self.params.get('sleep_interval') or 0
|
|
|
|
sleep_interval = random.uniform(
|
2022-04-17 23:09:25 +00:00
|
|
|
min_sleep_interval, self.params.get('max_sleep_interval') or min_sleep_interval)
|
2022-04-17 20:58:28 +00:00
|
|
|
if sleep_interval > 0:
|
|
|
|
self.to_screen(f'[download] Sleeping {sleep_interval:.2f} seconds ...')
|
|
|
|
time.sleep(sleep_interval)
|
|
|
|
|
2021-10-08 19:11:59 +00:00
|
|
|
ret = self.real_download(filename, info_dict)
|
|
|
|
self._finish_multiline_status()
|
|
|
|
return ret, True
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def real_download(self, filename, info_dict):
|
|
|
|
"""Real download process. Redefine in subclasses."""
|
2014-11-16 14:06:59 +00:00
|
|
|
raise NotImplementedError('This method must be implemented by subclasses')
|
2013-09-23 15:59:27 +00:00
|
|
|
|
2021-07-21 17:28:43 +00:00
|
|
|
def _hook_progress(self, status, info_dict):
|
2022-07-10 19:47:48 +00:00
|
|
|
# Ideally we want to make a copy of the dict, but that is too slow
|
2021-10-16 13:01:00 +00:00
|
|
|
status['info_dict'] = info_dict
|
2021-07-23 04:14:28 +00:00
|
|
|
# youtube-dl passes the same status object to all the hooks.
|
|
|
|
# Some third party scripts seems to be relying on this.
|
|
|
|
# So keep this behavior if possible
|
2013-09-23 15:59:27 +00:00
|
|
|
for ph in self._progress_hooks:
|
2021-07-23 04:14:28 +00:00
|
|
|
ph(status)
|
2013-09-23 15:59:27 +00:00
|
|
|
|
|
|
|
def add_progress_hook(self, ph):
|
2014-12-15 00:26:18 +00:00
|
|
|
# See YoutubeDl.py (search for progress_hooks) for a description of
|
|
|
|
# this interface
|
2013-09-23 15:59:27 +00:00
|
|
|
self._progress_hooks.append(ph)
|
2015-01-24 00:38:48 +00:00
|
|
|
|
2015-04-25 22:30:45 +00:00
|
|
|
def _debug_cmd(self, args, exe=None):
|
2015-01-24 00:38:48 +00:00
|
|
|
if not self.params.get('verbose', False):
|
|
|
|
return
|
|
|
|
|
|
|
|
if exe is None:
|
2024-11-16 23:24:11 +00:00
|
|
|
exe = os.path.basename(args[0])
|
2015-01-24 00:38:48 +00:00
|
|
|
|
2024-11-16 23:24:11 +00:00
|
|
|
self.write_debug(f'{exe} command line: {shell_quote(args)}')
|