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.

375 lines
14 KiB

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