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