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.

1607 lines
70 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import platform
  14. import re
  15. import shutil
  16. import subprocess
  17. import socket
  18. import sys
  19. import time
  20. import traceback
  21. if os.name == 'nt':
  22. import ctypes
  23. from .compat import (
  24. compat_cookiejar,
  25. compat_expanduser,
  26. compat_http_client,
  27. compat_kwargs,
  28. compat_str,
  29. compat_urllib_error,
  30. compat_urllib_request,
  31. )
  32. from .utils import (
  33. escape_url,
  34. ContentTooShortError,
  35. date_from_str,
  36. DateRange,
  37. DEFAULT_OUTTMPL,
  38. determine_ext,
  39. DownloadError,
  40. encodeFilename,
  41. ExtractorError,
  42. format_bytes,
  43. formatSeconds,
  44. get_term_width,
  45. locked_file,
  46. make_HTTPS_handler,
  47. MaxDownloadsReached,
  48. PagedList,
  49. parse_filesize,
  50. PostProcessingError,
  51. platform_name,
  52. preferredencoding,
  53. SameFileError,
  54. sanitize_filename,
  55. subtitles_filename,
  56. takewhile_inclusive,
  57. UnavailableVideoError,
  58. url_basename,
  59. version_tuple,
  60. write_json_file,
  61. write_string,
  62. YoutubeDLHandler,
  63. prepend_extension,
  64. args_to_str,
  65. age_restricted,
  66. )
  67. from .cache import Cache
  68. from .extractor import get_info_extractor, gen_extractors
  69. from .downloader import get_suitable_downloader
  70. from .downloader.rtmp import rtmpdump_version
  71. from .postprocessor import (
  72. FFmpegFixupM4aPP,
  73. FFmpegFixupStretchedPP,
  74. FFmpegMergerPP,
  75. FFmpegPostProcessor,
  76. get_postprocessor,
  77. )
  78. from .version import __version__
  79. class YoutubeDL(object):
  80. """YoutubeDL class.
  81. YoutubeDL objects are the ones responsible of downloading the
  82. actual video file and writing it to disk if the user has requested
  83. it, among some other tasks. In most cases there should be one per
  84. program. As, given a video URL, the downloader doesn't know how to
  85. extract all the needed information, task that InfoExtractors do, it
  86. has to pass the URL to one of them.
  87. For this, YoutubeDL objects have a method that allows
  88. InfoExtractors to be registered in a given order. When it is passed
  89. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  90. finds that reports being able to handle it. The InfoExtractor extracts
  91. all the information about the video or videos the URL refers to, and
  92. YoutubeDL process the extracted information, possibly using a File
  93. Downloader to download the video.
  94. YoutubeDL objects accept a lot of parameters. In order not to saturate
  95. the object constructor with arguments, it receives a dictionary of
  96. options instead. These options are available through the params
  97. attribute for the InfoExtractors to use. The YoutubeDL also
  98. registers itself as the downloader in charge for the InfoExtractors
  99. that are added to it, so this is a "mutual registration".
  100. Available options:
  101. username: Username for authentication purposes.
  102. password: Password for authentication purposes.
  103. videopassword: Password for acces a video.
  104. usenetrc: Use netrc for authentication instead.
  105. verbose: Print additional info to stdout.
  106. quiet: Do not print messages to stdout.
  107. no_warnings: Do not print out anything for warnings.
  108. forceurl: Force printing final URL.
  109. forcetitle: Force printing title.
  110. forceid: Force printing ID.
  111. forcethumbnail: Force printing thumbnail URL.
  112. forcedescription: Force printing description.
  113. forcefilename: Force printing final filename.
  114. forceduration: Force printing duration.
  115. forcejson: Force printing info_dict as JSON.
  116. dump_single_json: Force printing the info_dict of the whole playlist
  117. (or video) as a single JSON line.
  118. simulate: Do not download the video files.
  119. format: Video format code. See options.py for more information.
  120. format_limit: Highest quality format to try.
  121. outtmpl: Template for output names.
  122. restrictfilenames: Do not allow "&" and spaces in file names
  123. ignoreerrors: Do not stop on download errors.
  124. nooverwrites: Prevent overwriting files.
  125. playliststart: Playlist item to start at.
  126. playlistend: Playlist item to end at.
  127. playlistreverse: Download playlist items in reverse order.
  128. matchtitle: Download only matching titles.
  129. rejecttitle: Reject downloads for matching titles.
  130. logger: Log messages to a logging.Logger instance.
  131. logtostderr: Log messages to stderr instead of stdout.
  132. writedescription: Write the video description to a .description file
  133. writeinfojson: Write the video description to a .info.json file
  134. writeannotations: Write the video annotations to a .annotations.xml file
  135. writethumbnail: Write the thumbnail image to a file
  136. writesubtitles: Write the video subtitles to a file
  137. writeautomaticsub: Write the automatic subtitles to a file
  138. allsubtitles: Downloads all the subtitles of the video
  139. (requires writesubtitles or writeautomaticsub)
  140. listsubtitles: Lists all available subtitles for the video
  141. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  142. subtitleslangs: List of languages of the subtitles to download
  143. keepvideo: Keep the video file after post-processing
  144. daterange: A DateRange object, download only if the upload_date is in the range.
  145. skip_download: Skip the actual download of the video file
  146. cachedir: Location of the cache files in the filesystem.
  147. False to disable filesystem cache.
  148. noplaylist: Download single video instead of a playlist if in doubt.
  149. age_limit: An integer representing the user's age in years.
  150. Unsuitable videos for the given age are skipped.
  151. min_views: An integer representing the minimum view count the video
  152. must have in order to not be skipped.
  153. Videos without view count information are always
  154. downloaded. None for no limit.
  155. max_views: An integer representing the maximum view count.
  156. Videos that are more popular than that are not
  157. downloaded.
  158. Videos without view count information are always
  159. downloaded. None for no limit.
  160. download_archive: File name of a file where all downloads are recorded.
  161. Videos already present in the file are not downloaded
  162. again.
  163. cookiefile: File name where cookies should be read from and dumped to.
  164. nocheckcertificate:Do not verify SSL certificates
  165. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  166. At the moment, this is only supported by YouTube.
  167. proxy: URL of the proxy server to use
  168. socket_timeout: Time to wait for unresponsive hosts, in seconds
  169. bidi_workaround: Work around buggy terminals without bidirectional text
  170. support, using fridibi
  171. debug_printtraffic:Print out sent and received HTTP traffic
  172. include_ads: Download ads as well
  173. default_search: Prepend this string if an input url is not valid.
  174. 'auto' for elaborate guessing
  175. encoding: Use this encoding instead of the system-specified.
  176. extract_flat: Do not resolve URLs, return the immediate result.
  177. Pass in 'in_playlist' to only show this behavior for
  178. playlist items.
  179. postprocessors: A list of dictionaries, each with an entry
  180. * key: The name of the postprocessor. See
  181. youtube_dl/postprocessor/__init__.py for a list.
  182. as well as any further keyword arguments for the
  183. postprocessor.
  184. progress_hooks: A list of functions that get called on download
  185. progress, with a dictionary with the entries
  186. * filename: The final filename
  187. * status: One of "downloading" and "finished"
  188. The dict may also have some of the following entries:
  189. * downloaded_bytes: Bytes on disk
  190. * total_bytes: Size of the whole file, None if unknown
  191. * tmpfilename: The filename we're currently writing to
  192. * eta: The estimated time in seconds, None if unknown
  193. * speed: The download speed in bytes/second, None if
  194. unknown
  195. Progress hooks are guaranteed to be called at least once
  196. (with status "finished") if the download is successful.
  197. merge_output_format: Extension to use when merging formats.
  198. fixup: Automatically correct known faults of the file.
  199. One of:
  200. - "never": do nothing
  201. - "warn": only emit a warning
  202. - "detect_or_warn": check whether we can do anything
  203. about it, warn otherwise (default)
  204. source_address: (Experimental) Client-side IP address to bind to.
  205. call_home: Boolean, true iff we are allowed to contact the
  206. youtube-dl servers for debugging.
  207. sleep_interval: Number of seconds to sleep before each download.
  208. external_downloader: Executable of the external downloader to call.
  209. The following parameters are not used by YoutubeDL itself, they are used by
  210. the FileDownloader:
  211. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  212. noresizebuffer, retries, continuedl, noprogress, consoletitle
  213. The following options are used by the post processors:
  214. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  215. otherwise prefer avconv.
  216. exec_cmd: Arbitrary command to run after downloading
  217. """
  218. params = None
  219. _ies = []
  220. _pps = []
  221. _download_retcode = None
  222. _num_downloads = None
  223. _screen_file = None
  224. def __init__(self, params=None, auto_init=True):
  225. """Create a FileDownloader object with the given options."""
  226. if params is None:
  227. params = {}
  228. self._ies = []
  229. self._ies_instances = {}
  230. self._pps = []
  231. self._progress_hooks = []
  232. self._download_retcode = 0
  233. self._num_downloads = 0
  234. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  235. self._err_file = sys.stderr
  236. self.params = params
  237. self.cache = Cache(self)
  238. if params.get('bidi_workaround', False):
  239. try:
  240. import pty
  241. master, slave = pty.openpty()
  242. width = get_term_width()
  243. if width is None:
  244. width_args = []
  245. else:
  246. width_args = ['-w', str(width)]
  247. sp_kwargs = dict(
  248. stdin=subprocess.PIPE,
  249. stdout=slave,
  250. stderr=self._err_file)
  251. try:
  252. self._output_process = subprocess.Popen(
  253. ['bidiv'] + width_args, **sp_kwargs
  254. )
  255. except OSError:
  256. self._output_process = subprocess.Popen(
  257. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  258. self._output_channel = os.fdopen(master, 'rb')
  259. except OSError as ose:
  260. if ose.errno == 2:
  261. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  262. else:
  263. raise
  264. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  265. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  266. and not params.get('restrictfilenames', False)):
  267. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  268. self.report_warning(
  269. 'Assuming --restrict-filenames since file system encoding '
  270. 'cannot encode all characters. '
  271. 'Set the LC_ALL environment variable to fix this.')
  272. self.params['restrictfilenames'] = True
  273. if '%(stitle)s' in self.params.get('outtmpl', ''):
  274. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  275. self._setup_opener()
  276. if auto_init:
  277. self.print_debug_header()
  278. self.add_default_info_extractors()
  279. for pp_def_raw in self.params.get('postprocessors', []):
  280. pp_class = get_postprocessor(pp_def_raw['key'])
  281. pp_def = dict(pp_def_raw)
  282. del pp_def['key']
  283. pp = pp_class(self, **compat_kwargs(pp_def))
  284. self.add_post_processor(pp)
  285. for ph in self.params.get('progress_hooks', []):
  286. self.add_progress_hook(ph)
  287. def warn_if_short_id(self, argv):
  288. # short YouTube ID starting with dash?
  289. idxs = [
  290. i for i, a in enumerate(argv)
  291. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  292. if idxs:
  293. correct_argv = (
  294. ['youtube-dl'] +
  295. [a for i, a in enumerate(argv) if i not in idxs] +
  296. ['--'] + [argv[i] for i in idxs]
  297. )
  298. self.report_warning(
  299. 'Long argument string detected. '
  300. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  301. args_to_str(correct_argv))
  302. def add_info_extractor(self, ie):
  303. """Add an InfoExtractor object to the end of the list."""
  304. self._ies.append(ie)
  305. self._ies_instances[ie.ie_key()] = ie
  306. ie.set_downloader(self)
  307. def get_info_extractor(self, ie_key):
  308. """
  309. Get an instance of an IE with name ie_key, it will try to get one from
  310. the _ies list, if there's no instance it will create a new one and add
  311. it to the extractor list.
  312. """
  313. ie = self._ies_instances.get(ie_key)
  314. if ie is None:
  315. ie = get_info_extractor(ie_key)()
  316. self.add_info_extractor(ie)
  317. return ie
  318. def add_default_info_extractors(self):
  319. """
  320. Add the InfoExtractors returned by gen_extractors to the end of the list
  321. """
  322. for ie in gen_extractors():
  323. self.add_info_extractor(ie)
  324. def add_post_processor(self, pp):
  325. """Add a PostProcessor object to the end of the chain."""
  326. self._pps.append(pp)
  327. pp.set_downloader(self)
  328. def add_progress_hook(self, ph):
  329. """Add the progress hook (currently only for the file downloader)"""
  330. self._progress_hooks.append(ph)
  331. def _bidi_workaround(self, message):
  332. if not hasattr(self, '_output_channel'):
  333. return message
  334. assert hasattr(self, '_output_process')
  335. assert isinstance(message, compat_str)
  336. line_count = message.count('\n') + 1
  337. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  338. self._output_process.stdin.flush()
  339. res = ''.join(self._output_channel.readline().decode('utf-8')
  340. for _ in range(line_count))
  341. return res[:-len('\n')]
  342. def to_screen(self, message, skip_eol=False):
  343. """Print message to stdout if not in quiet mode."""
  344. return self.to_stdout(message, skip_eol, check_quiet=True)
  345. def _write_string(self, s, out=None):
  346. write_string(s, out=out, encoding=self.params.get('encoding'))
  347. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  348. """Print message to stdout if not in quiet mode."""
  349. if self.params.get('logger'):
  350. self.params['logger'].debug(message)
  351. elif not check_quiet or not self.params.get('quiet', False):
  352. message = self._bidi_workaround(message)
  353. terminator = ['\n', ''][skip_eol]
  354. output = message + terminator
  355. self._write_string(output, self._screen_file)
  356. def to_stderr(self, message):
  357. """Print message to stderr."""
  358. assert isinstance(message, compat_str)
  359. if self.params.get('logger'):
  360. self.params['logger'].error(message)
  361. else:
  362. message = self._bidi_workaround(message)
  363. output = message + '\n'
  364. self._write_string(output, self._err_file)
  365. def to_console_title(self, message):
  366. if not self.params.get('consoletitle', False):
  367. return
  368. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  369. # c_wchar_p() might not be necessary if `message` is
  370. # already of type unicode()
  371. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  372. elif 'TERM' in os.environ:
  373. self._write_string('\033]0;%s\007' % message, self._screen_file)
  374. def save_console_title(self):
  375. if not self.params.get('consoletitle', False):
  376. return
  377. if 'TERM' in os.environ:
  378. # Save the title on stack
  379. self._write_string('\033[22;0t', self._screen_file)
  380. def restore_console_title(self):
  381. if not self.params.get('consoletitle', False):
  382. return
  383. if 'TERM' in os.environ:
  384. # Restore the title from stack
  385. self._write_string('\033[23;0t', self._screen_file)
  386. def __enter__(self):
  387. self.save_console_title()
  388. return self
  389. def __exit__(self, *args):
  390. self.restore_console_title()
  391. if self.params.get('cookiefile') is not None:
  392. self.cookiejar.save()
  393. def trouble(self, message=None, tb=None):
  394. """Determine action to take when a download problem appears.
  395. Depending on if the downloader has been configured to ignore
  396. download errors or not, this method may throw an exception or
  397. not when errors are found, after printing the message.
  398. tb, if given, is additional traceback information.
  399. """
  400. if message is not None:
  401. self.to_stderr(message)
  402. if self.params.get('verbose'):
  403. if tb is None:
  404. if sys.exc_info()[0]: # if .trouble has been called from an except block
  405. tb = ''
  406. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  407. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  408. tb += compat_str(traceback.format_exc())
  409. else:
  410. tb_data = traceback.format_list(traceback.extract_stack())
  411. tb = ''.join(tb_data)
  412. self.to_stderr(tb)
  413. if not self.params.get('ignoreerrors', False):
  414. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  415. exc_info = sys.exc_info()[1].exc_info
  416. else:
  417. exc_info = sys.exc_info()
  418. raise DownloadError(message, exc_info)
  419. self._download_retcode = 1
  420. def report_warning(self, message):
  421. '''
  422. Print the message to stderr, it will be prefixed with 'WARNING:'
  423. If stderr is a tty file the 'WARNING:' will be colored
  424. '''
  425. if self.params.get('logger') is not None:
  426. self.params['logger'].warning(message)
  427. else:
  428. if self.params.get('no_warnings'):
  429. return
  430. if self._err_file.isatty() and os.name != 'nt':
  431. _msg_header = '\033[0;33mWARNING:\033[0m'
  432. else:
  433. _msg_header = 'WARNING:'
  434. warning_message = '%s %s' % (_msg_header, message)
  435. self.to_stderr(warning_message)
  436. def report_error(self, message, tb=None):
  437. '''
  438. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  439. in red if stderr is a tty file.
  440. '''
  441. if self._err_file.isatty() and os.name != 'nt':
  442. _msg_header = '\033[0;31mERROR:\033[0m'
  443. else:
  444. _msg_header = 'ERROR:'
  445. error_message = '%s %s' % (_msg_header, message)
  446. self.trouble(error_message, tb)
  447. def report_file_already_downloaded(self, file_name):
  448. """Report file has already been fully downloaded."""
  449. try:
  450. self.to_screen('[download] %s has already been downloaded' % file_name)
  451. except UnicodeEncodeError:
  452. self.to_screen('[download] The file has already been downloaded')
  453. def prepare_filename(self, info_dict):
  454. """Generate the output filename."""
  455. try:
  456. template_dict = dict(info_dict)
  457. template_dict['epoch'] = int(time.time())
  458. autonumber_size = self.params.get('autonumber_size')
  459. if autonumber_size is None:
  460. autonumber_size = 5
  461. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  462. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  463. if template_dict.get('playlist_index') is not None:
  464. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  465. if template_dict.get('resolution') is None:
  466. if template_dict.get('width') and template_dict.get('height'):
  467. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  468. elif template_dict.get('height'):
  469. template_dict['resolution'] = '%sp' % template_dict['height']
  470. elif template_dict.get('width'):
  471. template_dict['resolution'] = '?x%d' % template_dict['width']
  472. sanitize = lambda k, v: sanitize_filename(
  473. compat_str(v),
  474. restricted=self.params.get('restrictfilenames'),
  475. is_id=(k == 'id'))
  476. template_dict = dict((k, sanitize(k, v))
  477. for k, v in template_dict.items()
  478. if v is not None)
  479. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  480. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  481. tmpl = compat_expanduser(outtmpl)
  482. filename = tmpl % template_dict
  483. return filename
  484. except ValueError as err:
  485. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  486. return None
  487. def _match_entry(self, info_dict):
  488. """ Returns None iff the file should be downloaded """
  489. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  490. if 'title' in info_dict:
  491. # This can happen when we're just evaluating the playlist
  492. title = info_dict['title']
  493. matchtitle = self.params.get('matchtitle', False)
  494. if matchtitle:
  495. if not re.search(matchtitle, title, re.IGNORECASE):
  496. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  497. rejecttitle = self.params.get('rejecttitle', False)
  498. if rejecttitle:
  499. if re.search(rejecttitle, title, re.IGNORECASE):
  500. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  501. date = info_dict.get('upload_date', None)
  502. if date is not None:
  503. dateRange = self.params.get('daterange', DateRange())
  504. if date not in dateRange:
  505. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  506. view_count = info_dict.get('view_count', None)
  507. if view_count is not None:
  508. min_views = self.params.get('min_views')
  509. if min_views is not None and view_count < min_views:
  510. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  511. max_views = self.params.get('max_views')
  512. if max_views is not None and view_count > max_views:
  513. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  514. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  515. return 'Skipping "%s" because it is age restricted' % title
  516. if self.in_download_archive(info_dict):
  517. return '%s has already been recorded in archive' % video_title
  518. return None
  519. @staticmethod
  520. def add_extra_info(info_dict, extra_info):
  521. '''Set the keys from extra_info in info dict if they are missing'''
  522. for key, value in extra_info.items():
  523. info_dict.setdefault(key, value)
  524. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  525. process=True):
  526. '''
  527. Returns a list with a dictionary for each video we find.
  528. If 'download', also downloads the videos.
  529. extra_info is a dict containing the extra values to add to each result
  530. '''
  531. if ie_key:
  532. ies = [self.get_info_extractor(ie_key)]
  533. else:
  534. ies = self._ies
  535. for ie in ies:
  536. if not ie.suitable(url):
  537. continue
  538. if not ie.working():
  539. self.report_warning('The program functionality for this site has been marked as broken, '
  540. 'and will probably not work.')
  541. try:
  542. ie_result = ie.extract(url)
  543. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  544. break
  545. if isinstance(ie_result, list):
  546. # Backwards compatibility: old IE result format
  547. ie_result = {
  548. '_type': 'compat_list',
  549. 'entries': ie_result,
  550. }
  551. self.add_default_extra_info(ie_result, ie, url)
  552. if process:
  553. return self.process_ie_result(ie_result, download, extra_info)
  554. else:
  555. return ie_result
  556. except ExtractorError as de: # An error we somewhat expected
  557. self.report_error(compat_str(de), de.format_traceback())
  558. break
  559. except MaxDownloadsReached:
  560. raise
  561. except Exception as e:
  562. if self.params.get('ignoreerrors', False):
  563. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  564. break
  565. else:
  566. raise
  567. else:
  568. self.report_error('no suitable InfoExtractor for URL %s' % url)
  569. def add_default_extra_info(self, ie_result, ie, url):
  570. self.add_extra_info(ie_result, {
  571. 'extractor': ie.IE_NAME,
  572. 'webpage_url': url,
  573. 'webpage_url_basename': url_basename(url),
  574. 'extractor_key': ie.ie_key(),
  575. })
  576. def process_ie_result(self, ie_result, download=True, extra_info={}):
  577. """
  578. Take the result of the ie(may be modified) and resolve all unresolved
  579. references (URLs, playlist items).
  580. It will also download the videos if 'download'.
  581. Returns the resolved ie_result.
  582. """
  583. result_type = ie_result.get('_type', 'video')
  584. if result_type in ('url', 'url_transparent'):
  585. extract_flat = self.params.get('extract_flat', False)
  586. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  587. extract_flat is True):
  588. if self.params.get('forcejson', False):
  589. self.to_stdout(json.dumps(ie_result))
  590. return ie_result
  591. if result_type == 'video':
  592. self.add_extra_info(ie_result, extra_info)
  593. return self.process_video_result(ie_result, download=download)
  594. elif result_type == 'url':
  595. # We have to add extra_info to the results because it may be
  596. # contained in a playlist
  597. return self.extract_info(ie_result['url'],
  598. download,
  599. ie_key=ie_result.get('ie_key'),
  600. extra_info=extra_info)
  601. elif result_type == 'url_transparent':
  602. # Use the information from the embedding page
  603. info = self.extract_info(
  604. ie_result['url'], ie_key=ie_result.get('ie_key'),
  605. extra_info=extra_info, download=False, process=False)
  606. force_properties = dict(
  607. (k, v) for k, v in ie_result.items() if v is not None)
  608. for f in ('_type', 'url'):
  609. if f in force_properties:
  610. del force_properties[f]
  611. new_result = info.copy()
  612. new_result.update(force_properties)
  613. assert new_result.get('_type') != 'url_transparent'
  614. return self.process_ie_result(
  615. new_result, download=download, extra_info=extra_info)
  616. elif result_type == 'playlist' or result_type == 'multi_video':
  617. # We process each entry in the playlist
  618. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  619. self.to_screen('[download] Downloading playlist: %s' % playlist)
  620. playlist_results = []
  621. playliststart = self.params.get('playliststart', 1) - 1
  622. playlistend = self.params.get('playlistend', None)
  623. # For backwards compatibility, interpret -1 as whole list
  624. if playlistend == -1:
  625. playlistend = None
  626. ie_entries = ie_result['entries']
  627. if isinstance(ie_entries, list):
  628. n_all_entries = len(ie_entries)
  629. entries = ie_entries[playliststart:playlistend]
  630. n_entries = len(entries)
  631. self.to_screen(
  632. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  633. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  634. elif isinstance(ie_entries, PagedList):
  635. entries = ie_entries.getslice(
  636. playliststart, playlistend)
  637. n_entries = len(entries)
  638. self.to_screen(
  639. "[%s] playlist %s: Downloading %d videos" %
  640. (ie_result['extractor'], playlist, n_entries))
  641. else: # iterable
  642. entries = list(itertools.islice(
  643. ie_entries, playliststart, playlistend))
  644. n_entries = len(entries)
  645. self.to_screen(
  646. "[%s] playlist %s: Downloading %d videos" %
  647. (ie_result['extractor'], playlist, n_entries))
  648. if self.params.get('playlistreverse', False):
  649. entries = entries[::-1]
  650. for i, entry in enumerate(entries, 1):
  651. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  652. extra = {
  653. 'n_entries': n_entries,
  654. 'playlist': playlist,
  655. 'playlist_id': ie_result.get('id'),
  656. 'playlist_title': ie_result.get('title'),
  657. 'playlist_index': i + playliststart,
  658. 'extractor': ie_result['extractor'],
  659. 'webpage_url': ie_result['webpage_url'],
  660. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  661. 'extractor_key': ie_result['extractor_key'],
  662. }
  663. reason = self._match_entry(entry)
  664. if reason is not None:
  665. self.to_screen('[download] ' + reason)
  666. continue
  667. entry_result = self.process_ie_result(entry,
  668. download=download,
  669. extra_info=extra)
  670. playlist_results.append(entry_result)
  671. ie_result['entries'] = playlist_results
  672. return ie_result
  673. elif result_type == 'compat_list':
  674. self.report_warning(
  675. 'Extractor %s returned a compat_list result. '
  676. 'It needs to be updated.' % ie_result.get('extractor'))
  677. def _fixup(r):
  678. self.add_extra_info(
  679. r,
  680. {
  681. 'extractor': ie_result['extractor'],
  682. 'webpage_url': ie_result['webpage_url'],
  683. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  684. 'extractor_key': ie_result['extractor_key'],
  685. }
  686. )
  687. return r
  688. ie_result['entries'] = [
  689. self.process_ie_result(_fixup(r), download, extra_info)
  690. for r in ie_result['entries']
  691. ]
  692. return ie_result
  693. else:
  694. raise Exception('Invalid result type: %s' % result_type)
  695. def _apply_format_filter(self, format_spec, available_formats):
  696. " Returns a tuple of the remaining format_spec and filtered formats "
  697. OPERATORS = {
  698. '<': operator.lt,
  699. '<=': operator.le,
  700. '>': operator.gt,
  701. '>=': operator.ge,
  702. '=': operator.eq,
  703. '!=': operator.ne,
  704. }
  705. operator_rex = re.compile(r'''(?x)\s*\[
  706. (?P<key>width|height|tbr|abr|vbr|filesize)
  707. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  708. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  709. \]$
  710. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  711. m = operator_rex.search(format_spec)
  712. if not m:
  713. raise ValueError('Invalid format specification %r' % format_spec)
  714. try:
  715. comparison_value = int(m.group('value'))
  716. except ValueError:
  717. comparison_value = parse_filesize(m.group('value'))
  718. if comparison_value is None:
  719. comparison_value = parse_filesize(m.group('value') + 'B')
  720. if comparison_value is None:
  721. raise ValueError(
  722. 'Invalid value %r in format specification %r' % (
  723. m.group('value'), format_spec))
  724. op = OPERATORS[m.group('op')]
  725. def _filter(f):
  726. actual_value = f.get(m.group('key'))
  727. if actual_value is None:
  728. return m.group('none_inclusive')
  729. return op(actual_value, comparison_value)
  730. new_formats = [f for f in available_formats if _filter(f)]
  731. new_format_spec = format_spec[:-len(m.group(0))]
  732. if not new_format_spec:
  733. new_format_spec = 'best'
  734. return (new_format_spec, new_formats)
  735. def select_format(self, format_spec, available_formats):
  736. while format_spec.endswith(']'):
  737. format_spec, available_formats = self._apply_format_filter(
  738. format_spec, available_formats)
  739. if not available_formats:
  740. return None
  741. if format_spec == 'best' or format_spec is None:
  742. return available_formats[-1]
  743. elif format_spec == 'worst':
  744. return available_formats[0]
  745. elif format_spec == 'bestaudio':
  746. audio_formats = [
  747. f for f in available_formats
  748. if f.get('vcodec') == 'none']
  749. if audio_formats:
  750. return audio_formats[-1]
  751. elif format_spec == 'worstaudio':
  752. audio_formats = [
  753. f for f in available_formats
  754. if f.get('vcodec') == 'none']
  755. if audio_formats:
  756. return audio_formats[0]
  757. elif format_spec == 'bestvideo':
  758. video_formats = [
  759. f for f in available_formats
  760. if f.get('acodec') == 'none']
  761. if video_formats:
  762. return video_formats[-1]
  763. elif format_spec == 'worstvideo':
  764. video_formats = [
  765. f for f in available_formats
  766. if f.get('acodec') == 'none']
  767. if video_formats:
  768. return video_formats[0]
  769. else:
  770. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  771. if format_spec in extensions:
  772. filter_f = lambda f: f['ext'] == format_spec
  773. else:
  774. filter_f = lambda f: f['format_id'] == format_spec
  775. matches = list(filter(filter_f, available_formats))
  776. if matches:
  777. return matches[-1]
  778. return None
  779. def process_video_result(self, info_dict, download=True):
  780. assert info_dict.get('_type', 'video') == 'video'
  781. if 'id' not in info_dict:
  782. raise ExtractorError('Missing "id" field in extractor result')
  783. if 'title' not in info_dict:
  784. raise ExtractorError('Missing "title" field in extractor result')
  785. if 'playlist' not in info_dict:
  786. # It isn't part of a playlist
  787. info_dict['playlist'] = None
  788. info_dict['playlist_index'] = None
  789. thumbnails = info_dict.get('thumbnails')
  790. if thumbnails:
  791. thumbnails.sort(key=lambda t: (
  792. t.get('width'), t.get('height'), t.get('url')))
  793. for t in thumbnails:
  794. if 'width' in t and 'height' in t:
  795. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  796. if thumbnails and 'thumbnail' not in info_dict:
  797. info_dict['thumbnail'] = thumbnails[-1]['url']
  798. if 'display_id' not in info_dict and 'id' in info_dict:
  799. info_dict['display_id'] = info_dict['id']
  800. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  801. # Working around negative timestamps in Windows
  802. # (see http://bugs.python.org/issue1646728)
  803. if info_dict['timestamp'] < 0 and os.name == 'nt':
  804. info_dict['timestamp'] = 0
  805. upload_date = datetime.datetime.utcfromtimestamp(
  806. info_dict['timestamp'])
  807. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  808. # This extractors handle format selection themselves
  809. if info_dict['extractor'] in ['Youku']:
  810. if download:
  811. self.process_info(info_dict)
  812. return info_dict
  813. # We now pick which formats have to be downloaded
  814. if info_dict.get('formats') is None:
  815. # There's only one format available
  816. formats = [info_dict]
  817. else:
  818. formats = info_dict['formats']
  819. if not formats:
  820. raise ExtractorError('No video formats found!')
  821. # We check that all the formats have the format and format_id fields
  822. for i, format in enumerate(formats):
  823. if 'url' not in format:
  824. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  825. if format.get('format_id') is None:
  826. format['format_id'] = compat_str(i)
  827. if format.get('format') is None:
  828. format['format'] = '{id} - {res}{note}'.format(
  829. id=format['format_id'],
  830. res=self.format_resolution(format),
  831. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  832. )
  833. # Automatically determine file extension if missing
  834. if 'ext' not in format:
  835. format['ext'] = determine_ext(format['url']).lower()
  836. format_limit = self.params.get('format_limit', None)
  837. if format_limit:
  838. formats = list(takewhile_inclusive(
  839. lambda f: f['format_id'] != format_limit, formats
  840. ))
  841. # TODO Central sorting goes here
  842. if formats[0] is not info_dict:
  843. # only set the 'formats' fields if the original info_dict list them
  844. # otherwise we end up with a circular reference, the first (and unique)
  845. # element in the 'formats' field in info_dict is info_dict itself,
  846. # wich can't be exported to json
  847. info_dict['formats'] = formats
  848. if self.params.get('listformats', None):
  849. self.list_formats(info_dict)
  850. return
  851. req_format = self.params.get('format')
  852. if req_format is None:
  853. req_format = 'best'
  854. formats_to_download = []
  855. # The -1 is for supporting YoutubeIE
  856. if req_format in ('-1', 'all'):
  857. formats_to_download = formats
  858. else:
  859. for rfstr in req_format.split(','):
  860. # We can accept formats requested in the format: 34/5/best, we pick
  861. # the first that is available, starting from left
  862. req_formats = rfstr.split('/')
  863. for rf in req_formats:
  864. if re.match(r'.+?\+.+?', rf) is not None:
  865. # Two formats have been requested like '137+139'
  866. format_1, format_2 = rf.split('+')
  867. formats_info = (self.select_format(format_1, formats),
  868. self.select_format(format_2, formats))
  869. if all(formats_info):
  870. # The first format must contain the video and the
  871. # second the audio
  872. if formats_info[0].get('vcodec') == 'none':
  873. self.report_error('The first format must '
  874. 'contain the video, try using '
  875. '"-f %s+%s"' % (format_2, format_1))
  876. return
  877. output_ext = (
  878. formats_info[0]['ext']
  879. if self.params.get('merge_output_format') is None
  880. else self.params['merge_output_format'])
  881. selected_format = {
  882. 'requested_formats': formats_info,
  883. 'format': rf,
  884. 'ext': formats_info[0]['ext'],
  885. 'width': formats_info[0].get('width'),
  886. 'height': formats_info[0].get('height'),
  887. 'resolution': formats_info[0].get('resolution'),
  888. 'fps': formats_info[0].get('fps'),
  889. 'vcodec': formats_info[0].get('vcodec'),
  890. 'vbr': formats_info[0].get('vbr'),
  891. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  892. 'acodec': formats_info[1].get('acodec'),
  893. 'abr': formats_info[1].get('abr'),
  894. 'ext': output_ext,
  895. }
  896. else:
  897. selected_format = None
  898. else:
  899. selected_format = self.select_format(rf, formats)
  900. if selected_format is not None:
  901. formats_to_download.append(selected_format)
  902. break
  903. if not formats_to_download:
  904. raise ExtractorError('requested format not available',
  905. expected=True)
  906. if download:
  907. if len(formats_to_download) > 1:
  908. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  909. for format in formats_to_download:
  910. new_info = dict(info_dict)
  911. new_info.update(format)
  912. self.process_info(new_info)
  913. # We update the info dict with the best quality format (backwards compatibility)
  914. info_dict.update(formats_to_download[-1])
  915. return info_dict
  916. def process_info(self, info_dict):
  917. """Process a single resolved IE result."""
  918. assert info_dict.get('_type', 'video') == 'video'
  919. max_downloads = self.params.get('max_downloads')
  920. if max_downloads is not None:
  921. if self._num_downloads >= int(max_downloads):
  922. raise MaxDownloadsReached()
  923. info_dict['fulltitle'] = info_dict['title']
  924. if len(info_dict['title']) > 200:
  925. info_dict['title'] = info_dict['title'][:197] + '...'
  926. # Keep for backwards compatibility
  927. info_dict['stitle'] = info_dict['title']
  928. if 'format' not in info_dict:
  929. info_dict['format'] = info_dict['ext']
  930. reason = self._match_entry(info_dict)
  931. if reason is not None:
  932. self.to_screen('[download] ' + reason)
  933. return
  934. self._num_downloads += 1
  935. filename = self.prepare_filename(info_dict)
  936. # Forced printings
  937. if self.params.get('forcetitle', False):
  938. self.to_stdout(info_dict['fulltitle'])
  939. if self.params.get('forceid', False):
  940. self.to_stdout(info_dict['id'])
  941. if self.params.get('forceurl', False):
  942. if info_dict.get('requested_formats') is not None:
  943. for f in info_dict['requested_formats']:
  944. self.to_stdout(f['url'] + f.get('play_path', ''))
  945. else:
  946. # For RTMP URLs, also include the playpath
  947. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  948. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  949. self.to_stdout(info_dict['thumbnail'])
  950. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  951. self.to_stdout(info_dict['description'])
  952. if self.params.get('forcefilename', False) and filename is not None:
  953. self.to_stdout(filename)
  954. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  955. self.to_stdout(formatSeconds(info_dict['duration']))
  956. if self.params.get('forceformat', False):
  957. self.to_stdout(info_dict['format'])
  958. if self.params.get('forcejson', False):
  959. info_dict['_filename'] = filename
  960. self.to_stdout(json.dumps(info_dict))
  961. if self.params.get('dump_single_json', False):
  962. info_dict['_filename'] = filename
  963. # Do nothing else if in simulate mode
  964. if self.params.get('simulate', False):
  965. return
  966. if filename is None:
  967. return
  968. try:
  969. dn = os.path.dirname(encodeFilename(filename))
  970. if dn and not os.path.exists(dn):
  971. os.makedirs(dn)
  972. except (OSError, IOError) as err:
  973. self.report_error('unable to create directory ' + compat_str(err))
  974. return
  975. if self.params.get('writedescription', False):
  976. descfn = filename + '.description'
  977. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  978. self.to_screen('[info] Video description is already present')
  979. elif info_dict.get('description') is None:
  980. self.report_warning('There\'s no description to write.')
  981. else:
  982. try:
  983. self.to_screen('[info] Writing video description to: ' + descfn)
  984. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  985. descfile.write(info_dict['description'])
  986. except (OSError, IOError):
  987. self.report_error('Cannot write description file ' + descfn)
  988. return
  989. if self.params.get('writeannotations', False):
  990. annofn = filename + '.annotations.xml'
  991. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  992. self.to_screen('[info] Video annotations are already present')
  993. else:
  994. try:
  995. self.to_screen('[info] Writing video annotations to: ' + annofn)
  996. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  997. annofile.write(info_dict['annotations'])
  998. except (KeyError, TypeError):
  999. self.report_warning('There are no annotations to write.')
  1000. except (OSError, IOError):
  1001. self.report_error('Cannot write annotations file: ' + annofn)
  1002. return
  1003. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1004. self.params.get('writeautomaticsub')])
  1005. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1006. # subtitles download errors are already managed as troubles in relevant IE
  1007. # that way it will silently go on when used with unsupporting IE
  1008. subtitles = info_dict['subtitles']
  1009. sub_format = self.params.get('subtitlesformat', 'srt')
  1010. for sub_lang in subtitles.keys():
  1011. sub = subtitles[sub_lang]
  1012. if sub is None:
  1013. continue
  1014. try:
  1015. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1016. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1017. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1018. else:
  1019. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1020. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1021. subfile.write(sub)
  1022. except (OSError, IOError):
  1023. self.report_error('Cannot write subtitles file ' + sub_filename)
  1024. return
  1025. if self.params.get('writeinfojson', False):
  1026. infofn = os.path.splitext(filename)[0] + '.info.json'
  1027. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1028. self.to_screen('[info] Video description metadata is already present')
  1029. else:
  1030. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1031. try:
  1032. write_json_file(info_dict, infofn)
  1033. except (OSError, IOError):
  1034. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1035. return
  1036. if self.params.get('writethumbnail', False):
  1037. if info_dict.get('thumbnail') is not None:
  1038. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  1039. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  1040. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1041. self.to_screen('[%s] %s: Thumbnail is already present' %
  1042. (info_dict['extractor'], info_dict['id']))
  1043. else:
  1044. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  1045. (info_dict['extractor'], info_dict['id']))
  1046. try:
  1047. uf = self.urlopen(info_dict['thumbnail'])
  1048. with open(thumb_filename, 'wb') as thumbf:
  1049. shutil.copyfileobj(uf, thumbf)
  1050. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  1051. (info_dict['extractor'], info_dict['id'], thumb_filename))
  1052. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1053. self.report_warning('Unable to download thumbnail "%s": %s' %
  1054. (info_dict['thumbnail'], compat_str(err)))
  1055. if not self.params.get('skip_download', False):
  1056. try:
  1057. def dl(name, info):
  1058. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1059. for ph in self._progress_hooks:
  1060. fd.add_progress_hook(ph)
  1061. if self.params.get('verbose'):
  1062. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1063. return fd.download(name, info)
  1064. if info_dict.get('requested_formats') is not None:
  1065. downloaded = []
  1066. success = True
  1067. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1068. if not merger._executable:
  1069. postprocessors = []
  1070. self.report_warning('You have requested multiple '
  1071. 'formats but ffmpeg or avconv are not installed.'
  1072. ' The formats won\'t be merged')
  1073. else:
  1074. postprocessors = [merger]
  1075. for f in info_dict['requested_formats']:
  1076. new_info = dict(info_dict)
  1077. new_info.update(f)
  1078. fname = self.prepare_filename(new_info)
  1079. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1080. downloaded.append(fname)
  1081. partial_success = dl(fname, new_info)
  1082. success = success and partial_success
  1083. info_dict['__postprocessors'] = postprocessors
  1084. info_dict['__files_to_merge'] = downloaded
  1085. else:
  1086. # Just a single file
  1087. success = dl(filename, info_dict)
  1088. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1089. self.report_error('unable to download video data: %s' % str(err))
  1090. return
  1091. except (OSError, IOError) as err:
  1092. raise UnavailableVideoError(err)
  1093. except (ContentTooShortError, ) as err:
  1094. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1095. return
  1096. if success:
  1097. # Fixup content
  1098. fixup_policy = self.params.get('fixup')
  1099. if fixup_policy is None:
  1100. fixup_policy = 'detect_or_warn'
  1101. stretched_ratio = info_dict.get('stretched_ratio')
  1102. if stretched_ratio is not None and stretched_ratio != 1:
  1103. if fixup_policy == 'warn':
  1104. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1105. info_dict['id'], stretched_ratio))
  1106. elif fixup_policy == 'detect_or_warn':
  1107. stretched_pp = FFmpegFixupStretchedPP(self)
  1108. if stretched_pp.available:
  1109. info_dict.setdefault('__postprocessors', [])
  1110. info_dict['__postprocessors'].append(stretched_pp)
  1111. else:
  1112. self.report_warning(
  1113. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1114. info_dict['id'], stretched_ratio))
  1115. else:
  1116. assert fixup_policy in ('ignore', 'never')
  1117. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1118. if fixup_policy == 'warn':
  1119. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1120. info_dict['id']))
  1121. elif fixup_policy == 'detect_or_warn':
  1122. fixup_pp = FFmpegFixupM4aPP(self)
  1123. if fixup_pp.available:
  1124. info_dict.setdefault('__postprocessors', [])
  1125. info_dict['__postprocessors'].append(fixup_pp)
  1126. else:
  1127. self.report_warning(
  1128. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1129. info_dict['id']))
  1130. else:
  1131. assert fixup_policy in ('ignore', 'never')
  1132. try:
  1133. self.post_process(filename, info_dict)
  1134. except (PostProcessingError) as err:
  1135. self.report_error('postprocessing: %s' % str(err))
  1136. return
  1137. self.record_download_archive(info_dict)
  1138. def download(self, url_list):
  1139. """Download a given list of URLs."""
  1140. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1141. if (len(url_list) > 1 and
  1142. '%' not in outtmpl
  1143. and self.params.get('max_downloads') != 1):
  1144. raise SameFileError(outtmpl)
  1145. for url in url_list:
  1146. try:
  1147. # It also downloads the videos
  1148. res = self.extract_info(url)
  1149. except UnavailableVideoError:
  1150. self.report_error('unable to download video')
  1151. except MaxDownloadsReached:
  1152. self.to_screen('[info] Maximum number of downloaded files reached.')
  1153. raise
  1154. else:
  1155. if self.params.get('dump_single_json', False):
  1156. self.to_stdout(json.dumps(res))
  1157. return self._download_retcode
  1158. def download_with_info_file(self, info_filename):
  1159. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1160. info = json.load(f)
  1161. try:
  1162. self.process_ie_result(info, download=True)
  1163. except DownloadError:
  1164. webpage_url = info.get('webpage_url')
  1165. if webpage_url is not None:
  1166. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1167. return self.download([webpage_url])
  1168. else:
  1169. raise
  1170. return self._download_retcode
  1171. def post_process(self, filename, ie_info):
  1172. """Run all the postprocessors on the given file."""
  1173. info = dict(ie_info)
  1174. info['filepath'] = filename
  1175. pps_chain = []
  1176. if ie_info.get('__postprocessors') is not None:
  1177. pps_chain.extend(ie_info['__postprocessors'])
  1178. pps_chain.extend(self._pps)
  1179. for pp in pps_chain:
  1180. keep_video = None
  1181. old_filename = info['filepath']
  1182. try:
  1183. keep_video_wish, info = pp.run(info)
  1184. if keep_video_wish is not None:
  1185. if keep_video_wish:
  1186. keep_video = keep_video_wish
  1187. elif keep_video is None:
  1188. # No clear decision yet, let IE decide
  1189. keep_video = keep_video_wish
  1190. except PostProcessingError as e:
  1191. self.report_error(e.msg)
  1192. if keep_video is False and not self.params.get('keepvideo', False):
  1193. try:
  1194. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1195. os.remove(encodeFilename(old_filename))
  1196. except (IOError, OSError):
  1197. self.report_warning('Unable to remove downloaded video file')
  1198. def _make_archive_id(self, info_dict):
  1199. # Future-proof against any change in case
  1200. # and backwards compatibility with prior versions
  1201. extractor = info_dict.get('extractor_key')
  1202. if extractor is None:
  1203. if 'id' in info_dict:
  1204. extractor = info_dict.get('ie_key') # key in a playlist
  1205. if extractor is None:
  1206. return None # Incomplete video information
  1207. return extractor.lower() + ' ' + info_dict['id']
  1208. def in_download_archive(self, info_dict):
  1209. fn = self.params.get('download_archive')
  1210. if fn is None:
  1211. return False
  1212. vid_id = self._make_archive_id(info_dict)
  1213. if vid_id is None:
  1214. return False # Incomplete video information
  1215. try:
  1216. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1217. for line in archive_file:
  1218. if line.strip() == vid_id:
  1219. return True
  1220. except IOError as ioe:
  1221. if ioe.errno != errno.ENOENT:
  1222. raise
  1223. return False
  1224. def record_download_archive(self, info_dict):
  1225. fn = self.params.get('download_archive')
  1226. if fn is None:
  1227. return
  1228. vid_id = self._make_archive_id(info_dict)
  1229. assert vid_id
  1230. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1231. archive_file.write(vid_id + '\n')
  1232. @staticmethod
  1233. def format_resolution(format, default='unknown'):
  1234. if format.get('vcodec') == 'none':
  1235. return 'audio only'
  1236. if format.get('resolution') is not None:
  1237. return format['resolution']
  1238. if format.get('height') is not None:
  1239. if format.get('width') is not None:
  1240. res = '%sx%s' % (format['width'], format['height'])
  1241. else:
  1242. res = '%sp' % format['height']
  1243. elif format.get('width') is not None:
  1244. res = '?x%d' % format['width']
  1245. else:
  1246. res = default
  1247. return res
  1248. def _format_note(self, fdict):
  1249. res = ''
  1250. if fdict.get('ext') in ['f4f', 'f4m']:
  1251. res += '(unsupported) '
  1252. if fdict.get('format_note') is not None:
  1253. res += fdict['format_note'] + ' '
  1254. if fdict.get('tbr') is not None:
  1255. res += '%4dk ' % fdict['tbr']
  1256. if fdict.get('container') is not None:
  1257. if res:
  1258. res += ', '
  1259. res += '%s container' % fdict['container']
  1260. if (fdict.get('vcodec') is not None and
  1261. fdict.get('vcodec') != 'none'):
  1262. if res:
  1263. res += ', '
  1264. res += fdict['vcodec']
  1265. if fdict.get('vbr') is not None:
  1266. res += '@'
  1267. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1268. res += 'video@'
  1269. if fdict.get('vbr') is not None:
  1270. res += '%4dk' % fdict['vbr']
  1271. if fdict.get('fps') is not None:
  1272. res += ', %sfps' % fdict['fps']
  1273. if fdict.get('acodec') is not None:
  1274. if res:
  1275. res += ', '
  1276. if fdict['acodec'] == 'none':
  1277. res += 'video only'
  1278. else:
  1279. res += '%-5s' % fdict['acodec']
  1280. elif fdict.get('abr') is not None:
  1281. if res:
  1282. res += ', '
  1283. res += 'audio'
  1284. if fdict.get('abr') is not None:
  1285. res += '@%3dk' % fdict['abr']
  1286. if fdict.get('asr') is not None:
  1287. res += ' (%5dHz)' % fdict['asr']
  1288. if fdict.get('filesize') is not None:
  1289. if res:
  1290. res += ', '
  1291. res += format_bytes(fdict['filesize'])
  1292. elif fdict.get('filesize_approx') is not None:
  1293. if res:
  1294. res += ', '
  1295. res += '~' + format_bytes(fdict['filesize_approx'])
  1296. return res
  1297. def list_formats(self, info_dict):
  1298. def line(format, idlen=20):
  1299. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1300. format['format_id'],
  1301. format['ext'],
  1302. self.format_resolution(format),
  1303. self._format_note(format),
  1304. ))
  1305. formats = info_dict.get('formats', [info_dict])
  1306. idlen = max(len('format code'),
  1307. max(len(f['format_id']) for f in formats))
  1308. formats_s = [
  1309. line(f, idlen) for f in formats
  1310. if f.get('preference') is None or f['preference'] >= -1000]
  1311. if len(formats) > 1:
  1312. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1313. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1314. header_line = line({
  1315. 'format_id': 'format code', 'ext': 'extension',
  1316. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1317. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1318. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1319. def urlopen(self, req):
  1320. """ Start an HTTP download """
  1321. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1322. # always respected by websites, some tend to give out URLs with non percent-encoded
  1323. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1324. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1325. # To work around aforementioned issue we will replace request's original URL with
  1326. # percent-encoded one
  1327. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1328. url = req if req_is_string else req.get_full_url()
  1329. url_escaped = escape_url(url)
  1330. # Substitute URL if any change after escaping
  1331. if url != url_escaped:
  1332. if req_is_string:
  1333. req = url_escaped
  1334. else:
  1335. req = compat_urllib_request.Request(
  1336. url_escaped, data=req.data, headers=req.headers,
  1337. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1338. return self._opener.open(req, timeout=self._socket_timeout)
  1339. def print_debug_header(self):
  1340. if not self.params.get('verbose'):
  1341. return
  1342. if type('') is not compat_str:
  1343. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1344. self.report_warning(
  1345. 'Your Python is broken! Update to a newer and supported version')
  1346. stdout_encoding = getattr(
  1347. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1348. encoding_str = (
  1349. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1350. locale.getpreferredencoding(),
  1351. sys.getfilesystemencoding(),
  1352. stdout_encoding,
  1353. self.get_encoding()))
  1354. write_string(encoding_str, encoding=None)
  1355. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1356. try:
  1357. sp = subprocess.Popen(
  1358. ['git', 'rev-parse', '--short', 'HEAD'],
  1359. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1360. cwd=os.path.dirname(os.path.abspath(__file__)))
  1361. out, err = sp.communicate()
  1362. out = out.decode().strip()
  1363. if re.match('[0-9a-f]+', out):
  1364. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1365. except:
  1366. try:
  1367. sys.exc_clear()
  1368. except:
  1369. pass
  1370. self._write_string('[debug] Python version %s - %s\n' % (
  1371. platform.python_version(), platform_name()))
  1372. exe_versions = FFmpegPostProcessor.get_versions()
  1373. exe_versions['rtmpdump'] = rtmpdump_version()
  1374. exe_str = ', '.join(
  1375. '%s %s' % (exe, v)
  1376. for exe, v in sorted(exe_versions.items())
  1377. if v
  1378. )
  1379. if not exe_str:
  1380. exe_str = 'none'
  1381. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1382. proxy_map = {}
  1383. for handler in self._opener.handlers:
  1384. if hasattr(handler, 'proxies'):
  1385. proxy_map.update(handler.proxies)
  1386. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1387. if self.params.get('call_home', False):
  1388. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1389. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1390. latest_version = self.urlopen(
  1391. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1392. if version_tuple(latest_version) > version_tuple(__version__):
  1393. self.report_warning(
  1394. 'You are using an outdated version (newest version: %s)! '
  1395. 'See https://yt-dl.org/update if you need help updating.' %
  1396. latest_version)
  1397. def _setup_opener(self):
  1398. timeout_val = self.params.get('socket_timeout')
  1399. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1400. opts_cookiefile = self.params.get('cookiefile')
  1401. opts_proxy = self.params.get('proxy')
  1402. if opts_cookiefile is None:
  1403. self.cookiejar = compat_cookiejar.CookieJar()
  1404. else:
  1405. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1406. opts_cookiefile)
  1407. if os.access(opts_cookiefile, os.R_OK):
  1408. self.cookiejar.load()
  1409. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1410. self.cookiejar)
  1411. if opts_proxy is not None:
  1412. if opts_proxy == '':
  1413. proxies = {}
  1414. else:
  1415. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1416. else:
  1417. proxies = compat_urllib_request.getproxies()
  1418. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1419. if 'http' in proxies and 'https' not in proxies:
  1420. proxies['https'] = proxies['http']
  1421. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1422. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1423. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1424. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1425. opener = compat_urllib_request.build_opener(
  1426. https_handler, proxy_handler, cookie_processor, ydlh)
  1427. # Delete the default user-agent header, which would otherwise apply in
  1428. # cases where our custom HTTP handler doesn't come into play
  1429. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1430. opener.addheaders = []
  1431. self._opener = opener
  1432. def encode(self, s):
  1433. if isinstance(s, bytes):
  1434. return s # Already encoded
  1435. try:
  1436. return s.encode(self.get_encoding())
  1437. except UnicodeEncodeError as err:
  1438. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1439. raise
  1440. def get_encoding(self):
  1441. encoding = self.params.get('encoding')
  1442. if encoding is None:
  1443. encoding = preferredencoding()
  1444. return encoding