common.py 19 KB

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