You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
14 KiB

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