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.

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