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