1 from __future__ import division, unicode_literals
8 from ..compat import compat_str
17 class FileDownloader(object):
18 """File Downloader class.
20 File downloader objects are the ones responsible of downloading the
21 actual video file and writing it to disk.
23 File downloaders accept a lot of parameters. In order not to saturate
24 the object constructor with arguments, it receives a dictionary of
29 verbose: Print additional info to stdout.
30 quiet: Do not print messages to stdout.
31 ratelimit: Download speed limit, in bytes/sec.
32 retries: Number of times to retry for HTTP error 5xx
33 buffersize: Size of download buffer in bytes.
34 noresizebuffer: Do not automatically resize the download buffer.
35 continuedl: Try to continue downloads if possible.
36 noprogress: Do not print the progress bar.
37 logtostderr: Log messages to stderr instead of stdout.
38 consoletitle: Display progress in console window's titlebar.
39 nopart: Do not use temporary .part files.
40 updatetime: Use the Last-modified header to set output file timestamps.
41 test: Download only first bytes to test the downloader.
42 min_filesize: Skip files smaller than this size
43 max_filesize: Skip files larger than this size
44 xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
46 external_downloader_args: A list of additional command-line arguments for the
49 Subclasses of this one must re-define the real_download method.
52 _TEST_FILE_SIZE = 10241
55 def __init__(self, ydl, params):
56 """Create a FileDownloader object with the given options."""
58 self._progress_hooks = []
60 self.add_progress_hook(self.report_progress)
63 def format_seconds(seconds):
64 (mins, secs) = divmod(seconds, 60)
65 (hours, mins) = divmod(mins, 60)
69 return '%02d:%02d' % (mins, secs)
71 return '%02d:%02d:%02d' % (hours, mins, secs)
74 def calc_percent(byte_counter, data_len):
77 return float(byte_counter) / float(data_len) * 100.0
80 def format_percent(percent):
83 return '%6s' % ('%3.1f%%' % percent)
86 def calc_eta(start, now, total, current):
92 if current == 0 or dif < 0.001: # One millisecond
94 rate = float(current) / dif
95 return int((float(total) - float(current)) / rate)
101 return FileDownloader.format_seconds(eta)
104 def calc_speed(start, now, bytes):
106 if bytes == 0 or dif < 0.001: # One millisecond
108 return float(bytes) / dif
111 def format_speed(speed):
113 return '%10s' % '---b/s'
114 return '%10s' % ('%s/s' % format_bytes(speed))
117 def best_block_size(elapsed_time, bytes):
118 new_min = max(bytes / 2.0, 1.0)
119 new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
120 if elapsed_time < 0.001:
122 rate = bytes / elapsed_time
130 def parse_bytes(bytestr):
131 """Parse a string indicating a byte quantity into an integer."""
132 matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
135 number = float(matchobj.group(1))
136 multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
137 return int(round(number * multiplier))
139 def to_screen(self, *args, **kargs):
140 self.ydl.to_screen(*args, **kargs)
142 def to_stderr(self, message):
143 self.ydl.to_screen(message)
145 def to_console_title(self, message):
146 self.ydl.to_console_title(message)
148 def trouble(self, *args, **kargs):
149 self.ydl.trouble(*args, **kargs)
151 def report_warning(self, *args, **kargs):
152 self.ydl.report_warning(*args, **kargs)
154 def report_error(self, *args, **kargs):
155 self.ydl.report_error(*args, **kargs)
157 def slow_down(self, start_time, now, byte_counter):
158 """Sleep if the download speed is over the rate limit."""
159 rate_limit = self.params.get('ratelimit', None)
160 if rate_limit is None or byte_counter == 0:
164 elapsed = now - start_time
167 speed = float(byte_counter) / elapsed
168 if speed > rate_limit:
169 time.sleep(max((byte_counter // rate_limit) - elapsed, 0))
171 def temp_name(self, filename):
172 """Returns a temporary filename for the given filename."""
173 if self.params.get('nopart', False) or filename == '-' or \
174 (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
176 return filename + '.part'
178 def undo_temp_name(self, filename):
179 if filename.endswith('.part'):
180 return filename[:-len('.part')]
183 def try_rename(self, old_filename, new_filename):
185 if old_filename == new_filename:
187 os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
188 except (IOError, OSError) as err:
189 self.report_error('unable to rename file: %s' % compat_str(err))
191 def try_utime(self, filename, last_modified_hdr):
192 """Try to set the last-modified time of the given file."""
193 if last_modified_hdr is None:
195 if not os.path.isfile(encodeFilename(filename)):
197 timestr = last_modified_hdr
200 filetime = timeconvert(timestr)
203 # Ignore obviously invalid dates
207 os.utime(filename, (time.time(), filetime))
212 def report_destination(self, filename):
213 """Report destination filename."""
214 self.to_screen('[download] Destination: ' + filename)
216 def _report_progress_status(self, msg, is_last_line=False):
217 fullmsg = '[download] ' + msg
218 if self.params.get('progress_with_newline', False):
219 self.to_screen(fullmsg)
222 prev_len = getattr(self, '_report_progress_prev_line_length',
224 if prev_len > len(fullmsg):
225 fullmsg += ' ' * (prev_len - len(fullmsg))
226 self._report_progress_prev_line_length = len(fullmsg)
229 clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
230 self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
231 self.to_console_title('youtube-dl ' + msg)
233 def report_progress(self, s):
234 if s['status'] == 'finished':
235 if self.params.get('noprogress', False):
236 self.to_screen('[download] Download completed')
238 s['_total_bytes_str'] = format_bytes(s['total_bytes'])
239 if s.get('elapsed') is not None:
240 s['_elapsed_str'] = self.format_seconds(s['elapsed'])
241 msg_template = '100%% of %(_total_bytes_str)s in %(_elapsed_str)s'
243 msg_template = '100%% of %(_total_bytes_str)s'
244 self._report_progress_status(
245 msg_template % s, is_last_line=True)
247 if self.params.get('noprogress'):
250 if s['status'] != 'downloading':
253 if s.get('eta') is not None:
254 s['_eta_str'] = self.format_eta(s['eta'])
256 s['_eta_str'] = 'Unknown ETA'
258 if s.get('total_bytes') and s.get('downloaded_bytes') is not None:
259 s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])
260 elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:
261 s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])
263 if s.get('downloaded_bytes') == 0:
264 s['_percent_str'] = self.format_percent(0)
266 s['_percent_str'] = 'Unknown %'
268 if s.get('speed') is not None:
269 s['_speed_str'] = self.format_speed(s['speed'])
271 s['_speed_str'] = 'Unknown speed'
273 if s.get('total_bytes') is not None:
274 s['_total_bytes_str'] = format_bytes(s['total_bytes'])
275 msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
276 elif s.get('total_bytes_estimate') is not None:
277 s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])
278 msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
280 if s.get('downloaded_bytes') is not None:
281 s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])
283 s['_elapsed_str'] = self.format_seconds(s['elapsed'])
284 msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
286 msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'
288 msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
290 self._report_progress_status(msg_template % s)
292 def report_resuming_byte(self, resume_len):
293 """Report attempt to resume at given byte."""
294 self.to_screen('[download] Resuming download at byte %s' % resume_len)
296 def report_retry(self, count, retries):
297 """Report retry in case of HTTP error 5xx"""
298 self.to_screen('[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
300 def report_file_already_downloaded(self, file_name):
301 """Report file has already been fully downloaded."""
303 self.to_screen('[download] %s has already been downloaded' % file_name)
304 except UnicodeEncodeError:
305 self.to_screen('[download] The file has already been downloaded')
307 def report_unable_to_resume(self):
308 """Report it was impossible to resume download."""
309 self.to_screen('[download] Unable to resume')
311 def download(self, filename, info_dict):
312 """Download to a filename using the info from info_dict
313 Return True on success and False otherwise
316 nooverwrites_and_exists = (
317 self.params.get('nooverwrites', False) and
318 os.path.exists(encodeFilename(filename))
321 continuedl_and_exists = (
322 self.params.get('continuedl', True) and
323 os.path.isfile(encodeFilename(filename)) and
324 not self.params.get('nopart', False)
327 # Check file already present
328 if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
329 self.report_file_already_downloaded(filename)
330 self._hook_progress({
331 'filename': filename,
332 'status': 'finished',
333 'total_bytes': os.path.getsize(encodeFilename(filename)),
337 sleep_interval = self.params.get('sleep_interval')
339 self.to_screen('[download] Sleeping %s seconds...' % sleep_interval)
340 time.sleep(sleep_interval)
342 return self.real_download(filename, info_dict)
344 def real_download(self, filename, info_dict):
345 """Real download process. Redefine in subclasses."""
346 raise NotImplementedError('This method must be implemented by subclasses')
348 def _hook_progress(self, status):
349 for ph in self._progress_hooks:
352 def add_progress_hook(self, ph):
353 # See YoutubeDl.py (search for progress_hooks) for a description of
355 self._progress_hooks.append(ph)
357 def _debug_cmd(self, args, exe=None):
358 if not self.params.get('verbose', False):
361 str_args = [decodeArgument(a) for a in args]
364 exe = os.path.basename(str_args[0])
368 shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
371 self.to_screen('[debug] %s command line: %s' % (
372 exe, shell_quote(str_args)))