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.

320 lines
11 KiB

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