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.

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