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.

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