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