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.

1239 lines
53 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
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import errno
  6. import io
  7. import json
  8. import os
  9. import platform
  10. import re
  11. import shutil
  12. import subprocess
  13. import socket
  14. import sys
  15. import time
  16. import traceback
  17. if os.name == 'nt':
  18. import ctypes
  19. from .utils import (
  20. compat_cookiejar,
  21. compat_http_client,
  22. compat_str,
  23. compat_urllib_error,
  24. compat_urllib_request,
  25. ContentTooShortError,
  26. date_from_str,
  27. DateRange,
  28. determine_ext,
  29. DownloadError,
  30. encodeFilename,
  31. ExtractorError,
  32. format_bytes,
  33. formatSeconds,
  34. get_term_width,
  35. locked_file,
  36. make_HTTPS_handler,
  37. MaxDownloadsReached,
  38. PagedList,
  39. PostProcessingError,
  40. platform_name,
  41. preferredencoding,
  42. SameFileError,
  43. sanitize_filename,
  44. subtitles_filename,
  45. takewhile_inclusive,
  46. UnavailableVideoError,
  47. url_basename,
  48. write_json_file,
  49. write_string,
  50. YoutubeDLHandler,
  51. prepend_extension,
  52. )
  53. from .extractor import get_info_extractor, gen_extractors
  54. from .downloader import get_suitable_downloader
  55. from .postprocessor import FFmpegMergerPP
  56. from .version import __version__
  57. class YoutubeDL(object):
  58. """YoutubeDL class.
  59. YoutubeDL objects are the ones responsible of downloading the
  60. actual video file and writing it to disk if the user has requested
  61. it, among some other tasks. In most cases there should be one per
  62. program. As, given a video URL, the downloader doesn't know how to
  63. extract all the needed information, task that InfoExtractors do, it
  64. has to pass the URL to one of them.
  65. For this, YoutubeDL objects have a method that allows
  66. InfoExtractors to be registered in a given order. When it is passed
  67. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  68. finds that reports being able to handle it. The InfoExtractor extracts
  69. all the information about the video or videos the URL refers to, and
  70. YoutubeDL process the extracted information, possibly using a File
  71. Downloader to download the video.
  72. YoutubeDL objects accept a lot of parameters. In order not to saturate
  73. the object constructor with arguments, it receives a dictionary of
  74. options instead. These options are available through the params
  75. attribute for the InfoExtractors to use. The YoutubeDL also
  76. registers itself as the downloader in charge for the InfoExtractors
  77. that are added to it, so this is a "mutual registration".
  78. Available options:
  79. username: Username for authentication purposes.
  80. password: Password for authentication purposes.
  81. videopassword: Password for acces a video.
  82. usenetrc: Use netrc for authentication instead.
  83. verbose: Print additional info to stdout.
  84. quiet: Do not print messages to stdout.
  85. forceurl: Force printing final URL.
  86. forcetitle: Force printing title.
  87. forceid: Force printing ID.
  88. forcethumbnail: Force printing thumbnail URL.
  89. forcedescription: Force printing description.
  90. forcefilename: Force printing final filename.
  91. forceduration: Force printing duration.
  92. forcejson: Force printing info_dict as JSON.
  93. simulate: Do not download the video files.
  94. format: Video format code.
  95. format_limit: Highest quality format to try.
  96. outtmpl: Template for output names.
  97. restrictfilenames: Do not allow "&" and spaces in file names
  98. ignoreerrors: Do not stop on download errors.
  99. nooverwrites: Prevent overwriting files.
  100. playliststart: Playlist item to start at.
  101. playlistend: Playlist item to end at.
  102. matchtitle: Download only matching titles.
  103. rejecttitle: Reject downloads for matching titles.
  104. logger: Log messages to a logging.Logger instance.
  105. logtostderr: Log messages to stderr instead of stdout.
  106. writedescription: Write the video description to a .description file
  107. writeinfojson: Write the video description to a .info.json file
  108. writeannotations: Write the video annotations to a .annotations.xml file
  109. writethumbnail: Write the thumbnail image to a file
  110. writesubtitles: Write the video subtitles to a file
  111. writeautomaticsub: Write the automatic subtitles to a file
  112. allsubtitles: Downloads all the subtitles of the video
  113. (requires writesubtitles or writeautomaticsub)
  114. listsubtitles: Lists all available subtitles for the video
  115. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  116. subtitleslangs: List of languages of the subtitles to download
  117. keepvideo: Keep the video file after post-processing
  118. daterange: A DateRange object, download only if the upload_date is in the range.
  119. skip_download: Skip the actual download of the video file
  120. cachedir: Location of the cache files in the filesystem.
  121. None to disable filesystem cache.
  122. noplaylist: Download single video instead of a playlist if in doubt.
  123. age_limit: An integer representing the user's age in years.
  124. Unsuitable videos for the given age are skipped.
  125. min_views: An integer representing the minimum view count the video
  126. must have in order to not be skipped.
  127. Videos without view count information are always
  128. downloaded. None for no limit.
  129. max_views: An integer representing the maximum view count.
  130. Videos that are more popular than that are not
  131. downloaded.
  132. Videos without view count information are always
  133. downloaded. None for no limit.
  134. download_archive: File name of a file where all downloads are recorded.
  135. Videos already present in the file are not downloaded
  136. again.
  137. cookiefile: File name where cookies should be read from and dumped to.
  138. nocheckcertificate:Do not verify SSL certificates
  139. proxy: URL of the proxy server to use
  140. socket_timeout: Time to wait for unresponsive hosts, in seconds
  141. bidi_workaround: Work around buggy terminals without bidirectional text
  142. support, using fridibi
  143. debug_printtraffic:Print out sent and received HTTP traffic
  144. include_ads: Download ads as well
  145. default_search: Prepend this string if an input url is not valid.
  146. 'auto' for elaborate guessing
  147. The following parameters are not used by YoutubeDL itself, they are used by
  148. the FileDownloader:
  149. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  150. noresizebuffer, retries, continuedl, noprogress, consoletitle
  151. The following options are used by the post processors:
  152. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  153. otherwise prefer avconv.
  154. """
  155. params = None
  156. _ies = []
  157. _pps = []
  158. _download_retcode = None
  159. _num_downloads = None
  160. _screen_file = None
  161. def __init__(self, params=None):
  162. """Create a FileDownloader object with the given options."""
  163. if params is None:
  164. params = {}
  165. self._ies = []
  166. self._ies_instances = {}
  167. self._pps = []
  168. self._progress_hooks = []
  169. self._download_retcode = 0
  170. self._num_downloads = 0
  171. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  172. self._err_file = sys.stderr
  173. self.params = params
  174. if params.get('bidi_workaround', False):
  175. try:
  176. import pty
  177. master, slave = pty.openpty()
  178. width = get_term_width()
  179. if width is None:
  180. width_args = []
  181. else:
  182. width_args = ['-w', str(width)]
  183. sp_kwargs = dict(
  184. stdin=subprocess.PIPE,
  185. stdout=slave,
  186. stderr=self._err_file)
  187. try:
  188. self._output_process = subprocess.Popen(
  189. ['bidiv'] + width_args, **sp_kwargs
  190. )
  191. except OSError:
  192. self._output_process = subprocess.Popen(
  193. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  194. self._output_channel = os.fdopen(master, 'rb')
  195. except OSError as ose:
  196. if ose.errno == 2:
  197. 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.')
  198. else:
  199. raise
  200. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  201. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  202. and not params['restrictfilenames']):
  203. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  204. self.report_warning(
  205. 'Assuming --restrict-filenames since file system encoding '
  206. 'cannot encode all charactes. '
  207. 'Set the LC_ALL environment variable to fix this.')
  208. self.params['restrictfilenames'] = True
  209. if '%(stitle)s' in self.params.get('outtmpl', ''):
  210. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  211. self._setup_opener()
  212. def add_info_extractor(self, ie):
  213. """Add an InfoExtractor object to the end of the list."""
  214. self._ies.append(ie)
  215. self._ies_instances[ie.ie_key()] = ie
  216. ie.set_downloader(self)
  217. def get_info_extractor(self, ie_key):
  218. """
  219. Get an instance of an IE with name ie_key, it will try to get one from
  220. the _ies list, if there's no instance it will create a new one and add
  221. it to the extractor list.
  222. """
  223. ie = self._ies_instances.get(ie_key)
  224. if ie is None:
  225. ie = get_info_extractor(ie_key)()
  226. self.add_info_extractor(ie)
  227. return ie
  228. def add_default_info_extractors(self):
  229. """
  230. Add the InfoExtractors returned by gen_extractors to the end of the list
  231. """
  232. for ie in gen_extractors():
  233. self.add_info_extractor(ie)
  234. def add_post_processor(self, pp):
  235. """Add a PostProcessor object to the end of the chain."""
  236. self._pps.append(pp)
  237. pp.set_downloader(self)
  238. def add_progress_hook(self, ph):
  239. """Add the progress hook (currently only for the file downloader)"""
  240. self._progress_hooks.append(ph)
  241. def _bidi_workaround(self, message):
  242. if not hasattr(self, '_output_channel'):
  243. return message
  244. assert hasattr(self, '_output_process')
  245. assert type(message) == type('')
  246. line_count = message.count('\n') + 1
  247. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  248. self._output_process.stdin.flush()
  249. res = ''.join(self._output_channel.readline().decode('utf-8')
  250. for _ in range(line_count))
  251. return res[:-len('\n')]
  252. def to_screen(self, message, skip_eol=False):
  253. """Print message to stdout if not in quiet mode."""
  254. return self.to_stdout(message, skip_eol, check_quiet=True)
  255. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  256. """Print message to stdout if not in quiet mode."""
  257. if self.params.get('logger'):
  258. self.params['logger'].debug(message)
  259. elif not check_quiet or not self.params.get('quiet', False):
  260. message = self._bidi_workaround(message)
  261. terminator = ['\n', ''][skip_eol]
  262. output = message + terminator
  263. write_string(output, self._screen_file)
  264. def to_stderr(self, message):
  265. """Print message to stderr."""
  266. assert type(message) == type('')
  267. if self.params.get('logger'):
  268. self.params['logger'].error(message)
  269. else:
  270. message = self._bidi_workaround(message)
  271. output = message + '\n'
  272. write_string(output, self._err_file)
  273. def to_console_title(self, message):
  274. if not self.params.get('consoletitle', False):
  275. return
  276. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  277. # c_wchar_p() might not be necessary if `message` is
  278. # already of type unicode()
  279. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  280. elif 'TERM' in os.environ:
  281. write_string('\033]0;%s\007' % message, self._screen_file)
  282. def save_console_title(self):
  283. if not self.params.get('consoletitle', False):
  284. return
  285. if 'TERM' in os.environ:
  286. # Save the title on stack
  287. write_string('\033[22;0t', self._screen_file)
  288. def restore_console_title(self):
  289. if not self.params.get('consoletitle', False):
  290. return
  291. if 'TERM' in os.environ:
  292. # Restore the title from stack
  293. write_string('\033[23;0t', self._screen_file)
  294. def __enter__(self):
  295. self.save_console_title()
  296. return self
  297. def __exit__(self, *args):
  298. self.restore_console_title()
  299. if self.params.get('cookiefile') is not None:
  300. self.cookiejar.save()
  301. def trouble(self, message=None, tb=None):
  302. """Determine action to take when a download problem appears.
  303. Depending on if the downloader has been configured to ignore
  304. download errors or not, this method may throw an exception or
  305. not when errors are found, after printing the message.
  306. tb, if given, is additional traceback information.
  307. """
  308. if message is not None:
  309. self.to_stderr(message)
  310. if self.params.get('verbose'):
  311. if tb is None:
  312. if sys.exc_info()[0]: # if .trouble has been called from an except block
  313. tb = ''
  314. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  315. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  316. tb += compat_str(traceback.format_exc())
  317. else:
  318. tb_data = traceback.format_list(traceback.extract_stack())
  319. tb = ''.join(tb_data)
  320. self.to_stderr(tb)
  321. if not self.params.get('ignoreerrors', False):
  322. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  323. exc_info = sys.exc_info()[1].exc_info
  324. else:
  325. exc_info = sys.exc_info()
  326. raise DownloadError(message, exc_info)
  327. self._download_retcode = 1
  328. def report_warning(self, message):
  329. '''
  330. Print the message to stderr, it will be prefixed with 'WARNING:'
  331. If stderr is a tty file the 'WARNING:' will be colored
  332. '''
  333. if self._err_file.isatty() and os.name != 'nt':
  334. _msg_header = '\033[0;33mWARNING:\033[0m'
  335. else:
  336. _msg_header = 'WARNING:'
  337. warning_message = '%s %s' % (_msg_header, message)
  338. self.to_stderr(warning_message)
  339. def report_error(self, message, tb=None):
  340. '''
  341. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  342. in red if stderr is a tty file.
  343. '''
  344. if self._err_file.isatty() and os.name != 'nt':
  345. _msg_header = '\033[0;31mERROR:\033[0m'
  346. else:
  347. _msg_header = 'ERROR:'
  348. error_message = '%s %s' % (_msg_header, message)
  349. self.trouble(error_message, tb)
  350. def report_file_already_downloaded(self, file_name):
  351. """Report file has already been fully downloaded."""
  352. try:
  353. self.to_screen('[download] %s has already been downloaded' % file_name)
  354. except UnicodeEncodeError:
  355. self.to_screen('[download] The file has already been downloaded')
  356. def prepare_filename(self, info_dict):
  357. """Generate the output filename."""
  358. try:
  359. template_dict = dict(info_dict)
  360. template_dict['epoch'] = int(time.time())
  361. autonumber_size = self.params.get('autonumber_size')
  362. if autonumber_size is None:
  363. autonumber_size = 5
  364. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  365. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  366. if template_dict.get('playlist_index') is not None:
  367. template_dict['playlist_index'] = '%05d' % template_dict['playlist_index']
  368. if template_dict.get('resolution') is None:
  369. if template_dict.get('width') and template_dict.get('height'):
  370. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  371. elif template_dict.get('height'):
  372. res = '%sp' % template_dict['height']
  373. elif template_dict.get('width'):
  374. res = '?x%d' % template_dict['width']
  375. sanitize = lambda k, v: sanitize_filename(
  376. compat_str(v),
  377. restricted=self.params.get('restrictfilenames'),
  378. is_id=(k == 'id'))
  379. template_dict = dict((k, sanitize(k, v))
  380. for k, v in template_dict.items()
  381. if v is not None)
  382. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  383. tmpl = os.path.expanduser(self.params['outtmpl'])
  384. filename = tmpl % template_dict
  385. return filename
  386. except ValueError as err:
  387. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  388. return None
  389. def _match_entry(self, info_dict):
  390. """ Returns None iff the file should be downloaded """
  391. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  392. if 'title' in info_dict:
  393. # This can happen when we're just evaluating the playlist
  394. title = info_dict['title']
  395. matchtitle = self.params.get('matchtitle', False)
  396. if matchtitle:
  397. if not re.search(matchtitle, title, re.IGNORECASE):
  398. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  399. rejecttitle = self.params.get('rejecttitle', False)
  400. if rejecttitle:
  401. if re.search(rejecttitle, title, re.IGNORECASE):
  402. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  403. date = info_dict.get('upload_date', None)
  404. if date is not None:
  405. dateRange = self.params.get('daterange', DateRange())
  406. if date not in dateRange:
  407. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  408. view_count = info_dict.get('view_count', None)
  409. if view_count is not None:
  410. min_views = self.params.get('min_views')
  411. if min_views is not None and view_count < min_views:
  412. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  413. max_views = self.params.get('max_views')
  414. if max_views is not None and view_count > max_views:
  415. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  416. age_limit = self.params.get('age_limit')
  417. if age_limit is not None:
  418. if age_limit < info_dict.get('age_limit', 0):
  419. return 'Skipping "' + title + '" because it is age restricted'
  420. if self.in_download_archive(info_dict):
  421. return '%s has already been recorded in archive' % video_title
  422. return None
  423. @staticmethod
  424. def add_extra_info(info_dict, extra_info):
  425. '''Set the keys from extra_info in info dict if they are missing'''
  426. for key, value in extra_info.items():
  427. info_dict.setdefault(key, value)
  428. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  429. process=True):
  430. '''
  431. Returns a list with a dictionary for each video we find.
  432. If 'download', also downloads the videos.
  433. extra_info is a dict containing the extra values to add to each result
  434. '''
  435. if ie_key:
  436. ies = [self.get_info_extractor(ie_key)]
  437. else:
  438. ies = self._ies
  439. for ie in ies:
  440. if not ie.suitable(url):
  441. continue
  442. if not ie.working():
  443. self.report_warning('The program functionality for this site has been marked as broken, '
  444. 'and will probably not work.')
  445. try:
  446. ie_result = ie.extract(url)
  447. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  448. break
  449. if isinstance(ie_result, list):
  450. # Backwards compatibility: old IE result format
  451. ie_result = {
  452. '_type': 'compat_list',
  453. 'entries': ie_result,
  454. }
  455. self.add_extra_info(ie_result,
  456. {
  457. 'extractor': ie.IE_NAME,
  458. 'webpage_url': url,
  459. 'webpage_url_basename': url_basename(url),
  460. 'extractor_key': ie.ie_key(),
  461. })
  462. if process:
  463. return self.process_ie_result(ie_result, download, extra_info)
  464. else:
  465. return ie_result
  466. except ExtractorError as de: # An error we somewhat expected
  467. self.report_error(compat_str(de), de.format_traceback())
  468. break
  469. except MaxDownloadsReached:
  470. raise
  471. except Exception as e:
  472. if self.params.get('ignoreerrors', False):
  473. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  474. break
  475. else:
  476. raise
  477. else:
  478. self.report_error('no suitable InfoExtractor: %s' % url)
  479. def process_ie_result(self, ie_result, download=True, extra_info={}):
  480. """
  481. Take the result of the ie(may be modified) and resolve all unresolved
  482. references (URLs, playlist items).
  483. It will also download the videos if 'download'.
  484. Returns the resolved ie_result.
  485. """
  486. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  487. if result_type == 'video':
  488. self.add_extra_info(ie_result, extra_info)
  489. return self.process_video_result(ie_result, download=download)
  490. elif result_type == 'url':
  491. # We have to add extra_info to the results because it may be
  492. # contained in a playlist
  493. return self.extract_info(ie_result['url'],
  494. download,
  495. ie_key=ie_result.get('ie_key'),
  496. extra_info=extra_info)
  497. elif result_type == 'url_transparent':
  498. # Use the information from the embedding page
  499. info = self.extract_info(
  500. ie_result['url'], ie_key=ie_result.get('ie_key'),
  501. extra_info=extra_info, download=False, process=False)
  502. def make_result(embedded_info):
  503. new_result = ie_result.copy()
  504. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  505. 'entries', 'ie_key', 'duration',
  506. 'subtitles', 'annotations', 'format',
  507. 'thumbnail', 'thumbnails'):
  508. if f in new_result:
  509. del new_result[f]
  510. if f in embedded_info:
  511. new_result[f] = embedded_info[f]
  512. return new_result
  513. new_result = make_result(info)
  514. assert new_result.get('_type') != 'url_transparent'
  515. if new_result.get('_type') == 'compat_list':
  516. new_result['entries'] = [
  517. make_result(e) for e in new_result['entries']]
  518. return self.process_ie_result(
  519. new_result, download=download, extra_info=extra_info)
  520. elif result_type == 'playlist':
  521. # We process each entry in the playlist
  522. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  523. self.to_screen('[download] Downloading playlist: %s' % playlist)
  524. playlist_results = []
  525. playliststart = self.params.get('playliststart', 1) - 1
  526. playlistend = self.params.get('playlistend', None)
  527. # For backwards compatibility, interpret -1 as whole list
  528. if playlistend == -1:
  529. playlistend = None
  530. if isinstance(ie_result['entries'], list):
  531. n_all_entries = len(ie_result['entries'])
  532. entries = ie_result['entries'][playliststart:playlistend]
  533. n_entries = len(entries)
  534. self.to_screen(
  535. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  536. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  537. else:
  538. assert isinstance(ie_result['entries'], PagedList)
  539. entries = ie_result['entries'].getslice(
  540. playliststart, playlistend)
  541. n_entries = len(entries)
  542. self.to_screen(
  543. "[%s] playlist %s: Downloading %d videos" %
  544. (ie_result['extractor'], playlist, n_entries))
  545. for i, entry in enumerate(entries, 1):
  546. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  547. extra = {
  548. 'playlist': playlist,
  549. 'playlist_index': i + playliststart,
  550. 'extractor': ie_result['extractor'],
  551. 'webpage_url': ie_result['webpage_url'],
  552. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  553. 'extractor_key': ie_result['extractor_key'],
  554. }
  555. reason = self._match_entry(entry)
  556. if reason is not None:
  557. self.to_screen('[download] ' + reason)
  558. continue
  559. entry_result = self.process_ie_result(entry,
  560. download=download,
  561. extra_info=extra)
  562. playlist_results.append(entry_result)
  563. ie_result['entries'] = playlist_results
  564. return ie_result
  565. elif result_type == 'compat_list':
  566. def _fixup(r):
  567. self.add_extra_info(r,
  568. {
  569. 'extractor': ie_result['extractor'],
  570. 'webpage_url': ie_result['webpage_url'],
  571. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  572. 'extractor_key': ie_result['extractor_key'],
  573. })
  574. return r
  575. ie_result['entries'] = [
  576. self.process_ie_result(_fixup(r), download, extra_info)
  577. for r in ie_result['entries']
  578. ]
  579. return ie_result
  580. else:
  581. raise Exception('Invalid result type: %s' % result_type)
  582. def select_format(self, format_spec, available_formats):
  583. if format_spec == 'best' or format_spec is None:
  584. return available_formats[-1]
  585. elif format_spec == 'worst':
  586. return available_formats[0]
  587. elif format_spec == 'bestaudio':
  588. audio_formats = [
  589. f for f in available_formats
  590. if f.get('vcodec') == 'none']
  591. if audio_formats:
  592. return audio_formats[-1]
  593. elif format_spec == 'worstaudio':
  594. audio_formats = [
  595. f for f in available_formats
  596. if f.get('vcodec') == 'none']
  597. if audio_formats:
  598. return audio_formats[0]
  599. else:
  600. extensions = ['mp4', 'flv', 'webm', '3gp']
  601. if format_spec in extensions:
  602. filter_f = lambda f: f['ext'] == format_spec
  603. else:
  604. filter_f = lambda f: f['format_id'] == format_spec
  605. matches = list(filter(filter_f, available_formats))
  606. if matches:
  607. return matches[-1]
  608. return None
  609. def process_video_result(self, info_dict, download=True):
  610. assert info_dict.get('_type', 'video') == 'video'
  611. if 'playlist' not in info_dict:
  612. # It isn't part of a playlist
  613. info_dict['playlist'] = None
  614. info_dict['playlist_index'] = None
  615. if 'display_id' not in info_dict and 'id' in info_dict:
  616. info_dict['display_id'] = info_dict['id']
  617. # This extractors handle format selection themselves
  618. if info_dict['extractor'] in ['Youku']:
  619. if download:
  620. self.process_info(info_dict)
  621. return info_dict
  622. # We now pick which formats have to be downloaded
  623. if info_dict.get('formats') is None:
  624. # There's only one format available
  625. formats = [info_dict]
  626. else:
  627. formats = info_dict['formats']
  628. # We check that all the formats have the format and format_id fields
  629. for (i, format) in enumerate(formats):
  630. if format.get('format_id') is None:
  631. format['format_id'] = compat_str(i)
  632. if format.get('format') is None:
  633. format['format'] = '{id} - {res}{note}'.format(
  634. id=format['format_id'],
  635. res=self.format_resolution(format),
  636. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  637. )
  638. # Automatically determine file extension if missing
  639. if 'ext' not in format:
  640. format['ext'] = determine_ext(format['url'])
  641. format_limit = self.params.get('format_limit', None)
  642. if format_limit:
  643. formats = list(takewhile_inclusive(
  644. lambda f: f['format_id'] != format_limit, formats
  645. ))
  646. # TODO Central sorting goes here
  647. if formats[0] is not info_dict:
  648. # only set the 'formats' fields if the original info_dict list them
  649. # otherwise we end up with a circular reference, the first (and unique)
  650. # element in the 'formats' field in info_dict is info_dict itself,
  651. # wich can't be exported to json
  652. info_dict['formats'] = formats
  653. if self.params.get('listformats', None):
  654. self.list_formats(info_dict)
  655. return
  656. req_format = self.params.get('format')
  657. if req_format is None:
  658. req_format = 'best'
  659. formats_to_download = []
  660. # The -1 is for supporting YoutubeIE
  661. if req_format in ('-1', 'all'):
  662. formats_to_download = formats
  663. else:
  664. # We can accept formats requested in the format: 34/5/best, we pick
  665. # the first that is available, starting from left
  666. req_formats = req_format.split('/')
  667. for rf in req_formats:
  668. if re.match(r'.+?\+.+?', rf) is not None:
  669. # Two formats have been requested like '137+139'
  670. format_1, format_2 = rf.split('+')
  671. formats_info = (self.select_format(format_1, formats),
  672. self.select_format(format_2, formats))
  673. if all(formats_info):
  674. selected_format = {
  675. 'requested_formats': formats_info,
  676. 'format': rf,
  677. 'ext': formats_info[0]['ext'],
  678. }
  679. else:
  680. selected_format = None
  681. else:
  682. selected_format = self.select_format(rf, formats)
  683. if selected_format is not None:
  684. formats_to_download = [selected_format]
  685. break
  686. if not formats_to_download:
  687. raise ExtractorError('requested format not available',
  688. expected=True)
  689. if download:
  690. if len(formats_to_download) > 1:
  691. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  692. for format in formats_to_download:
  693. new_info = dict(info_dict)
  694. new_info.update(format)
  695. self.process_info(new_info)
  696. # We update the info dict with the best quality format (backwards compatibility)
  697. info_dict.update(formats_to_download[-1])
  698. return info_dict
  699. def process_info(self, info_dict):
  700. """Process a single resolved IE result."""
  701. assert info_dict.get('_type', 'video') == 'video'
  702. max_downloads = self.params.get('max_downloads')
  703. if max_downloads is not None:
  704. if self._num_downloads >= int(max_downloads):
  705. raise MaxDownloadsReached()
  706. info_dict['fulltitle'] = info_dict['title']
  707. if len(info_dict['title']) > 200:
  708. info_dict['title'] = info_dict['title'][:197] + '...'
  709. # Keep for backwards compatibility
  710. info_dict['stitle'] = info_dict['title']
  711. if not 'format' in info_dict:
  712. info_dict['format'] = info_dict['ext']
  713. reason = self._match_entry(info_dict)
  714. if reason is not None:
  715. self.to_screen('[download] ' + reason)
  716. return
  717. self._num_downloads += 1
  718. filename = self.prepare_filename(info_dict)
  719. # Forced printings
  720. if self.params.get('forcetitle', False):
  721. self.to_stdout(info_dict['fulltitle'])
  722. if self.params.get('forceid', False):
  723. self.to_stdout(info_dict['id'])
  724. if self.params.get('forceurl', False):
  725. # For RTMP URLs, also include the playpath
  726. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  727. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  728. self.to_stdout(info_dict['thumbnail'])
  729. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  730. self.to_stdout(info_dict['description'])
  731. if self.params.get('forcefilename', False) and filename is not None:
  732. self.to_stdout(filename)
  733. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  734. self.to_stdout(formatSeconds(info_dict['duration']))
  735. if self.params.get('forceformat', False):
  736. self.to_stdout(info_dict['format'])
  737. if self.params.get('forcejson', False):
  738. info_dict['_filename'] = filename
  739. self.to_stdout(json.dumps(info_dict))
  740. # Do nothing else if in simulate mode
  741. if self.params.get('simulate', False):
  742. return
  743. if filename is None:
  744. return
  745. try:
  746. dn = os.path.dirname(encodeFilename(filename))
  747. if dn != '' and not os.path.exists(dn):
  748. os.makedirs(dn)
  749. except (OSError, IOError) as err:
  750. self.report_error('unable to create directory ' + compat_str(err))
  751. return
  752. if self.params.get('writedescription', False):
  753. descfn = filename + '.description'
  754. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  755. self.to_screen('[info] Video description is already present')
  756. else:
  757. try:
  758. self.to_screen('[info] Writing video description to: ' + descfn)
  759. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  760. descfile.write(info_dict['description'])
  761. except (KeyError, TypeError):
  762. self.report_warning('There\'s no description to write.')
  763. except (OSError, IOError):
  764. self.report_error('Cannot write description file ' + descfn)
  765. return
  766. if self.params.get('writeannotations', False):
  767. annofn = filename + '.annotations.xml'
  768. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  769. self.to_screen('[info] Video annotations are already present')
  770. else:
  771. try:
  772. self.to_screen('[info] Writing video annotations to: ' + annofn)
  773. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  774. annofile.write(info_dict['annotations'])
  775. except (KeyError, TypeError):
  776. self.report_warning('There are no annotations to write.')
  777. except (OSError, IOError):
  778. self.report_error('Cannot write annotations file: ' + annofn)
  779. return
  780. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  781. self.params.get('writeautomaticsub')])
  782. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  783. # subtitles download errors are already managed as troubles in relevant IE
  784. # that way it will silently go on when used with unsupporting IE
  785. subtitles = info_dict['subtitles']
  786. sub_format = self.params.get('subtitlesformat', 'srt')
  787. for sub_lang in subtitles.keys():
  788. sub = subtitles[sub_lang]
  789. if sub is None:
  790. continue
  791. try:
  792. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  793. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  794. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  795. else:
  796. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  797. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  798. subfile.write(sub)
  799. except (OSError, IOError):
  800. self.report_error('Cannot write subtitles file ' + descfn)
  801. return
  802. if self.params.get('writeinfojson', False):
  803. infofn = os.path.splitext(filename)[0] + '.info.json'
  804. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  805. self.to_screen('[info] Video description metadata is already present')
  806. else:
  807. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  808. try:
  809. write_json_file(info_dict, encodeFilename(infofn))
  810. except (OSError, IOError):
  811. self.report_error('Cannot write metadata to JSON file ' + infofn)
  812. return
  813. if self.params.get('writethumbnail', False):
  814. if info_dict.get('thumbnail') is not None:
  815. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  816. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  817. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  818. self.to_screen('[%s] %s: Thumbnail is already present' %
  819. (info_dict['extractor'], info_dict['id']))
  820. else:
  821. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  822. (info_dict['extractor'], info_dict['id']))
  823. try:
  824. uf = self.urlopen(info_dict['thumbnail'])
  825. with open(thumb_filename, 'wb') as thumbf:
  826. shutil.copyfileobj(uf, thumbf)
  827. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  828. (info_dict['extractor'], info_dict['id'], thumb_filename))
  829. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  830. self.report_warning('Unable to download thumbnail "%s": %s' %
  831. (info_dict['thumbnail'], compat_str(err)))
  832. if not self.params.get('skip_download', False):
  833. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  834. success = True
  835. else:
  836. try:
  837. def dl(name, info):
  838. fd = get_suitable_downloader(info)(self, self.params)
  839. for ph in self._progress_hooks:
  840. fd.add_progress_hook(ph)
  841. return fd.download(name, info)
  842. if info_dict.get('requested_formats') is not None:
  843. downloaded = []
  844. success = True
  845. merger = FFmpegMergerPP(self)
  846. if not merger._get_executable():
  847. postprocessors = []
  848. self.report_warning('You have requested multiple '
  849. 'formats but ffmpeg or avconv are not installed.'
  850. ' The formats won\'t be merged')
  851. else:
  852. postprocessors = [merger]
  853. for f in info_dict['requested_formats']:
  854. new_info = dict(info_dict)
  855. new_info.update(f)
  856. fname = self.prepare_filename(new_info)
  857. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  858. downloaded.append(fname)
  859. partial_success = dl(fname, new_info)
  860. success = success and partial_success
  861. info_dict['__postprocessors'] = postprocessors
  862. info_dict['__files_to_merge'] = downloaded
  863. else:
  864. # Just a single file
  865. success = dl(filename, info_dict)
  866. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  867. self.report_error('unable to download video data: %s' % str(err))
  868. return
  869. except (OSError, IOError) as err:
  870. raise UnavailableVideoError(err)
  871. except (ContentTooShortError, ) as err:
  872. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  873. return
  874. if success:
  875. try:
  876. self.post_process(filename, info_dict)
  877. except (PostProcessingError) as err:
  878. self.report_error('postprocessing: %s' % str(err))
  879. return
  880. self.record_download_archive(info_dict)
  881. def download(self, url_list):
  882. """Download a given list of URLs."""
  883. if (len(url_list) > 1 and
  884. '%' not in self.params['outtmpl']
  885. and self.params.get('max_downloads') != 1):
  886. raise SameFileError(self.params['outtmpl'])
  887. for url in url_list:
  888. try:
  889. #It also downloads the videos
  890. self.extract_info(url)
  891. except UnavailableVideoError:
  892. self.report_error('unable to download video')
  893. except MaxDownloadsReached:
  894. self.to_screen('[info] Maximum number of downloaded files reached.')
  895. raise
  896. return self._download_retcode
  897. def download_with_info_file(self, info_filename):
  898. with io.open(info_filename, 'r', encoding='utf-8') as f:
  899. info = json.load(f)
  900. try:
  901. self.process_ie_result(info, download=True)
  902. except DownloadError:
  903. webpage_url = info.get('webpage_url')
  904. if webpage_url is not None:
  905. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  906. return self.download([webpage_url])
  907. else:
  908. raise
  909. return self._download_retcode
  910. def post_process(self, filename, ie_info):
  911. """Run all the postprocessors on the given file."""
  912. info = dict(ie_info)
  913. info['filepath'] = filename
  914. keep_video = None
  915. pps_chain = []
  916. if ie_info.get('__postprocessors') is not None:
  917. pps_chain.extend(ie_info['__postprocessors'])
  918. pps_chain.extend(self._pps)
  919. for pp in pps_chain:
  920. try:
  921. keep_video_wish, new_info = pp.run(info)
  922. if keep_video_wish is not None:
  923. if keep_video_wish:
  924. keep_video = keep_video_wish
  925. elif keep_video is None:
  926. # No clear decision yet, let IE decide
  927. keep_video = keep_video_wish
  928. except PostProcessingError as e:
  929. self.report_error(e.msg)
  930. if keep_video is False and not self.params.get('keepvideo', False):
  931. try:
  932. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  933. os.remove(encodeFilename(filename))
  934. except (IOError, OSError):
  935. self.report_warning('Unable to remove downloaded video file')
  936. def _make_archive_id(self, info_dict):
  937. # Future-proof against any change in case
  938. # and backwards compatibility with prior versions
  939. extractor = info_dict.get('extractor_key')
  940. if extractor is None:
  941. if 'id' in info_dict:
  942. extractor = info_dict.get('ie_key') # key in a playlist
  943. if extractor is None:
  944. return None # Incomplete video information
  945. return extractor.lower() + ' ' + info_dict['id']
  946. def in_download_archive(self, info_dict):
  947. fn = self.params.get('download_archive')
  948. if fn is None:
  949. return False
  950. vid_id = self._make_archive_id(info_dict)
  951. if vid_id is None:
  952. return False # Incomplete video information
  953. try:
  954. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  955. for line in archive_file:
  956. if line.strip() == vid_id:
  957. return True
  958. except IOError as ioe:
  959. if ioe.errno != errno.ENOENT:
  960. raise
  961. return False
  962. def record_download_archive(self, info_dict):
  963. fn = self.params.get('download_archive')
  964. if fn is None:
  965. return
  966. vid_id = self._make_archive_id(info_dict)
  967. assert vid_id
  968. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  969. archive_file.write(vid_id + '\n')
  970. @staticmethod
  971. def format_resolution(format, default='unknown'):
  972. if format.get('vcodec') == 'none':
  973. return 'audio only'
  974. if format.get('resolution') is not None:
  975. return format['resolution']
  976. if format.get('height') is not None:
  977. if format.get('width') is not None:
  978. res = '%sx%s' % (format['width'], format['height'])
  979. else:
  980. res = '%sp' % format['height']
  981. elif format.get('width') is not None:
  982. res = '?x%d' % format['width']
  983. else:
  984. res = default
  985. return res
  986. def list_formats(self, info_dict):
  987. def format_note(fdict):
  988. res = ''
  989. if fdict.get('ext') in ['f4f', 'f4m']:
  990. res += '(unsupported) '
  991. if fdict.get('format_note') is not None:
  992. res += fdict['format_note'] + ' '
  993. if fdict.get('tbr') is not None:
  994. res += '%4dk ' % fdict['tbr']
  995. if fdict.get('container') is not None:
  996. if res:
  997. res += ', '
  998. res += '%s container' % fdict['container']
  999. if (fdict.get('vcodec') is not None and
  1000. fdict.get('vcodec') != 'none'):
  1001. if res:
  1002. res += ', '
  1003. res += fdict['vcodec']
  1004. if fdict.get('vbr') is not None:
  1005. res += '@'
  1006. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1007. res += 'video@'
  1008. if fdict.get('vbr') is not None:
  1009. res += '%4dk' % fdict['vbr']
  1010. if fdict.get('acodec') is not None:
  1011. if res:
  1012. res += ', '
  1013. if fdict['acodec'] == 'none':
  1014. res += 'video only'
  1015. else:
  1016. res += '%-5s' % fdict['acodec']
  1017. elif fdict.get('abr') is not None:
  1018. if res:
  1019. res += ', '
  1020. res += 'audio'
  1021. if fdict.get('abr') is not None:
  1022. res += '@%3dk' % fdict['abr']
  1023. if fdict.get('asr') is not None:
  1024. res += ' (%5dHz)' % fdict['asr']
  1025. if fdict.get('filesize') is not None:
  1026. if res:
  1027. res += ', '
  1028. res += format_bytes(fdict['filesize'])
  1029. return res
  1030. def line(format, idlen=20):
  1031. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1032. format['format_id'],
  1033. format['ext'],
  1034. self.format_resolution(format),
  1035. format_note(format),
  1036. ))
  1037. formats = info_dict.get('formats', [info_dict])
  1038. idlen = max(len('format code'),
  1039. max(len(f['format_id']) for f in formats))
  1040. formats_s = [line(f, idlen) for f in formats]
  1041. if len(formats) > 1:
  1042. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1043. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1044. header_line = line({
  1045. 'format_id': 'format code', 'ext': 'extension',
  1046. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1047. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1048. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1049. def urlopen(self, req):
  1050. """ Start an HTTP download """
  1051. return self._opener.open(req)
  1052. def print_debug_header(self):
  1053. if not self.params.get('verbose'):
  1054. return
  1055. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1056. try:
  1057. sp = subprocess.Popen(
  1058. ['git', 'rev-parse', '--short', 'HEAD'],
  1059. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1060. cwd=os.path.dirname(os.path.abspath(__file__)))
  1061. out, err = sp.communicate()
  1062. out = out.decode().strip()
  1063. if re.match('[0-9a-f]+', out):
  1064. write_string('[debug] Git HEAD: ' + out + '\n')
  1065. except:
  1066. try:
  1067. sys.exc_clear()
  1068. except:
  1069. pass
  1070. write_string('[debug] Python version %s - %s' %
  1071. (platform.python_version(), platform_name()) + '\n')
  1072. proxy_map = {}
  1073. for handler in self._opener.handlers:
  1074. if hasattr(handler, 'proxies'):
  1075. proxy_map.update(handler.proxies)
  1076. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1077. def _setup_opener(self):
  1078. timeout_val = self.params.get('socket_timeout')
  1079. timeout = 600 if timeout_val is None else float(timeout_val)
  1080. opts_cookiefile = self.params.get('cookiefile')
  1081. opts_proxy = self.params.get('proxy')
  1082. if opts_cookiefile is None:
  1083. self.cookiejar = compat_cookiejar.CookieJar()
  1084. else:
  1085. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1086. opts_cookiefile)
  1087. if os.access(opts_cookiefile, os.R_OK):
  1088. self.cookiejar.load()
  1089. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1090. self.cookiejar)
  1091. if opts_proxy is not None:
  1092. if opts_proxy == '':
  1093. proxies = {}
  1094. else:
  1095. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1096. else:
  1097. proxies = compat_urllib_request.getproxies()
  1098. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1099. if 'http' in proxies and 'https' not in proxies:
  1100. proxies['https'] = proxies['http']
  1101. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1102. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1103. https_handler = make_HTTPS_handler(
  1104. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1105. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1106. opener = compat_urllib_request.build_opener(
  1107. https_handler, proxy_handler, cookie_processor, ydlh)
  1108. # Delete the default user-agent header, which would otherwise apply in
  1109. # cases where our custom HTTP handler doesn't come into play
  1110. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1111. opener.addheaders = []
  1112. self._opener = opener
  1113. # TODO remove this global modification
  1114. compat_urllib_request.install_opener(opener)
  1115. socket.setdefaulttimeout(timeout)