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