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.

694 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. template_dict['title'] = template_dict['stitle'] # Keep both for backwards compatibility
  283. filename = self.params['outtmpl'] % template_dict
  284. return filename
  285. except (ValueError, KeyError), err:
  286. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  287. return None
  288. def _match_entry(self, info_dict):
  289. """ Returns None iff the file should be downloaded """
  290. title = info_dict['title']
  291. matchtitle = self.params.get('matchtitle', False)
  292. if matchtitle:
  293. matchtitle = matchtitle.decode('utf8')
  294. if not re.search(matchtitle, title, re.IGNORECASE):
  295. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  296. rejecttitle = self.params.get('rejecttitle', False)
  297. if rejecttitle:
  298. rejecttitle = rejecttitle.decode('utf8')
  299. if re.search(rejecttitle, title, re.IGNORECASE):
  300. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  301. return None
  302. def process_info(self, info_dict):
  303. """Process a single dictionary returned by an InfoExtractor."""
  304. info_dict['stitle'] = sanitize_filename(info_dict['title'])
  305. reason = self._match_entry(info_dict)
  306. if reason is not None:
  307. self.to_screen(u'[download] ' + reason)
  308. return
  309. max_downloads = self.params.get('max_downloads')
  310. if max_downloads is not None:
  311. if self._num_downloads > int(max_downloads):
  312. raise MaxDownloadsReached()
  313. filename = self.prepare_filename(info_dict)
  314. # Forced printings
  315. if self.params.get('forcetitle', False):
  316. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  317. if self.params.get('forceurl', False):
  318. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  319. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  320. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  321. if self.params.get('forcedescription', False) and 'description' in info_dict:
  322. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  323. if self.params.get('forcefilename', False) and filename is not None:
  324. print filename.encode(preferredencoding(), 'xmlcharrefreplace')
  325. if self.params.get('forceformat', False):
  326. print info_dict['format'].encode(preferredencoding(), 'xmlcharrefreplace')
  327. # Do nothing else if in simulate mode
  328. if self.params.get('simulate', False):
  329. return
  330. if filename is None:
  331. return
  332. try:
  333. dn = os.path.dirname(encodeFilename(filename))
  334. if dn != '' and not os.path.exists(dn): # dn is already encoded
  335. os.makedirs(dn)
  336. except (OSError, IOError), err:
  337. self.trouble(u'ERROR: unable to create directory ' + unicode(err))
  338. return
  339. if self.params.get('writedescription', False):
  340. try:
  341. descfn = filename + u'.description'
  342. self.report_writedescription(descfn)
  343. descfile = open(encodeFilename(descfn), 'wb')
  344. try:
  345. descfile.write(info_dict['description'].encode('utf-8'))
  346. finally:
  347. descfile.close()
  348. except (OSError, IOError):
  349. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  350. return
  351. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  352. # subtitles download errors are already managed as troubles in relevant IE
  353. # that way it will silently go on when used with unsupporting IE
  354. try:
  355. srtfn = filename.rsplit('.', 1)[0] + u'.srt'
  356. self.report_writesubtitles(srtfn)
  357. srtfile = open(encodeFilename(srtfn), 'wb')
  358. try:
  359. srtfile.write(info_dict['subtitles'].encode('utf-8'))
  360. finally:
  361. srtfile.close()
  362. except (OSError, IOError):
  363. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  364. return
  365. if self.params.get('writeinfojson', False):
  366. infofn = filename + u'.info.json'
  367. self.report_writeinfojson(infofn)
  368. try:
  369. json.dump
  370. except (NameError,AttributeError):
  371. self.trouble(u'ERROR: No JSON encoder found. Update to Python 2.6+, setup a json module, or leave out --write-info-json.')
  372. return
  373. try:
  374. infof = open(encodeFilename(infofn), 'wb')
  375. try:
  376. json_info_dict = dict((k,v) for k,v in info_dict.iteritems() if not k in ('urlhandle',))
  377. json.dump(json_info_dict, infof)
  378. finally:
  379. infof.close()
  380. except (OSError, IOError):
  381. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  382. return
  383. if not self.params.get('skip_download', False):
  384. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  385. success = True
  386. else:
  387. try:
  388. success = self._do_download(filename, info_dict)
  389. except (OSError, IOError), err:
  390. raise UnavailableVideoError
  391. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  392. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  393. return
  394. except (ContentTooShortError, ), err:
  395. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  396. return
  397. if success:
  398. try:
  399. self.post_process(filename, info_dict)
  400. except (PostProcessingError), err:
  401. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  402. return
  403. def download(self, url_list):
  404. """Download a given list of URLs."""
  405. if len(url_list) > 1 and self.fixed_template():
  406. raise SameFileError(self.params['outtmpl'])
  407. for url in url_list:
  408. suitable_found = False
  409. for ie in self._ies:
  410. # Go to next InfoExtractor if not suitable
  411. if not ie.suitable(url):
  412. continue
  413. # Suitable InfoExtractor found
  414. suitable_found = True
  415. # Extract information from URL and process it
  416. videos = ie.extract(url)
  417. for video in videos or []:
  418. video['extractor'] = ie.IE_NAME
  419. try:
  420. self.increment_downloads()
  421. self.process_info(video)
  422. except UnavailableVideoError:
  423. self.trouble(u'\nERROR: unable to download video')
  424. # Suitable InfoExtractor had been found; go to next URL
  425. break
  426. if not suitable_found:
  427. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  428. return self._download_retcode
  429. def post_process(self, filename, ie_info):
  430. """Run the postprocessing chain on the given file."""
  431. info = dict(ie_info)
  432. info['filepath'] = filename
  433. for pp in self._pps:
  434. info = pp.run(info)
  435. if info is None:
  436. break
  437. def _download_with_rtmpdump(self, filename, url, player_url):
  438. self.report_destination(filename)
  439. tmpfilename = self.temp_name(filename)
  440. # Check for rtmpdump first
  441. try:
  442. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  443. except (OSError, IOError):
  444. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  445. return False
  446. # Download using rtmpdump. rtmpdump returns exit code 2 when
  447. # the connection was interrumpted and resuming appears to be
  448. # possible. This is part of rtmpdump's normal usage, AFAIK.
  449. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  450. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  451. if self.params.get('verbose', False):
  452. try:
  453. import pipes
  454. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  455. except ImportError:
  456. shell_quote = repr
  457. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  458. retval = subprocess.call(args)
  459. while retval == 2 or retval == 1:
  460. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  461. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  462. time.sleep(5.0) # This seems to be needed
  463. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  464. cursize = os.path.getsize(encodeFilename(tmpfilename))
  465. if prevsize == cursize and retval == 1:
  466. break
  467. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  468. if prevsize == cursize and retval == 2 and cursize > 1024:
  469. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  470. retval = 0
  471. break
  472. if retval == 0:
  473. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(encodeFilename(tmpfilename)))
  474. self.try_rename(tmpfilename, filename)
  475. return True
  476. else:
  477. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  478. return False
  479. def _do_download(self, filename, info_dict):
  480. url = info_dict['url']
  481. player_url = info_dict.get('player_url', None)
  482. # Check file already present
  483. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  484. self.report_file_already_downloaded(filename)
  485. return True
  486. # Attempt to download using rtmpdump
  487. if url.startswith('rtmp'):
  488. return self._download_with_rtmpdump(filename, url, player_url)
  489. tmpfilename = self.temp_name(filename)
  490. stream = None
  491. # Do not include the Accept-Encoding header
  492. headers = {'Youtubedl-no-compression': 'True'}
  493. basic_request = urllib2.Request(url, None, headers)
  494. request = urllib2.Request(url, None, headers)
  495. # Establish possible resume length
  496. if os.path.isfile(encodeFilename(tmpfilename)):
  497. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  498. else:
  499. resume_len = 0
  500. open_mode = 'wb'
  501. if resume_len != 0:
  502. if self.params.get('continuedl', False):
  503. self.report_resuming_byte(resume_len)
  504. request.add_header('Range','bytes=%d-' % resume_len)
  505. open_mode = 'ab'
  506. else:
  507. resume_len = 0
  508. count = 0
  509. retries = self.params.get('retries', 0)
  510. while count <= retries:
  511. # Establish connection
  512. try:
  513. if count == 0 and 'urlhandle' in info_dict:
  514. data = info_dict['urlhandle']
  515. data = urllib2.urlopen(request)
  516. break
  517. except (urllib2.HTTPError, ), err:
  518. if (err.code < 500 or err.code >= 600) and err.code != 416:
  519. # Unexpected HTTP error
  520. raise
  521. elif err.code == 416:
  522. # Unable to resume (requested range not satisfiable)
  523. try:
  524. # Open the connection again without the range header
  525. data = urllib2.urlopen(basic_request)
  526. content_length = data.info()['Content-Length']
  527. except (urllib2.HTTPError, ), err:
  528. if err.code < 500 or err.code >= 600:
  529. raise
  530. else:
  531. # Examine the reported length
  532. if (content_length is not None and
  533. (resume_len - 100 < long(content_length) < resume_len + 100)):
  534. # The file had already been fully downloaded.
  535. # Explanation to the above condition: in issue #175 it was revealed that
  536. # YouTube sometimes adds or removes a few bytes from the end of the file,
  537. # changing the file size slightly and causing problems for some users. So
  538. # I decided to implement a suggested change and consider the file
  539. # completely downloaded if the file size differs less than 100 bytes from
  540. # the one in the hard drive.
  541. self.report_file_already_downloaded(filename)
  542. self.try_rename(tmpfilename, filename)
  543. return True
  544. else:
  545. # The length does not match, we start the download over
  546. self.report_unable_to_resume()
  547. open_mode = 'wb'
  548. break
  549. # Retry
  550. count += 1
  551. if count <= retries:
  552. self.report_retry(count, retries)
  553. if count > retries:
  554. self.trouble(u'ERROR: giving up after %s retries' % retries)
  555. return False
  556. data_len = data.info().get('Content-length', None)
  557. if data_len is not None:
  558. data_len = long(data_len) + resume_len
  559. data_len_str = self.format_bytes(data_len)
  560. byte_counter = 0 + resume_len
  561. block_size = 1024
  562. start = time.time()
  563. while True:
  564. # Download and write
  565. before = time.time()
  566. data_block = data.read(block_size)
  567. after = time.time()
  568. if len(data_block) == 0:
  569. break
  570. byte_counter += len(data_block)
  571. # Open file just in time
  572. if stream is None:
  573. try:
  574. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  575. assert stream is not None
  576. filename = self.undo_temp_name(tmpfilename)
  577. self.report_destination(filename)
  578. except (OSError, IOError), err:
  579. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  580. return False
  581. try:
  582. stream.write(data_block)
  583. except (IOError, OSError), err:
  584. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  585. return False
  586. block_size = self.best_block_size(after - before, len(data_block))
  587. # Progress message
  588. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  589. if data_len is None:
  590. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  591. else:
  592. percent_str = self.calc_percent(byte_counter, data_len)
  593. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  594. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  595. # Apply rate limit
  596. self.slow_down(start, byte_counter - resume_len)
  597. if stream is None:
  598. self.trouble(u'\nERROR: Did not get any data blocks')
  599. return False
  600. stream.close()
  601. self.report_finish()
  602. if data_len is not None and byte_counter != data_len:
  603. raise ContentTooShortError(byte_counter, long(data_len))
  604. self.try_rename(tmpfilename, filename)
  605. # Update file modification time
  606. if self.params.get('updatetime', True):
  607. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  608. return True