]>
Commit | Line | Data |
---|---|---|
5cda4eda | 1 | from __future__ import division, unicode_literals |
b6b70730 | 2 | |
3bc2ddcc JMF |
3 | import os |
4 | import re | |
3bc2ddcc JMF |
5 | import sys |
6 | import time | |
7 | ||
e9c0cdd3 | 8 | from ..compat import compat_os_name |
3bc2ddcc JMF |
9 | from ..utils import ( |
10 | encodeFilename, | |
9b9c5355 | 11 | error_to_compat_str, |
cd8a07a7 | 12 | decodeArgument, |
3bc2ddcc | 13 | format_bytes, |
e3ced9ed | 14 | timeconvert, |
3bc2ddcc JMF |
15 | ) |
16 | ||
17 | ||
18 | class FileDownloader(object): | |
19 | """File Downloader class. | |
20 | ||
21 | File downloader objects are the ones responsible of downloading the | |
22 | actual video file and writing it to disk. | |
23 | ||
24 | File downloaders accept a lot of parameters. In order not to saturate | |
25 | the object constructor with arguments, it receives a dictionary of | |
26 | options instead. | |
27 | ||
28 | Available options: | |
29 | ||
881e6a1f PH |
30 | verbose: Print additional info to stdout. |
31 | quiet: Do not print messages to stdout. | |
32 | ratelimit: Download speed limit, in bytes/sec. | |
33 | retries: Number of times to retry for HTTP error 5xx | |
34 | buffersize: Size of download buffer in bytes. | |
35 | noresizebuffer: Do not automatically resize the download buffer. | |
36 | continuedl: Try to continue downloads if possible. | |
37 | noprogress: Do not print the progress bar. | |
38 | logtostderr: Log messages to stderr instead of stdout. | |
39 | consoletitle: Display progress in console window's titlebar. | |
40 | nopart: Do not use temporary .part files. | |
41 | updatetime: Use the Last-modified header to set output file timestamps. | |
42 | test: Download only first bytes to test the downloader. | |
43 | min_filesize: Skip files smaller than this size | |
44 | max_filesize: Skip files larger than this size | |
45 | xattr_set_filesize: Set ytdl.filesize user xattribute with expected size. | |
17cc1534 | 46 | (experimental) |
c75f0b36 PH |
47 | external_downloader_args: A list of additional command-line arguments for the |
48 | external downloader. | |
7d106a65 | 49 | hls_use_mpegts: Use the mpegts container for HLS videos. |
3bc2ddcc JMF |
50 | |
51 | Subclasses of this one must re-define the real_download method. | |
52 | """ | |
53 | ||
b686fc18 | 54 | _TEST_FILE_SIZE = 10241 |
3bc2ddcc JMF |
55 | params = None |
56 | ||
57 | def __init__(self, ydl, params): | |
58 | """Create a FileDownloader object with the given options.""" | |
59 | self.ydl = ydl | |
60 | self._progress_hooks = [] | |
61 | self.params = params | |
5cda4eda | 62 | self.add_progress_hook(self.report_progress) |
3bc2ddcc JMF |
63 | |
64 | @staticmethod | |
65 | def format_seconds(seconds): | |
66 | (mins, secs) = divmod(seconds, 60) | |
67 | (hours, mins) = divmod(mins, 60) | |
68 | if hours > 99: | |
69 | return '--:--:--' | |
70 | if hours == 0: | |
71 | return '%02d:%02d' % (mins, secs) | |
72 | else: | |
73 | return '%02d:%02d:%02d' % (hours, mins, secs) | |
74 | ||
75 | @staticmethod | |
76 | def calc_percent(byte_counter, data_len): | |
77 | if data_len is None: | |
78 | return None | |
79 | return float(byte_counter) / float(data_len) * 100.0 | |
80 | ||
81 | @staticmethod | |
82 | def format_percent(percent): | |
83 | if percent is None: | |
84 | return '---.-%' | |
85 | return '%6s' % ('%3.1f%%' % percent) | |
86 | ||
87 | @staticmethod | |
88 | def calc_eta(start, now, total, current): | |
89 | if total is None: | |
90 | return None | |
c7667c2d S |
91 | if now is None: |
92 | now = time.time() | |
3bc2ddcc | 93 | dif = now - start |
5f6a1245 | 94 | if current == 0 or dif < 0.001: # One millisecond |
3bc2ddcc JMF |
95 | return None |
96 | rate = float(current) / dif | |
97 | return int((float(total) - float(current)) / rate) | |
98 | ||
99 | @staticmethod | |
100 | def format_eta(eta): | |
101 | if eta is None: | |
102 | return '--:--' | |
103 | return FileDownloader.format_seconds(eta) | |
104 | ||
105 | @staticmethod | |
106 | def calc_speed(start, now, bytes): | |
107 | dif = now - start | |
5f6a1245 | 108 | if bytes == 0 or dif < 0.001: # One millisecond |
3bc2ddcc JMF |
109 | return None |
110 | return float(bytes) / dif | |
111 | ||
112 | @staticmethod | |
113 | def format_speed(speed): | |
114 | if speed is None: | |
115 | return '%10s' % '---b/s' | |
116 | return '%10s' % ('%s/s' % format_bytes(speed)) | |
117 | ||
118 | @staticmethod | |
119 | def best_block_size(elapsed_time, bytes): | |
120 | new_min = max(bytes / 2.0, 1.0) | |
5f6a1245 | 121 | new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB |
3bc2ddcc JMF |
122 | if elapsed_time < 0.001: |
123 | return int(new_max) | |
124 | rate = bytes / elapsed_time | |
125 | if rate > new_max: | |
126 | return int(new_max) | |
127 | if rate < new_min: | |
128 | return int(new_min) | |
129 | return int(rate) | |
130 | ||
131 | @staticmethod | |
132 | def parse_bytes(bytestr): | |
133 | """Parse a string indicating a byte quantity into an integer.""" | |
134 | matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr) | |
135 | if matchobj is None: | |
136 | return None | |
137 | number = float(matchobj.group(1)) | |
138 | multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower()) | |
139 | return int(round(number * multiplier)) | |
140 | ||
141 | def to_screen(self, *args, **kargs): | |
142 | self.ydl.to_screen(*args, **kargs) | |
143 | ||
144 | def to_stderr(self, message): | |
145 | self.ydl.to_screen(message) | |
146 | ||
147 | def to_console_title(self, message): | |
148 | self.ydl.to_console_title(message) | |
149 | ||
150 | def trouble(self, *args, **kargs): | |
151 | self.ydl.trouble(*args, **kargs) | |
152 | ||
153 | def report_warning(self, *args, **kargs): | |
154 | self.ydl.report_warning(*args, **kargs) | |
155 | ||
156 | def report_error(self, *args, **kargs): | |
157 | self.ydl.report_error(*args, **kargs) | |
158 | ||
c7667c2d | 159 | def slow_down(self, start_time, now, byte_counter): |
3bc2ddcc | 160 | """Sleep if the download speed is over the rate limit.""" |
d800609c | 161 | rate_limit = self.params.get('ratelimit') |
3bc2ddcc JMF |
162 | if rate_limit is None or byte_counter == 0: |
163 | return | |
c7667c2d S |
164 | if now is None: |
165 | now = time.time() | |
3bc2ddcc JMF |
166 | elapsed = now - start_time |
167 | if elapsed <= 0.0: | |
168 | return | |
169 | speed = float(byte_counter) / elapsed | |
170 | if speed > rate_limit: | |
cc8c9281 | 171 | time.sleep(max((byte_counter // rate_limit) - elapsed, 0)) |
3bc2ddcc JMF |
172 | |
173 | def temp_name(self, filename): | |
174 | """Returns a temporary filename for the given filename.""" | |
b6b70730 | 175 | if self.params.get('nopart', False) or filename == '-' or \ |
3bc2ddcc JMF |
176 | (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))): |
177 | return filename | |
b6b70730 | 178 | return filename + '.part' |
3bc2ddcc JMF |
179 | |
180 | def undo_temp_name(self, filename): | |
b6b70730 PH |
181 | if filename.endswith('.part'): |
182 | return filename[:-len('.part')] | |
3bc2ddcc JMF |
183 | return filename |
184 | ||
185 | def try_rename(self, old_filename, new_filename): | |
186 | try: | |
187 | if old_filename == new_filename: | |
188 | return | |
189 | os.rename(encodeFilename(old_filename), encodeFilename(new_filename)) | |
190 | except (IOError, OSError) as err: | |
9b9c5355 | 191 | self.report_error('unable to rename file: %s' % error_to_compat_str(err)) |
3bc2ddcc JMF |
192 | |
193 | def try_utime(self, filename, last_modified_hdr): | |
194 | """Try to set the last-modified time of the given file.""" | |
195 | if last_modified_hdr is None: | |
196 | return | |
197 | if not os.path.isfile(encodeFilename(filename)): | |
198 | return | |
199 | timestr = last_modified_hdr | |
200 | if timestr is None: | |
201 | return | |
202 | filetime = timeconvert(timestr) | |
203 | if filetime is None: | |
204 | return filetime | |
205 | # Ignore obviously invalid dates | |
206 | if filetime == 0: | |
207 | return | |
208 | try: | |
209 | os.utime(filename, (time.time(), filetime)) | |
70a1165b | 210 | except Exception: |
3bc2ddcc JMF |
211 | pass |
212 | return filetime | |
213 | ||
214 | def report_destination(self, filename): | |
215 | """Report destination filename.""" | |
b6b70730 | 216 | self.to_screen('[download] Destination: ' + filename) |
3bc2ddcc JMF |
217 | |
218 | def _report_progress_status(self, msg, is_last_line=False): | |
b6b70730 | 219 | fullmsg = '[download] ' + msg |
3bc2ddcc JMF |
220 | if self.params.get('progress_with_newline', False): |
221 | self.to_screen(fullmsg) | |
222 | else: | |
e9c0cdd3 | 223 | if compat_os_name == 'nt': |
3bc2ddcc JMF |
224 | prev_len = getattr(self, '_report_progress_prev_line_length', |
225 | 0) | |
226 | if prev_len > len(fullmsg): | |
b6b70730 | 227 | fullmsg += ' ' * (prev_len - len(fullmsg)) |
3bc2ddcc | 228 | self._report_progress_prev_line_length = len(fullmsg) |
b6b70730 | 229 | clear_line = '\r' |
3bc2ddcc | 230 | else: |
b6b70730 | 231 | clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r') |
3bc2ddcc | 232 | self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line) |
b6b70730 | 233 | self.to_console_title('youtube-dl ' + msg) |
3bc2ddcc | 234 | |
5cda4eda PH |
235 | def report_progress(self, s): |
236 | if s['status'] == 'finished': | |
237 | if self.params.get('noprogress', False): | |
238 | self.to_screen('[download] Download completed') | |
239 | else: | |
240 | s['_total_bytes_str'] = format_bytes(s['total_bytes']) | |
241 | if s.get('elapsed') is not None: | |
242 | s['_elapsed_str'] = self.format_seconds(s['elapsed']) | |
243 | msg_template = '100%% of %(_total_bytes_str)s in %(_elapsed_str)s' | |
244 | else: | |
245 | msg_template = '100%% of %(_total_bytes_str)s' | |
246 | self._report_progress_status( | |
247 | msg_template % s, is_last_line=True) | |
248 | ||
249 | if self.params.get('noprogress'): | |
3bc2ddcc | 250 | return |
5cda4eda PH |
251 | |
252 | if s['status'] != 'downloading': | |
253 | return | |
254 | ||
255 | if s.get('eta') is not None: | |
256 | s['_eta_str'] = self.format_eta(s['eta']) | |
3bc2ddcc | 257 | else: |
5cda4eda | 258 | s['_eta_str'] = 'Unknown ETA' |
3bc2ddcc | 259 | |
5cda4eda PH |
260 | if s.get('total_bytes') and s.get('downloaded_bytes') is not None: |
261 | s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes']) | |
262 | elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None: | |
263 | s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate']) | |
264 | else: | |
265 | if s.get('downloaded_bytes') == 0: | |
266 | s['_percent_str'] = self.format_percent(0) | |
267 | else: | |
268 | s['_percent_str'] = 'Unknown %' | |
3bc2ddcc | 269 | |
5cda4eda PH |
270 | if s.get('speed') is not None: |
271 | s['_speed_str'] = self.format_speed(s['speed']) | |
272 | else: | |
273 | s['_speed_str'] = 'Unknown speed' | |
274 | ||
275 | if s.get('total_bytes') is not None: | |
276 | s['_total_bytes_str'] = format_bytes(s['total_bytes']) | |
277 | msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s' | |
278 | elif s.get('total_bytes_estimate') is not None: | |
279 | s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate']) | |
280 | msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s' | |
3bc2ddcc | 281 | else: |
5cda4eda PH |
282 | if s.get('downloaded_bytes') is not None: |
283 | s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes']) | |
284 | if s.get('elapsed'): | |
285 | s['_elapsed_str'] = self.format_seconds(s['elapsed']) | |
286 | msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)' | |
287 | else: | |
288 | msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s' | |
289 | else: | |
290 | msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s' | |
291 | ||
292 | self._report_progress_status(msg_template % s) | |
3bc2ddcc JMF |
293 | |
294 | def report_resuming_byte(self, resume_len): | |
295 | """Report attempt to resume at given byte.""" | |
b6b70730 | 296 | self.to_screen('[download] Resuming download at byte %s' % resume_len) |
3bc2ddcc JMF |
297 | |
298 | def report_retry(self, count, retries): | |
299 | """Report retry in case of HTTP error 5xx""" | |
32d77eeb | 300 | self.to_screen('[download] Got server HTTP error. Retrying (attempt %d of %.0f)...' % (count, retries)) |
3bc2ddcc JMF |
301 | |
302 | def report_file_already_downloaded(self, file_name): | |
303 | """Report file has already been fully downloaded.""" | |
304 | try: | |
b6b70730 | 305 | self.to_screen('[download] %s has already been downloaded' % file_name) |
3bc2ddcc | 306 | except UnicodeEncodeError: |
b6b70730 | 307 | self.to_screen('[download] The file has already been downloaded') |
3bc2ddcc JMF |
308 | |
309 | def report_unable_to_resume(self): | |
310 | """Report it was impossible to resume download.""" | |
b6b70730 | 311 | self.to_screen('[download] Unable to resume') |
3bc2ddcc JMF |
312 | |
313 | def download(self, filename, info_dict): | |
314 | """Download to a filename using the info from info_dict | |
315 | Return True on success and False otherwise | |
316 | """ | |
5f0d813d | 317 | |
4340deca | 318 | nooverwrites_and_exists = ( |
8fb3ac36 PH |
319 | self.params.get('nooverwrites', False) and |
320 | os.path.exists(encodeFilename(filename)) | |
4340deca P |
321 | ) |
322 | ||
323 | continuedl_and_exists = ( | |
c59e701e | 324 | self.params.get('continuedl', True) and |
8fb3ac36 PH |
325 | os.path.isfile(encodeFilename(filename)) and |
326 | not self.params.get('nopart', False) | |
4340deca P |
327 | ) |
328 | ||
3bc2ddcc | 329 | # Check file already present |
964e7b2d | 330 | if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists): |
3bc2ddcc JMF |
331 | self.report_file_already_downloaded(filename) |
332 | self._hook_progress({ | |
333 | 'filename': filename, | |
334 | 'status': 'finished', | |
335 | 'total_bytes': os.path.getsize(encodeFilename(filename)), | |
336 | }) | |
337 | return True | |
dabc1273 | 338 | |
5f0d813d PH |
339 | sleep_interval = self.params.get('sleep_interval') |
340 | if sleep_interval: | |
341 | self.to_screen('[download] Sleeping %s seconds...' % sleep_interval) | |
342 | time.sleep(sleep_interval) | |
343 | ||
dabc1273 | 344 | return self.real_download(filename, info_dict) |
3bc2ddcc JMF |
345 | |
346 | def real_download(self, filename, info_dict): | |
347 | """Real download process. Redefine in subclasses.""" | |
b6b70730 | 348 | raise NotImplementedError('This method must be implemented by subclasses') |
3bc2ddcc JMF |
349 | |
350 | def _hook_progress(self, status): | |
351 | for ph in self._progress_hooks: | |
352 | ph(status) | |
353 | ||
354 | def add_progress_hook(self, ph): | |
71b640cc PH |
355 | # See YoutubeDl.py (search for progress_hooks) for a description of |
356 | # this interface | |
3bc2ddcc | 357 | self._progress_hooks.append(ph) |
222516d9 | 358 | |
cd8a07a7 | 359 | def _debug_cmd(self, args, exe=None): |
222516d9 PH |
360 | if not self.params.get('verbose', False): |
361 | return | |
362 | ||
cd8a07a7 S |
363 | str_args = [decodeArgument(a) for a in args] |
364 | ||
222516d9 | 365 | if exe is None: |
cd8a07a7 | 366 | exe = os.path.basename(str_args[0]) |
222516d9 | 367 | |
222516d9 PH |
368 | try: |
369 | import pipes | |
370 | shell_quote = lambda args: ' '.join(map(pipes.quote, str_args)) | |
371 | except ImportError: | |
372 | shell_quote = repr | |
373 | self.to_screen('[debug] %s command line: %s' % ( | |
374 | exe, shell_quote(str_args))) |