2
0

common.py 14 KB

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