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.

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