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