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.

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