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.

1232 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. sanitize = lambda k, v: sanitize_filename(
  369. compat_str(v),
  370. restricted=self.params.get('restrictfilenames'),
  371. is_id=(k == 'id'))
  372. template_dict = dict((k, sanitize(k, v))
  373. for k, v in template_dict.items()
  374. if v is not None)
  375. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  376. tmpl = os.path.expanduser(self.params['outtmpl'])
  377. filename = tmpl % template_dict
  378. return filename
  379. except ValueError as err:
  380. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  381. return None
  382. def _match_entry(self, info_dict):
  383. """ Returns None iff the file should be downloaded """
  384. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  385. if 'title' in info_dict:
  386. # This can happen when we're just evaluating the playlist
  387. title = info_dict['title']
  388. matchtitle = self.params.get('matchtitle', False)
  389. if matchtitle:
  390. if not re.search(matchtitle, title, re.IGNORECASE):
  391. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  392. rejecttitle = self.params.get('rejecttitle', False)
  393. if rejecttitle:
  394. if re.search(rejecttitle, title, re.IGNORECASE):
  395. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  396. date = info_dict.get('upload_date', None)
  397. if date is not None:
  398. dateRange = self.params.get('daterange', DateRange())
  399. if date not in dateRange:
  400. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  401. view_count = info_dict.get('view_count', None)
  402. if view_count is not None:
  403. min_views = self.params.get('min_views')
  404. if min_views is not None and view_count < min_views:
  405. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  406. max_views = self.params.get('max_views')
  407. if max_views is not None and view_count > max_views:
  408. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  409. age_limit = self.params.get('age_limit')
  410. if age_limit is not None:
  411. if age_limit < info_dict.get('age_limit', 0):
  412. return 'Skipping "' + title + '" because it is age restricted'
  413. if self.in_download_archive(info_dict):
  414. return '%s has already been recorded in archive' % video_title
  415. return None
  416. @staticmethod
  417. def add_extra_info(info_dict, extra_info):
  418. '''Set the keys from extra_info in info dict if they are missing'''
  419. for key, value in extra_info.items():
  420. info_dict.setdefault(key, value)
  421. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  422. process=True):
  423. '''
  424. Returns a list with a dictionary for each video we find.
  425. If 'download', also downloads the videos.
  426. extra_info is a dict containing the extra values to add to each result
  427. '''
  428. if ie_key:
  429. ies = [self.get_info_extractor(ie_key)]
  430. else:
  431. ies = self._ies
  432. for ie in ies:
  433. if not ie.suitable(url):
  434. continue
  435. if not ie.working():
  436. self.report_warning('The program functionality for this site has been marked as broken, '
  437. 'and will probably not work.')
  438. try:
  439. ie_result = ie.extract(url)
  440. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  441. break
  442. if isinstance(ie_result, list):
  443. # Backwards compatibility: old IE result format
  444. ie_result = {
  445. '_type': 'compat_list',
  446. 'entries': ie_result,
  447. }
  448. self.add_extra_info(ie_result,
  449. {
  450. 'extractor': ie.IE_NAME,
  451. 'webpage_url': url,
  452. 'webpage_url_basename': url_basename(url),
  453. 'extractor_key': ie.ie_key(),
  454. })
  455. if process:
  456. return self.process_ie_result(ie_result, download, extra_info)
  457. else:
  458. return ie_result
  459. except ExtractorError as de: # An error we somewhat expected
  460. self.report_error(compat_str(de), de.format_traceback())
  461. break
  462. except MaxDownloadsReached:
  463. raise
  464. except Exception as e:
  465. if self.params.get('ignoreerrors', False):
  466. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  467. break
  468. else:
  469. raise
  470. else:
  471. self.report_error('no suitable InfoExtractor: %s' % url)
  472. def process_ie_result(self, ie_result, download=True, extra_info={}):
  473. """
  474. Take the result of the ie(may be modified) and resolve all unresolved
  475. references (URLs, playlist items).
  476. It will also download the videos if 'download'.
  477. Returns the resolved ie_result.
  478. """
  479. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  480. if result_type == 'video':
  481. self.add_extra_info(ie_result, extra_info)
  482. return self.process_video_result(ie_result, download=download)
  483. elif result_type == 'url':
  484. # We have to add extra_info to the results because it may be
  485. # contained in a playlist
  486. return self.extract_info(ie_result['url'],
  487. download,
  488. ie_key=ie_result.get('ie_key'),
  489. extra_info=extra_info)
  490. elif result_type == 'url_transparent':
  491. # Use the information from the embedding page
  492. info = self.extract_info(
  493. ie_result['url'], ie_key=ie_result.get('ie_key'),
  494. extra_info=extra_info, download=False, process=False)
  495. def make_result(embedded_info):
  496. new_result = ie_result.copy()
  497. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  498. 'entries', 'ie_key', 'duration',
  499. 'subtitles', 'annotations', 'format',
  500. 'thumbnail', 'thumbnails'):
  501. if f in new_result:
  502. del new_result[f]
  503. if f in embedded_info:
  504. new_result[f] = embedded_info[f]
  505. return new_result
  506. new_result = make_result(info)
  507. assert new_result.get('_type') != 'url_transparent'
  508. if new_result.get('_type') == 'compat_list':
  509. new_result['entries'] = [
  510. make_result(e) for e in new_result['entries']]
  511. return self.process_ie_result(
  512. new_result, download=download, extra_info=extra_info)
  513. elif result_type == 'playlist':
  514. # We process each entry in the playlist
  515. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  516. self.to_screen('[download] Downloading playlist: %s' % playlist)
  517. playlist_results = []
  518. playliststart = self.params.get('playliststart', 1) - 1
  519. playlistend = self.params.get('playlistend', None)
  520. # For backwards compatibility, interpret -1 as whole list
  521. if playlistend == -1:
  522. playlistend = None
  523. if isinstance(ie_result['entries'], list):
  524. n_all_entries = len(ie_result['entries'])
  525. entries = ie_result['entries'][playliststart:playlistend]
  526. n_entries = len(entries)
  527. self.to_screen(
  528. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  529. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  530. else:
  531. assert isinstance(ie_result['entries'], PagedList)
  532. entries = ie_result['entries'].getslice(
  533. playliststart, playlistend)
  534. n_entries = len(entries)
  535. self.to_screen(
  536. "[%s] playlist %s: Downloading %d videos" %
  537. (ie_result['extractor'], playlist, n_entries))
  538. for i, entry in enumerate(entries, 1):
  539. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  540. extra = {
  541. 'playlist': playlist,
  542. 'playlist_index': i + playliststart,
  543. 'extractor': ie_result['extractor'],
  544. 'webpage_url': ie_result['webpage_url'],
  545. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  546. 'extractor_key': ie_result['extractor_key'],
  547. }
  548. reason = self._match_entry(entry)
  549. if reason is not None:
  550. self.to_screen('[download] ' + reason)
  551. continue
  552. entry_result = self.process_ie_result(entry,
  553. download=download,
  554. extra_info=extra)
  555. playlist_results.append(entry_result)
  556. ie_result['entries'] = playlist_results
  557. return ie_result
  558. elif result_type == 'compat_list':
  559. def _fixup(r):
  560. self.add_extra_info(r,
  561. {
  562. 'extractor': ie_result['extractor'],
  563. 'webpage_url': ie_result['webpage_url'],
  564. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  565. 'extractor_key': ie_result['extractor_key'],
  566. })
  567. return r
  568. ie_result['entries'] = [
  569. self.process_ie_result(_fixup(r), download, extra_info)
  570. for r in ie_result['entries']
  571. ]
  572. return ie_result
  573. else:
  574. raise Exception('Invalid result type: %s' % result_type)
  575. def select_format(self, format_spec, available_formats):
  576. if format_spec == 'best' or format_spec is None:
  577. return available_formats[-1]
  578. elif format_spec == 'worst':
  579. return available_formats[0]
  580. elif format_spec == 'bestaudio':
  581. audio_formats = [
  582. f for f in available_formats
  583. if f.get('vcodec') == 'none']
  584. if audio_formats:
  585. return audio_formats[-1]
  586. elif format_spec == 'worstaudio':
  587. audio_formats = [
  588. f for f in available_formats
  589. if f.get('vcodec') == 'none']
  590. if audio_formats:
  591. return audio_formats[0]
  592. else:
  593. extensions = ['mp4', 'flv', 'webm', '3gp']
  594. if format_spec in extensions:
  595. filter_f = lambda f: f['ext'] == format_spec
  596. else:
  597. filter_f = lambda f: f['format_id'] == format_spec
  598. matches = list(filter(filter_f, available_formats))
  599. if matches:
  600. return matches[-1]
  601. return None
  602. def process_video_result(self, info_dict, download=True):
  603. assert info_dict.get('_type', 'video') == 'video'
  604. if 'playlist' not in info_dict:
  605. # It isn't part of a playlist
  606. info_dict['playlist'] = None
  607. info_dict['playlist_index'] = None
  608. if 'display_id' not in info_dict and 'id' in info_dict:
  609. info_dict['display_id'] = info_dict['id']
  610. # This extractors handle format selection themselves
  611. if info_dict['extractor'] in ['Youku']:
  612. if download:
  613. self.process_info(info_dict)
  614. return info_dict
  615. # We now pick which formats have to be downloaded
  616. if info_dict.get('formats') is None:
  617. # There's only one format available
  618. formats = [info_dict]
  619. else:
  620. formats = info_dict['formats']
  621. # We check that all the formats have the format and format_id fields
  622. for (i, format) in enumerate(formats):
  623. if format.get('format_id') is None:
  624. format['format_id'] = compat_str(i)
  625. if format.get('format') is None:
  626. format['format'] = '{id} - {res}{note}'.format(
  627. id=format['format_id'],
  628. res=self.format_resolution(format),
  629. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  630. )
  631. # Automatically determine file extension if missing
  632. if 'ext' not in format:
  633. format['ext'] = determine_ext(format['url'])
  634. format_limit = self.params.get('format_limit', None)
  635. if format_limit:
  636. formats = list(takewhile_inclusive(
  637. lambda f: f['format_id'] != format_limit, formats
  638. ))
  639. # TODO Central sorting goes here
  640. if formats[0] is not info_dict:
  641. # only set the 'formats' fields if the original info_dict list them
  642. # otherwise we end up with a circular reference, the first (and unique)
  643. # element in the 'formats' field in info_dict is info_dict itself,
  644. # wich can't be exported to json
  645. info_dict['formats'] = formats
  646. if self.params.get('listformats', None):
  647. self.list_formats(info_dict)
  648. return
  649. req_format = self.params.get('format')
  650. if req_format is None:
  651. req_format = 'best'
  652. formats_to_download = []
  653. # The -1 is for supporting YoutubeIE
  654. if req_format in ('-1', 'all'):
  655. formats_to_download = formats
  656. else:
  657. # We can accept formats requested in the format: 34/5/best, we pick
  658. # the first that is available, starting from left
  659. req_formats = req_format.split('/')
  660. for rf in req_formats:
  661. if re.match(r'.+?\+.+?', rf) is not None:
  662. # Two formats have been requested like '137+139'
  663. format_1, format_2 = rf.split('+')
  664. formats_info = (self.select_format(format_1, formats),
  665. self.select_format(format_2, formats))
  666. if all(formats_info):
  667. selected_format = {
  668. 'requested_formats': formats_info,
  669. 'format': rf,
  670. 'ext': formats_info[0]['ext'],
  671. }
  672. else:
  673. selected_format = None
  674. else:
  675. selected_format = self.select_format(rf, formats)
  676. if selected_format is not None:
  677. formats_to_download = [selected_format]
  678. break
  679. if not formats_to_download:
  680. raise ExtractorError('requested format not available',
  681. expected=True)
  682. if download:
  683. if len(formats_to_download) > 1:
  684. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  685. for format in formats_to_download:
  686. new_info = dict(info_dict)
  687. new_info.update(format)
  688. self.process_info(new_info)
  689. # We update the info dict with the best quality format (backwards compatibility)
  690. info_dict.update(formats_to_download[-1])
  691. return info_dict
  692. def process_info(self, info_dict):
  693. """Process a single resolved IE result."""
  694. assert info_dict.get('_type', 'video') == 'video'
  695. max_downloads = self.params.get('max_downloads')
  696. if max_downloads is not None:
  697. if self._num_downloads >= int(max_downloads):
  698. raise MaxDownloadsReached()
  699. info_dict['fulltitle'] = info_dict['title']
  700. if len(info_dict['title']) > 200:
  701. info_dict['title'] = info_dict['title'][:197] + '...'
  702. # Keep for backwards compatibility
  703. info_dict['stitle'] = info_dict['title']
  704. if not 'format' in info_dict:
  705. info_dict['format'] = info_dict['ext']
  706. reason = self._match_entry(info_dict)
  707. if reason is not None:
  708. self.to_screen('[download] ' + reason)
  709. return
  710. self._num_downloads += 1
  711. filename = self.prepare_filename(info_dict)
  712. # Forced printings
  713. if self.params.get('forcetitle', False):
  714. self.to_stdout(info_dict['fulltitle'])
  715. if self.params.get('forceid', False):
  716. self.to_stdout(info_dict['id'])
  717. if self.params.get('forceurl', False):
  718. # For RTMP URLs, also include the playpath
  719. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  720. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  721. self.to_stdout(info_dict['thumbnail'])
  722. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  723. self.to_stdout(info_dict['description'])
  724. if self.params.get('forcefilename', False) and filename is not None:
  725. self.to_stdout(filename)
  726. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  727. self.to_stdout(formatSeconds(info_dict['duration']))
  728. if self.params.get('forceformat', False):
  729. self.to_stdout(info_dict['format'])
  730. if self.params.get('forcejson', False):
  731. info_dict['_filename'] = filename
  732. self.to_stdout(json.dumps(info_dict))
  733. # Do nothing else if in simulate mode
  734. if self.params.get('simulate', False):
  735. return
  736. if filename is None:
  737. return
  738. try:
  739. dn = os.path.dirname(encodeFilename(filename))
  740. if dn != '' and not os.path.exists(dn):
  741. os.makedirs(dn)
  742. except (OSError, IOError) as err:
  743. self.report_error('unable to create directory ' + compat_str(err))
  744. return
  745. if self.params.get('writedescription', False):
  746. descfn = filename + '.description'
  747. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  748. self.to_screen('[info] Video description is already present')
  749. else:
  750. try:
  751. self.to_screen('[info] Writing video description to: ' + descfn)
  752. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  753. descfile.write(info_dict['description'])
  754. except (KeyError, TypeError):
  755. self.report_warning('There\'s no description to write.')
  756. except (OSError, IOError):
  757. self.report_error('Cannot write description file ' + descfn)
  758. return
  759. if self.params.get('writeannotations', False):
  760. annofn = filename + '.annotations.xml'
  761. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  762. self.to_screen('[info] Video annotations are already present')
  763. else:
  764. try:
  765. self.to_screen('[info] Writing video annotations to: ' + annofn)
  766. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  767. annofile.write(info_dict['annotations'])
  768. except (KeyError, TypeError):
  769. self.report_warning('There are no annotations to write.')
  770. except (OSError, IOError):
  771. self.report_error('Cannot write annotations file: ' + annofn)
  772. return
  773. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  774. self.params.get('writeautomaticsub')])
  775. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  776. # subtitles download errors are already managed as troubles in relevant IE
  777. # that way it will silently go on when used with unsupporting IE
  778. subtitles = info_dict['subtitles']
  779. sub_format = self.params.get('subtitlesformat', 'srt')
  780. for sub_lang in subtitles.keys():
  781. sub = subtitles[sub_lang]
  782. if sub is None:
  783. continue
  784. try:
  785. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  786. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  787. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  788. else:
  789. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  790. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  791. subfile.write(sub)
  792. except (OSError, IOError):
  793. self.report_error('Cannot write subtitles file ' + descfn)
  794. return
  795. if self.params.get('writeinfojson', False):
  796. infofn = os.path.splitext(filename)[0] + '.info.json'
  797. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  798. self.to_screen('[info] Video description metadata is already present')
  799. else:
  800. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  801. try:
  802. write_json_file(info_dict, encodeFilename(infofn))
  803. except (OSError, IOError):
  804. self.report_error('Cannot write metadata to JSON file ' + infofn)
  805. return
  806. if self.params.get('writethumbnail', False):
  807. if info_dict.get('thumbnail') is not None:
  808. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  809. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  810. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  811. self.to_screen('[%s] %s: Thumbnail is already present' %
  812. (info_dict['extractor'], info_dict['id']))
  813. else:
  814. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  815. (info_dict['extractor'], info_dict['id']))
  816. try:
  817. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  818. with open(thumb_filename, 'wb') as thumbf:
  819. shutil.copyfileobj(uf, thumbf)
  820. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  821. (info_dict['extractor'], info_dict['id'], thumb_filename))
  822. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  823. self.report_warning('Unable to download thumbnail "%s": %s' %
  824. (info_dict['thumbnail'], compat_str(err)))
  825. if not self.params.get('skip_download', False):
  826. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  827. success = True
  828. else:
  829. try:
  830. def dl(name, info):
  831. fd = get_suitable_downloader(info)(self, self.params)
  832. for ph in self._progress_hooks:
  833. fd.add_progress_hook(ph)
  834. return fd.download(name, info)
  835. if info_dict.get('requested_formats') is not None:
  836. downloaded = []
  837. success = True
  838. merger = FFmpegMergerPP(self)
  839. if not merger._get_executable():
  840. postprocessors = []
  841. self.report_warning('You have requested multiple '
  842. 'formats but ffmpeg or avconv are not installed.'
  843. ' The formats won\'t be merged')
  844. else:
  845. postprocessors = [merger]
  846. for f in info_dict['requested_formats']:
  847. new_info = dict(info_dict)
  848. new_info.update(f)
  849. fname = self.prepare_filename(new_info)
  850. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  851. downloaded.append(fname)
  852. partial_success = dl(fname, new_info)
  853. success = success and partial_success
  854. info_dict['__postprocessors'] = postprocessors
  855. info_dict['__files_to_merge'] = downloaded
  856. else:
  857. # Just a single file
  858. success = dl(filename, info_dict)
  859. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  860. self.report_error('unable to download video data: %s' % str(err))
  861. return
  862. except (OSError, IOError) as err:
  863. raise UnavailableVideoError(err)
  864. except (ContentTooShortError, ) as err:
  865. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  866. return
  867. if success:
  868. try:
  869. self.post_process(filename, info_dict)
  870. except (PostProcessingError) as err:
  871. self.report_error('postprocessing: %s' % str(err))
  872. return
  873. self.record_download_archive(info_dict)
  874. def download(self, url_list):
  875. """Download a given list of URLs."""
  876. if (len(url_list) > 1 and
  877. '%' not in self.params['outtmpl']
  878. and self.params.get('max_downloads') != 1):
  879. raise SameFileError(self.params['outtmpl'])
  880. for url in url_list:
  881. try:
  882. #It also downloads the videos
  883. self.extract_info(url)
  884. except UnavailableVideoError:
  885. self.report_error('unable to download video')
  886. except MaxDownloadsReached:
  887. self.to_screen('[info] Maximum number of downloaded files reached.')
  888. raise
  889. return self._download_retcode
  890. def download_with_info_file(self, info_filename):
  891. with io.open(info_filename, 'r', encoding='utf-8') as f:
  892. info = json.load(f)
  893. try:
  894. self.process_ie_result(info, download=True)
  895. except DownloadError:
  896. webpage_url = info.get('webpage_url')
  897. if webpage_url is not None:
  898. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  899. return self.download([webpage_url])
  900. else:
  901. raise
  902. return self._download_retcode
  903. def post_process(self, filename, ie_info):
  904. """Run all the postprocessors on the given file."""
  905. info = dict(ie_info)
  906. info['filepath'] = filename
  907. keep_video = None
  908. pps_chain = []
  909. if ie_info.get('__postprocessors') is not None:
  910. pps_chain.extend(ie_info['__postprocessors'])
  911. pps_chain.extend(self._pps)
  912. for pp in pps_chain:
  913. try:
  914. keep_video_wish, new_info = pp.run(info)
  915. if keep_video_wish is not None:
  916. if keep_video_wish:
  917. keep_video = keep_video_wish
  918. elif keep_video is None:
  919. # No clear decision yet, let IE decide
  920. keep_video = keep_video_wish
  921. except PostProcessingError as e:
  922. self.report_error(e.msg)
  923. if keep_video is False and not self.params.get('keepvideo', False):
  924. try:
  925. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  926. os.remove(encodeFilename(filename))
  927. except (IOError, OSError):
  928. self.report_warning('Unable to remove downloaded video file')
  929. def _make_archive_id(self, info_dict):
  930. # Future-proof against any change in case
  931. # and backwards compatibility with prior versions
  932. extractor = info_dict.get('extractor_key')
  933. if extractor is None:
  934. if 'id' in info_dict:
  935. extractor = info_dict.get('ie_key') # key in a playlist
  936. if extractor is None:
  937. return None # Incomplete video information
  938. return extractor.lower() + ' ' + info_dict['id']
  939. def in_download_archive(self, info_dict):
  940. fn = self.params.get('download_archive')
  941. if fn is None:
  942. return False
  943. vid_id = self._make_archive_id(info_dict)
  944. if vid_id is None:
  945. return False # Incomplete video information
  946. try:
  947. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  948. for line in archive_file:
  949. if line.strip() == vid_id:
  950. return True
  951. except IOError as ioe:
  952. if ioe.errno != errno.ENOENT:
  953. raise
  954. return False
  955. def record_download_archive(self, info_dict):
  956. fn = self.params.get('download_archive')
  957. if fn is None:
  958. return
  959. vid_id = self._make_archive_id(info_dict)
  960. assert vid_id
  961. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  962. archive_file.write(vid_id + '\n')
  963. @staticmethod
  964. def format_resolution(format, default='unknown'):
  965. if format.get('vcodec') == 'none':
  966. return 'audio only'
  967. if format.get('resolution') is not None:
  968. return format['resolution']
  969. if format.get('height') is not None:
  970. if format.get('width') is not None:
  971. res = '%sx%s' % (format['width'], format['height'])
  972. else:
  973. res = '%sp' % format['height']
  974. elif format.get('width') is not None:
  975. res = '?x%d' % format['width']
  976. else:
  977. res = default
  978. return res
  979. def list_formats(self, info_dict):
  980. def format_note(fdict):
  981. res = ''
  982. if fdict.get('ext') in ['f4f', 'f4m']:
  983. res += '(unsupported) '
  984. if fdict.get('format_note') is not None:
  985. res += fdict['format_note'] + ' '
  986. if fdict.get('tbr') is not None:
  987. res += '%4dk ' % fdict['tbr']
  988. if fdict.get('container') is not None:
  989. if res:
  990. res += ', '
  991. res += '%s container' % fdict['container']
  992. if (fdict.get('vcodec') is not None and
  993. fdict.get('vcodec') != 'none'):
  994. if res:
  995. res += ', '
  996. res += fdict['vcodec']
  997. if fdict.get('vbr') is not None:
  998. res += '@'
  999. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1000. res += 'video@'
  1001. if fdict.get('vbr') is not None:
  1002. res += '%4dk' % fdict['vbr']
  1003. if fdict.get('acodec') is not None:
  1004. if res:
  1005. res += ', '
  1006. if fdict['acodec'] == 'none':
  1007. res += 'video only'
  1008. else:
  1009. res += '%-5s' % fdict['acodec']
  1010. elif fdict.get('abr') is not None:
  1011. if res:
  1012. res += ', '
  1013. res += 'audio'
  1014. if fdict.get('abr') is not None:
  1015. res += '@%3dk' % fdict['abr']
  1016. if fdict.get('asr') is not None:
  1017. res += ' (%5dHz)' % fdict['asr']
  1018. if fdict.get('filesize') is not None:
  1019. if res:
  1020. res += ', '
  1021. res += format_bytes(fdict['filesize'])
  1022. return res
  1023. def line(format, idlen=20):
  1024. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1025. format['format_id'],
  1026. format['ext'],
  1027. self.format_resolution(format),
  1028. format_note(format),
  1029. ))
  1030. formats = info_dict.get('formats', [info_dict])
  1031. idlen = max(len('format code'),
  1032. max(len(f['format_id']) for f in formats))
  1033. formats_s = [line(f, idlen) for f in formats]
  1034. if len(formats) > 1:
  1035. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1036. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1037. header_line = line({
  1038. 'format_id': 'format code', 'ext': 'extension',
  1039. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1040. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1041. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1042. def urlopen(self, req):
  1043. """ Start an HTTP download """
  1044. return self._opener.open(req)
  1045. def print_debug_header(self):
  1046. if not self.params.get('verbose'):
  1047. return
  1048. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1049. try:
  1050. sp = subprocess.Popen(
  1051. ['git', 'rev-parse', '--short', 'HEAD'],
  1052. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1053. cwd=os.path.dirname(os.path.abspath(__file__)))
  1054. out, err = sp.communicate()
  1055. out = out.decode().strip()
  1056. if re.match('[0-9a-f]+', out):
  1057. write_string('[debug] Git HEAD: ' + out + '\n')
  1058. except:
  1059. try:
  1060. sys.exc_clear()
  1061. except:
  1062. pass
  1063. write_string('[debug] Python version %s - %s' %
  1064. (platform.python_version(), platform_name()) + '\n')
  1065. proxy_map = {}
  1066. for handler in self._opener.handlers:
  1067. if hasattr(handler, 'proxies'):
  1068. proxy_map.update(handler.proxies)
  1069. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1070. def _setup_opener(self):
  1071. timeout_val = self.params.get('socket_timeout')
  1072. timeout = 600 if timeout_val is None else float(timeout_val)
  1073. opts_cookiefile = self.params.get('cookiefile')
  1074. opts_proxy = self.params.get('proxy')
  1075. if opts_cookiefile is None:
  1076. self.cookiejar = compat_cookiejar.CookieJar()
  1077. else:
  1078. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1079. opts_cookiefile)
  1080. if os.access(opts_cookiefile, os.R_OK):
  1081. self.cookiejar.load()
  1082. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1083. self.cookiejar)
  1084. if opts_proxy is not None:
  1085. if opts_proxy == '':
  1086. proxies = {}
  1087. else:
  1088. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1089. else:
  1090. proxies = compat_urllib_request.getproxies()
  1091. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1092. if 'http' in proxies and 'https' not in proxies:
  1093. proxies['https'] = proxies['http']
  1094. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1095. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1096. https_handler = make_HTTPS_handler(
  1097. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1098. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1099. opener = compat_urllib_request.build_opener(
  1100. https_handler, proxy_handler, cookie_processor, ydlh)
  1101. # Delete the default user-agent header, which would otherwise apply in
  1102. # cases where our custom HTTP handler doesn't come into play
  1103. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1104. opener.addheaders = []
  1105. self._opener = opener
  1106. # TODO remove this global modification
  1107. compat_urllib_request.install_opener(opener)
  1108. socket.setdefaulttimeout(timeout)