common.py 19 KB

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