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