common.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. (experimental)
  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. @staticmethod
  78. def calc_eta(start, now, total, current):
  79. if total is None:
  80. return None
  81. if now is None:
  82. now = time.time()
  83. dif = now - start
  84. if current == 0 or dif < 0.001: # One millisecond
  85. return None
  86. rate = float(current) / dif
  87. return int((float(total) - float(current)) / rate)
  88. @staticmethod
  89. def format_eta(eta):
  90. if eta is None:
  91. return '--:--'
  92. return FileDownloader.format_seconds(eta)
  93. @staticmethod
  94. def calc_speed(start, now, bytes):
  95. dif = now - start
  96. if bytes == 0 or dif < 0.001: # One millisecond
  97. return None
  98. return float(bytes) / dif
  99. @staticmethod
  100. def format_speed(speed):
  101. if speed is None:
  102. return '%10s' % '---b/s'
  103. return '%10s' % ('%s/s' % format_bytes(speed))
  104. @staticmethod
  105. def format_retries(retries):
  106. return 'inf' if retries == float('inf') else '%.0f' % retries
  107. @staticmethod
  108. def best_block_size(elapsed_time, bytes):
  109. new_min = max(bytes / 2.0, 1.0)
  110. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  111. if elapsed_time < 0.001:
  112. return int(new_max)
  113. rate = bytes / elapsed_time
  114. if rate > new_max:
  115. return int(new_max)
  116. if rate < new_min:
  117. return int(new_min)
  118. return int(rate)
  119. @staticmethod
  120. def parse_bytes(bytestr):
  121. """Parse a string indicating a byte quantity into an integer."""
  122. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  123. if matchobj is None:
  124. return None
  125. number = float(matchobj.group(1))
  126. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  127. return int(round(number * multiplier))
  128. def to_screen(self, *args, **kargs):
  129. self.ydl.to_screen(*args, **kargs)
  130. def to_stderr(self, message):
  131. self.ydl.to_screen(message)
  132. def to_console_title(self, message):
  133. self.ydl.to_console_title(message)
  134. def trouble(self, *args, **kargs):
  135. self.ydl.trouble(*args, **kargs)
  136. def report_warning(self, *args, **kargs):
  137. self.ydl.report_warning(*args, **kargs)
  138. def report_error(self, *args, **kargs):
  139. self.ydl.report_error(*args, **kargs)
  140. def slow_down(self, start_time, now, byte_counter):
  141. """Sleep if the download speed is over the rate limit."""
  142. rate_limit = self.params.get('ratelimit')
  143. if rate_limit is None or byte_counter == 0:
  144. return
  145. if now is None:
  146. now = time.time()
  147. elapsed = now - start_time
  148. if elapsed <= 0.0:
  149. return
  150. speed = float(byte_counter) / elapsed
  151. if speed > rate_limit:
  152. time.sleep(max((byte_counter // rate_limit) - elapsed, 0))
  153. def temp_name(self, filename):
  154. """Returns a temporary filename for the given filename."""
  155. if self.params.get('nopart', False) or filename == '-' or \
  156. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  157. return filename
  158. return filename + '.part'
  159. def undo_temp_name(self, filename):
  160. if filename.endswith('.part'):
  161. return filename[:-len('.part')]
  162. return filename
  163. def ytdl_filename(self, filename):
  164. return filename + '.ytdl'
  165. def try_rename(self, old_filename, new_filename):
  166. try:
  167. if old_filename == new_filename:
  168. return
  169. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  170. except (IOError, OSError) as err:
  171. self.report_error('unable to rename file: %s' % error_to_compat_str(err))
  172. def try_utime(self, filename, last_modified_hdr):
  173. """Try to set the last-modified time of the given file."""
  174. if last_modified_hdr is None:
  175. return
  176. if not os.path.isfile(encodeFilename(filename)):
  177. return
  178. timestr = last_modified_hdr
  179. if timestr is None:
  180. return
  181. filetime = timeconvert(timestr)
  182. if filetime is None:
  183. return filetime
  184. # Ignore obviously invalid dates
  185. if filetime == 0:
  186. return
  187. try:
  188. os.utime(filename, (time.time(), filetime))
  189. except Exception:
  190. pass
  191. return filetime
  192. def report_destination(self, filename):
  193. """Report destination filename."""
  194. self.to_screen('[download] Destination: ' + filename)
  195. def _report_progress_status(self, msg, is_last_line=False):
  196. fullmsg = '[download] ' + msg
  197. if self.params.get('progress_with_newline', False):
  198. self.to_screen(fullmsg)
  199. else:
  200. if compat_os_name == 'nt':
  201. prev_len = getattr(self, '_report_progress_prev_line_length',
  202. 0)
  203. if prev_len > len(fullmsg):
  204. fullmsg += ' ' * (prev_len - len(fullmsg))
  205. self._report_progress_prev_line_length = len(fullmsg)
  206. clear_line = '\r'
  207. else:
  208. clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
  209. self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
  210. self.to_console_title('youtube-dl ' + msg)
  211. def report_progress(self, s):
  212. if s['status'] == 'finished':
  213. if self.params.get('noprogress', False):
  214. self.to_screen('[download] Download completed')
  215. else:
  216. if s.get('total_bytes') is not None:
  217. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  218. msg_template = '100%% of %(_total_bytes_str)s'
  219. else:
  220. msg_template = 'Completed'
  221. if s.get('elapsed') is not None:
  222. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  223. msg_template += ' in %(_elapsed_str)s'
  224. self._report_progress_status(
  225. msg_template % s, is_last_line=True)
  226. if self.params.get('noprogress'):
  227. return
  228. if s['status'] != 'downloading':
  229. return
  230. if s.get('eta') is not None:
  231. s['_eta_str'] = self.format_eta(s['eta'])
  232. else:
  233. s['_eta_str'] = 'Unknown ETA'
  234. if s.get('total_bytes') and s.get('downloaded_bytes') is not None:
  235. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])
  236. elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:
  237. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])
  238. else:
  239. if s.get('downloaded_bytes') == 0:
  240. s['_percent_str'] = self.format_percent(0)
  241. else:
  242. s['_percent_str'] = 'Unknown %'
  243. if s.get('speed') is not None:
  244. s['_speed_str'] = self.format_speed(s['speed'])
  245. else:
  246. s['_speed_str'] = 'Unknown speed'
  247. if s.get('total_bytes') is not None:
  248. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  249. msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
  250. elif s.get('total_bytes_estimate') is not None:
  251. s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])
  252. msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
  253. else:
  254. if s.get('downloaded_bytes') is not None:
  255. s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])
  256. if s.get('elapsed'):
  257. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  258. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
  259. else:
  260. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'
  261. else:
  262. msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
  263. self._report_progress_status(msg_template % s)
  264. def report_resuming_byte(self, resume_len):
  265. """Report attempt to resume at given byte."""
  266. self.to_screen('[download] Resuming download at byte %s' % resume_len)
  267. def report_retry(self, err, count, retries):
  268. """Report retry in case of HTTP error 5xx"""
  269. self.to_screen(
  270. '[download] Got server HTTP error: %s. Retrying (attempt %d of %s)...'
  271. % (error_to_compat_str(err), count, self.format_retries(retries)))
  272. def report_file_already_downloaded(self, file_name):
  273. """Report file has already been fully downloaded."""
  274. try:
  275. self.to_screen('[download] %s has already been downloaded' % file_name)
  276. except UnicodeEncodeError:
  277. self.to_screen('[download] The file has already been downloaded')
  278. def report_unable_to_resume(self):
  279. """Report it was impossible to resume download."""
  280. self.to_screen('[download] Unable to resume')
  281. def download(self, filename, info_dict):
  282. """Download to a filename using the info from info_dict
  283. Return True on success and False otherwise
  284. """
  285. nooverwrites_and_exists = (
  286. self.params.get('nooverwrites', False) and
  287. os.path.exists(encodeFilename(filename))
  288. )
  289. if not hasattr(filename, 'write'):
  290. continuedl_and_exists = (
  291. self.params.get('continuedl', True) and
  292. os.path.isfile(encodeFilename(filename)) and
  293. not self.params.get('nopart', False)
  294. )
  295. # Check file already present
  296. if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
  297. self.report_file_already_downloaded(filename)
  298. self._hook_progress({
  299. 'filename': filename,
  300. 'status': 'finished',
  301. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  302. })
  303. return True
  304. min_sleep_interval = self.params.get('sleep_interval')
  305. if min_sleep_interval:
  306. max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval)
  307. sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval)
  308. self.to_screen(
  309. '[download] Sleeping %s seconds...' % (
  310. int(sleep_interval) if sleep_interval.is_integer()
  311. else '%.2f' % sleep_interval))
  312. time.sleep(sleep_interval)
  313. return self.real_download(filename, info_dict)
  314. def real_download(self, filename, info_dict):
  315. """Real download process. Redefine in subclasses."""
  316. raise NotImplementedError('This method must be implemented by subclasses')
  317. def _hook_progress(self, status):
  318. for ph in self._progress_hooks:
  319. ph(status)
  320. def add_progress_hook(self, ph):
  321. # See YoutubeDl.py (search for progress_hooks) for a description of
  322. # this interface
  323. self._progress_hooks.append(ph)
  324. def _debug_cmd(self, args, exe=None):
  325. if not self.params.get('verbose', False):
  326. return
  327. str_args = [decodeArgument(a) for a in args]
  328. if exe is None:
  329. exe = os.path.basename(str_args[0])
  330. self.to_screen('[debug] %s command line: %s' % (
  331. exe, shell_quote(str_args)))