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.

718 lines
30 KiB

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