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