FileDownloader.py 25 KB

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