1 from __future__
import division
, unicode_literals
18 from ..minicurses
import (
21 QuietMultilinePrinter
,
22 BreaklineStatusPrinter
26 class FileDownloader(object):
27 """File Downloader class.
29 File downloader objects are the ones responsible of downloading the
30 actual video file and writing it to disk.
32 File downloaders accept a lot of parameters. In order not to saturate
33 the object constructor with arguments, it receives a dictionary of
38 verbose: Print additional info to stdout.
39 quiet: Do not print messages to stdout.
40 ratelimit: Download speed limit, in bytes/sec.
41 throttledratelimit: Assume the download is being throttled below this speed (bytes/sec)
42 retries: Number of times to retry for HTTP error 5xx
43 buffersize: Size of download buffer in bytes.
44 noresizebuffer: Do not automatically resize the download buffer.
45 continuedl: Try to continue downloads if possible.
46 noprogress: Do not print the progress bar.
47 nopart: Do not use temporary .part files.
48 updatetime: Use the Last-modified header to set output file timestamps.
49 test: Download only first bytes to test the downloader.
50 min_filesize: Skip files smaller than this size
51 max_filesize: Skip files larger than this size
52 xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
53 external_downloader_args: A dictionary of downloader keys (in lower case)
54 and a list of additional command-line arguments for the
55 executable. Use 'default' as the name for arguments to be
56 passed to all downloaders. For compatibility with youtube-dl,
57 a single list of args can also be used
58 hls_use_mpegts: Use the mpegts container for HLS videos.
59 http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be
60 useful for bypassing bandwidth throttling imposed by
61 a webserver (experimental)
62 progress_template: See YoutubeDL.py
64 Subclasses of this one must re-define the real_download method.
67 _TEST_FILE_SIZE
= 10241
70 def __init__(self
, ydl
, params
):
71 """Create a FileDownloader object with the given options."""
73 self
._progress
_hooks
= []
75 self
._prepare
_multiline
_status
()
76 self
.add_progress_hook(self
.report_progress
)
79 def format_seconds(seconds
):
80 (mins
, secs
) = divmod(seconds
, 60)
81 (hours
, mins
) = divmod(mins
, 60)
85 return '%02d:%02d' % (mins
, secs
)
87 return '%02d:%02d:%02d' % (hours
, mins
, secs
)
90 def calc_percent(byte_counter
, data_len
):
93 return float(byte_counter
) / float(data_len
) * 100.0
96 def format_percent(percent
):
99 return '%6s' % ('%3.1f%%' % percent
)
102 def calc_eta(start
, now
, total
, current
):
108 if current
== 0 or dif
< 0.001: # One millisecond
110 rate
= float(current
) / dif
111 return int((float(total
) - float(current
)) / rate
)
117 return FileDownloader
.format_seconds(eta
)
120 def calc_speed(start
, now
, bytes):
122 if bytes == 0 or dif
< 0.001: # One millisecond
124 return float(bytes) / dif
127 def format_speed(speed
):
129 return '%10s' % '---b/s'
130 return '%10s' % ('%s/s' % format_bytes(speed
))
133 def format_retries(retries
):
134 return 'inf' if retries
== float('inf') else '%.0f' % retries
137 def best_block_size(elapsed_time
, bytes):
138 new_min
= max(bytes / 2.0, 1.0)
139 new_max
= min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
140 if elapsed_time
< 0.001:
142 rate
= bytes / elapsed_time
150 def parse_bytes(bytestr
):
151 """Parse a string indicating a byte quantity into an integer."""
152 matchobj
= re
.match(r
'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr
)
155 number
= float(matchobj
.group(1))
156 multiplier
= 1024.0 ** 'bkmgtpezy'.index(matchobj
.group(2).lower())
157 return int(round(number
* multiplier
))
159 def to_screen(self
, *args
, **kargs
):
160 self
.ydl
.to_stdout(*args
, quiet
=self
.params
.get('quiet'), **kargs
)
162 def to_stderr(self
, message
):
163 self
.ydl
.to_stderr(message
)
165 def to_console_title(self
, message
):
166 self
.ydl
.to_console_title(message
)
168 def trouble(self
, *args
, **kargs
):
169 self
.ydl
.trouble(*args
, **kargs
)
171 def report_warning(self
, *args
, **kargs
):
172 self
.ydl
.report_warning(*args
, **kargs
)
174 def report_error(self
, *args
, **kargs
):
175 self
.ydl
.report_error(*args
, **kargs
)
177 def write_debug(self
, *args
, **kargs
):
178 self
.ydl
.write_debug(*args
, **kargs
)
180 def slow_down(self
, start_time
, now
, byte_counter
):
181 """Sleep if the download speed is over the rate limit."""
182 rate_limit
= self
.params
.get('ratelimit')
183 if rate_limit
is None or byte_counter
== 0:
187 elapsed
= now
- start_time
190 speed
= float(byte_counter
) / elapsed
191 if speed
> rate_limit
:
192 sleep_time
= float(byte_counter
) / rate_limit
- elapsed
194 time
.sleep(sleep_time
)
196 def temp_name(self
, filename
):
197 """Returns a temporary filename for the given filename."""
198 if self
.params
.get('nopart', False) or filename
== '-' or \
199 (os
.path
.exists(encodeFilename(filename
)) and not os
.path
.isfile(encodeFilename(filename
))):
201 return filename
+ '.part'
203 def undo_temp_name(self
, filename
):
204 if filename
.endswith('.part'):
205 return filename
[:-len('.part')]
208 def ytdl_filename(self
, filename
):
209 return filename
+ '.ytdl'
211 def try_rename(self
, old_filename
, new_filename
):
212 if old_filename
== new_filename
:
215 os
.replace(old_filename
, new_filename
)
216 except (IOError, OSError) as err
:
217 self
.report_error(f
'unable to rename file: {err}')
219 def try_utime(self
, filename
, last_modified_hdr
):
220 """Try to set the last-modified time of the given file."""
221 if last_modified_hdr
is None:
223 if not os
.path
.isfile(encodeFilename(filename
)):
225 timestr
= last_modified_hdr
228 filetime
= timeconvert(timestr
)
231 # Ignore obviously invalid dates
235 os
.utime(filename
, (time
.time(), filetime
))
240 def report_destination(self
, filename
):
241 """Report destination filename."""
242 self
.to_screen('[download] Destination: ' + filename
)
244 def _prepare_multiline_status(self
, lines
=1):
245 if self
.params
.get('noprogress'):
246 self
._multiline
= QuietMultilinePrinter()
247 elif self
.ydl
.params
.get('logger'):
248 self
._multiline
= MultilineLogger(self
.ydl
.params
['logger'], lines
)
249 elif self
.params
.get('progress_with_newline'):
250 self
._multiline
= BreaklineStatusPrinter(sys
.stderr
, lines
)
252 self
._multiline
= MultilinePrinter(sys
.stderr
, lines
, not self
.params
.get('quiet'))
254 def _finish_multiline_status(self
):
255 self
._multiline
.end()
257 def _report_progress_status(self
, s
):
258 progress_dict
= s
.copy()
259 progress_dict
.pop('info_dict')
260 progress_dict
= {'info': s['info_dict'], 'progress': progress_dict}
262 progress_template
= self
.params
.get('progress_template', {})
263 self
._multiline
.print_at_line(self
.ydl
.evaluate_outtmpl(
264 progress_template
.get('download') or '[download] %(progress._default_template)s',
265 progress_dict
), s
.get('progress_idx') or 0)
266 self
.to_console_title(self
.ydl
.evaluate_outtmpl(
267 progress_template
.get('download-title') or 'yt-dlp %(progress._default_template)s',
270 def report_progress(self
, s
):
271 if s
['status'] == 'finished':
272 if self
.params
.get('noprogress'):
273 self
.to_screen('[download] Download completed')
274 msg_template
= '100%%'
275 if s
.get('total_bytes') is not None:
276 s
['_total_bytes_str'] = format_bytes(s
['total_bytes'])
277 msg_template
+= ' of %(_total_bytes_str)s'
278 if s
.get('elapsed') is not None:
279 s
['_elapsed_str'] = self
.format_seconds(s
['elapsed'])
280 msg_template
+= ' in %(_elapsed_str)s'
281 s
['_percent_str'] = self
.format_percent(100)
282 s
['_default_template'] = msg_template
% s
283 self
._report
_progress
_status
(s
)
286 if s
['status'] != 'downloading':
289 if s
.get('eta') is not None:
290 s
['_eta_str'] = self
.format_eta(s
['eta'])
292 s
['_eta_str'] = 'Unknown ETA'
294 if s
.get('total_bytes') and s
.get('downloaded_bytes') is not None:
295 s
['_percent_str'] = self
.format_percent(100 * s
['downloaded_bytes'] / s
['total_bytes'])
296 elif s
.get('total_bytes_estimate') and s
.get('downloaded_bytes') is not None:
297 s
['_percent_str'] = self
.format_percent(100 * s
['downloaded_bytes'] / s
['total_bytes_estimate'])
299 if s
.get('downloaded_bytes') == 0:
300 s
['_percent_str'] = self
.format_percent(0)
302 s
['_percent_str'] = 'Unknown %'
304 if s
.get('speed') is not None:
305 s
['_speed_str'] = self
.format_speed(s
['speed'])
307 s
['_speed_str'] = 'Unknown speed'
309 if s
.get('total_bytes') is not None:
310 s
['_total_bytes_str'] = format_bytes(s
['total_bytes'])
311 msg_template
= '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
312 elif s
.get('total_bytes_estimate') is not None:
313 s
['_total_bytes_estimate_str'] = format_bytes(s
['total_bytes_estimate'])
314 msg_template
= '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
316 if s
.get('downloaded_bytes') is not None:
317 s
['_downloaded_bytes_str'] = format_bytes(s
['downloaded_bytes'])
319 s
['_elapsed_str'] = self
.format_seconds(s
['elapsed'])
320 msg_template
= '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
322 msg_template
= '%(_downloaded_bytes_str)s at %(_speed_str)s'
324 msg_template
= '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
325 s
['_default_template'] = msg_template
% s
326 self
._report
_progress
_status
(s
)
328 def report_resuming_byte(self
, resume_len
):
329 """Report attempt to resume at given byte."""
330 self
.to_screen('[download] Resuming download at byte %s' % resume_len
)
332 def report_retry(self
, err
, count
, retries
):
333 """Report retry in case of HTTP error 5xx"""
335 '[download] Got server HTTP error: %s. Retrying (attempt %d of %s) ...'
336 % (error_to_compat_str(err
), count
, self
.format_retries(retries
)))
338 def report_file_already_downloaded(self
, *args
, **kwargs
):
339 """Report file has already been fully downloaded."""
340 return self
.ydl
.report_file_already_downloaded(*args
, **kwargs
)
342 def report_unable_to_resume(self
):
343 """Report it was impossible to resume download."""
344 self
.to_screen('[download] Unable to resume')
347 def supports_manifest(manifest
):
348 """ Whether the downloader can download the fragments from the manifest.
349 Redefine in subclasses if needed. """
352 def download(self
, filename
, info_dict
, subtitle
=False):
353 """Download to a filename using the info from info_dict
354 Return True on success and False otherwise
357 nooverwrites_and_exists
= (
358 not self
.params
.get('overwrites', True)
359 and os
.path
.exists(encodeFilename(filename
))
362 if not hasattr(filename
, 'write'):
363 continuedl_and_exists
= (
364 self
.params
.get('continuedl', True)
365 and os
.path
.isfile(encodeFilename(filename
))
366 and not self
.params
.get('nopart', False)
369 # Check file already present
370 if filename
!= '-' and (nooverwrites_and_exists
or continuedl_and_exists
):
371 self
.report_file_already_downloaded(filename
)
372 self
._hook
_progress
({
373 'filename': filename
,
374 'status': 'finished',
375 'total_bytes': os
.path
.getsize(encodeFilename(filename
)),
379 if subtitle
is False:
380 min_sleep_interval
= self
.params
.get('sleep_interval')
381 if min_sleep_interval
:
382 max_sleep_interval
= self
.params
.get('max_sleep_interval', min_sleep_interval
)
383 sleep_interval
= random
.uniform(min_sleep_interval
, max_sleep_interval
)
385 '[download] Sleeping %s seconds ...' % (
386 int(sleep_interval
) if sleep_interval
.is_integer()
387 else '%.2f' % sleep_interval
))
388 time
.sleep(sleep_interval
)
390 sleep_interval_sub
= 0
391 if type(self
.params
.get('sleep_interval_subtitles')) is int:
392 sleep_interval_sub
= self
.params
.get('sleep_interval_subtitles')
393 if sleep_interval_sub
> 0:
395 '[download] Sleeping %s seconds ...' % (
397 time
.sleep(sleep_interval_sub
)
398 ret
= self
.real_download(filename
, info_dict
)
399 self
._finish
_multiline
_status
()
402 def real_download(self
, filename
, info_dict
):
403 """Real download process. Redefine in subclasses."""
404 raise NotImplementedError('This method must be implemented by subclasses')
406 def _hook_progress(self
, status
, info_dict
):
407 if not self
._progress
_hooks
:
409 info_dict
= dict(info_dict
)
410 for key
in ('__original_infodict', '__postprocessors'):
411 info_dict
.pop(key
, None)
412 # youtube-dl passes the same status object to all the hooks.
413 # Some third party scripts seems to be relying on this.
414 # So keep this behavior if possible
415 status
['info_dict'] = copy
.deepcopy(info_dict
)
416 for ph
in self
._progress
_hooks
:
419 def add_progress_hook(self
, ph
):
420 # See YoutubeDl.py (search for progress_hooks) for a description of
422 self
._progress
_hooks
.append(ph
)
424 def _debug_cmd(self
, args
, exe
=None):
425 if not self
.params
.get('verbose', False):
428 str_args
= [decodeArgument(a
) for a
in args
]
431 exe
= os
.path
.basename(str_args
[0])
433 self
.write_debug('%s command line: %s' % (exe
, shell_quote(str_args
)))