Merge branch 'master' into rtmpdump
[youtube-dl] / youtube_dl / FileDownloader.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     compat_urllib_error,
10     compat_urllib_request,
11     ContentTooShortError,
12     determine_ext,
13     encodeFilename,
14     sanitize_open,
15     timeconvert,
16 )
17
18
19 class FileDownloader(object):
20     """File Downloader class.
21
22     File downloader objects are the ones responsible of downloading the
23     actual video file and writing it to disk.
24
25     File downloaders accept a lot of parameters. In order not to saturate
26     the object constructor with arguments, it receives a dictionary of
27     options instead.
28
29     Available options:
30
31     verbose:           Print additional info to stdout.
32     quiet:             Do not print messages to stdout.
33     ratelimit:         Download speed limit, in bytes/sec.
34     retries:           Number of times to retry for HTTP error 5xx
35     buffersize:        Size of download buffer in bytes.
36     noresizebuffer:    Do not automatically resize the download buffer.
37     continuedl:        Try to continue downloads if possible.
38     noprogress:        Do not print the progress bar.
39     logtostderr:       Log messages to stderr instead of stdout.
40     consoletitle:      Display progress in console window's titlebar.
41     nopart:            Do not use temporary .part files.
42     updatetime:        Use the Last-modified header to set output file timestamps.
43     test:              Download only first bytes to test the downloader.
44     min_filesize:      Skip files smaller than this size
45     max_filesize:      Skip files larger than this size
46     """
47
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_bytes(bytes):
58         if bytes is None:
59             return 'N/A'
60         if type(bytes) is str:
61             bytes = float(bytes)
62         if bytes == 0.0:
63             exponent = 0
64         else:
65             exponent = int(math.log(bytes, 1024.0))
66         suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
67         converted = float(bytes) / float(1024 ** exponent)
68         return '%.2f%s' % (converted, suffix)
69
70     @staticmethod
71     def format_seconds(seconds):
72         (mins, secs) = divmod(seconds, 60)
73         (hours, mins) = divmod(mins, 60)
74         if hours > 99:
75             return '--:--:--'
76         if hours == 0:
77             return '%02d:%02d' % (mins, secs)
78         else:
79             return '%02d:%02d:%02d' % (hours, mins, secs)
80
81     @staticmethod
82     def calc_percent(byte_counter, data_len):
83         if data_len is None:
84             return None
85         return float(byte_counter) / float(data_len) * 100.0
86
87     @staticmethod
88     def format_percent(percent):
89         if percent is None:
90             return '---.-%'
91         return '%6s' % ('%3.1f%%' % percent)
92
93     @staticmethod
94     def calc_eta(start, now, total, current):
95         if total is None:
96             return None
97         dif = now - start
98         if current == 0 or dif < 0.001: # One millisecond
99             return None
100         rate = float(current) / dif
101         return int((float(total) - float(current)) / rate)
102
103     @staticmethod
104     def format_eta(eta):
105         if eta is None:
106             return '--:--'
107         return FileDownloader.format_seconds(eta)
108
109     @staticmethod
110     def calc_speed(start, now, bytes):
111         dif = now - start
112         if bytes == 0 or dif < 0.001: # One millisecond
113             return None
114         return float(bytes) / dif
115
116     @staticmethod
117     def format_speed(speed):
118         if speed is None:
119             return '%10s' % '---b/s'
120         return '%10s' % ('%s/s' % FileDownloader.format_bytes(speed))
121
122     @staticmethod
123     def best_block_size(elapsed_time, bytes):
124         new_min = max(bytes / 2.0, 1.0)
125         new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
126         if elapsed_time < 0.001:
127             return int(new_max)
128         rate = bytes / elapsed_time
129         if rate > new_max:
130             return int(new_max)
131         if rate < new_min:
132             return int(new_min)
133         return int(rate)
134
135     @staticmethod
136     def parse_bytes(bytestr):
137         """Parse a string indicating a byte quantity into an integer."""
138         matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
139         if matchobj is None:
140             return None
141         number = float(matchobj.group(1))
142         multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
143         return int(round(number * multiplier))
144
145     def to_screen(self, *args, **kargs):
146         self.ydl.to_screen(*args, **kargs)
147
148     def to_stderr(self, message):
149         self.ydl.to_screen(message)
150
151     def to_console_title(self, message):
152         self.ydl.to_console_title(message)
153
154     def trouble(self, *args, **kargs):
155         self.ydl.trouble(*args, **kargs)
156
157     def report_warning(self, *args, **kargs):
158         self.ydl.report_warning(*args, **kargs)
159
160     def report_error(self, *args, **kargs):
161         self.ydl.report_error(*args, **kargs)
162
163     def slow_down(self, start_time, byte_counter):
164         """Sleep if the download speed is over the rate limit."""
165         rate_limit = self.params.get('ratelimit', None)
166         if rate_limit is None or byte_counter == 0:
167             return
168         now = time.time()
169         elapsed = now - start_time
170         if elapsed <= 0.0:
171             return
172         speed = float(byte_counter) / elapsed
173         if speed > rate_limit:
174             time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
175
176     def temp_name(self, filename):
177         """Returns a temporary filename for the given filename."""
178         if self.params.get('nopart', False) or filename == u'-' or \
179                 (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
180             return filename
181         return filename + u'.part'
182
183     def undo_temp_name(self, filename):
184         if filename.endswith(u'.part'):
185             return filename[:-len(u'.part')]
186         return filename
187
188     def try_rename(self, old_filename, new_filename):
189         try:
190             if old_filename == new_filename:
191                 return
192             os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
193         except (IOError, OSError):
194             self.report_error(u'unable to rename file')
195
196     def try_utime(self, filename, last_modified_hdr):
197         """Try to set the last-modified time of the given file."""
198         if last_modified_hdr is None:
199             return
200         if not os.path.isfile(encodeFilename(filename)):
201             return
202         timestr = last_modified_hdr
203         if timestr is None:
204             return
205         filetime = timeconvert(timestr)
206         if filetime is None:
207             return filetime
208         # Ignore obviously invalid dates
209         if filetime == 0:
210             return
211         try:
212             os.utime(filename, (time.time(), filetime))
213         except:
214             pass
215         return filetime
216
217     def report_destination(self, filename):
218         """Report destination filename."""
219         self.to_screen(u'[download] Destination: ' + filename)
220
221     def report_progress(self, percent, data_len_str, speed, eta):
222         """Report download progress."""
223         if self.params.get('noprogress', False):
224             return
225         clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
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         if self.params.get('progress_with_newline', False):
236             self.to_screen(u'[download] %s of %s at %s ETA %s' %
237                 (percent_str, data_len_str, speed_str, eta_str))
238         else:
239             self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
240                 (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
241         self.to_console_title(u'youtube-dl - %s of %s at %s ETA %s' %
242                 (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
243
244     def report_resuming_byte(self, resume_len):
245         """Report attempt to resume at given byte."""
246         self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
247
248     def report_retry(self, count, retries):
249         """Report retry in case of HTTP error 5xx"""
250         self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
251
252     def report_file_already_downloaded(self, file_name):
253         """Report file has already been fully downloaded."""
254         try:
255             self.to_screen(u'[download] %s has already been downloaded' % file_name)
256         except UnicodeEncodeError:
257             self.to_screen(u'[download] The file has already been downloaded')
258
259     def report_unable_to_resume(self):
260         """Report it was impossible to resume download."""
261         self.to_screen(u'[download] Unable to resume')
262
263     def report_finish(self, data_len_str, tot_time):
264         """Report download finished."""
265         if self.params.get('noprogress', False):
266             self.to_screen(u'[download] Download completed')
267         else:
268             clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
269             self.to_screen(u'\r%s[download] 100%% of %s in %s' %
270                 (clear_line, data_len_str, self.format_seconds(tot_time)))
271
272     def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live):
273         def run_rtmpdump(args):
274             start = time.time()
275             resume_percent = None
276             resume_downloaded_data_len = None
277             proc = subprocess.Popen(args, stderr=subprocess.PIPE)
278             cursor_in_new_line = True
279             proc_stderr_closed = False
280             while not proc_stderr_closed:
281                 # read line from stderr
282                 line = u''
283                 while True:
284                     char = proc.stderr.read(1)
285                     if not char:
286                         proc_stderr_closed = True
287                         break
288                     if char in [b'\r', b'\n']:
289                         break
290                     line += char.decode('ascii', 'replace')
291                 if not line:
292                     # proc_stderr_closed is True
293                     continue
294                 mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
295                 if mobj:
296                     downloaded_data_len = int(float(mobj.group(1))*1024)
297                     percent = float(mobj.group(2))
298                     if not resume_percent:
299                         resume_percent = percent
300                         resume_downloaded_data_len = downloaded_data_len
301                     eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
302                     speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
303                     data_len = None
304                     if percent > 0:
305                         data_len = int(downloaded_data_len * 100 / percent)
306                     data_len_str = u'~'+self.format_bytes(data_len)
307                     self.report_progress(percent, data_len_str, speed, eta)
308                     cursor_in_new_line = False
309                     self._hook_progress({
310                         'downloaded_bytes': downloaded_data_len,
311                         'total_bytes': data_len,
312                         'tmpfilename': tmpfilename,
313                         'filename': filename,
314                         'status': 'downloading',
315                         'eta': eta,
316                         'speed': speed,
317                     })
318                 elif self.params.get('verbose', False):
319                     if not cursor_in_new_line:
320                         self.to_screen(u'')
321                     cursor_in_new_line = True
322                     self.to_screen(u'[rtmpdump] '+line)
323             proc.wait()
324             if not cursor_in_new_line:
325                 self.to_screen(u'')
326             return proc.returncode
327
328         self.report_destination(filename)
329         tmpfilename = self.temp_name(filename)
330         test = self.params.get('test', False)
331
332         # Check for rtmpdump first
333         try:
334             subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
335         except (OSError, IOError):
336             self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
337             return False
338
339         # Download using rtmpdump. rtmpdump returns exit code 2 when
340         # the connection was interrumpted and resuming appears to be
341         # possible. This is part of rtmpdump's normal usage, AFAIK.
342         basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
343         if player_url is not None:
344             basic_args += ['--swfVfy', player_url]
345         if page_url is not None:
346             basic_args += ['--pageUrl', page_url]
347         if play_path is not None:
348             basic_args += ['--playpath', play_path]
349         if tc_url is not None:
350             basic_args += ['--tcUrl', url]
351         if test:
352             basic_args += ['--stop', '1']
353         if live:
354             basic_args += ['--live']
355         args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
356         if self.params.get('verbose', False):
357             try:
358                 import pipes
359                 shell_quote = lambda args: ' '.join(map(pipes.quote, args))
360             except ImportError:
361                 shell_quote = repr
362             self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
363
364         retval = run_rtmpdump(args)
365
366         while (retval == 2 or retval == 1) and not test:
367             prevsize = os.path.getsize(encodeFilename(tmpfilename))
368             self.to_screen(u'[rtmpdump] %s bytes' % prevsize)
369             time.sleep(5.0) # This seems to be needed
370             retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
371             cursize = os.path.getsize(encodeFilename(tmpfilename))
372             if prevsize == cursize and retval == 1:
373                 break
374              # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
375             if prevsize == cursize and retval == 2 and cursize > 1024:
376                 self.to_screen(u'[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
377                 retval = 0
378                 break
379         if retval == 0 or (test and retval == 2):
380             fsize = os.path.getsize(encodeFilename(tmpfilename))
381             self.to_screen(u'[rtmpdump] %s bytes' % fsize)
382             self.try_rename(tmpfilename, filename)
383             self._hook_progress({
384                 'downloaded_bytes': fsize,
385                 'total_bytes': fsize,
386                 'filename': filename,
387                 'status': 'finished',
388             })
389             return True
390         else:
391             self.to_stderr(u"\n")
392             self.report_error(u'rtmpdump exited with code %d' % retval)
393             return False
394
395     def _download_with_mplayer(self, filename, url):
396         self.report_destination(filename)
397         tmpfilename = self.temp_name(filename)
398
399         args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
400         # Check for mplayer first
401         try:
402             subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
403         except (OSError, IOError):
404             self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
405             return False
406
407         # Download using mplayer. 
408         retval = subprocess.call(args)
409         if retval == 0:
410             fsize = os.path.getsize(encodeFilename(tmpfilename))
411             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
412             self.try_rename(tmpfilename, filename)
413             self._hook_progress({
414                 'downloaded_bytes': fsize,
415                 'total_bytes': fsize,
416                 'filename': filename,
417                 'status': 'finished',
418             })
419             return True
420         else:
421             self.to_stderr(u"\n")
422             self.report_error(u'mplayer exited with code %d' % retval)
423             return False
424
425     def _download_m3u8_with_ffmpeg(self, filename, url):
426         self.report_destination(filename)
427         tmpfilename = self.temp_name(filename)
428
429         args = ['-y', '-i', url, '-f', 'mp4', '-c', 'copy',
430             '-bsf:a', 'aac_adtstoasc', tmpfilename]
431
432         for program in ['avconv', 'ffmpeg']:
433             try:
434                 subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
435                 break
436             except (OSError, IOError):
437                 pass
438         else:
439             self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
440         cmd = [program] + args
441
442         retval = subprocess.call(cmd)
443         if retval == 0:
444             fsize = os.path.getsize(encodeFilename(tmpfilename))
445             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
446             self.try_rename(tmpfilename, filename)
447             self._hook_progress({
448                 'downloaded_bytes': fsize,
449                 'total_bytes': fsize,
450                 'filename': filename,
451                 'status': 'finished',
452             })
453             return True
454         else:
455             self.to_stderr(u"\n")
456             self.report_error(u'ffmpeg exited with code %d' % retval)
457             return False
458
459
460     def _do_download(self, filename, info_dict):
461         url = info_dict['url']
462
463         # Check file already present
464         if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
465             self.report_file_already_downloaded(filename)
466             self._hook_progress({
467                 'filename': filename,
468                 'status': 'finished',
469                 'total_bytes': os.path.getsize(encodeFilename(filename)),
470             })
471             return True
472
473         # Attempt to download using rtmpdump
474         if url.startswith('rtmp'):
475             return self._download_with_rtmpdump(filename, url,
476                                                 info_dict.get('player_url', None),
477                                                 info_dict.get('page_url', None),
478                                                 info_dict.get('play_path', None),
479                                                 info_dict.get('tc_url', None),
480                                                 info_dict.get('rtmp_live', False))
481
482         # Attempt to download using mplayer
483         if url.startswith('mms') or url.startswith('rtsp'):
484             return self._download_with_mplayer(filename, url)
485
486         # m3u8 manifest are downloaded with ffmpeg
487         if determine_ext(url) == u'm3u8':
488             return self._download_m3u8_with_ffmpeg(filename, url)
489
490         tmpfilename = self.temp_name(filename)
491         stream = None
492
493         # Do not include the Accept-Encoding header
494         headers = {'Youtubedl-no-compression': 'True'}
495         if 'user_agent' in info_dict:
496             headers['Youtubedl-user-agent'] = info_dict['user_agent']
497         basic_request = compat_urllib_request.Request(url, None, headers)
498         request = compat_urllib_request.Request(url, None, headers)
499
500         if self.params.get('test', False):
501             request.add_header('Range','bytes=0-10240')
502
503         # Establish possible resume length
504         if os.path.isfile(encodeFilename(tmpfilename)):
505             resume_len = os.path.getsize(encodeFilename(tmpfilename))
506         else:
507             resume_len = 0
508
509         open_mode = 'wb'
510         if resume_len != 0:
511             if self.params.get('continuedl', False):
512                 self.report_resuming_byte(resume_len)
513                 request.add_header('Range','bytes=%d-' % resume_len)
514                 open_mode = 'ab'
515             else:
516                 resume_len = 0
517
518         count = 0
519         retries = self.params.get('retries', 0)
520         while count <= retries:
521             # Establish connection
522             try:
523                 if count == 0 and 'urlhandle' in info_dict:
524                     data = info_dict['urlhandle']
525                 data = compat_urllib_request.urlopen(request)
526                 break
527             except (compat_urllib_error.HTTPError, ) as err:
528                 if (err.code < 500 or err.code >= 600) and err.code != 416:
529                     # Unexpected HTTP error
530                     raise
531                 elif err.code == 416:
532                     # Unable to resume (requested range not satisfiable)
533                     try:
534                         # Open the connection again without the range header
535                         data = compat_urllib_request.urlopen(basic_request)
536                         content_length = data.info()['Content-Length']
537                     except (compat_urllib_error.HTTPError, ) as err:
538                         if err.code < 500 or err.code >= 600:
539                             raise
540                     else:
541                         # Examine the reported length
542                         if (content_length is not None and
543                                 (resume_len - 100 < int(content_length) < resume_len + 100)):
544                             # The file had already been fully downloaded.
545                             # Explanation to the above condition: in issue #175 it was revealed that
546                             # YouTube sometimes adds or removes a few bytes from the end of the file,
547                             # changing the file size slightly and causing problems for some users. So
548                             # I decided to implement a suggested change and consider the file
549                             # completely downloaded if the file size differs less than 100 bytes from
550                             # the one in the hard drive.
551                             self.report_file_already_downloaded(filename)
552                             self.try_rename(tmpfilename, filename)
553                             self._hook_progress({
554                                 'filename': filename,
555                                 'status': 'finished',
556                             })
557                             return True
558                         else:
559                             # The length does not match, we start the download over
560                             self.report_unable_to_resume()
561                             open_mode = 'wb'
562                             break
563             # Retry
564             count += 1
565             if count <= retries:
566                 self.report_retry(count, retries)
567
568         if count > retries:
569             self.report_error(u'giving up after %s retries' % retries)
570             return False
571
572         data_len = data.info().get('Content-length', None)
573         if data_len is not None:
574             data_len = int(data_len) + resume_len
575             min_data_len = self.params.get("min_filesize", None)
576             max_data_len =  self.params.get("max_filesize", None)
577             if min_data_len is not None and data_len < min_data_len:
578                 self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
579                 return False
580             if max_data_len is not None and data_len > max_data_len:
581                 self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
582                 return False
583
584         data_len_str = self.format_bytes(data_len)
585         byte_counter = 0 + resume_len
586         block_size = self.params.get('buffersize', 1024)
587         start = time.time()
588         while True:
589             # Download and write
590             before = time.time()
591             data_block = data.read(block_size)
592             after = time.time()
593             if len(data_block) == 0:
594                 break
595             byte_counter += len(data_block)
596
597             # Open file just in time
598             if stream is None:
599                 try:
600                     (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
601                     assert stream is not None
602                     filename = self.undo_temp_name(tmpfilename)
603                     self.report_destination(filename)
604                 except (OSError, IOError) as err:
605                     self.report_error(u'unable to open for writing: %s' % str(err))
606                     return False
607             try:
608                 stream.write(data_block)
609             except (IOError, OSError) as err:
610                 self.to_stderr(u"\n")
611                 self.report_error(u'unable to write data: %s' % str(err))
612                 return False
613             if not self.params.get('noresizebuffer', False):
614                 block_size = self.best_block_size(after - before, len(data_block))
615
616             # Progress message
617             speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
618             if data_len is None:
619                 eta = percent = None
620             else:
621                 percent = self.calc_percent(byte_counter, data_len)
622                 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
623             self.report_progress(percent, data_len_str, speed, eta)
624
625             self._hook_progress({
626                 'downloaded_bytes': byte_counter,
627                 'total_bytes': data_len,
628                 'tmpfilename': tmpfilename,
629                 'filename': filename,
630                 'status': 'downloading',
631                 'eta': eta,
632                 'speed': speed,
633             })
634
635             # Apply rate limit
636             self.slow_down(start, byte_counter - resume_len)
637
638         if stream is None:
639             self.to_stderr(u"\n")
640             self.report_error(u'Did not get any data blocks')
641             return False
642         stream.close()
643         self.report_finish(data_len_str, (time.time() - start))
644         if data_len is not None and byte_counter != data_len:
645             raise ContentTooShortError(byte_counter, int(data_len))
646         self.try_rename(tmpfilename, filename)
647
648         # Update file modification time
649         if self.params.get('updatetime', True):
650             info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
651
652         self._hook_progress({
653             'downloaded_bytes': byte_counter,
654             'total_bytes': byte_counter,
655             'filename': filename,
656             'status': 'finished',
657         })
658
659         return True
660
661     def _hook_progress(self, status):
662         for ph in self._progress_hooks:
663             ph(status)
664
665     def add_progress_hook(self, ph):
666         """ ph gets called on download progress, with a dictionary with the entries
667         * filename: The final filename
668         * status: One of "downloading" and "finished"
669
670         It can also have some of the following entries:
671
672         * downloaded_bytes: Bytes on disks
673         * total_bytes: Total bytes, None if unknown
674         * tmpfilename: The filename we're currently writing to
675         * eta: The estimated time in seconds, None if unknown
676         * speed: The download speed in bytes/second, None if unknown
677
678         Hooks are guaranteed to be called at least once (with status "finished")
679         if the download is successful.
680         """
681         self._progress_hooks.append(ph)