FileDownloader.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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(self, percent, data_len_str, speed, eta):
  177. """Report download progress."""
  178. if self.params.get('noprogress', False):
  179. return
  180. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  181. if eta is not None:
  182. eta_str = self.format_eta(eta)
  183. else:
  184. eta_str = 'Unknown ETA'
  185. if percent is not None:
  186. percent_str = self.format_percent(percent)
  187. else:
  188. percent_str = 'Unknown %'
  189. speed_str = self.format_speed(speed)
  190. if self.params.get('progress_with_newline', False):
  191. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  192. (percent_str, data_len_str, speed_str, eta_str))
  193. else:
  194. self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
  195. (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  196. self.to_console_title(u'youtube-dl - %s of %s at %s ETA %s' %
  197. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  198. def report_progress_live_stream(self, downloaded_data_len, speed, elapsed):
  199. if self.params.get('noprogress', False):
  200. return
  201. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  202. downloaded_str = format_bytes(downloaded_data_len)
  203. speed_str = self.format_speed(speed)
  204. elapsed_str = FileDownloader.format_seconds(elapsed)
  205. if self.params.get('progress_with_newline', False):
  206. self.to_screen(u'[download] %s at %s' %
  207. (downloaded_str, speed_str))
  208. else:
  209. self.to_screen(u'\r%s[download] %s at %s ET %s' %
  210. (clear_line, downloaded_str, speed_str, elapsed_str), skip_eol=True)
  211. self.to_console_title(u'youtube-dl - %s at %s ET %s' %
  212. (downloaded_str.strip(), speed_str.strip(), elapsed_str.strip()))
  213. def report_resuming_byte(self, resume_len):
  214. """Report attempt to resume at given byte."""
  215. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  216. def report_retry(self, count, retries):
  217. """Report retry in case of HTTP error 5xx"""
  218. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  219. def report_file_already_downloaded(self, file_name):
  220. """Report file has already been fully downloaded."""
  221. try:
  222. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  223. except UnicodeEncodeError:
  224. self.to_screen(u'[download] The file has already been downloaded')
  225. def report_unable_to_resume(self):
  226. """Report it was impossible to resume download."""
  227. self.to_screen(u'[download] Unable to resume')
  228. def report_finish(self, data_len_str, tot_time):
  229. """Report download finished."""
  230. if self.params.get('noprogress', False):
  231. self.to_screen(u'[download] Download completed')
  232. else:
  233. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  234. self.to_screen(u'\r%s[download] 100%% of %s in %s' %
  235. (clear_line, data_len_str, self.format_seconds(tot_time)))
  236. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live, conn):
  237. def run_rtmpdump(args):
  238. start = time.time()
  239. resume_percent = None
  240. resume_downloaded_data_len = None
  241. proc = subprocess.Popen(args, stderr=subprocess.PIPE)
  242. cursor_in_new_line = True
  243. proc_stderr_closed = False
  244. while not proc_stderr_closed:
  245. # read line from stderr
  246. line = u''
  247. while True:
  248. char = proc.stderr.read(1)
  249. if not char:
  250. proc_stderr_closed = True
  251. break
  252. if char in [b'\r', b'\n']:
  253. break
  254. line += char.decode('ascii', 'replace')
  255. if not line:
  256. # proc_stderr_closed is True
  257. continue
  258. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
  259. if mobj:
  260. downloaded_data_len = int(float(mobj.group(1))*1024)
  261. percent = float(mobj.group(2))
  262. if not resume_percent:
  263. resume_percent = percent
  264. resume_downloaded_data_len = downloaded_data_len
  265. eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
  266. speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
  267. data_len = None
  268. if percent > 0:
  269. data_len = int(downloaded_data_len * 100 / percent)
  270. data_len_str = u'~' + format_bytes(data_len)
  271. self.report_progress(percent, data_len_str, speed, eta)
  272. cursor_in_new_line = False
  273. self._hook_progress({
  274. 'downloaded_bytes': downloaded_data_len,
  275. 'total_bytes': data_len,
  276. 'tmpfilename': tmpfilename,
  277. 'filename': filename,
  278. 'status': 'downloading',
  279. 'eta': eta,
  280. 'speed': speed,
  281. })
  282. else:
  283. # no percent for live streams
  284. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
  285. if mobj:
  286. downloaded_data_len = int(float(mobj.group(1))*1024)
  287. time_now = time.time()
  288. speed = self.calc_speed(start, time_now, downloaded_data_len)
  289. self.report_progress_live_stream(downloaded_data_len, speed, time_now - start)
  290. cursor_in_new_line = False
  291. self._hook_progress({
  292. 'downloaded_bytes': downloaded_data_len,
  293. 'tmpfilename': tmpfilename,
  294. 'filename': filename,
  295. 'status': 'downloading',
  296. 'speed': speed,
  297. })
  298. elif self.params.get('verbose', False):
  299. if not cursor_in_new_line:
  300. self.to_screen(u'')
  301. cursor_in_new_line = True
  302. self.to_screen(u'[rtmpdump] '+line)
  303. proc.wait()
  304. if not cursor_in_new_line:
  305. self.to_screen(u'')
  306. return proc.returncode
  307. self.report_destination(filename)
  308. tmpfilename = self.temp_name(filename)
  309. test = self.params.get('test', False)
  310. # Check for rtmpdump first
  311. try:
  312. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  313. except (OSError, IOError):
  314. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  315. return False
  316. # Download using rtmpdump. rtmpdump returns exit code 2 when
  317. # the connection was interrumpted and resuming appears to be
  318. # possible. This is part of rtmpdump's normal usage, AFAIK.
  319. basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
  320. if player_url is not None:
  321. basic_args += ['--swfVfy', player_url]
  322. if page_url is not None:
  323. basic_args += ['--pageUrl', page_url]
  324. if play_path is not None:
  325. basic_args += ['--playpath', play_path]
  326. if tc_url is not None:
  327. basic_args += ['--tcUrl', url]
  328. if test:
  329. basic_args += ['--stop', '1']
  330. if live:
  331. basic_args += ['--live']
  332. if conn:
  333. basic_args += ['--conn', conn]
  334. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  335. if sys.platform == 'win32' and sys.version_info < (3, 0):
  336. # Windows subprocess module does not actually support Unicode
  337. # on Python 2.x
  338. # See http://stackoverflow.com/a/9951851/35070
  339. subprocess_encoding = sys.getfilesystemencoding()
  340. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  341. else:
  342. subprocess_encoding = None
  343. if self.params.get('verbose', False):
  344. if subprocess_encoding:
  345. str_args = [
  346. a.decode(subprocess_encoding) if isinstance(a, bytes) else a
  347. for a in args]
  348. else:
  349. str_args = args
  350. try:
  351. import pipes
  352. shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
  353. except ImportError:
  354. shell_quote = repr
  355. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(str_args))
  356. retval = run_rtmpdump(args)
  357. while (retval == 2 or retval == 1) and not test:
  358. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  359. self.to_screen(u'[rtmpdump] %s bytes' % prevsize)
  360. time.sleep(5.0) # This seems to be needed
  361. retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  362. cursize = os.path.getsize(encodeFilename(tmpfilename))
  363. if prevsize == cursize and retval == 1:
  364. break
  365. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  366. if prevsize == cursize and retval == 2 and cursize > 1024:
  367. self.to_screen(u'[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  368. retval = 0
  369. break
  370. if retval == 0 or (test and retval == 2):
  371. fsize = os.path.getsize(encodeFilename(tmpfilename))
  372. self.to_screen(u'[rtmpdump] %s bytes' % fsize)
  373. self.try_rename(tmpfilename, filename)
  374. self._hook_progress({
  375. 'downloaded_bytes': fsize,
  376. 'total_bytes': fsize,
  377. 'filename': filename,
  378. 'status': 'finished',
  379. })
  380. return True
  381. else:
  382. self.to_stderr(u"\n")
  383. self.report_error(u'rtmpdump exited with code %d' % retval)
  384. return False
  385. def _download_with_mplayer(self, filename, url):
  386. self.report_destination(filename)
  387. tmpfilename = self.temp_name(filename)
  388. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  389. # Check for mplayer first
  390. try:
  391. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  392. except (OSError, IOError):
  393. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  394. return False
  395. # Download using mplayer.
  396. retval = subprocess.call(args)
  397. if retval == 0:
  398. fsize = os.path.getsize(encodeFilename(tmpfilename))
  399. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  400. self.try_rename(tmpfilename, filename)
  401. self._hook_progress({
  402. 'downloaded_bytes': fsize,
  403. 'total_bytes': fsize,
  404. 'filename': filename,
  405. 'status': 'finished',
  406. })
  407. return True
  408. else:
  409. self.to_stderr(u"\n")
  410. self.report_error(u'mplayer exited with code %d' % retval)
  411. return False
  412. def _download_m3u8_with_ffmpeg(self, filename, url):
  413. self.report_destination(filename)
  414. tmpfilename = self.temp_name(filename)
  415. args = ['-y', '-i', url, '-f', 'mp4', '-c', 'copy',
  416. '-bsf:a', 'aac_adtstoasc', tmpfilename]
  417. for program in ['avconv', 'ffmpeg']:
  418. try:
  419. subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  420. break
  421. except (OSError, IOError):
  422. pass
  423. else:
  424. self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
  425. cmd = [program] + args
  426. retval = subprocess.call(cmd)
  427. if retval == 0:
  428. fsize = os.path.getsize(encodeFilename(tmpfilename))
  429. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  430. self.try_rename(tmpfilename, filename)
  431. self._hook_progress({
  432. 'downloaded_bytes': fsize,
  433. 'total_bytes': fsize,
  434. 'filename': filename,
  435. 'status': 'finished',
  436. })
  437. return True
  438. else:
  439. self.to_stderr(u"\n")
  440. self.report_error(u'ffmpeg exited with code %d' % retval)
  441. return False
  442. def _do_download(self, filename, info_dict):
  443. url = info_dict['url']
  444. # Check file already present
  445. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  446. self.report_file_already_downloaded(filename)
  447. self._hook_progress({
  448. 'filename': filename,
  449. 'status': 'finished',
  450. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  451. })
  452. return True
  453. # Attempt to download using rtmpdump
  454. if url.startswith('rtmp'):
  455. return self._download_with_rtmpdump(filename, url,
  456. info_dict.get('player_url', None),
  457. info_dict.get('page_url', None),
  458. info_dict.get('play_path', None),
  459. info_dict.get('tc_url', None),
  460. info_dict.get('rtmp_live', False),
  461. info_dict.get('rtmp_conn', None))
  462. # Attempt to download using mplayer
  463. if url.startswith('mms') or url.startswith('rtsp'):
  464. return self._download_with_mplayer(filename, url)
  465. # m3u8 manifest are downloaded with ffmpeg
  466. if determine_ext(url) == u'm3u8':
  467. return self._download_m3u8_with_ffmpeg(filename, url)
  468. tmpfilename = self.temp_name(filename)
  469. stream = None
  470. # Do not include the Accept-Encoding header
  471. headers = {'Youtubedl-no-compression': 'True'}
  472. if 'user_agent' in info_dict:
  473. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  474. basic_request = compat_urllib_request.Request(url, None, headers)
  475. request = compat_urllib_request.Request(url, None, headers)
  476. if self.params.get('test', False):
  477. request.add_header('Range','bytes=0-10240')
  478. # Establish possible resume length
  479. if os.path.isfile(encodeFilename(tmpfilename)):
  480. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  481. else:
  482. resume_len = 0
  483. open_mode = 'wb'
  484. if resume_len != 0:
  485. if self.params.get('continuedl', False):
  486. self.report_resuming_byte(resume_len)
  487. request.add_header('Range','bytes=%d-' % resume_len)
  488. open_mode = 'ab'
  489. else:
  490. resume_len = 0
  491. count = 0
  492. retries = self.params.get('retries', 0)
  493. while count <= retries:
  494. # Establish connection
  495. try:
  496. if count == 0 and 'urlhandle' in info_dict:
  497. data = info_dict['urlhandle']
  498. data = compat_urllib_request.urlopen(request)
  499. break
  500. except (compat_urllib_error.HTTPError, ) as err:
  501. if (err.code < 500 or err.code >= 600) and err.code != 416:
  502. # Unexpected HTTP error
  503. raise
  504. elif err.code == 416:
  505. # Unable to resume (requested range not satisfiable)
  506. try:
  507. # Open the connection again without the range header
  508. data = compat_urllib_request.urlopen(basic_request)
  509. content_length = data.info()['Content-Length']
  510. except (compat_urllib_error.HTTPError, ) as err:
  511. if err.code < 500 or err.code >= 600:
  512. raise
  513. else:
  514. # Examine the reported length
  515. if (content_length is not None and
  516. (resume_len - 100 < int(content_length) < resume_len + 100)):
  517. # The file had already been fully downloaded.
  518. # Explanation to the above condition: in issue #175 it was revealed that
  519. # YouTube sometimes adds or removes a few bytes from the end of the file,
  520. # changing the file size slightly and causing problems for some users. So
  521. # I decided to implement a suggested change and consider the file
  522. # completely downloaded if the file size differs less than 100 bytes from
  523. # the one in the hard drive.
  524. self.report_file_already_downloaded(filename)
  525. self.try_rename(tmpfilename, filename)
  526. self._hook_progress({
  527. 'filename': filename,
  528. 'status': 'finished',
  529. })
  530. return True
  531. else:
  532. # The length does not match, we start the download over
  533. self.report_unable_to_resume()
  534. open_mode = 'wb'
  535. break
  536. # Retry
  537. count += 1
  538. if count <= retries:
  539. self.report_retry(count, retries)
  540. if count > retries:
  541. self.report_error(u'giving up after %s retries' % retries)
  542. return False
  543. data_len = data.info().get('Content-length', None)
  544. if data_len is not None:
  545. data_len = int(data_len) + resume_len
  546. min_data_len = self.params.get("min_filesize", None)
  547. max_data_len = self.params.get("max_filesize", None)
  548. if min_data_len is not None and data_len < min_data_len:
  549. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  550. return False
  551. if max_data_len is not None and data_len > max_data_len:
  552. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  553. return False
  554. data_len_str = format_bytes(data_len)
  555. byte_counter = 0 + resume_len
  556. block_size = self.params.get('buffersize', 1024)
  557. start = time.time()
  558. while True:
  559. # Download and write
  560. before = time.time()
  561. data_block = data.read(block_size)
  562. after = time.time()
  563. if len(data_block) == 0:
  564. break
  565. byte_counter += len(data_block)
  566. # Open file just in time
  567. if stream is None:
  568. try:
  569. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  570. assert stream is not None
  571. filename = self.undo_temp_name(tmpfilename)
  572. self.report_destination(filename)
  573. except (OSError, IOError) as err:
  574. self.report_error(u'unable to open for writing: %s' % str(err))
  575. return False
  576. try:
  577. stream.write(data_block)
  578. except (IOError, OSError) as err:
  579. self.to_stderr(u"\n")
  580. self.report_error(u'unable to write data: %s' % str(err))
  581. return False
  582. if not self.params.get('noresizebuffer', False):
  583. block_size = self.best_block_size(after - before, len(data_block))
  584. # Progress message
  585. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  586. if data_len is None:
  587. eta = percent = None
  588. else:
  589. percent = self.calc_percent(byte_counter, data_len)
  590. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  591. self.report_progress(percent, data_len_str, speed, eta)
  592. self._hook_progress({
  593. 'downloaded_bytes': byte_counter,
  594. 'total_bytes': data_len,
  595. 'tmpfilename': tmpfilename,
  596. 'filename': filename,
  597. 'status': 'downloading',
  598. 'eta': eta,
  599. 'speed': speed,
  600. })
  601. # Apply rate limit
  602. self.slow_down(start, byte_counter - resume_len)
  603. if stream is None:
  604. self.to_stderr(u"\n")
  605. self.report_error(u'Did not get any data blocks')
  606. return False
  607. stream.close()
  608. self.report_finish(data_len_str, (time.time() - start))
  609. if data_len is not None and byte_counter != data_len:
  610. raise ContentTooShortError(byte_counter, int(data_len))
  611. self.try_rename(tmpfilename, filename)
  612. # Update file modification time
  613. if self.params.get('updatetime', True):
  614. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  615. self._hook_progress({
  616. 'downloaded_bytes': byte_counter,
  617. 'total_bytes': byte_counter,
  618. 'filename': filename,
  619. 'status': 'finished',
  620. })
  621. return True
  622. def _hook_progress(self, status):
  623. for ph in self._progress_hooks:
  624. ph(status)
  625. def add_progress_hook(self, ph):
  626. """ ph gets called on download progress, with a dictionary with the entries
  627. * filename: The final filename
  628. * status: One of "downloading" and "finished"
  629. It can also have some of the following entries:
  630. * downloaded_bytes: Bytes on disks
  631. * total_bytes: Total bytes, None if unknown
  632. * tmpfilename: The filename we're currently writing to
  633. * eta: The estimated time in seconds, None if unknown
  634. * speed: The download speed in bytes/second, None if unknown
  635. Hooks are guaranteed to be called at least once (with status "finished")
  636. if the download is successful.
  637. """
  638. self._progress_hooks.append(ph)