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.

350 lines
12 KiB

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