logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

common.py (15417B)


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