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.

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