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.

690 lines
24 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import httplib
  4. import math
  5. import os
  6. import re
  7. import socket
  8. import subprocess
  9. import sys
  10. import time
  11. import urllib2
  12. if os.name == 'nt':
  13. import ctypes
  14. from utils import *
  15. class FileDownloader(object):
  16. """File Downloader class.
  17. File downloader objects are the ones responsible of downloading the
  18. actual video file and writing it to disk if the user has requested
  19. it, among some other tasks. In most cases there should be one per
  20. program. As, given a video URL, the downloader doesn't know how to
  21. extract all the needed information, task that InfoExtractors do, it
  22. has to pass the URL to one of them.
  23. For this, file downloader objects have a method that allows
  24. InfoExtractors to be registered in a given order. When it is passed
  25. a URL, the file downloader handles it to the first InfoExtractor it
  26. finds that reports being able to handle it. The InfoExtractor extracts
  27. all the information about the video or videos the URL refers to, and
  28. asks the FileDownloader to process the video information, possibly
  29. downloading the video.
  30. File downloaders accept a lot of parameters. In order not to saturate
  31. the object constructor with arguments, it receives a dictionary of
  32. options instead. These options are available through the params
  33. attribute for the InfoExtractors to use. The FileDownloader also
  34. registers itself as the downloader in charge for the InfoExtractors
  35. that are added to it, so this is a "mutual registration".
  36. Available options:
  37. username: Username for authentication purposes.
  38. password: Password for authentication purposes.
  39. usenetrc: Use netrc for authentication instead.
  40. quiet: Do not print messages to stdout.
  41. forceurl: Force printing final URL.
  42. forcetitle: Force printing title.
  43. forcethumbnail: Force printing thumbnail URL.
  44. forcedescription: Force printing description.
  45. forcefilename: Force printing final filename.
  46. simulate: Do not download the video files.
  47. format: Video format code.
  48. format_limit: Highest quality format to try.
  49. outtmpl: Template for output names.
  50. ignoreerrors: Do not stop on download errors.
  51. ratelimit: Download speed limit, in bytes/sec.
  52. nooverwrites: Prevent overwriting files.
  53. retries: Number of times to retry for HTTP error 5xx
  54. continuedl: Try to continue downloads if possible.
  55. noprogress: Do not print the progress bar.
  56. playliststart: Playlist item to start at.
  57. playlistend: Playlist item to end at.
  58. matchtitle: Download only matching titles.
  59. rejecttitle: Reject downloads for matching titles.
  60. logtostderr: Log messages to stderr instead of stdout.
  61. consoletitle: Display progress in console window's titlebar.
  62. nopart: Do not use temporary .part files.
  63. updatetime: Use the Last-modified header to set output file timestamps.
  64. writedescription: Write the video description to a .description file
  65. writeinfojson: Write the video description to a .info.json file
  66. writesubtitles: Write the video subtitles to a .srt file
  67. subtitleslang: Language of the subtitles to download
  68. """
  69. params = None
  70. _ies = []
  71. _pps = []
  72. _download_retcode = None
  73. _num_downloads = None
  74. _screen_file = None
  75. def __init__(self, params):
  76. """Create a FileDownloader object with the given options."""
  77. self._ies = []
  78. self._pps = []
  79. self._download_retcode = 0
  80. self._num_downloads = 0
  81. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  82. self.params = params
  83. @staticmethod
  84. def format_bytes(bytes):
  85. if bytes is None:
  86. return 'N/A'
  87. if type(bytes) is str:
  88. bytes = float(bytes)
  89. if bytes == 0.0:
  90. exponent = 0
  91. else:
  92. exponent = long(math.log(bytes, 1024.0))
  93. suffix = 'bkMGTPEZY'[exponent]
  94. converted = float(bytes) / float(1024 ** exponent)
  95. return '%.2f%s' % (converted, suffix)
  96. @staticmethod
  97. def calc_percent(byte_counter, data_len):
  98. if data_len is None:
  99. return '---.-%'
  100. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  101. @staticmethod
  102. def calc_eta(start, now, total, current):
  103. if total is None:
  104. return '--:--'
  105. dif = now - start
  106. if current == 0 or dif < 0.001: # One millisecond
  107. return '--:--'
  108. rate = float(current) / dif
  109. eta = long((float(total) - float(current)) / rate)
  110. (eta_mins, eta_secs) = divmod(eta, 60)
  111. if eta_mins > 99:
  112. return '--:--'
  113. return '%02d:%02d' % (eta_mins, eta_secs)
  114. @staticmethod
  115. def calc_speed(start, now, bytes):
  116. dif = now - start
  117. if bytes == 0 or dif < 0.001: # One millisecond
  118. return '%10s' % '---b/s'
  119. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  120. @staticmethod
  121. def best_block_size(elapsed_time, bytes):
  122. new_min = max(bytes / 2.0, 1.0)
  123. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  124. if elapsed_time < 0.001:
  125. return long(new_max)
  126. rate = bytes / elapsed_time
  127. if rate > new_max:
  128. return long(new_max)
  129. if rate < new_min:
  130. return long(new_min)
  131. return long(rate)
  132. @staticmethod
  133. def parse_bytes(bytestr):
  134. """Parse a string indicating a byte quantity into a long integer."""
  135. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  136. if matchobj is None:
  137. return None
  138. number = float(matchobj.group(1))
  139. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  140. return long(round(number * multiplier))
  141. def add_info_extractor(self, ie):
  142. """Add an InfoExtractor object to the end of the list."""
  143. self._ies.append(ie)
  144. ie.set_downloader(self)
  145. def add_post_processor(self, pp):
  146. """Add a PostProcessor object to the end of the chain."""
  147. self._pps.append(pp)
  148. pp.set_downloader(self)
  149. def to_screen(self, message, skip_eol=False):
  150. """Print message to stdout if not in quiet mode."""
  151. assert type(message) == type(u'')
  152. if not self.params.get('quiet', False):
  153. terminator = [u'\n', u''][skip_eol]
  154. output = message + terminator
  155. if 'b' not in self._screen_file.mode or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  156. output = output.encode(preferredencoding(), 'ignore')
  157. self._screen_file.write(output)
  158. self._screen_file.flush()
  159. def to_stderr(self, message):
  160. """Print message to stderr."""
  161. print >>sys.stderr, message.encode(preferredencoding())
  162. def to_cons_title(self, message):
  163. """Set console/terminal window title to message."""
  164. if not self.params.get('consoletitle', False):
  165. return
  166. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  167. # c_wchar_p() might not be necessary if `message` is
  168. # already of type unicode()
  169. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  170. elif 'TERM' in os.environ:
  171. sys.stderr.write('\033]0;%s\007' % message.encode(preferredencoding()))
  172. def fixed_template(self):
  173. """Checks if the output template is fixed."""
  174. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  175. def trouble(self, message=None):
  176. """Determine action to take when a download problem appears.
  177. Depending on if the downloader has been configured to ignore
  178. download errors or not, this method may throw an exception or
  179. not when errors are found, after printing the message.
  180. """
  181. if message is not None:
  182. self.to_stderr(message)
  183. if not self.params.get('ignoreerrors', False):
  184. raise DownloadError(message)
  185. self._download_retcode = 1
  186. def slow_down(self, start_time, byte_counter):
  187. """Sleep if the download speed is over the rate limit."""
  188. rate_limit = self.params.get('ratelimit', None)
  189. if rate_limit is None or byte_counter == 0:
  190. return
  191. now = time.time()
  192. elapsed = now - start_time
  193. if elapsed <= 0.0:
  194. return
  195. speed = float(byte_counter) / elapsed
  196. if speed > rate_limit:
  197. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  198. def temp_name(self, filename):
  199. """Returns a temporary filename for the given filename."""
  200. if self.params.get('nopart', False) or filename == u'-' or \
  201. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  202. return filename
  203. return filename + u'.part'
  204. def undo_temp_name(self, filename):
  205. if filename.endswith(u'.part'):
  206. return filename[:-len(u'.part')]
  207. return filename
  208. def try_rename(self, old_filename, new_filename):
  209. try:
  210. if old_filename == new_filename:
  211. return
  212. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  213. except (IOError, OSError), err:
  214. self.trouble(u'ERROR: unable to rename file')
  215. def try_utime(self, filename, last_modified_hdr):
  216. """Try to set the last-modified time of the given file."""
  217. if last_modified_hdr is None:
  218. return
  219. if not os.path.isfile(encodeFilename(filename)):
  220. return
  221. timestr = last_modified_hdr
  222. if timestr is None:
  223. return
  224. filetime = timeconvert(timestr)
  225. if filetime is None:
  226. return filetime
  227. try:
  228. os.utime(filename, (time.time(), filetime))
  229. except:
  230. pass
  231. return filetime
  232. def report_writedescription(self, descfn):
  233. """ Report that the description file is being written """
  234. self.to_screen(u'[info] Writing video description to: ' + descfn)
  235. def report_writesubtitles(self, srtfn):
  236. """ Report that the subtitles file is being written """
  237. self.to_screen(u'[info] Writing video subtitles to: ' + srtfn)
  238. def report_writeinfojson(self, infofn):
  239. """ Report that the metadata file has been written """
  240. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  241. def report_destination(self, filename):
  242. """Report destination filename."""
  243. self.to_screen(u'[download] Destination: ' + filename)
  244. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  245. """Report download progress."""
  246. if self.params.get('noprogress', False):
  247. return
  248. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  249. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  250. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  251. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  252. def report_resuming_byte(self, resume_len):
  253. """Report attempt to resume at given byte."""
  254. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  255. def report_retry(self, count, retries):
  256. """Report retry in case of HTTP error 5xx"""
  257. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  258. def report_file_already_downloaded(self, file_name):
  259. """Report file has already been fully downloaded."""
  260. try:
  261. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  262. except (UnicodeEncodeError), err:
  263. self.to_screen(u'[download] The file has already been downloaded')
  264. def report_unable_to_resume(self):
  265. """Report it was impossible to resume download."""
  266. self.to_screen(u'[download] Unable to resume')
  267. def report_finish(self):
  268. """Report download finished."""
  269. if self.params.get('noprogress', False):
  270. self.to_screen(u'[download] Download completed')
  271. else:
  272. self.to_screen(u'')
  273. def increment_downloads(self):
  274. """Increment the ordinal that assigns a number to each file."""
  275. self._num_downloads += 1
  276. def prepare_filename(self, info_dict):
  277. """Generate the output filename."""
  278. try:
  279. template_dict = dict(info_dict)
  280. template_dict['epoch'] = unicode(long(time.time()))
  281. template_dict['autonumber'] = unicode('%05d' % self._num_downloads)
  282. filename = self.params['outtmpl'] % template_dict
  283. return filename
  284. except (ValueError, KeyError), err:
  285. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  286. return None
  287. def _match_entry(self, info_dict):
  288. """ Returns None iff the file should be downloaded """
  289. title = info_dict['title']
  290. matchtitle = self.params.get('matchtitle', False)
  291. if matchtitle and not re.search(matchtitle, title, re.IGNORECASE):
  292. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  293. rejecttitle = self.params.get('rejecttitle', False)
  294. if rejecttitle and re.search(rejecttitle, title, re.IGNORECASE):
  295. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  296. return None
  297. def process_info(self, info_dict):
  298. """Process a single dictionary returned by an InfoExtractor."""
  299. info_dict['stitle'] = sanitize_filename(info_dict['title'])
  300. reason = self._match_entry(info_dict)
  301. if reason is not None:
  302. self.to_screen(u'[download] ' + reason)
  303. return
  304. max_downloads = self.params.get('max_downloads')
  305. if max_downloads is not None:
  306. if self._num_downloads > int(max_downloads):
  307. raise MaxDownloadsReached()
  308. filename = self.prepare_filename(info_dict)
  309. # Forced printings
  310. if self.params.get('forcetitle', False):
  311. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  312. if self.params.get('forceurl', False):
  313. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  314. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  315. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  316. if self.params.get('forcedescription', False) and 'description' in info_dict:
  317. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  318. if self.params.get('forcefilename', False) and filename is not None:
  319. print filename.encode(preferredencoding(), 'xmlcharrefreplace')
  320. if self.params.get('forceformat', False):
  321. print info_dict['format'].encode(preferredencoding(), 'xmlcharrefreplace')
  322. # Do nothing else if in simulate mode
  323. if self.params.get('simulate', False):
  324. return
  325. if filename is None:
  326. return
  327. try:
  328. dn = os.path.dirname(encodeFilename(filename))
  329. if dn != '' and not os.path.exists(dn): # dn is already encoded
  330. os.makedirs(dn)
  331. except (OSError, IOError), err:
  332. self.trouble(u'ERROR: unable to create directory ' + unicode(err))
  333. return
  334. if self.params.get('writedescription', False):
  335. try:
  336. descfn = filename + u'.description'
  337. self.report_writedescription(descfn)
  338. descfile = open(encodeFilename(descfn), 'wb')
  339. try:
  340. descfile.write(info_dict['description'].encode('utf-8'))
  341. finally:
  342. descfile.close()
  343. except (OSError, IOError):
  344. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  345. return
  346. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  347. # subtitles download errors are already managed as troubles in relevant IE
  348. # that way it will silently go on when used with unsupporting IE
  349. try:
  350. srtfn = filename.rsplit('.', 1)[0] + u'.srt'
  351. self.report_writesubtitles(srtfn)
  352. srtfile = open(encodeFilename(srtfn), 'wb')
  353. try:
  354. srtfile.write(info_dict['subtitles'].encode('utf-8'))
  355. finally:
  356. srtfile.close()
  357. except (OSError, IOError):
  358. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  359. return
  360. if self.params.get('writeinfojson', False):
  361. infofn = filename + u'.info.json'
  362. self.report_writeinfojson(infofn)
  363. try:
  364. json.dump
  365. except (NameError,AttributeError):
  366. self.trouble(u'ERROR: No JSON encoder found. Update to Python 2.6+, setup a json module, or leave out --write-info-json.')
  367. return
  368. try:
  369. infof = open(encodeFilename(infofn), 'wb')
  370. try:
  371. json_info_dict = dict((k,v) for k,v in info_dict.iteritems() if not k in ('urlhandle',))
  372. json.dump(json_info_dict, infof)
  373. finally:
  374. infof.close()
  375. except (OSError, IOError):
  376. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  377. return
  378. if not self.params.get('skip_download', False):
  379. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  380. success = True
  381. else:
  382. try:
  383. success = self._do_download(filename, info_dict)
  384. except (OSError, IOError), err:
  385. raise UnavailableVideoError
  386. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  387. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  388. return
  389. except (ContentTooShortError, ), err:
  390. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  391. return
  392. if success:
  393. try:
  394. self.post_process(filename, info_dict)
  395. except (PostProcessingError), err:
  396. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  397. return
  398. def download(self, url_list):
  399. """Download a given list of URLs."""
  400. if len(url_list) > 1 and self.fixed_template():
  401. raise SameFileError(self.params['outtmpl'])
  402. for url in url_list:
  403. suitable_found = False
  404. for ie in self._ies:
  405. # Go to next InfoExtractor if not suitable
  406. if not ie.suitable(url):
  407. continue
  408. # Suitable InfoExtractor found
  409. suitable_found = True
  410. # Extract information from URL and process it
  411. videos = ie.extract(url)
  412. for video in videos or []:
  413. video['extractor'] = ie.IE_NAME
  414. try:
  415. self.increment_downloads()
  416. self.process_info(video)
  417. except UnavailableVideoError:
  418. self.trouble(u'\nERROR: unable to download video')
  419. # Suitable InfoExtractor had been found; go to next URL
  420. break
  421. if not suitable_found:
  422. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  423. return self._download_retcode
  424. def post_process(self, filename, ie_info):
  425. """Run the postprocessing chain on the given file."""
  426. info = dict(ie_info)
  427. info['filepath'] = filename
  428. for pp in self._pps:
  429. info = pp.run(info)
  430. if info is None:
  431. break
  432. def _download_with_rtmpdump(self, filename, url, player_url):
  433. self.report_destination(filename)
  434. tmpfilename = self.temp_name(filename)
  435. # Check for rtmpdump first
  436. try:
  437. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  438. except (OSError, IOError):
  439. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  440. return False
  441. # Download using rtmpdump. rtmpdump returns exit code 2 when
  442. # the connection was interrumpted and resuming appears to be
  443. # possible. This is part of rtmpdump's normal usage, AFAIK.
  444. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  445. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  446. if self.params.get('verbose', False):
  447. try:
  448. import pipes
  449. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  450. except ImportError:
  451. shell_quote = repr
  452. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  453. retval = subprocess.call(args)
  454. while retval == 2 or retval == 1:
  455. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  456. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  457. time.sleep(5.0) # This seems to be needed
  458. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  459. cursize = os.path.getsize(encodeFilename(tmpfilename))
  460. if prevsize == cursize and retval == 1:
  461. break
  462. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  463. if prevsize == cursize and retval == 2 and cursize > 1024:
  464. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  465. retval = 0
  466. break
  467. if retval == 0:
  468. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(encodeFilename(tmpfilename)))
  469. self.try_rename(tmpfilename, filename)
  470. return True
  471. else:
  472. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  473. return False
  474. def _do_download(self, filename, info_dict):
  475. url = info_dict['url']
  476. player_url = info_dict.get('player_url', None)
  477. # Check file already present
  478. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  479. self.report_file_already_downloaded(filename)
  480. return True
  481. # Attempt to download using rtmpdump
  482. if url.startswith('rtmp'):
  483. return self._download_with_rtmpdump(filename, url, player_url)
  484. tmpfilename = self.temp_name(filename)
  485. stream = None
  486. # Do not include the Accept-Encoding header
  487. headers = {'Youtubedl-no-compression': 'True'}
  488. basic_request = urllib2.Request(url, None, headers)
  489. request = urllib2.Request(url, None, headers)
  490. # Establish possible resume length
  491. if os.path.isfile(encodeFilename(tmpfilename)):
  492. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  493. else:
  494. resume_len = 0
  495. open_mode = 'wb'
  496. if resume_len != 0:
  497. if self.params.get('continuedl', False):
  498. self.report_resuming_byte(resume_len)
  499. request.add_header('Range','bytes=%d-' % resume_len)
  500. open_mode = 'ab'
  501. else:
  502. resume_len = 0
  503. count = 0
  504. retries = self.params.get('retries', 0)
  505. while count <= retries:
  506. # Establish connection
  507. try:
  508. if count == 0 and 'urlhandle' in info_dict:
  509. data = info_dict['urlhandle']
  510. data = urllib2.urlopen(request)
  511. break
  512. except (urllib2.HTTPError, ), err:
  513. if (err.code < 500 or err.code >= 600) and err.code != 416:
  514. # Unexpected HTTP error
  515. raise
  516. elif err.code == 416:
  517. # Unable to resume (requested range not satisfiable)
  518. try:
  519. # Open the connection again without the range header
  520. data = urllib2.urlopen(basic_request)
  521. content_length = data.info()['Content-Length']
  522. except (urllib2.HTTPError, ), err:
  523. if err.code < 500 or err.code >= 600:
  524. raise
  525. else:
  526. # Examine the reported length
  527. if (content_length is not None and
  528. (resume_len - 100 < long(content_length) < resume_len + 100)):
  529. # The file had already been fully downloaded.
  530. # Explanation to the above condition: in issue #175 it was revealed that
  531. # YouTube sometimes adds or removes a few bytes from the end of the file,
  532. # changing the file size slightly and causing problems for some users. So
  533. # I decided to implement a suggested change and consider the file
  534. # completely downloaded if the file size differs less than 100 bytes from
  535. # the one in the hard drive.
  536. self.report_file_already_downloaded(filename)
  537. self.try_rename(tmpfilename, filename)
  538. return True
  539. else:
  540. # The length does not match, we start the download over
  541. self.report_unable_to_resume()
  542. open_mode = 'wb'
  543. break
  544. # Retry
  545. count += 1
  546. if count <= retries:
  547. self.report_retry(count, retries)
  548. if count > retries:
  549. self.trouble(u'ERROR: giving up after %s retries' % retries)
  550. return False
  551. data_len = data.info().get('Content-length', None)
  552. if data_len is not None:
  553. data_len = long(data_len) + resume_len
  554. data_len_str = self.format_bytes(data_len)
  555. byte_counter = 0 + resume_len
  556. block_size = 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), err:
  574. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  575. return False
  576. try:
  577. stream.write(data_block)
  578. except (IOError, OSError), err:
  579. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  580. return False
  581. block_size = self.best_block_size(after - before, len(data_block))
  582. # Progress message
  583. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  584. if data_len is None:
  585. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  586. else:
  587. percent_str = self.calc_percent(byte_counter, data_len)
  588. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  589. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  590. # Apply rate limit
  591. self.slow_down(start, byte_counter - resume_len)
  592. if stream is None:
  593. self.trouble(u'\nERROR: Did not get any data blocks')
  594. return False
  595. stream.close()
  596. self.report_finish()
  597. if data_len is not None and byte_counter != data_len:
  598. raise ContentTooShortError(byte_counter, long(data_len))
  599. self.try_rename(tmpfilename, filename)
  600. # Update file modification time
  601. if self.params.get('updatetime', True):
  602. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  603. return True