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.

738 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. tb, if given, is additional traceback information.
  192. """
  193. if message is not None:
  194. self.to_stderr(message)
  195. if self.params.get('verbose'):
  196. if tb is None:
  197. tb_data = traceback.format_list(traceback.extract_stack())
  198. tb = u''.join(tb_data)
  199. self.to_stderr(tb)
  200. if not self.params.get('ignoreerrors', False):
  201. raise DownloadError(message)
  202. self._download_retcode = 1
  203. def slow_down(self, start_time, byte_counter):
  204. """Sleep if the download speed is over the rate limit."""
  205. rate_limit = self.params.get('ratelimit', None)
  206. if rate_limit is None or byte_counter == 0:
  207. return
  208. now = time.time()
  209. elapsed = now - start_time
  210. if elapsed <= 0.0:
  211. return
  212. speed = float(byte_counter) / elapsed
  213. if speed > rate_limit:
  214. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  215. def temp_name(self, filename):
  216. """Returns a temporary filename for the given filename."""
  217. if self.params.get('nopart', False) or filename == u'-' or \
  218. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  219. return filename
  220. return filename + u'.part'
  221. def undo_temp_name(self, filename):
  222. if filename.endswith(u'.part'):
  223. return filename[:-len(u'.part')]
  224. return filename
  225. def try_rename(self, old_filename, new_filename):
  226. try:
  227. if old_filename == new_filename:
  228. return
  229. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  230. except (IOError, OSError) as err:
  231. self.trouble(u'ERROR: unable to rename file')
  232. def try_utime(self, filename, last_modified_hdr):
  233. """Try to set the last-modified time of the given file."""
  234. if last_modified_hdr is None:
  235. return
  236. if not os.path.isfile(encodeFilename(filename)):
  237. return
  238. timestr = last_modified_hdr
  239. if timestr is None:
  240. return
  241. filetime = timeconvert(timestr)
  242. if filetime is None:
  243. return filetime
  244. try:
  245. os.utime(filename, (time.time(), filetime))
  246. except:
  247. pass
  248. return filetime
  249. def report_writedescription(self, descfn):
  250. """ Report that the description file is being written """
  251. self.to_screen(u'[info] Writing video description to: ' + descfn)
  252. def report_writesubtitles(self, srtfn):
  253. """ Report that the subtitles file is being written """
  254. self.to_screen(u'[info] Writing video subtitles to: ' + srtfn)
  255. def report_writeinfojson(self, infofn):
  256. """ Report that the metadata file has been written """
  257. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  258. def report_destination(self, filename):
  259. """Report destination filename."""
  260. self.to_screen(u'[download] Destination: ' + filename)
  261. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  262. """Report download progress."""
  263. if self.params.get('noprogress', False):
  264. return
  265. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  266. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  267. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  268. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  269. def report_resuming_byte(self, resume_len):
  270. """Report attempt to resume at given byte."""
  271. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  272. def report_retry(self, count, retries):
  273. """Report retry in case of HTTP error 5xx"""
  274. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  275. def report_file_already_downloaded(self, file_name):
  276. """Report file has already been fully downloaded."""
  277. try:
  278. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  279. except (UnicodeEncodeError) as err:
  280. self.to_screen(u'[download] The file has already been downloaded')
  281. def report_unable_to_resume(self):
  282. """Report it was impossible to resume download."""
  283. self.to_screen(u'[download] Unable to resume')
  284. def report_finish(self):
  285. """Report download finished."""
  286. if self.params.get('noprogress', False):
  287. self.to_screen(u'[download] Download completed')
  288. else:
  289. self.to_screen(u'')
  290. def increment_downloads(self):
  291. """Increment the ordinal that assigns a number to each file."""
  292. self._num_downloads += 1
  293. def prepare_filename(self, info_dict):
  294. """Generate the output filename."""
  295. try:
  296. template_dict = dict(info_dict)
  297. template_dict['epoch'] = int(time.time())
  298. template_dict['autonumber'] = u'%05d' % self._num_downloads
  299. sanitize = lambda k,v: sanitize_filename(
  300. u'NA' if v is None else compat_str(v),
  301. restricted=self.params.get('restrictfilenames'),
  302. is_id=(k==u'id'))
  303. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  304. filename = self.params['outtmpl'] % template_dict
  305. return filename
  306. except (ValueError, KeyError) as err:
  307. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  308. return None
  309. def _match_entry(self, info_dict):
  310. """ Returns None iff the file should be downloaded """
  311. title = info_dict['title']
  312. matchtitle = self.params.get('matchtitle', False)
  313. if matchtitle:
  314. matchtitle = matchtitle.decode('utf8')
  315. if not re.search(matchtitle, title, re.IGNORECASE):
  316. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  317. rejecttitle = self.params.get('rejecttitle', False)
  318. if rejecttitle:
  319. rejecttitle = rejecttitle.decode('utf8')
  320. if re.search(rejecttitle, title, re.IGNORECASE):
  321. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  322. return None
  323. def process_info(self, info_dict):
  324. """Process a single dictionary returned by an InfoExtractor."""
  325. # Keep for backwards compatibility
  326. info_dict['stitle'] = info_dict['title']
  327. if not 'format' in info_dict:
  328. info_dict['format'] = info_dict['ext']
  329. reason = self._match_entry(info_dict)
  330. if reason is not None:
  331. self.to_screen(u'[download] ' + reason)
  332. return
  333. max_downloads = self.params.get('max_downloads')
  334. if max_downloads is not None:
  335. if self._num_downloads > int(max_downloads):
  336. raise MaxDownloadsReached()
  337. filename = self.prepare_filename(info_dict)
  338. # Forced printings
  339. if self.params.get('forcetitle', False):
  340. compat_print(info_dict['title'])
  341. if self.params.get('forceurl', False):
  342. compat_print(info_dict['url'])
  343. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  344. compat_print(info_dict['thumbnail'])
  345. if self.params.get('forcedescription', False) and 'description' in info_dict:
  346. compat_print(info_dict['description'])
  347. if self.params.get('forcefilename', False) and filename is not None:
  348. compat_print(filename)
  349. if self.params.get('forceformat', False):
  350. compat_print(info_dict['format'])
  351. # Do nothing else if in simulate mode
  352. if self.params.get('simulate', False):
  353. return
  354. if filename is None:
  355. return
  356. try:
  357. dn = os.path.dirname(encodeFilename(filename))
  358. if dn != '' and not os.path.exists(dn): # dn is already encoded
  359. os.makedirs(dn)
  360. except (OSError, IOError) as err:
  361. self.trouble(u'ERROR: unable to create directory ' + compat_str(err))
  362. return
  363. if self.params.get('writedescription', False):
  364. try:
  365. descfn = filename + u'.description'
  366. self.report_writedescription(descfn)
  367. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  368. descfile.write(info_dict['description'])
  369. except (OSError, IOError):
  370. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  371. return
  372. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  373. # subtitles download errors are already managed as troubles in relevant IE
  374. # that way it will silently go on when used with unsupporting IE
  375. try:
  376. srtfn = filename.rsplit('.', 1)[0] + u'.srt'
  377. self.report_writesubtitles(srtfn)
  378. with io.open(encodeFilename(srtfn), 'w', encoding='utf-8') as srtfile:
  379. srtfile.write(info_dict['subtitles'])
  380. except (OSError, IOError):
  381. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  382. return
  383. if self.params.get('writeinfojson', False):
  384. infofn = filename + u'.info.json'
  385. self.report_writeinfojson(infofn)
  386. try:
  387. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  388. write_json_file(json_info_dict, encodeFilename(infofn))
  389. except (OSError, IOError):
  390. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  391. return
  392. if not self.params.get('skip_download', False):
  393. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  394. success = True
  395. else:
  396. try:
  397. success = self._do_download(filename, info_dict)
  398. except (OSError, IOError) as err:
  399. raise UnavailableVideoError()
  400. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  401. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  402. return
  403. except (ContentTooShortError, ) as err:
  404. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  405. return
  406. if success:
  407. try:
  408. self.post_process(filename, info_dict)
  409. except (PostProcessingError) as err:
  410. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  411. return
  412. def download(self, url_list):
  413. """Download a given list of URLs."""
  414. if len(url_list) > 1 and self.fixed_template():
  415. raise SameFileError(self.params['outtmpl'])
  416. for url in url_list:
  417. suitable_found = False
  418. for ie in self._ies:
  419. # Go to next InfoExtractor if not suitable
  420. if not ie.suitable(url):
  421. continue
  422. # Warn if the _WORKING attribute is False
  423. if not ie.working():
  424. self.to_stderr(u'WARNING: the program functionality for this site has been marked as broken, '
  425. u'and will probably not work. If you want to go on, use the -i option.')
  426. # Suitable InfoExtractor found
  427. suitable_found = True
  428. # Extract information from URL and process it
  429. try:
  430. videos = ie.extract(url)
  431. except ExtractorError as de: # An error we somewhat expected
  432. self.trouble(u'ERROR: ' + compat_str(de), de.format_traceback())
  433. break
  434. except Exception as e:
  435. if self.params.get('ignoreerrors', False):
  436. self.trouble(u'ERROR: ' + compat_str(e), tb=compat_str(traceback.format_exc()))
  437. break
  438. else:
  439. raise
  440. if len(videos or []) > 1 and self.fixed_template():
  441. raise SameFileError(self.params['outtmpl'])
  442. for video in videos or []:
  443. video['extractor'] = ie.IE_NAME
  444. try:
  445. self.increment_downloads()
  446. self.process_info(video)
  447. except UnavailableVideoError:
  448. self.trouble(u'\nERROR: unable to download video')
  449. # Suitable InfoExtractor had been found; go to next URL
  450. break
  451. if not suitable_found:
  452. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  453. return self._download_retcode
  454. def post_process(self, filename, ie_info):
  455. """Run the postprocessing chain on the given file."""
  456. info = dict(ie_info)
  457. info['filepath'] = filename
  458. for pp in self._pps:
  459. info = pp.run(info)
  460. if info is None:
  461. break
  462. def _download_with_rtmpdump(self, filename, url, player_url, page_url):
  463. self.report_destination(filename)
  464. tmpfilename = self.temp_name(filename)
  465. # Check for rtmpdump first
  466. try:
  467. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  468. except (OSError, IOError):
  469. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  470. return False
  471. # Download using rtmpdump. rtmpdump returns exit code 2 when
  472. # the connection was interrumpted and resuming appears to be
  473. # possible. This is part of rtmpdump's normal usage, AFAIK.
  474. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  475. if player_url is not None:
  476. basic_args += ['-W', player_url]
  477. if page_url is not None:
  478. basic_args += ['--pageUrl', page_url]
  479. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  480. if self.params.get('verbose', False):
  481. try:
  482. import pipes
  483. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  484. except ImportError:
  485. shell_quote = repr
  486. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  487. retval = subprocess.call(args)
  488. while retval == 2 or retval == 1:
  489. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  490. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  491. time.sleep(5.0) # This seems to be needed
  492. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  493. cursize = os.path.getsize(encodeFilename(tmpfilename))
  494. if prevsize == cursize and retval == 1:
  495. break
  496. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  497. if prevsize == cursize and retval == 2 and cursize > 1024:
  498. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  499. retval = 0
  500. break
  501. if retval == 0:
  502. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(encodeFilename(tmpfilename)))
  503. self.try_rename(tmpfilename, filename)
  504. return True
  505. else:
  506. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  507. return False
  508. def _do_download(self, filename, info_dict):
  509. url = info_dict['url']
  510. # Check file already present
  511. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  512. self.report_file_already_downloaded(filename)
  513. return True
  514. # Attempt to download using rtmpdump
  515. if url.startswith('rtmp'):
  516. return self._download_with_rtmpdump(filename, url,
  517. info_dict.get('player_url', None),
  518. info_dict.get('page_url', None))
  519. tmpfilename = self.temp_name(filename)
  520. stream = None
  521. # Do not include the Accept-Encoding header
  522. headers = {'Youtubedl-no-compression': 'True'}
  523. basic_request = compat_urllib_request.Request(url, None, headers)
  524. request = compat_urllib_request.Request(url, None, headers)
  525. if self.params.get('test', False):
  526. request.add_header('Range','bytes=0-10240')
  527. # Establish possible resume length
  528. if os.path.isfile(encodeFilename(tmpfilename)):
  529. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  530. else:
  531. resume_len = 0
  532. open_mode = 'wb'
  533. if resume_len != 0:
  534. if self.params.get('continuedl', False):
  535. self.report_resuming_byte(resume_len)
  536. request.add_header('Range','bytes=%d-' % resume_len)
  537. open_mode = 'ab'
  538. else:
  539. resume_len = 0
  540. count = 0
  541. retries = self.params.get('retries', 0)
  542. while count <= retries:
  543. # Establish connection
  544. try:
  545. if count == 0 and 'urlhandle' in info_dict:
  546. data = info_dict['urlhandle']
  547. data = compat_urllib_request.urlopen(request)
  548. break
  549. except (compat_urllib_error.HTTPError, ) as err:
  550. if (err.code < 500 or err.code >= 600) and err.code != 416:
  551. # Unexpected HTTP error
  552. raise
  553. elif err.code == 416:
  554. # Unable to resume (requested range not satisfiable)
  555. try:
  556. # Open the connection again without the range header
  557. data = compat_urllib_request.urlopen(basic_request)
  558. content_length = data.info()['Content-Length']
  559. except (compat_urllib_error.HTTPError, ) as err:
  560. if err.code < 500 or err.code >= 600:
  561. raise
  562. else:
  563. # Examine the reported length
  564. if (content_length is not None and
  565. (resume_len - 100 < int(content_length) < resume_len + 100)):
  566. # The file had already been fully downloaded.
  567. # Explanation to the above condition: in issue #175 it was revealed that
  568. # YouTube sometimes adds or removes a few bytes from the end of the file,
  569. # changing the file size slightly and causing problems for some users. So
  570. # I decided to implement a suggested change and consider the file
  571. # completely downloaded if the file size differs less than 100 bytes from
  572. # the one in the hard drive.
  573. self.report_file_already_downloaded(filename)
  574. self.try_rename(tmpfilename, filename)
  575. return True
  576. else:
  577. # The length does not match, we start the download over
  578. self.report_unable_to_resume()
  579. open_mode = 'wb'
  580. break
  581. # Retry
  582. count += 1
  583. if count <= retries:
  584. self.report_retry(count, retries)
  585. if count > retries:
  586. self.trouble(u'ERROR: giving up after %s retries' % retries)
  587. return False
  588. data_len = data.info().get('Content-length', None)
  589. if data_len is not None:
  590. data_len = int(data_len) + resume_len
  591. data_len_str = self.format_bytes(data_len)
  592. byte_counter = 0 + resume_len
  593. block_size = self.params.get('buffersize', 1024)
  594. start = time.time()
  595. while True:
  596. # Download and write
  597. before = time.time()
  598. data_block = data.read(block_size)
  599. after = time.time()
  600. if len(data_block) == 0:
  601. break
  602. byte_counter += len(data_block)
  603. # Open file just in time
  604. if stream is None:
  605. try:
  606. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  607. assert stream is not None
  608. filename = self.undo_temp_name(tmpfilename)
  609. self.report_destination(filename)
  610. except (OSError, IOError) as err:
  611. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  612. return False
  613. try:
  614. stream.write(data_block)
  615. except (IOError, OSError) as err:
  616. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  617. return False
  618. if not self.params.get('noresizebuffer', False):
  619. block_size = self.best_block_size(after - before, len(data_block))
  620. # Progress message
  621. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  622. if data_len is None:
  623. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  624. else:
  625. percent_str = self.calc_percent(byte_counter, data_len)
  626. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  627. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  628. # Apply rate limit
  629. self.slow_down(start, byte_counter - resume_len)
  630. if stream is None:
  631. self.trouble(u'\nERROR: Did not get any data blocks')
  632. return False
  633. stream.close()
  634. self.report_finish()
  635. if data_len is not None and byte_counter != data_len:
  636. raise ContentTooShortError(byte_counter, int(data_len))
  637. self.try_rename(tmpfilename, filename)
  638. # Update file modification time
  639. if self.params.get('updatetime', True):
  640. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  641. return True