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.

730 lines
31 KiB

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