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