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.

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