]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/common.py
de6b9311d59b3a270cc0a7dc58d05b4f0692e896
1 from __future__
import unicode_literals
8 from ..compat
import compat_str
16 class FileDownloader(object):
17 """File Downloader class.
19 File downloader objects are the ones responsible of downloading the
20 actual video file and writing it to disk.
22 File downloaders accept a lot of parameters. In order not to saturate
23 the object constructor with arguments, it receives a dictionary of
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
44 Subclasses of this one must re-define the real_download method.
47 _TEST_FILE_SIZE
= 10241
50 def __init__(self
, ydl
, params
):
51 """Create a FileDownloader object with the given options."""
53 self
._progress
_hooks
= []
57 def format_seconds(seconds
):
58 (mins
, secs
) = divmod(seconds
, 60)
59 (hours
, mins
) = divmod(mins
, 60)
63 return '%02d:%02d' % (mins
, secs
)
65 return '%02d:%02d:%02d' % (hours
, mins
, secs
)
68 def calc_percent(byte_counter
, data_len
):
71 return float(byte_counter
) / float(data_len
) * 100.0
74 def format_percent(percent
):
77 return '%6s' % ('%3.1f%%' % percent
)
80 def calc_eta(start
, now
, total
, current
):
86 if current
== 0 or dif
< 0.001: # One millisecond
88 rate
= float(current
) / dif
89 return int((float(total
) - float(current
)) / rate
)
95 return FileDownloader
.format_seconds(eta
)
98 def calc_speed(start
, now
, bytes):
100 if bytes == 0 or dif
< 0.001: # One millisecond
102 return float(bytes) / dif
105 def format_speed(speed
):
107 return '%10s' % '---b/s'
108 return '%10s' % ('%s/s' % format_bytes(speed
))
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:
116 rate
= bytes / elapsed_time
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
)
129 number
= float(matchobj
.group(1))
130 multiplier
= 1024.0 ** 'bkmgtpezy'.index(matchobj
.group(2).lower())
131 return int(round(number
* multiplier
))
133 def to_screen(self
, *args
, **kargs
):
134 self
.ydl
.to_screen(*args
, **kargs
)
136 def to_stderr(self
, message
):
137 self
.ydl
.to_screen(message
)
139 def to_console_title(self
, message
):
140 self
.ydl
.to_console_title(message
)
142 def trouble(self
, *args
, **kargs
):
143 self
.ydl
.trouble(*args
, **kargs
)
145 def report_warning(self
, *args
, **kargs
):
146 self
.ydl
.report_warning(*args
, **kargs
)
148 def report_error(self
, *args
, **kargs
):
149 self
.ydl
.report_error(*args
, **kargs
)
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:
158 elapsed
= now
- start_time
161 speed
= float(byte_counter
) / elapsed
162 if speed
> rate_limit
:
163 time
.sleep(max((byte_counter
// rate_limit
) - elapsed
, 0))
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
))):
170 return filename
+ '.part'
172 def undo_temp_name(self
, filename
):
173 if filename
.endswith('.part'):
174 return filename
[:-len('.part')]
177 def try_rename(self
, old_filename
, new_filename
):
179 if old_filename
== new_filename
:
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
))
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:
189 if not os
.path
.isfile(encodeFilename(filename
)):
191 timestr
= last_modified_hdr
194 filetime
= timeconvert(timestr
)
197 # Ignore obviously invalid dates
201 os
.utime(filename
, (time
.time(), filetime
))
206 def report_destination(self
, filename
):
207 """Report destination filename."""
208 self
.to_screen('[download] Destination: ' + filename
)
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
)
216 prev_len
= getattr(self
, '_report_progress_prev_line_length',
218 if prev_len
> len(fullmsg
):
219 fullmsg
+= ' ' * (prev_len
- len(fullmsg
))
220 self
._report
_progress
_prev
_line
_length
= len(fullmsg
)
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
)
227 def report_progress(self
, percent
, data_len_str
, speed
, eta
):
228 """Report download progress."""
229 if self
.params
.get('noprogress', False):
232 eta_str
= self
.format_eta(eta
)
234 eta_str
= 'Unknown ETA'
235 if percent
is not None:
236 percent_str
= self
.format_percent(percent
)
238 percent_str
= 'Unknown %'
239 speed_str
= self
.format_speed(speed
)
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
)
245 def report_progress_live_stream(self
, downloaded_data_len
, speed
, elapsed
):
246 if self
.params
.get('noprogress', False):
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
)
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')
259 self
._report
_progress
_status
(
260 ('100%% of %s in %s' %
261 (data_len_str
, self
.format_seconds(tot_time
))),
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
)
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
))
272 def report_file_already_downloaded(self
, file_name
):
273 """Report file has already been fully downloaded."""
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')
279 def report_unable_to_resume(self
):
280 """Report it was impossible to resume download."""
281 self
.to_screen('[download] Unable to resume')
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
287 nooverwrites_and_exists
= (
288 self
.params
.get('nooverwrites', False)
289 and os
.path
.exists(encodeFilename(filename
))
292 continuedl_and_exists
= (
293 self
.params
.get('continuedl', False)
294 and os
.path
.isfile(encodeFilename(filename
))
295 and not self
.params
.get('nopart', False)
298 # Check file already present
299 if filename
!= '-' and nooverwrites_and_exists
or continuedl_and_exists
:
300 self
.report_file_already_downloaded(filename
)
301 self
._hook
_progress
({
302 'filename': filename
,
303 'status': 'finished',
304 'total_bytes': os
.path
.getsize(encodeFilename(filename
)),
308 return self
.real_download(filename
, info_dict
)
310 def real_download(self
, filename
, info_dict
):
311 """Real download process. Redefine in subclasses."""
312 raise NotImplementedError('This method must be implemented by subclasses')
314 def _hook_progress(self
, status
):
315 for ph
in self
._progress
_hooks
:
318 def add_progress_hook(self
, ph
):
319 # See YoutubeDl.py (search for progress_hooks) for a description of
321 self
._progress
_hooks
.append(ph
)