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