]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/common.py
2d51540518f7ee40c7d002d632007d5aa9542697
1 from __future__
import division
, unicode_literals
17 class FileDownloader(object):
18 """File Downloader class.
20 File downloader objects are the ones responsible of downloading the
21 actual video file and writing it to disk.
23 File downloaders accept a lot of parameters. In order not to saturate
24 the object constructor with arguments, it receives a dictionary of
29 verbose: Print additional info to stdout.
30 quiet: Do not print messages to stdout.
31 ratelimit: Download speed limit, in bytes/sec.
32 retries: Number of times to retry for HTTP error 5xx
33 buffersize: Size of download buffer in bytes.
34 noresizebuffer: Do not automatically resize the download buffer.
35 continuedl: Try to continue downloads if possible.
36 noprogress: Do not print the progress bar.
37 logtostderr: Log messages to stderr instead of stdout.
38 consoletitle: Display progress in console window's titlebar.
39 nopart: Do not use temporary .part files.
40 updatetime: Use the Last-modified header to set output file timestamps.
41 test: Download only first bytes to test the downloader.
42 min_filesize: Skip files smaller than this size
43 max_filesize: Skip files larger than this size
44 xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
46 external_downloader_args: A list of additional command-line arguments for the
48 hls_use_mpegts: Use the mpegts container for HLS videos.
50 Subclasses of this one must re-define the real_download method.
53 _TEST_FILE_SIZE
= 10241
56 def __init__(self
, ydl
, params
):
57 """Create a FileDownloader object with the given options."""
59 self
._progress
_hooks
= []
61 self
.add_progress_hook(self
.report_progress
)
64 def format_seconds(seconds
):
65 (mins
, secs
) = divmod(seconds
, 60)
66 (hours
, mins
) = divmod(mins
, 60)
70 return '%02d:%02d' % (mins
, secs
)
72 return '%02d:%02d:%02d' % (hours
, mins
, secs
)
75 def calc_percent(byte_counter
, data_len
):
78 return float(byte_counter
) / float(data_len
) * 100.0
81 def format_percent(percent
):
84 return '%6s' % ('%3.1f%%' % percent
)
87 def calc_eta(start
, now
, total
, current
):
93 if current
== 0 or dif
< 0.001: # One millisecond
95 rate
= float(current
) / dif
96 return int((float(total
) - float(current
)) / rate
)
102 return FileDownloader
.format_seconds(eta
)
105 def calc_speed(start
, now
, bytes):
107 if bytes == 0 or dif
< 0.001: # One millisecond
109 return float(bytes) / dif
112 def format_speed(speed
):
114 return '%10s' % '---b/s'
115 return '%10s' % ('%s/s' % format_bytes(speed
))
118 def best_block_size(elapsed_time
, bytes):
119 new_min
= max(bytes / 2.0, 1.0)
120 new_max
= min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
121 if elapsed_time
< 0.001:
123 rate
= bytes / elapsed_time
131 def parse_bytes(bytestr
):
132 """Parse a string indicating a byte quantity into an integer."""
133 matchobj
= re
.match(r
'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr
)
136 number
= float(matchobj
.group(1))
137 multiplier
= 1024.0 ** 'bkmgtpezy'.index(matchobj
.group(2).lower())
138 return int(round(number
* multiplier
))
140 def to_screen(self
, *args
, **kargs
):
141 self
.ydl
.to_screen(*args
, **kargs
)
143 def to_stderr(self
, message
):
144 self
.ydl
.to_screen(message
)
146 def to_console_title(self
, message
):
147 self
.ydl
.to_console_title(message
)
149 def trouble(self
, *args
, **kargs
):
150 self
.ydl
.trouble(*args
, **kargs
)
152 def report_warning(self
, *args
, **kargs
):
153 self
.ydl
.report_warning(*args
, **kargs
)
155 def report_error(self
, *args
, **kargs
):
156 self
.ydl
.report_error(*args
, **kargs
)
158 def slow_down(self
, start_time
, now
, byte_counter
):
159 """Sleep if the download speed is over the rate limit."""
160 rate_limit
= self
.params
.get('ratelimit')
161 if rate_limit
is None or byte_counter
== 0:
165 elapsed
= now
- start_time
168 speed
= float(byte_counter
) / elapsed
169 if speed
> rate_limit
:
170 time
.sleep(max((byte_counter
// rate_limit
) - elapsed
, 0))
172 def temp_name(self
, filename
):
173 """Returns a temporary filename for the given filename."""
174 if self
.params
.get('nopart', False) or filename
== '-' or \
175 (os
.path
.exists(encodeFilename(filename
)) and not os
.path
.isfile(encodeFilename(filename
))):
177 return filename
+ '.part'
179 def undo_temp_name(self
, filename
):
180 if filename
.endswith('.part'):
181 return filename
[:-len('.part')]
184 def try_rename(self
, old_filename
, new_filename
):
186 if old_filename
== new_filename
:
188 os
.rename(encodeFilename(old_filename
), encodeFilename(new_filename
))
189 except (IOError, OSError) as err
:
190 self
.report_error('unable to rename file: %s' % error_to_compat_str(err
))
192 def try_utime(self
, filename
, last_modified_hdr
):
193 """Try to set the last-modified time of the given file."""
194 if last_modified_hdr
is None:
196 if not os
.path
.isfile(encodeFilename(filename
)):
198 timestr
= last_modified_hdr
201 filetime
= timeconvert(timestr
)
204 # Ignore obviously invalid dates
208 os
.utime(filename
, (time
.time(), filetime
))
213 def report_destination(self
, filename
):
214 """Report destination filename."""
215 self
.to_screen('[download] Destination: ' + filename
)
217 def _report_progress_status(self
, msg
, is_last_line
=False):
218 fullmsg
= '[download] ' + msg
219 if self
.params
.get('progress_with_newline', False):
220 self
.to_screen(fullmsg
)
223 prev_len
= getattr(self
, '_report_progress_prev_line_length',
225 if prev_len
> len(fullmsg
):
226 fullmsg
+= ' ' * (prev_len
- len(fullmsg
))
227 self
._report
_progress
_prev
_line
_length
= len(fullmsg
)
230 clear_line
= ('\r\x1b[K' if sys
.stderr
.isatty() else '\r')
231 self
.to_screen(clear_line
+ fullmsg
, skip_eol
=not is_last_line
)
232 self
.to_console_title('youtube-dl ' + msg
)
234 def report_progress(self
, s
):
235 if s
['status'] == 'finished':
236 if self
.params
.get('noprogress', False):
237 self
.to_screen('[download] Download completed')
239 s
['_total_bytes_str'] = format_bytes(s
['total_bytes'])
240 if s
.get('elapsed') is not None:
241 s
['_elapsed_str'] = self
.format_seconds(s
['elapsed'])
242 msg_template
= '100%% of %(_total_bytes_str)s in %(_elapsed_str)s'
244 msg_template
= '100%% of %(_total_bytes_str)s'
245 self
._report
_progress
_status
(
246 msg_template
% s
, is_last_line
=True)
248 if self
.params
.get('noprogress'):
251 if s
['status'] != 'downloading':
254 if s
.get('eta') is not None:
255 s
['_eta_str'] = self
.format_eta(s
['eta'])
257 s
['_eta_str'] = 'Unknown ETA'
259 if s
.get('total_bytes') and s
.get('downloaded_bytes') is not None:
260 s
['_percent_str'] = self
.format_percent(100 * s
['downloaded_bytes'] / s
['total_bytes'])
261 elif s
.get('total_bytes_estimate') and s
.get('downloaded_bytes') is not None:
262 s
['_percent_str'] = self
.format_percent(100 * s
['downloaded_bytes'] / s
['total_bytes_estimate'])
264 if s
.get('downloaded_bytes') == 0:
265 s
['_percent_str'] = self
.format_percent(0)
267 s
['_percent_str'] = 'Unknown %'
269 if s
.get('speed') is not None:
270 s
['_speed_str'] = self
.format_speed(s
['speed'])
272 s
['_speed_str'] = 'Unknown speed'
274 if s
.get('total_bytes') is not None:
275 s
['_total_bytes_str'] = format_bytes(s
['total_bytes'])
276 msg_template
= '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s'
277 elif s
.get('total_bytes_estimate') is not None:
278 s
['_total_bytes_estimate_str'] = format_bytes(s
['total_bytes_estimate'])
279 msg_template
= '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s'
281 if s
.get('downloaded_bytes') is not None:
282 s
['_downloaded_bytes_str'] = format_bytes(s
['downloaded_bytes'])
284 s
['_elapsed_str'] = self
.format_seconds(s
['elapsed'])
285 msg_template
= '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)'
287 msg_template
= '%(_downloaded_bytes_str)s at %(_speed_str)s'
289 msg_template
= '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s'
291 self
._report
_progress
_status
(msg_template
% s
)
293 def report_resuming_byte(self
, resume_len
):
294 """Report attempt to resume at given byte."""
295 self
.to_screen('[download] Resuming download at byte %s' % resume_len
)
297 def report_retry(self
, count
, retries
):
298 """Report retry in case of HTTP error 5xx"""
299 self
.to_screen('[download] Got server HTTP error. Retrying (attempt %d of %.0f)...' % (count
, retries
))
301 def report_file_already_downloaded(self
, file_name
):
302 """Report file has already been fully downloaded."""
304 self
.to_screen('[download] %s has already been downloaded' % file_name
)
305 except UnicodeEncodeError:
306 self
.to_screen('[download] The file has already been downloaded')
308 def report_unable_to_resume(self
):
309 """Report it was impossible to resume download."""
310 self
.to_screen('[download] Unable to resume')
312 def download(self
, filename
, info_dict
):
313 """Download to a filename using the info from info_dict
314 Return True on success and False otherwise
317 nooverwrites_and_exists
= (
318 self
.params
.get('nooverwrites', False) and
319 os
.path
.exists(encodeFilename(filename
))
322 continuedl_and_exists
= (
323 self
.params
.get('continuedl', True) and
324 os
.path
.isfile(encodeFilename(filename
)) and
325 not self
.params
.get('nopart', False)
328 # Check file already present
329 if filename
!= '-' and (nooverwrites_and_exists
or continuedl_and_exists
):
330 self
.report_file_already_downloaded(filename
)
331 self
._hook
_progress
({
332 'filename': filename
,
333 'status': 'finished',
334 'total_bytes': os
.path
.getsize(encodeFilename(filename
)),
338 sleep_interval
= self
.params
.get('sleep_interval')
340 self
.to_screen('[download] Sleeping %s seconds...' % sleep_interval
)
341 time
.sleep(sleep_interval
)
343 return self
.real_download(filename
, info_dict
)
345 def real_download(self
, filename
, info_dict
):
346 """Real download process. Redefine in subclasses."""
347 raise NotImplementedError('This method must be implemented by subclasses')
349 def _hook_progress(self
, status
):
350 for ph
in self
._progress
_hooks
:
353 def add_progress_hook(self
, ph
):
354 # See YoutubeDl.py (search for progress_hooks) for a description of
356 self
._progress
_hooks
.append(ph
)
358 def _debug_cmd(self
, args
, exe
=None):
359 if not self
.params
.get('verbose', False):
362 str_args
= [decodeArgument(a
) for a
in args
]
365 exe
= os
.path
.basename(str_args
[0])
369 shell_quote
= lambda args
: ' '.join(map(pipes
.quote
, str_args
))
372 self
.to_screen('[debug] %s command line: %s' % (
373 exe
, shell_quote(str_args
)))