]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/common.py
[cleanup] Misc cleanup
[yt-dlp.git] / yt_dlp / downloader / common.py
1 from __future__ import division, unicode_literals
2
3 import os
4 import re
5 import time
6 import random
7
8 from ..utils import (
9 decodeArgument,
10 encodeFilename,
11 error_to_compat_str,
12 format_bytes,
13 shell_quote,
14 timeconvert,
15 timetuple_from_msec,
16 )
17 from ..minicurses import (
18 MultilineLogger,
19 MultilinePrinter,
20 QuietMultilinePrinter,
21 BreaklineStatusPrinter
22 )
23
24
25 class FileDownloader(object):
26 """File Downloader class.
27
28 File downloader objects are the ones responsible of downloading the
29 actual video file and writing it to disk.
30
31 File downloaders accept a lot of parameters. In order not to saturate
32 the object constructor with arguments, it receives a dictionary of
33 options instead.
34
35 Available options:
36
37 verbose: Print additional info to stdout.
38 quiet: Do not print messages to stdout.
39 ratelimit: Download speed limit, in bytes/sec.
40 throttledratelimit: Assume the download is being throttled below this speed (bytes/sec)
41 retries: Number of times to retry for HTTP error 5xx
42 buffersize: Size of download buffer in bytes.
43 noresizebuffer: Do not automatically resize the download buffer.
44 continuedl: Try to continue downloads if possible.
45 noprogress: Do not print the progress bar.
46 nopart: Do not use temporary .part files.
47 updatetime: Use the Last-modified header to set output file timestamps.
48 test: Download only first bytes to test the downloader.
49 min_filesize: Skip files smaller than this size
50 max_filesize: Skip files larger than this size
51 xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
52 external_downloader_args: A dictionary of downloader keys (in lower case)
53 and a list of additional command-line arguments for the
54 executable. Use 'default' as the name for arguments to be
55 passed to all downloaders. For compatibility with youtube-dl,
56 a single list of args can also be used
57 hls_use_mpegts: Use the mpegts container for HLS videos.
58 http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be
59 useful for bypassing bandwidth throttling imposed by
60 a webserver (experimental)
61 progress_template: See YoutubeDL.py
62
63 Subclasses of this one must re-define the real_download method.
64 """
65
66 _TEST_FILE_SIZE = 10241
67 params = None
68
69 def __init__(self, ydl, params):
70 """Create a FileDownloader object with the given options."""
71 self.ydl = ydl
72 self._progress_hooks = []
73 self.params = params
74 self._prepare_multiline_status()
75 self.add_progress_hook(self.report_progress)
76
77 @staticmethod
78 def format_seconds(seconds):
79 time = timetuple_from_msec(seconds * 1000)
80 if time.hours > 99:
81 return '--:--:--'
82 if not time.hours:
83 return '%02d:%02d' % time[1:-1]
84 return '%02d:%02d:%02d' % time[:-1]
85
86 @staticmethod
87 def calc_percent(byte_counter, data_len):
88 if data_len is None:
89 return None
90 return float(byte_counter) / float(data_len) * 100.0
91
92 @staticmethod
93 def format_percent(percent):
94 if percent is None:
95 return '---.-%'
96 elif percent == 100:
97 return '100%'
98 return '%6s' % ('%3.1f%%' % percent)
99
100 @staticmethod
101 def calc_eta(start, now, total, current):
102 if total is None:
103 return None
104 if now is None:
105 now = time.time()
106 dif = now - start
107 if current == 0 or dif < 0.001: # One millisecond
108 return None
109 rate = float(current) / dif
110 return int((float(total) - float(current)) / rate)
111
112 @staticmethod
113 def format_eta(eta):
114 if eta is None:
115 return '--:--'
116 return FileDownloader.format_seconds(eta)
117
118 @staticmethod
119 def calc_speed(start, now, bytes):
120 dif = now - start
121 if bytes == 0 or dif < 0.001: # One millisecond
122 return None
123 return float(bytes) / dif
124
125 @staticmethod
126 def format_speed(speed):
127 if speed is None:
128 return '%10s' % '---b/s'
129 return '%10s' % ('%s/s' % format_bytes(speed))
130
131 @staticmethod
132 def format_retries(retries):
133 return 'inf' if retries == float('inf') else '%.0f' % retries
134
135 @staticmethod
136 def best_block_size(elapsed_time, bytes):
137 new_min = max(bytes / 2.0, 1.0)
138 new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
139 if elapsed_time < 0.001:
140 return int(new_max)
141 rate = bytes / elapsed_time
142 if rate > new_max:
143 return int(new_max)
144 if rate < new_min:
145 return int(new_min)
146 return int(rate)
147
148 @staticmethod
149 def parse_bytes(bytestr):
150 """Parse a string indicating a byte quantity into an integer."""
151 matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
152 if matchobj is None:
153 return None
154 number = float(matchobj.group(1))
155 multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
156 return int(round(number * multiplier))
157
158 def to_screen(self, *args, **kargs):
159 self.ydl.to_stdout(*args, quiet=self.params.get('quiet'), **kargs)
160
161 def to_stderr(self, message):
162 self.ydl.to_stderr(message)
163
164 def to_console_title(self, message):
165 self.ydl.to_console_title(message)
166
167 def trouble(self, *args, **kargs):
168 self.ydl.trouble(*args, **kargs)
169
170 def report_warning(self, *args, **kargs):
171 self.ydl.report_warning(*args, **kargs)
172
173 def report_error(self, *args, **kargs):
174 self.ydl.report_error(*args, **kargs)
175
176 def write_debug(self, *args, **kargs):
177 self.ydl.write_debug(*args, **kargs)
178
179 def slow_down(self, start_time, now, byte_counter):
180 """Sleep if the download speed is over the rate limit."""
181 rate_limit = self.params.get('ratelimit')
182 if rate_limit is None or byte_counter == 0:
183 return
184 if now is None:
185 now = time.time()
186 elapsed = now - start_time
187 if elapsed <= 0.0:
188 return
189 speed = float(byte_counter) / elapsed
190 if speed > rate_limit:
191 sleep_time = float(byte_counter) / rate_limit - elapsed
192 if sleep_time > 0:
193 time.sleep(sleep_time)
194
195 def temp_name(self, filename):
196 """Returns a temporary filename for the given filename."""
197 if self.params.get('nopart', False) or filename == '-' or \
198 (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
199 return filename
200 return filename + '.part'
201
202 def undo_temp_name(self, filename):
203 if filename.endswith('.part'):
204 return filename[:-len('.part')]
205 return filename
206
207 def ytdl_filename(self, filename):
208 return filename + '.ytdl'
209
210 def try_rename(self, old_filename, new_filename):
211 if old_filename == new_filename:
212 return
213 try:
214 os.replace(old_filename, new_filename)
215 except (IOError, OSError) as err:
216 self.report_error(f'unable to rename file: {err}')
217
218 def try_utime(self, filename, last_modified_hdr):
219 """Try to set the last-modified time of the given file."""
220 if last_modified_hdr is None:
221 return
222 if not os.path.isfile(encodeFilename(filename)):
223 return
224 timestr = last_modified_hdr
225 if timestr is None:
226 return
227 filetime = timeconvert(timestr)
228 if filetime is None:
229 return filetime
230 # Ignore obviously invalid dates
231 if filetime == 0:
232 return
233 try:
234 os.utime(filename, (time.time(), filetime))
235 except Exception:
236 pass
237 return filetime
238
239 def report_destination(self, filename):
240 """Report destination filename."""
241 self.to_screen('[download] Destination: ' + filename)
242
243 def _prepare_multiline_status(self, lines=1):
244 if self.params.get('noprogress'):
245 self._multiline = QuietMultilinePrinter()
246 elif self.ydl.params.get('logger'):
247 self._multiline = MultilineLogger(self.ydl.params['logger'], lines)
248 elif self.params.get('progress_with_newline'):
249 self._multiline = BreaklineStatusPrinter(self.ydl._screen_file, lines)
250 else:
251 self._multiline = MultilinePrinter(self.ydl._screen_file, lines, not self.params.get('quiet'))
252 self._multiline.allow_colors = self._multiline._HAVE_FULLCAP and not self.params.get('no_color')
253
254 def _finish_multiline_status(self):
255 self._multiline.end()
256
257 _progress_styles = {
258 'downloaded_bytes': 'light blue',
259 'percent': 'light blue',
260 'eta': 'yellow',
261 'speed': 'green',
262 'elapsed': 'bold white',
263 'total_bytes': '',
264 'total_bytes_estimate': '',
265 }
266
267 def _report_progress_status(self, s, default_template):
268 for name, style in self._progress_styles.items():
269 name = f'_{name}_str'
270 if name not in s:
271 continue
272 s[name] = self._format_progress(s[name], style)
273 s['_default_template'] = default_template % s
274
275 progress_dict = s.copy()
276 progress_dict.pop('info_dict')
277 progress_dict = {'info': s['info_dict'], 'progress': progress_dict}
278
279 progress_template = self.params.get('progress_template', {})
280 self._multiline.print_at_line(self.ydl.evaluate_outtmpl(
281 progress_template.get('download') or '[download] %(progress._default_template)s',
282 progress_dict), s.get('progress_idx') or 0)
283 self.to_console_title(self.ydl.evaluate_outtmpl(
284 progress_template.get('download-title') or 'yt-dlp %(progress._default_template)s',
285 progress_dict))
286
287 def _format_progress(self, *args, **kwargs):
288 return self.ydl._format_text(
289 self._multiline.stream, self._multiline.allow_colors, *args, **kwargs)
290
291 def report_progress(self, s):
292 if s['status'] == 'finished':
293 if self.params.get('noprogress'):
294 self.to_screen('[download] Download completed')
295 msg_template = '100%%'
296 if s.get('total_bytes') is not None:
297 s['_total_bytes_str'] = format_bytes(s['total_bytes'])
298 msg_template += ' of %(_total_bytes_str)s'
299 if s.get('elapsed') is not None:
300 s['_elapsed_str'] = self.format_seconds(s['elapsed'])
301 msg_template += ' in %(_elapsed_str)s'
302 s['_percent_str'] = self.format_percent(100)
303 self._report_progress_status(s, msg_template)
304 return
305
306 if s['status'] != 'downloading':
307 return
308
309 if s.get('eta') is not None:
310 s['_eta_str'] = self.format_eta(s['eta'])
311 else:
312 s['_eta_str'] = 'Unknown'
313
314 if s.get('total_bytes') and s.get('downloaded_bytes') is not None:
315 s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes'])
316 elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None:
317 s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate'])
318 else:
319 if s.get('downloaded_bytes') == 0:
320 s['_percent_str'] = self.format_percent(0)
321 else:
322 s['_percent_str'] = 'Unknown %'
323
324 if s.get('speed') is not None:
325 s['_speed_str'] = self.format_speed(s['speed'])
326 else:
327 s['_speed_str'] = 'Unknown speed'
328
329 if s.get('total_bytes') is not None:
330 s['_total_bytes_str'] = format_bytes(s['total_bytes'])
331 msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
332 elif s.get('total_bytes_estimate') is not None:
333 s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate'])
334 msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
335 else:
336 if s.get('downloaded_bytes') is not None:
337 s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes'])
338 if s.get('elapsed'):
339 s['_elapsed_str'] = self.format_seconds(s['elapsed'])
340 msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
341 else:
342 msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s'
343 else:
344 msg_template = '%(_percent_str)s at %(_speed_str)s ETA %(_eta_str)s'
345 if s.get('fragment_index') and s.get('fragment_count'):
346 msg_template += ' (frag %(fragment_index)s/%(fragment_count)s)'
347 elif s.get('fragment_index'):
348 msg_template += ' (frag %(fragment_index)s)'
349 self._report_progress_status(s, msg_template)
350
351 def report_resuming_byte(self, resume_len):
352 """Report attempt to resume at given byte."""
353 self.to_screen('[download] Resuming download at byte %s' % resume_len)
354
355 def report_retry(self, err, count, retries):
356 """Report retry in case of HTTP error 5xx"""
357 self.to_screen(
358 '[download] Got server HTTP error: %s. Retrying (attempt %d of %s) ...'
359 % (error_to_compat_str(err), count, self.format_retries(retries)))
360
361 def report_file_already_downloaded(self, *args, **kwargs):
362 """Report file has already been fully downloaded."""
363 return self.ydl.report_file_already_downloaded(*args, **kwargs)
364
365 def report_unable_to_resume(self):
366 """Report it was impossible to resume download."""
367 self.to_screen('[download] Unable to resume')
368
369 @staticmethod
370 def supports_manifest(manifest):
371 """ Whether the downloader can download the fragments from the manifest.
372 Redefine in subclasses if needed. """
373 pass
374
375 def download(self, filename, info_dict, subtitle=False):
376 """Download to a filename using the info from info_dict
377 Return True on success and False otherwise
378 """
379
380 nooverwrites_and_exists = (
381 not self.params.get('overwrites', True)
382 and os.path.exists(encodeFilename(filename))
383 )
384
385 if not hasattr(filename, 'write'):
386 continuedl_and_exists = (
387 self.params.get('continuedl', True)
388 and os.path.isfile(encodeFilename(filename))
389 and not self.params.get('nopart', False)
390 )
391
392 # Check file already present
393 if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists):
394 self.report_file_already_downloaded(filename)
395 self._hook_progress({
396 'filename': filename,
397 'status': 'finished',
398 'total_bytes': os.path.getsize(encodeFilename(filename)),
399 }, info_dict)
400 return True, False
401
402 if subtitle is False:
403 min_sleep_interval = self.params.get('sleep_interval')
404 if min_sleep_interval:
405 max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval)
406 sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval)
407 self.to_screen(
408 '[download] Sleeping %s seconds ...' % (
409 int(sleep_interval) if sleep_interval.is_integer()
410 else '%.2f' % sleep_interval))
411 time.sleep(sleep_interval)
412 else:
413 sleep_interval_sub = 0
414 if type(self.params.get('sleep_interval_subtitles')) is int:
415 sleep_interval_sub = self.params.get('sleep_interval_subtitles')
416 if sleep_interval_sub > 0:
417 self.to_screen(
418 '[download] Sleeping %s seconds ...' % (
419 sleep_interval_sub))
420 time.sleep(sleep_interval_sub)
421 ret = self.real_download(filename, info_dict)
422 self._finish_multiline_status()
423 return ret, True
424
425 def real_download(self, filename, info_dict):
426 """Real download process. Redefine in subclasses."""
427 raise NotImplementedError('This method must be implemented by subclasses')
428
429 def _hook_progress(self, status, info_dict):
430 if not self._progress_hooks:
431 return
432 status['info_dict'] = info_dict
433 # youtube-dl passes the same status object to all the hooks.
434 # Some third party scripts seems to be relying on this.
435 # So keep this behavior if possible
436 for ph in self._progress_hooks:
437 ph(status)
438
439 def add_progress_hook(self, ph):
440 # See YoutubeDl.py (search for progress_hooks) for a description of
441 # this interface
442 self._progress_hooks.append(ph)
443
444 def _debug_cmd(self, args, exe=None):
445 if not self.params.get('verbose', False):
446 return
447
448 str_args = [decodeArgument(a) for a in args]
449
450 if exe is None:
451 exe = os.path.basename(str_args[0])
452
453 self.write_debug('%s command line: %s' % (exe, shell_quote(str_args)))