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.

1229 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. # This extractors handle format selection themselves
  609. if info_dict['extractor'] in ['Youku']:
  610. if download:
  611. self.process_info(info_dict)
  612. return info_dict
  613. # We now pick which formats have to be downloaded
  614. if info_dict.get('formats') is None:
  615. # There's only one format available
  616. formats = [info_dict]
  617. else:
  618. formats = info_dict['formats']
  619. # We check that all the formats have the format and format_id fields
  620. for (i, format) in enumerate(formats):
  621. if format.get('format_id') is None:
  622. format['format_id'] = compat_str(i)
  623. if format.get('format') is None:
  624. format['format'] = '{id} - {res}{note}'.format(
  625. id=format['format_id'],
  626. res=self.format_resolution(format),
  627. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  628. )
  629. # Automatically determine file extension if missing
  630. if 'ext' not in format:
  631. format['ext'] = determine_ext(format['url'])
  632. format_limit = self.params.get('format_limit', None)
  633. if format_limit:
  634. formats = list(takewhile_inclusive(
  635. lambda f: f['format_id'] != format_limit, formats
  636. ))
  637. # TODO Central sorting goes here
  638. if formats[0] is not info_dict:
  639. # only set the 'formats' fields if the original info_dict list them
  640. # otherwise we end up with a circular reference, the first (and unique)
  641. # element in the 'formats' field in info_dict is info_dict itself,
  642. # wich can't be exported to json
  643. info_dict['formats'] = formats
  644. if self.params.get('listformats', None):
  645. self.list_formats(info_dict)
  646. return
  647. req_format = self.params.get('format')
  648. if req_format is None:
  649. req_format = 'best'
  650. formats_to_download = []
  651. # The -1 is for supporting YoutubeIE
  652. if req_format in ('-1', 'all'):
  653. formats_to_download = formats
  654. else:
  655. # We can accept formats requested in the format: 34/5/best, we pick
  656. # the first that is available, starting from left
  657. req_formats = req_format.split('/')
  658. for rf in req_formats:
  659. if re.match(r'.+?\+.+?', rf) is not None:
  660. # Two formats have been requested like '137+139'
  661. format_1, format_2 = rf.split('+')
  662. formats_info = (self.select_format(format_1, formats),
  663. self.select_format(format_2, formats))
  664. if all(formats_info):
  665. selected_format = {
  666. 'requested_formats': formats_info,
  667. 'format': rf,
  668. 'ext': formats_info[0]['ext'],
  669. }
  670. else:
  671. selected_format = None
  672. else:
  673. selected_format = self.select_format(rf, formats)
  674. if selected_format is not None:
  675. formats_to_download = [selected_format]
  676. break
  677. if not formats_to_download:
  678. raise ExtractorError('requested format not available',
  679. expected=True)
  680. if download:
  681. if len(formats_to_download) > 1:
  682. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  683. for format in formats_to_download:
  684. new_info = dict(info_dict)
  685. new_info.update(format)
  686. self.process_info(new_info)
  687. # We update the info dict with the best quality format (backwards compatibility)
  688. info_dict.update(formats_to_download[-1])
  689. return info_dict
  690. def process_info(self, info_dict):
  691. """Process a single resolved IE result."""
  692. assert info_dict.get('_type', 'video') == 'video'
  693. max_downloads = self.params.get('max_downloads')
  694. if max_downloads is not None:
  695. if self._num_downloads >= int(max_downloads):
  696. raise MaxDownloadsReached()
  697. info_dict['fulltitle'] = info_dict['title']
  698. if len(info_dict['title']) > 200:
  699. info_dict['title'] = info_dict['title'][:197] + '...'
  700. # Keep for backwards compatibility
  701. info_dict['stitle'] = info_dict['title']
  702. if not 'format' in info_dict:
  703. info_dict['format'] = info_dict['ext']
  704. reason = self._match_entry(info_dict)
  705. if reason is not None:
  706. self.to_screen('[download] ' + reason)
  707. return
  708. self._num_downloads += 1
  709. filename = self.prepare_filename(info_dict)
  710. # Forced printings
  711. if self.params.get('forcetitle', False):
  712. self.to_stdout(info_dict['fulltitle'])
  713. if self.params.get('forceid', False):
  714. self.to_stdout(info_dict['id'])
  715. if self.params.get('forceurl', False):
  716. # For RTMP URLs, also include the playpath
  717. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  718. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  719. self.to_stdout(info_dict['thumbnail'])
  720. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  721. self.to_stdout(info_dict['description'])
  722. if self.params.get('forcefilename', False) and filename is not None:
  723. self.to_stdout(filename)
  724. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  725. self.to_stdout(formatSeconds(info_dict['duration']))
  726. if self.params.get('forceformat', False):
  727. self.to_stdout(info_dict['format'])
  728. if self.params.get('forcejson', False):
  729. info_dict['_filename'] = filename
  730. self.to_stdout(json.dumps(info_dict))
  731. # Do nothing else if in simulate mode
  732. if self.params.get('simulate', False):
  733. return
  734. if filename is None:
  735. return
  736. try:
  737. dn = os.path.dirname(encodeFilename(filename))
  738. if dn != '' and not os.path.exists(dn):
  739. os.makedirs(dn)
  740. except (OSError, IOError) as err:
  741. self.report_error('unable to create directory ' + compat_str(err))
  742. return
  743. if self.params.get('writedescription', False):
  744. descfn = filename + '.description'
  745. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  746. self.to_screen('[info] Video description is already present')
  747. else:
  748. try:
  749. self.to_screen('[info] Writing video description to: ' + descfn)
  750. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  751. descfile.write(info_dict['description'])
  752. except (KeyError, TypeError):
  753. self.report_warning('There\'s no description to write.')
  754. except (OSError, IOError):
  755. self.report_error('Cannot write description file ' + descfn)
  756. return
  757. if self.params.get('writeannotations', False):
  758. annofn = filename + '.annotations.xml'
  759. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  760. self.to_screen('[info] Video annotations are already present')
  761. else:
  762. try:
  763. self.to_screen('[info] Writing video annotations to: ' + annofn)
  764. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  765. annofile.write(info_dict['annotations'])
  766. except (KeyError, TypeError):
  767. self.report_warning('There are no annotations to write.')
  768. except (OSError, IOError):
  769. self.report_error('Cannot write annotations file: ' + annofn)
  770. return
  771. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  772. self.params.get('writeautomaticsub')])
  773. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  774. # subtitles download errors are already managed as troubles in relevant IE
  775. # that way it will silently go on when used with unsupporting IE
  776. subtitles = info_dict['subtitles']
  777. sub_format = self.params.get('subtitlesformat', 'srt')
  778. for sub_lang in subtitles.keys():
  779. sub = subtitles[sub_lang]
  780. if sub is None:
  781. continue
  782. try:
  783. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  784. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  785. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  786. else:
  787. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  788. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  789. subfile.write(sub)
  790. except (OSError, IOError):
  791. self.report_error('Cannot write subtitles file ' + descfn)
  792. return
  793. if self.params.get('writeinfojson', False):
  794. infofn = os.path.splitext(filename)[0] + '.info.json'
  795. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  796. self.to_screen('[info] Video description metadata is already present')
  797. else:
  798. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  799. try:
  800. write_json_file(info_dict, encodeFilename(infofn))
  801. except (OSError, IOError):
  802. self.report_error('Cannot write metadata to JSON file ' + infofn)
  803. return
  804. if self.params.get('writethumbnail', False):
  805. if info_dict.get('thumbnail') is not None:
  806. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  807. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  808. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  809. self.to_screen('[%s] %s: Thumbnail is already present' %
  810. (info_dict['extractor'], info_dict['id']))
  811. else:
  812. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  813. (info_dict['extractor'], info_dict['id']))
  814. try:
  815. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  816. with open(thumb_filename, 'wb') as thumbf:
  817. shutil.copyfileobj(uf, thumbf)
  818. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  819. (info_dict['extractor'], info_dict['id'], thumb_filename))
  820. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  821. self.report_warning('Unable to download thumbnail "%s": %s' %
  822. (info_dict['thumbnail'], compat_str(err)))
  823. if not self.params.get('skip_download', False):
  824. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  825. success = True
  826. else:
  827. try:
  828. def dl(name, info):
  829. fd = get_suitable_downloader(info)(self, self.params)
  830. for ph in self._progress_hooks:
  831. fd.add_progress_hook(ph)
  832. return fd.download(name, info)
  833. if info_dict.get('requested_formats') is not None:
  834. downloaded = []
  835. success = True
  836. merger = FFmpegMergerPP(self)
  837. if not merger._get_executable():
  838. postprocessors = []
  839. self.report_warning('You have requested multiple '
  840. 'formats but ffmpeg or avconv are not installed.'
  841. ' The formats won\'t be merged')
  842. else:
  843. postprocessors = [merger]
  844. for f in info_dict['requested_formats']:
  845. new_info = dict(info_dict)
  846. new_info.update(f)
  847. fname = self.prepare_filename(new_info)
  848. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  849. downloaded.append(fname)
  850. partial_success = dl(fname, new_info)
  851. success = success and partial_success
  852. info_dict['__postprocessors'] = postprocessors
  853. info_dict['__files_to_merge'] = downloaded
  854. else:
  855. # Just a single file
  856. success = dl(filename, info_dict)
  857. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  858. self.report_error('unable to download video data: %s' % str(err))
  859. return
  860. except (OSError, IOError) as err:
  861. raise UnavailableVideoError(err)
  862. except (ContentTooShortError, ) as err:
  863. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  864. return
  865. if success:
  866. try:
  867. self.post_process(filename, info_dict)
  868. except (PostProcessingError) as err:
  869. self.report_error('postprocessing: %s' % str(err))
  870. return
  871. self.record_download_archive(info_dict)
  872. def download(self, url_list):
  873. """Download a given list of URLs."""
  874. if (len(url_list) > 1 and
  875. '%' not in self.params['outtmpl']
  876. and self.params.get('max_downloads') != 1):
  877. raise SameFileError(self.params['outtmpl'])
  878. for url in url_list:
  879. try:
  880. #It also downloads the videos
  881. self.extract_info(url)
  882. except UnavailableVideoError:
  883. self.report_error('unable to download video')
  884. except MaxDownloadsReached:
  885. self.to_screen('[info] Maximum number of downloaded files reached.')
  886. raise
  887. return self._download_retcode
  888. def download_with_info_file(self, info_filename):
  889. with io.open(info_filename, 'r', encoding='utf-8') as f:
  890. info = json.load(f)
  891. try:
  892. self.process_ie_result(info, download=True)
  893. except DownloadError:
  894. webpage_url = info.get('webpage_url')
  895. if webpage_url is not None:
  896. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  897. return self.download([webpage_url])
  898. else:
  899. raise
  900. return self._download_retcode
  901. def post_process(self, filename, ie_info):
  902. """Run all the postprocessors on the given file."""
  903. info = dict(ie_info)
  904. info['filepath'] = filename
  905. keep_video = None
  906. pps_chain = []
  907. if ie_info.get('__postprocessors') is not None:
  908. pps_chain.extend(ie_info['__postprocessors'])
  909. pps_chain.extend(self._pps)
  910. for pp in pps_chain:
  911. try:
  912. keep_video_wish, new_info = pp.run(info)
  913. if keep_video_wish is not None:
  914. if keep_video_wish:
  915. keep_video = keep_video_wish
  916. elif keep_video is None:
  917. # No clear decision yet, let IE decide
  918. keep_video = keep_video_wish
  919. except PostProcessingError as e:
  920. self.report_error(e.msg)
  921. if keep_video is False and not self.params.get('keepvideo', False):
  922. try:
  923. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  924. os.remove(encodeFilename(filename))
  925. except (IOError, OSError):
  926. self.report_warning('Unable to remove downloaded video file')
  927. def _make_archive_id(self, info_dict):
  928. # Future-proof against any change in case
  929. # and backwards compatibility with prior versions
  930. extractor = info_dict.get('extractor_key')
  931. if extractor is None:
  932. if 'id' in info_dict:
  933. extractor = info_dict.get('ie_key') # key in a playlist
  934. if extractor is None:
  935. return None # Incomplete video information
  936. return extractor.lower() + ' ' + info_dict['id']
  937. def in_download_archive(self, info_dict):
  938. fn = self.params.get('download_archive')
  939. if fn is None:
  940. return False
  941. vid_id = self._make_archive_id(info_dict)
  942. if vid_id is None:
  943. return False # Incomplete video information
  944. try:
  945. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  946. for line in archive_file:
  947. if line.strip() == vid_id:
  948. return True
  949. except IOError as ioe:
  950. if ioe.errno != errno.ENOENT:
  951. raise
  952. return False
  953. def record_download_archive(self, info_dict):
  954. fn = self.params.get('download_archive')
  955. if fn is None:
  956. return
  957. vid_id = self._make_archive_id(info_dict)
  958. assert vid_id
  959. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  960. archive_file.write(vid_id + '\n')
  961. @staticmethod
  962. def format_resolution(format, default='unknown'):
  963. if format.get('vcodec') == 'none':
  964. return 'audio only'
  965. if format.get('resolution') is not None:
  966. return format['resolution']
  967. if format.get('height') is not None:
  968. if format.get('width') is not None:
  969. res = '%sx%s' % (format['width'], format['height'])
  970. else:
  971. res = '%sp' % format['height']
  972. elif format.get('width') is not None:
  973. res = '?x%d' % format['width']
  974. else:
  975. res = default
  976. return res
  977. def list_formats(self, info_dict):
  978. def format_note(fdict):
  979. res = ''
  980. if fdict.get('ext') in ['f4f', 'f4m']:
  981. res += '(unsupported) '
  982. if fdict.get('format_note') is not None:
  983. res += fdict['format_note'] + ' '
  984. if fdict.get('tbr') is not None:
  985. res += '%4dk ' % fdict['tbr']
  986. if fdict.get('container') is not None:
  987. if res:
  988. res += ', '
  989. res += '%s container' % fdict['container']
  990. if (fdict.get('vcodec') is not None and
  991. fdict.get('vcodec') != 'none'):
  992. if res:
  993. res += ', '
  994. res += fdict['vcodec']
  995. if fdict.get('vbr') is not None:
  996. res += '@'
  997. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  998. res += 'video@'
  999. if fdict.get('vbr') is not None:
  1000. res += '%4dk' % fdict['vbr']
  1001. if fdict.get('acodec') is not None:
  1002. if res:
  1003. res += ', '
  1004. if fdict['acodec'] == 'none':
  1005. res += 'video only'
  1006. else:
  1007. res += '%-5s' % fdict['acodec']
  1008. elif fdict.get('abr') is not None:
  1009. if res:
  1010. res += ', '
  1011. res += 'audio'
  1012. if fdict.get('abr') is not None:
  1013. res += '@%3dk' % fdict['abr']
  1014. if fdict.get('asr') is not None:
  1015. res += ' (%5dHz)' % fdict['asr']
  1016. if fdict.get('filesize') is not None:
  1017. if res:
  1018. res += ', '
  1019. res += format_bytes(fdict['filesize'])
  1020. return res
  1021. def line(format, idlen=20):
  1022. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1023. format['format_id'],
  1024. format['ext'],
  1025. self.format_resolution(format),
  1026. format_note(format),
  1027. ))
  1028. formats = info_dict.get('formats', [info_dict])
  1029. idlen = max(len('format code'),
  1030. max(len(f['format_id']) for f in formats))
  1031. formats_s = [line(f, idlen) for f in formats]
  1032. if len(formats) > 1:
  1033. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1034. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1035. header_line = line({
  1036. 'format_id': 'format code', 'ext': 'extension',
  1037. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1038. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1039. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1040. def urlopen(self, req):
  1041. """ Start an HTTP download """
  1042. return self._opener.open(req)
  1043. def print_debug_header(self):
  1044. if not self.params.get('verbose'):
  1045. return
  1046. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1047. try:
  1048. sp = subprocess.Popen(
  1049. ['git', 'rev-parse', '--short', 'HEAD'],
  1050. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1051. cwd=os.path.dirname(os.path.abspath(__file__)))
  1052. out, err = sp.communicate()
  1053. out = out.decode().strip()
  1054. if re.match('[0-9a-f]+', out):
  1055. write_string('[debug] Git HEAD: ' + out + '\n')
  1056. except:
  1057. try:
  1058. sys.exc_clear()
  1059. except:
  1060. pass
  1061. write_string('[debug] Python version %s - %s' %
  1062. (platform.python_version(), platform_name()) + '\n')
  1063. proxy_map = {}
  1064. for handler in self._opener.handlers:
  1065. if hasattr(handler, 'proxies'):
  1066. proxy_map.update(handler.proxies)
  1067. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1068. def _setup_opener(self):
  1069. timeout_val = self.params.get('socket_timeout')
  1070. timeout = 600 if timeout_val is None else float(timeout_val)
  1071. opts_cookiefile = self.params.get('cookiefile')
  1072. opts_proxy = self.params.get('proxy')
  1073. if opts_cookiefile is None:
  1074. self.cookiejar = compat_cookiejar.CookieJar()
  1075. else:
  1076. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1077. opts_cookiefile)
  1078. if os.access(opts_cookiefile, os.R_OK):
  1079. self.cookiejar.load()
  1080. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1081. self.cookiejar)
  1082. if opts_proxy is not None:
  1083. if opts_proxy == '':
  1084. proxies = {}
  1085. else:
  1086. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1087. else:
  1088. proxies = compat_urllib_request.getproxies()
  1089. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1090. if 'http' in proxies and 'https' not in proxies:
  1091. proxies['https'] = proxies['http']
  1092. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1093. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1094. https_handler = make_HTTPS_handler(
  1095. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1096. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1097. opener = compat_urllib_request.build_opener(
  1098. https_handler, proxy_handler, cookie_processor, ydlh)
  1099. # Delete the default user-agent header, which would otherwise apply in
  1100. # cases where our custom HTTP handler doesn't come into play
  1101. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1102. opener.addheaders = []
  1103. self._opener = opener
  1104. # TODO remove this global modification
  1105. compat_urllib_request.install_opener(opener)
  1106. socket.setdefaulttimeout(timeout)