]>
Commit | Line | Data |
---|---|---|
5cda4eda | 1 | from __future__ import division, unicode_literals |
b6b70730 | 2 | |
3ba7740d | 3 | import copy |
3bc2ddcc JMF |
4 | import os |
5 | import re | |
3bc2ddcc JMF |
6 | import sys |
7 | import time | |
065bc354 | 8 | import random |
3bc2ddcc JMF |
9 | |
10 | from ..utils import ( | |
1433734c | 11 | decodeArgument, |
3bc2ddcc | 12 | encodeFilename, |
9b9c5355 | 13 | error_to_compat_str, |
3bc2ddcc | 14 | format_bytes, |
1433734c | 15 | shell_quote, |
e3ced9ed | 16 | timeconvert, |
3bc2ddcc | 17 | ) |
bd50a52b | 18 | from ..minicurses import ( |
819e0531 | 19 | MultilineLogger, |
bd50a52b THD |
20 | MultilinePrinter, |
21 | QuietMultilinePrinter, | |
22 | BreaklineStatusPrinter | |
23 | ) | |
3bc2ddcc JMF |
24 | |
25 | ||
26 | class FileDownloader(object): | |
27 | """File Downloader class. | |
28 | ||
29 | File downloader objects are the ones responsible of downloading the | |
30 | actual video file and writing it to disk. | |
31 | ||
32 | File downloaders accept a lot of parameters. In order not to saturate | |
33 | the object constructor with arguments, it receives a dictionary of | |
34 | options instead. | |
35 | ||
36 | Available options: | |
37 | ||
881e6a1f PH |
38 | verbose: Print additional info to stdout. |
39 | quiet: Do not print messages to stdout. | |
40 | ratelimit: Download speed limit, in bytes/sec. | |
51d9739f | 41 | throttledratelimit: Assume the download is being throttled below this speed (bytes/sec) |
881e6a1f PH |
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. | |
881e6a1f PH |
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. | |
34488702 | 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 | |
7d106a65 | 58 | hls_use_mpegts: Use the mpegts container for HLS videos. |
073cca3d | 59 | http_chunk_size: Size of a chunk for chunk-based HTTP downloading. May be |
b54d4a5c S |
60 | useful for bypassing bandwidth throttling imposed by |
61 | a webserver (experimental) | |
819e0531 | 62 | progress_template: See YoutubeDL.py |
3bc2ddcc JMF |
63 | |
64 | Subclasses of this one must re-define the real_download method. | |
65 | """ | |
66 | ||
b686fc18 | 67 | _TEST_FILE_SIZE = 10241 |
3bc2ddcc JMF |
68 | params = None |
69 | ||
70 | def __init__(self, ydl, params): | |
71 | """Create a FileDownloader object with the given options.""" | |
72 | self.ydl = ydl | |
73 | self._progress_hooks = [] | |
74 | self.params = params | |
819e0531 | 75 | self._prepare_multiline_status() |
5cda4eda | 76 | self.add_progress_hook(self.report_progress) |
3bc2ddcc JMF |
77 | |
78 | @staticmethod | |
79 | def format_seconds(seconds): | |
80 | (mins, secs) = divmod(seconds, 60) | |
81 | (hours, mins) = divmod(mins, 60) | |
82 | if hours > 99: | |
83 | return '--:--:--' | |
84 | if hours == 0: | |
85 | return '%02d:%02d' % (mins, secs) | |
86 | else: | |
87 | return '%02d:%02d:%02d' % (hours, mins, secs) | |
88 | ||
89 | @staticmethod | |
90 | def calc_percent(byte_counter, data_len): | |
91 | if data_len is None: | |
92 | return None | |
93 | return float(byte_counter) / float(data_len) * 100.0 | |
94 | ||
95 | @staticmethod | |
96 | def format_percent(percent): | |
97 | if percent is None: | |
98 | return '---.-%' | |
99 | return '%6s' % ('%3.1f%%' % percent) | |
100 | ||
101 | @staticmethod | |
102 | def calc_eta(start, now, total, current): | |
103 | if total is None: | |
104 | return None | |
c7667c2d S |
105 | if now is None: |
106 | now = time.time() | |
3bc2ddcc | 107 | dif = now - start |
5f6a1245 | 108 | if current == 0 or dif < 0.001: # One millisecond |
3bc2ddcc JMF |
109 | return None |
110 | rate = float(current) / dif | |
111 | return int((float(total) - float(current)) / rate) | |
112 | ||
113 | @staticmethod | |
114 | def format_eta(eta): | |
115 | if eta is None: | |
116 | return '--:--' | |
117 | return FileDownloader.format_seconds(eta) | |
118 | ||
119 | @staticmethod | |
120 | def calc_speed(start, now, bytes): | |
121 | dif = now - start | |
5f6a1245 | 122 | if bytes == 0 or dif < 0.001: # One millisecond |
3bc2ddcc JMF |
123 | return None |
124 | return float(bytes) / dif | |
125 | ||
126 | @staticmethod | |
127 | def format_speed(speed): | |
128 | if speed is None: | |
129 | return '%10s' % '---b/s' | |
130 | return '%10s' % ('%s/s' % format_bytes(speed)) | |
131 | ||
617e58d8 S |
132 | @staticmethod |
133 | def format_retries(retries): | |
134 | return 'inf' if retries == float('inf') else '%.0f' % retries | |
135 | ||
3bc2ddcc JMF |
136 | @staticmethod |
137 | def best_block_size(elapsed_time, bytes): | |
138 | new_min = max(bytes / 2.0, 1.0) | |
5f6a1245 | 139 | new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB |
3bc2ddcc JMF |
140 | if elapsed_time < 0.001: |
141 | return int(new_max) | |
142 | rate = bytes / elapsed_time | |
143 | if rate > new_max: | |
144 | return int(new_max) | |
145 | if rate < new_min: | |
146 | return int(new_min) | |
147 | return int(rate) | |
148 | ||
149 | @staticmethod | |
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) | |
153 | if matchobj is None: | |
154 | return None | |
155 | number = float(matchobj.group(1)) | |
156 | multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower()) | |
157 | return int(round(number * multiplier)) | |
158 | ||
159 | def to_screen(self, *args, **kargs): | |
848887eb | 160 | self.ydl.to_stdout(*args, quiet=self.params.get('quiet'), **kargs) |
3bc2ddcc JMF |
161 | |
162 | def to_stderr(self, message): | |
848887eb | 163 | self.ydl.to_stderr(message) |
3bc2ddcc JMF |
164 | |
165 | def to_console_title(self, message): | |
166 | self.ydl.to_console_title(message) | |
167 | ||
168 | def trouble(self, *args, **kargs): | |
169 | self.ydl.trouble(*args, **kargs) | |
170 | ||
171 | def report_warning(self, *args, **kargs): | |
172 | self.ydl.report_warning(*args, **kargs) | |
173 | ||
174 | def report_error(self, *args, **kargs): | |
175 | self.ydl.report_error(*args, **kargs) | |
176 | ||
856bb8f9 | 177 | def write_debug(self, *args, **kargs): |
178 | self.ydl.write_debug(*args, **kargs) | |
179 | ||
c7667c2d | 180 | def slow_down(self, start_time, now, byte_counter): |
3bc2ddcc | 181 | """Sleep if the download speed is over the rate limit.""" |
d800609c | 182 | rate_limit = self.params.get('ratelimit') |
8a77e5e6 | 183 | if rate_limit is None or byte_counter == 0: |
3bc2ddcc | 184 | return |
c7667c2d S |
185 | if now is None: |
186 | now = time.time() | |
3bc2ddcc JMF |
187 | elapsed = now - start_time |
188 | if elapsed <= 0.0: | |
189 | return | |
190 | speed = float(byte_counter) / elapsed | |
8a77e5e6 | 191 | if speed > rate_limit: |
1a01639b S |
192 | sleep_time = float(byte_counter) / rate_limit - elapsed |
193 | if sleep_time > 0: | |
194 | time.sleep(sleep_time) | |
3bc2ddcc JMF |
195 | |
196 | def temp_name(self, filename): | |
197 | """Returns a temporary filename for the given filename.""" | |
b6b70730 | 198 | if self.params.get('nopart', False) or filename == '-' or \ |
3bc2ddcc JMF |
199 | (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))): |
200 | return filename | |
b6b70730 | 201 | return filename + '.part' |
3bc2ddcc JMF |
202 | |
203 | def undo_temp_name(self, filename): | |
b6b70730 PH |
204 | if filename.endswith('.part'): |
205 | return filename[:-len('.part')] | |
3bc2ddcc JMF |
206 | return filename |
207 | ||
ea0c2f21 RA |
208 | def ytdl_filename(self, filename): |
209 | return filename + '.ytdl' | |
210 | ||
3bc2ddcc | 211 | def try_rename(self, old_filename, new_filename): |
f775c831 | 212 | if old_filename == new_filename: |
213 | return | |
3bc2ddcc | 214 | try: |
d75201a8 | 215 | os.replace(old_filename, new_filename) |
3bc2ddcc | 216 | except (IOError, OSError) as err: |
d75201a8 | 217 | self.report_error(f'unable to rename file: {err}') |
3bc2ddcc JMF |
218 | |
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: | |
222 | return | |
223 | if not os.path.isfile(encodeFilename(filename)): | |
224 | return | |
225 | timestr = last_modified_hdr | |
226 | if timestr is None: | |
227 | return | |
228 | filetime = timeconvert(timestr) | |
229 | if filetime is None: | |
230 | return filetime | |
231 | # Ignore obviously invalid dates | |
232 | if filetime == 0: | |
233 | return | |
234 | try: | |
235 | os.utime(filename, (time.time(), filetime)) | |
70a1165b | 236 | except Exception: |
3bc2ddcc JMF |
237 | pass |
238 | return filetime | |
239 | ||
240 | def report_destination(self, filename): | |
241 | """Report destination filename.""" | |
b6b70730 | 242 | self.to_screen('[download] Destination: ' + filename) |
3bc2ddcc | 243 | |
819e0531 | 244 | def _prepare_multiline_status(self, lines=1): |
245 | if self.params.get('noprogress'): | |
bd50a52b | 246 | self._multiline = QuietMultilinePrinter() |
819e0531 | 247 | elif self.ydl.params.get('logger'): |
248 | self._multiline = MultilineLogger(self.ydl.params['logger'], lines) | |
249 | elif self.params.get('progress_with_newline'): | |
bd50a52b | 250 | self._multiline = BreaklineStatusPrinter(sys.stderr, lines) |
bd50a52b | 251 | else: |
819e0531 | 252 | self._multiline = MultilinePrinter(sys.stderr, lines, not self.params.get('quiet')) |
bd50a52b THD |
253 | |
254 | def _finish_multiline_status(self): | |
819e0531 | 255 | self._multiline.end() |
256 | ||
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} | |
261 | ||
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', | |
268 | progress_dict)) | |
3bc2ddcc | 269 | |
5cda4eda PH |
270 | def report_progress(self, s): |
271 | if s['status'] == 'finished': | |
819e0531 | 272 | if self.params.get('noprogress'): |
5cda4eda | 273 | self.to_screen('[download] Download completed') |
819e0531 | 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) | |
3bc2ddcc | 284 | return |
5cda4eda PH |
285 | |
286 | if s['status'] != 'downloading': | |
287 | return | |
288 | ||
289 | if s.get('eta') is not None: | |
290 | s['_eta_str'] = self.format_eta(s['eta']) | |
3bc2ddcc | 291 | else: |
5cda4eda | 292 | s['_eta_str'] = 'Unknown ETA' |
3bc2ddcc | 293 | |
5cda4eda PH |
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']) | |
298 | else: | |
299 | if s.get('downloaded_bytes') == 0: | |
300 | s['_percent_str'] = self.format_percent(0) | |
301 | else: | |
302 | s['_percent_str'] = 'Unknown %' | |
3bc2ddcc | 303 | |
5cda4eda PH |
304 | if s.get('speed') is not None: |
305 | s['_speed_str'] = self.format_speed(s['speed']) | |
306 | else: | |
307 | s['_speed_str'] = 'Unknown speed' | |
308 | ||
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' | |
3bc2ddcc | 315 | else: |
5cda4eda PH |
316 | if s.get('downloaded_bytes') is not None: |
317 | s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes']) | |
318 | if s.get('elapsed'): | |
319 | s['_elapsed_str'] = self.format_seconds(s['elapsed']) | |
320 | msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)' | |
321 | else: | |
322 | msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s' | |
323 | else: | |
324 | msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s' | |
819e0531 | 325 | s['_default_template'] = msg_template % s |
326 | self._report_progress_status(s) | |
3bc2ddcc JMF |
327 | |
328 | def report_resuming_byte(self, resume_len): | |
329 | """Report attempt to resume at given byte.""" | |
b6b70730 | 330 | self.to_screen('[download] Resuming download at byte %s' % resume_len) |
3bc2ddcc | 331 | |
a3c3a1e1 | 332 | def report_retry(self, err, count, retries): |
3bc2ddcc | 333 | """Report retry in case of HTTP error 5xx""" |
617e58d8 | 334 | self.to_screen( |
5ef7d9bd | 335 | '[download] Got server HTTP error: %s. Retrying (attempt %d of %s) ...' |
a3c3a1e1 | 336 | % (error_to_compat_str(err), count, self.format_retries(retries))) |
3bc2ddcc | 337 | |
b868936c | 338 | def report_file_already_downloaded(self, *args, **kwargs): |
3bc2ddcc | 339 | """Report file has already been fully downloaded.""" |
b868936c | 340 | return self.ydl.report_file_already_downloaded(*args, **kwargs) |
3bc2ddcc JMF |
341 | |
342 | def report_unable_to_resume(self): | |
343 | """Report it was impossible to resume download.""" | |
b6b70730 | 344 | self.to_screen('[download] Unable to resume') |
3bc2ddcc | 345 | |
0a473f2f | 346 | @staticmethod |
347 | def supports_manifest(manifest): | |
348 | """ Whether the downloader can download the fragments from the manifest. | |
349 | Redefine in subclasses if needed. """ | |
350 | pass | |
351 | ||
9f448fcb | 352 | def download(self, filename, info_dict, subtitle=False): |
3bc2ddcc JMF |
353 | """Download to a filename using the info from info_dict |
354 | Return True on success and False otherwise | |
355 | """ | |
5f0d813d | 356 | |
4340deca | 357 | nooverwrites_and_exists = ( |
9cc1a313 | 358 | not self.params.get('overwrites', True) |
3089bc74 | 359 | and os.path.exists(encodeFilename(filename)) |
4340deca P |
360 | ) |
361 | ||
75a24854 RA |
362 | if not hasattr(filename, 'write'): |
363 | continuedl_and_exists = ( | |
3089bc74 S |
364 | self.params.get('continuedl', True) |
365 | and os.path.isfile(encodeFilename(filename)) | |
366 | and not self.params.get('nopart', False) | |
75a24854 RA |
367 | ) |
368 | ||
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)), | |
3ba7740d | 376 | }, info_dict) |
a9e7f546 | 377 | return True, False |
dabc1273 | 378 | |
9f448fcb U |
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) | |
384 | self.to_screen( | |
5ef7d9bd | 385 | '[download] Sleeping %s seconds ...' % ( |
9f448fcb U |
386 | int(sleep_interval) if sleep_interval.is_integer() |
387 | else '%.2f' % sleep_interval)) | |
388 | time.sleep(sleep_interval) | |
389 | else: | |
b860e4cc NS |
390 | sleep_interval_sub = 0 |
391 | if type(self.params.get('sleep_interval_subtitles')) is int: | |
31108ce9 | 392 | sleep_interval_sub = self.params.get('sleep_interval_subtitles') |
b860e4cc | 393 | if sleep_interval_sub > 0: |
31108ce9 | 394 | self.to_screen( |
5ef7d9bd | 395 | '[download] Sleeping %s seconds ...' % ( |
31108ce9 U |
396 | sleep_interval_sub)) |
397 | time.sleep(sleep_interval_sub) | |
819e0531 | 398 | ret = self.real_download(filename, info_dict) |
399 | self._finish_multiline_status() | |
400 | return ret, True | |
3bc2ddcc JMF |
401 | |
402 | def real_download(self, filename, info_dict): | |
403 | """Real download process. Redefine in subclasses.""" | |
b6b70730 | 404 | raise NotImplementedError('This method must be implemented by subclasses') |
3bc2ddcc | 405 | |
3ba7740d | 406 | def _hook_progress(self, status, info_dict): |
407 | if not self._progress_hooks: | |
408 | return | |
409 | info_dict = dict(info_dict) | |
410 | for key in ('__original_infodict', '__postprocessors'): | |
411 | info_dict.pop(key, None) | |
f45e6c11 | 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) | |
3bc2ddcc | 416 | for ph in self._progress_hooks: |
f45e6c11 | 417 | ph(status) |
3bc2ddcc JMF |
418 | |
419 | def add_progress_hook(self, ph): | |
71b640cc PH |
420 | # See YoutubeDl.py (search for progress_hooks) for a description of |
421 | # this interface | |
3bc2ddcc | 422 | self._progress_hooks.append(ph) |
222516d9 | 423 | |
cd8a07a7 | 424 | def _debug_cmd(self, args, exe=None): |
222516d9 PH |
425 | if not self.params.get('verbose', False): |
426 | return | |
427 | ||
cd8a07a7 S |
428 | str_args = [decodeArgument(a) for a in args] |
429 | ||
222516d9 | 430 | if exe is None: |
cd8a07a7 | 431 | exe = os.path.basename(str_args[0]) |
222516d9 | 432 | |
0760b0a7 | 433 | self.write_debug('%s command line: %s' % (exe, shell_quote(str_args))) |