common.py 14 KB

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