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