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