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.

383 lines
14 KiB

10 years ago
10 years ago
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. 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 try_rename(self, old_filename, new_filename):
  160. try:
  161. if old_filename == new_filename:
  162. return
  163. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  164. except (IOError, OSError) as err:
  165. self.report_error('unable to rename file: %s' % error_to_compat_str(err))
  166. def try_utime(self, filename, last_modified_hdr):
  167. """Try to set the last-modified time of the given file."""
  168. if last_modified_hdr is None:
  169. return
  170. if not os.path.isfile(encodeFilename(filename)):
  171. return
  172. timestr = last_modified_hdr
  173. if timestr is None:
  174. return
  175. filetime = timeconvert(timestr)
  176. if filetime is None:
  177. return filetime
  178. # Ignore obviously invalid dates
  179. if filetime == 0:
  180. return
  181. try:
  182. os.utime(filename, (time.time(), filetime))
  183. except Exception:
  184. pass
  185. return filetime
  186. def report_destination(self, filename):
  187. """Report destination filename."""
  188. self.to_screen('[download] Destination: ' + filename)
  189. def _report_progress_status(self, msg, is_last_line=False):
  190. fullmsg = '[download] ' + msg
  191. if self.params.get('progress_with_newline', False):
  192. self.to_screen(fullmsg)
  193. else:
  194. if compat_os_name == 'nt':
  195. prev_len = getattr(self, '_report_progress_prev_line_length',
  196. 0)
  197. if prev_len > len(fullmsg):
  198. fullmsg += ' ' * (prev_len - len(fullmsg))
  199. self._report_progress_prev_line_length = len(fullmsg)
  200. clear_line = '\r'
  201. else:
  202. clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
  203. self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
  204. self.to_console_title('youtube-dl ' + msg)
  205. def report_progress(self, s):
  206. if s['status'] == 'finished':
  207. if self.params.get('noprogress', False):
  208. self.to_screen('[download] Download completed')
  209. else:
  210. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  211. if s.get('elapsed') is not None:
  212. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  213. msg_template = '100%% of %(_total_bytes_str)s in %(_elapsed_str)s'
  214. else:
  215. msg_template = '100%% of %(_total_bytes_str)s'
  216. self._report_progress_status(
  217. msg_template % s, is_last_line=True)
  218. if self.params.get('noprogress'):
  219. return
  220. if s['status'] != 'downloading':
  221. return
  222. if s.get('eta') is not None:
  223. s['_eta_str'] = self.format_eta(s['eta'])
  224. else:
  225. s['_eta_str'] = 'Unknown ETA'
  226. if s.get('total_bytes') and s.get('downloaded_bytes') is not None:
  227. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])
  228. elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:
  229. s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])
  230. else:
  231. if s.get('downloaded_bytes') == 0:
  232. s['_percent_str'] = self.format_percent(0)
  233. else:
  234. s['_percent_str'] = 'Unknown %'
  235. if s.get('speed') is not None:
  236. s['_speed_str'] = self.format_speed(s['speed'])
  237. else:
  238. s['_speed_str'] = 'Unknown speed'
  239. if s.get('total_bytes') is not None:
  240. s['_total_bytes_str'] = format_bytes(s['total_bytes'])
  241. msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
  242. elif s.get('total_bytes_estimate') is not None:
  243. s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])
  244. msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
  245. else:
  246. if s.get('downloaded_bytes') is not None:
  247. s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])
  248. if s.get('elapsed'):
  249. s['_elapsed_str'] = self.format_seconds(s['elapsed'])
  250. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
  251. else:
  252. msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'
  253. else:
  254. msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
  255. self._report_progress_status(msg_template % s)
  256. def report_resuming_byte(self, resume_len):
  257. """Report attempt to resume at given byte."""
  258. self.to_screen('[download] Resuming download at byte %s' % resume_len)
  259. def report_retry(self, count, retries):
  260. """Report retry in case of HTTP error 5xx"""
  261. self.to_screen(
  262. '[download] Got server HTTP error. Retrying (attempt %d of %s)...'
  263. % (count, self.format_retries(retries)))
  264. def report_file_already_downloaded(self, file_name):
  265. """Report file has already been fully downloaded."""
  266. try:
  267. self.to_screen('[download] %s has already been downloaded' % file_name)
  268. except UnicodeEncodeError:
  269. self.to_screen('[download] The file has already been downloaded')
  270. def report_unable_to_resume(self):
  271. """Report it was impossible to resume download."""
  272. self.to_screen('[download] Unable to resume')
  273. def download(self, filename, info_dict):
  274. """Download to a filename using the info from info_dict
  275. Return True on success and False otherwise
  276. """
  277. nooverwrites_and_exists = (
  278. self.params.get('nooverwrites', False) and
  279. os.path.exists(encodeFilename(filename))
  280. )
  281. continuedl_and_exists = (
  282. self.params.get('continuedl', True) and
  283. os.path.isfile(encodeFilename(filename)) and
  284. not self.params.get('nopart', False)
  285. )
  286. # Check file already present
  287. if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
  288. self.report_file_already_downloaded(filename)
  289. self._hook_progress({
  290. 'filename': filename,
  291. 'status': 'finished',
  292. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  293. })
  294. return True
  295. min_sleep_interval = self.params.get('sleep_interval')
  296. if min_sleep_interval:
  297. max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval)
  298. sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval)
  299. self.to_screen('[download] Sleeping %s seconds...' % sleep_interval)
  300. time.sleep(sleep_interval)
  301. return self.real_download(filename, info_dict)
  302. def real_download(self, filename, info_dict):
  303. """Real download process. Redefine in subclasses."""
  304. raise NotImplementedError('This method must be implemented by subclasses')
  305. def _hook_progress(self, status):
  306. for ph in self._progress_hooks:
  307. ph(status)
  308. def add_progress_hook(self, ph):
  309. # See YoutubeDl.py (search for progress_hooks) for a description of
  310. # this interface
  311. self._progress_hooks.append(ph)
  312. def _debug_cmd(self, args, exe=None):
  313. if not self.params.get('verbose', False):
  314. return
  315. str_args = [decodeArgument(a) for a in args]
  316. if exe is None:
  317. exe = os.path.basename(str_args[0])
  318. try:
  319. import pipes
  320. shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
  321. except ImportError:
  322. shell_quote = repr
  323. self.to_screen('[debug] %s command line: %s' % (
  324. exe, shell_quote(str_args)))