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.

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