common.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. from __future__ import division, unicode_literals
  2. import os
  3. import re
  4. import sys
  5. import time
  6. import random
  7. from ..compat import compat_os_name
  8. from ..utils import (
  9. decodeArgument,
  10. encodeFilename,
  11. error_to_compat_str,
  12. float_or_none,
  13. format_bytes,
  14. shell_quote,
  15. timeconvert,
  16. )
  17. class FileDownloader(object):
  18. """File Downloader class.
  19. File downloader objects are the ones responsible of downloading the
  20. actual video file and writing it to disk.
  21. File downloaders accept a lot of parameters. In order not to saturate
  22. the object constructor with arguments, it receives a dictionary of
  23. options instead.
  24. Available options:
  25. verbose: Print additional info to stdout.
  26. quiet: Do not print messages to stdout.
  27. ratelimit: Download speed limit, in bytes/sec.
  28. retries: Number of times to retry for HTTP error 5xx
  29. buffersize: Size of download buffer in bytes.
  30. noresizebuffer: Do not automatically resize the download buffer.
  31. continuedl: Try to continue downloads if possible.
  32. noprogress: Do not print the progress bar.
  33. logtostderr: Log messages to stderr instead of stdout.
  34. consoletitle: Display progress in console window's titlebar.
  35. nopart: Do not use temporary .part files.
  36. updatetime: Use the Last-modified header to set output file timestamps.
  37. test: Download only first bytes to test the downloader.
  38. min_filesize: Skip files smaller than this size
  39. max_filesize: Skip files larger than this size
  40. xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
  41. external_downloader_args: A list of additional command-line arguments for the
  42. external downloader.
  43. hls_use_mpegts: Use the mpegts container for HLS videos.
  44. http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be
  45. useful for bypassing bandwidth throttling imposed by
  46. a webserver (experimental)
  47. Subclasses of this one must re-define the real_download method.
  48. """
  49. _TEST_FILE_SIZE = 10241
  50. params = None
  51. def __init__(self, ydl, params):
  52. """Create a FileDownloader object with the given options."""
  53. self.ydl = ydl
  54. self._progress_hooks = []
  55. self.params = params
  56. self.add_progress_hook(self.report_progress)
  57. @staticmethod
  58. def format_seconds(seconds):
  59. (mins, secs) = divmod(seconds, 60)
  60. (hours, mins) = divmod(mins, 60)
  61. if hours > 99:
  62. return '--:--:--'
  63. if hours == 0:
  64. return '%02d:%02d' % (mins, secs)
  65. else:
  66. return '%02d:%02d:%02d' % (hours, mins, secs)
  67. @staticmethod
  68. def calc_percent(byte_counter, data_len):
  69. if data_len is None:
  70. return None
  71. return float(byte_counter) / float(data_len) * 100.0
  72. @staticmethod
  73. def format_percent(percent):
  74. if percent is None:
  75. return '---.-%'
  76. return '%6s' % ('%3.1f%%' % percent)
  77. @classmethod
  78. def calc_eta(cls, start_or_rate, now_or_remaining, *args):
  79. if len(args) < 2:
  80. rate, remaining = (start_or_rate, now_or_remaining)
  81. if None in (rate, remaining):
  82. return None
  83. return int(float(remaining) / rate)
  84. start, now = (start_or_rate, now_or_remaining)
  85. total, current = args[:2]
  86. if total is None:
  87. return None
  88. if now is None:
  89. now = time.time()
  90. rate = cls.calc_speed(start, now, current)
  91. return rate and int((float(total) - float(current)) / rate)
  92. @staticmethod
  93. def format_eta(eta):
  94. if eta is None:
  95. return '--:--'
  96. return FileDownloader.format_seconds(eta)
  97. @staticmethod
  98. def calc_speed(start, now, bytes):
  99. dif = now - start
  100. if bytes == 0 or dif < 0.001: # One millisecond
  101. return None
  102. return float(bytes) / dif
  103. @staticmethod
  104. def format_speed(speed):
  105. if speed is None:
  106. return '%10s' % '---b/s'
  107. return '%10s' % ('%s/s' % format_bytes(speed))
  108. @staticmethod
  109. def format_retries(retries):
  110. return 'inf' if retries == float('inf') else '%.0f' % retries
  111. @staticmethod
  112. def filesize_or_none(unencoded_filename):
  113. fn = encodeFilename(unencoded_filename)
  114. if os.path.isfile(fn):
  115. return os.path.getsize(fn)
  116. @staticmethod
  117. def best_block_size(elapsed_time, bytes):
  118. new_min = max(bytes / 2.0, 1.0)
  119. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  120. if elapsed_time < 0.001:
  121. return int(new_max)
  122. rate = bytes / elapsed_time
  123. if rate > new_max:
  124. return int(new_max)
  125. if rate < new_min:
  126. return int(new_min)
  127. return int(rate)
  128. @staticmethod
  129. def parse_bytes(bytestr):
  130. """Parse a string indicating a byte quantity into an integer."""
  131. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  132. if matchobj is None:
  133. return None
  134. number = float(matchobj.group(1))
  135. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  136. return int(round(number * multiplier))
  137. def to_screen(self, *args, **kargs):
  138. self.ydl.to_screen(*args, **kargs)
  139. def to_stderr(self, message):
  140. self.ydl.to_screen(message)
  141. def to_console_title(self, message):
  142. self.ydl.to_console_title(message)
  143. def trouble(self, *args, **kargs):
  144. self.ydl.trouble(*args, **kargs)
  145. def report_warning(self, *args, **kargs):
  146. self.ydl.report_warning(*args, **kargs)
  147. def report_error(self, *args, **kargs):
  148. self.ydl.report_error(*args, **kargs)
  149. def slow_down(self, start_time, now, byte_counter):
  150. """Sleep if the download speed is over the rate limit."""
  151. rate_limit = self.params.get('ratelimit')
  152. if rate_limit is None or byte_counter == 0:
  153. return
  154. if now is None:
  155. now = time.time()
  156. elapsed = now - start_time
  157. if elapsed <= 0.0:
  158. return
  159. speed = float(byte_counter) / elapsed
  160. if speed > rate_limit:
  161. sleep_time = float(byte_counter) / rate_limit - elapsed
  162. if sleep_time > 0:
  163. time.sleep(sleep_time)
  164. def temp_name(self, filename):
  165. """Returns a temporary filename for the given filename."""
  166. if self.params.get('nopart', False) or filename == '-' or \
  167. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  168. return filename
  169. return filename + '.part'
  170. def undo_temp_name(self, filename):
  171. if filename.endswith('.part'):
  172. return filename[:-len('.part')]
  173. return filename
  174. def ytdl_filename(self, filename):
  175. return filename + '.ytdl'
  176. def try_rename(self, old_filename, new_filename):
  177. try:
  178. if old_filename == new_filename:
  179. return
  180. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  181. except (IOError, OSError) as err:
  182. self.report_error('unable to rename file: %s' % error_to_compat_str(err))
  183. def try_utime(self, filename, last_modified_hdr):
  184. """Try to set the last-modified time of the given file."""
  185. if last_modified_hdr is None:
  186. return
  187. if not os.path.isfile(encodeFilename(filename)):
  188. return
  189. timestr = last_modified_hdr
  190. if timestr is None:
  191. return
  192. filetime = timeconvert(timestr)
  193. if filetime is None:
  194. return filetime
  195. # Ignore obviously invalid dates
  196. if filetime == 0:
  197. return
  198. try:
  199. os.utime(filename, (time.time(), filetime))
  200. except Exception:
  201. pass
  202. return filetime
  203. def report_destination(self, filename):
  204. """Report destination filename."""
  205. self.to_screen('[download] Destination: ' + filename)
  206. def _report_progress_status(self, msg, is_last_line=False):
  207. fullmsg = '[download] ' + msg
  208. if self.params.get('progress_with_newline', False):
  209. self.to_screen(fullmsg)
  210. else:
  211. if compat_os_name == 'nt':
  212. prev_len = getattr(self, '_report_progress_prev_line_length',
  213. 0)
  214. if prev_len > len(fullmsg):
  215. fullmsg += ' ' * (prev_len - len(fullmsg))
  216. self._report_progress_prev_line_length = len(fullmsg)
  217. clear_line = '\r'
  218. else:
  219. clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
  220. self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
  221. self.to_console_title('youtube-dl ' + msg)
  222. def report_progress(self, s):
  223. if s['status'] == 'finished':
  224. if self.params.get('noprogress', False):
  225. self.to_screen('[download] Download completed')
  226. else:
  227. msg_template = '100%%'
  228. if s.get('total_bytes') is not None:
  229. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  230. msg_template += ' of %(_total_bytes_str)s'
  231. if s.get('elapsed') is not None:
  232. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  233. msg_template += ' in %(_elapsed_str)s'
  234. self._report_progress_status(
  235. msg_template % s, is_last_line=True)
  236. if self.params.get('noprogress'):
  237. return
  238. if s['status'] != 'downloading':
  239. return
  240. if s.get('eta') is not None:
  241. s['_eta_str'] = self.format_eta(s['eta'])
  242. else:
  243. s['_eta_str'] = 'Unknown ETA'
  244. if s.get('total_bytes') and s.get('downloaded_bytes') is not None:
  245. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])
  246. elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:
  247. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])
  248. else:
  249. if s.get('downloaded_bytes') == 0:
  250. s['_percent_str'] = self.format_percent(0)
  251. else:
  252. s['_percent_str'] = 'Unknown %'
  253. if s.get('speed') is not None:
  254. s['_speed_str'] = self.format_speed(s['speed'])
  255. else:
  256. s['_speed_str'] = 'Unknown speed'
  257. if s.get('total_bytes') is not None:
  258. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  259. msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
  260. elif s.get('total_bytes_estimate') is not None:
  261. s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])
  262. msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
  263. else:
  264. if s.get('downloaded_bytes') is not None:
  265. s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])
  266. if s.get('elapsed'):
  267. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  268. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
  269. else:
  270. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'
  271. else:
  272. msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
  273. self._report_progress_status(msg_template % s)
  274. def report_resuming_byte(self, resume_len):
  275. """Report attempt to resume at given byte."""
  276. self.to_screen('[download] Resuming download at byte %s' % resume_len)
  277. def report_retry(self, err, count, retries):
  278. """Report retry in case of HTTP error 5xx"""
  279. self.to_screen(
  280. '[download] Got server HTTP error: %s. Retrying (attempt %d of %s)...'
  281. % (error_to_compat_str(err), count, self.format_retries(retries)))
  282. def report_file_already_downloaded(self, file_name):
  283. """Report file has already been fully downloaded."""
  284. try:
  285. self.to_screen('[download] %s has already been downloaded' % file_name)
  286. except UnicodeEncodeError:
  287. self.to_screen('[download] The file has already been downloaded')
  288. def report_unable_to_resume(self):
  289. """Report it was impossible to resume download."""
  290. self.to_screen('[download] Unable to resume')
  291. def download(self, filename, info_dict):
  292. """Download to a filename using the info from info_dict
  293. Return True on success and False otherwise
  294. This method filters the `Cookie` header from the info_dict to prevent leaks.
  295. Downloaders have their own way of handling cookies.
  296. See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  297. """
  298. nooverwrites_and_exists = (
  299. self.params.get('nooverwrites', False)
  300. and os.path.exists(encodeFilename(filename))
  301. )
  302. if not hasattr(filename, 'write'):
  303. continuedl_and_exists = (
  304. self.params.get('continuedl', True)
  305. and os.path.isfile(encodeFilename(filename))
  306. and not self.params.get('nopart', False)
  307. )
  308. # Check file already present
  309. if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
  310. self.report_file_already_downloaded(filename)
  311. self._hook_progress({
  312. 'filename': filename,
  313. 'status': 'finished',
  314. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  315. })
  316. return True
  317. min_sleep_interval, max_sleep_interval = (
  318. float_or_none(self.params.get(interval), default=0)
  319. for interval in ('sleep_interval', 'max_sleep_interval'))
  320. sleep_note = ''
  321. available_at = info_dict.get('available_at')
  322. if available_at:
  323. forced_sleep_interval = available_at - int(time.time())
  324. if forced_sleep_interval > min_sleep_interval:
  325. sleep_note = 'as required by the site'
  326. min_sleep_interval = forced_sleep_interval
  327. if forced_sleep_interval > max_sleep_interval:
  328. max_sleep_interval = forced_sleep_interval
  329. sleep_interval = random.uniform(
  330. min_sleep_interval, max_sleep_interval or min_sleep_interval)
  331. if sleep_interval > 0:
  332. self.to_screen(
  333. '[download] Sleeping %.2f seconds %s...' % (
  334. sleep_interval, sleep_note))
  335. time.sleep(sleep_interval)
  336. return self.real_download(filename, info_dict)
  337. def real_download(self, filename, info_dict):
  338. """Real download process. Redefine in subclasses."""
  339. raise NotImplementedError('This method must be implemented by subclasses')
  340. def _hook_progress(self, status):
  341. for ph in self._progress_hooks:
  342. ph(status)
  343. def add_progress_hook(self, ph):
  344. # See YoutubeDl.py (search for progress_hooks) for a description of
  345. # this interface
  346. self._progress_hooks.append(ph)
  347. def _debug_cmd(self, args, exe=None):
  348. if not self.params.get('verbose', False):
  349. return
  350. str_args = [decodeArgument(a) for a in args]
  351. if exe is None:
  352. exe = os.path.basename(str_args[0])
  353. self.to_screen('[debug] %s command line: %s' % (
  354. exe, shell_quote(str_args)))