You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

724 lines
29 KiB

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