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.

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