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.

1222 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 increment_downloads(self):
  357. """Increment the ordinal that assigns a number to each file."""
  358. self._num_downloads += 1
  359. def prepare_filename(self, info_dict):
  360. """Generate the output filename."""
  361. try:
  362. template_dict = dict(info_dict)
  363. template_dict['epoch'] = int(time.time())
  364. autonumber_size = self.params.get('autonumber_size')
  365. if autonumber_size is None:
  366. autonumber_size = 5
  367. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  368. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  369. if template_dict.get('playlist_index') is not None:
  370. template_dict['playlist_index'] = '%05d' % template_dict['playlist_index']
  371. sanitize = lambda k, v: sanitize_filename(
  372. compat_str(v),
  373. restricted=self.params.get('restrictfilenames'),
  374. is_id=(k == 'id'))
  375. template_dict = dict((k, sanitize(k, v))
  376. for k, v in template_dict.items()
  377. if v is not None)
  378. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  379. tmpl = os.path.expanduser(self.params['outtmpl'])
  380. filename = tmpl % template_dict
  381. return filename
  382. except ValueError as err:
  383. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  384. return None
  385. def _match_entry(self, info_dict):
  386. """ Returns None iff the file should be downloaded """
  387. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  388. if 'title' in info_dict:
  389. # This can happen when we're just evaluating the playlist
  390. title = info_dict['title']
  391. matchtitle = self.params.get('matchtitle', False)
  392. if matchtitle:
  393. if not re.search(matchtitle, title, re.IGNORECASE):
  394. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  395. rejecttitle = self.params.get('rejecttitle', False)
  396. if rejecttitle:
  397. if re.search(rejecttitle, title, re.IGNORECASE):
  398. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  399. date = info_dict.get('upload_date', None)
  400. if date is not None:
  401. dateRange = self.params.get('daterange', DateRange())
  402. if date not in dateRange:
  403. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  404. view_count = info_dict.get('view_count', None)
  405. if view_count is not None:
  406. min_views = self.params.get('min_views')
  407. if min_views is not None and view_count < min_views:
  408. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  409. max_views = self.params.get('max_views')
  410. if max_views is not None and view_count > max_views:
  411. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  412. age_limit = self.params.get('age_limit')
  413. if age_limit is not None:
  414. if age_limit < info_dict.get('age_limit', 0):
  415. return 'Skipping "' + title + '" because it is age restricted'
  416. if self.in_download_archive(info_dict):
  417. return '%s has already been recorded in archive' % video_title
  418. return None
  419. @staticmethod
  420. def add_extra_info(info_dict, extra_info):
  421. '''Set the keys from extra_info in info dict if they are missing'''
  422. for key, value in extra_info.items():
  423. info_dict.setdefault(key, value)
  424. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  425. process=True):
  426. '''
  427. Returns a list with a dictionary for each video we find.
  428. If 'download', also downloads the videos.
  429. extra_info is a dict containing the extra values to add to each result
  430. '''
  431. if ie_key:
  432. ies = [self.get_info_extractor(ie_key)]
  433. else:
  434. ies = self._ies
  435. for ie in ies:
  436. if not ie.suitable(url):
  437. continue
  438. if not ie.working():
  439. self.report_warning('The program functionality for this site has been marked as broken, '
  440. 'and will probably not work.')
  441. try:
  442. ie_result = ie.extract(url)
  443. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  444. break
  445. if isinstance(ie_result, list):
  446. # Backwards compatibility: old IE result format
  447. ie_result = {
  448. '_type': 'compat_list',
  449. 'entries': ie_result,
  450. }
  451. self.add_extra_info(ie_result,
  452. {
  453. 'extractor': ie.IE_NAME,
  454. 'webpage_url': url,
  455. 'webpage_url_basename': url_basename(url),
  456. 'extractor_key': ie.ie_key(),
  457. })
  458. if process:
  459. return self.process_ie_result(ie_result, download, extra_info)
  460. else:
  461. return ie_result
  462. except ExtractorError as de: # An error we somewhat expected
  463. self.report_error(compat_str(de), de.format_traceback())
  464. break
  465. except Exception as e:
  466. if self.params.get('ignoreerrors', False):
  467. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  468. break
  469. else:
  470. raise
  471. else:
  472. self.report_error('no suitable InfoExtractor: %s' % url)
  473. def process_ie_result(self, ie_result, download=True, extra_info={}):
  474. """
  475. Take the result of the ie(may be modified) and resolve all unresolved
  476. references (URLs, playlist items).
  477. It will also download the videos if 'download'.
  478. Returns the resolved ie_result.
  479. """
  480. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  481. if result_type == 'video':
  482. self.add_extra_info(ie_result, extra_info)
  483. return self.process_video_result(ie_result, download=download)
  484. elif result_type == 'url':
  485. # We have to add extra_info to the results because it may be
  486. # contained in a playlist
  487. return self.extract_info(ie_result['url'],
  488. download,
  489. ie_key=ie_result.get('ie_key'),
  490. extra_info=extra_info)
  491. elif result_type == 'url_transparent':
  492. # Use the information from the embedding page
  493. info = self.extract_info(
  494. ie_result['url'], ie_key=ie_result.get('ie_key'),
  495. extra_info=extra_info, download=False, process=False)
  496. def make_result(embedded_info):
  497. new_result = ie_result.copy()
  498. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  499. 'entries', 'ie_key', 'duration',
  500. 'subtitles', 'annotations', 'format',
  501. 'thumbnail', 'thumbnails'):
  502. if f in new_result:
  503. del new_result[f]
  504. if f in embedded_info:
  505. new_result[f] = embedded_info[f]
  506. return new_result
  507. new_result = make_result(info)
  508. assert new_result.get('_type') != 'url_transparent'
  509. if new_result.get('_type') == 'compat_list':
  510. new_result['entries'] = [
  511. make_result(e) for e in new_result['entries']]
  512. return self.process_ie_result(
  513. new_result, download=download, extra_info=extra_info)
  514. elif result_type == 'playlist':
  515. # We process each entry in the playlist
  516. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  517. self.to_screen('[download] Downloading playlist: %s' % playlist)
  518. playlist_results = []
  519. playliststart = self.params.get('playliststart', 1) - 1
  520. playlistend = self.params.get('playlistend', None)
  521. # For backwards compatibility, interpret -1 as whole list
  522. if playlistend == -1:
  523. playlistend = None
  524. if isinstance(ie_result['entries'], list):
  525. n_all_entries = len(ie_result['entries'])
  526. entries = ie_result['entries'][playliststart:playlistend]
  527. n_entries = len(entries)
  528. self.to_screen(
  529. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  530. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  531. else:
  532. assert isinstance(ie_result['entries'], PagedList)
  533. entries = ie_result['entries'].getslice(
  534. playliststart, playlistend)
  535. n_entries = len(entries)
  536. self.to_screen(
  537. "[%s] playlist %s: Downloading %d videos" %
  538. (ie_result['extractor'], playlist, n_entries))
  539. for i, entry in enumerate(entries, 1):
  540. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  541. extra = {
  542. 'playlist': playlist,
  543. 'playlist_index': i + playliststart,
  544. 'extractor': ie_result['extractor'],
  545. 'webpage_url': ie_result['webpage_url'],
  546. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  547. 'extractor_key': ie_result['extractor_key'],
  548. }
  549. reason = self._match_entry(entry)
  550. if reason is not None:
  551. self.to_screen('[download] ' + reason)
  552. continue
  553. entry_result = self.process_ie_result(entry,
  554. download=download,
  555. extra_info=extra)
  556. playlist_results.append(entry_result)
  557. ie_result['entries'] = playlist_results
  558. return ie_result
  559. elif result_type == 'compat_list':
  560. def _fixup(r):
  561. self.add_extra_info(r,
  562. {
  563. 'extractor': ie_result['extractor'],
  564. 'webpage_url': ie_result['webpage_url'],
  565. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  566. 'extractor_key': ie_result['extractor_key'],
  567. })
  568. return r
  569. ie_result['entries'] = [
  570. self.process_ie_result(_fixup(r), download, extra_info)
  571. for r in ie_result['entries']
  572. ]
  573. return ie_result
  574. else:
  575. raise Exception('Invalid result type: %s' % result_type)
  576. def select_format(self, format_spec, available_formats):
  577. if format_spec == 'best' or format_spec is None:
  578. return available_formats[-1]
  579. elif format_spec == 'worst':
  580. return available_formats[0]
  581. elif format_spec == 'bestaudio':
  582. audio_formats = [
  583. f for f in available_formats
  584. if f.get('vcodec') == 'none']
  585. if audio_formats:
  586. return audio_formats[-1]
  587. elif format_spec == 'worstaudio':
  588. audio_formats = [
  589. f for f in available_formats
  590. if f.get('vcodec') == 'none']
  591. if audio_formats:
  592. return audio_formats[0]
  593. else:
  594. extensions = ['mp4', 'flv', 'webm', '3gp']
  595. if format_spec in extensions:
  596. filter_f = lambda f: f['ext'] == format_spec
  597. else:
  598. filter_f = lambda f: f['format_id'] == format_spec
  599. matches = list(filter(filter_f, available_formats))
  600. if matches:
  601. return matches[-1]
  602. return None
  603. def process_video_result(self, info_dict, download=True):
  604. assert info_dict.get('_type', 'video') == 'video'
  605. if 'playlist' not in info_dict:
  606. # It isn't part of a playlist
  607. info_dict['playlist'] = None
  608. info_dict['playlist_index'] = None
  609. # This extractors handle format selection themselves
  610. if info_dict['extractor'] in ['Youku']:
  611. if download:
  612. self.process_info(info_dict)
  613. return info_dict
  614. # We now pick which formats have to be downloaded
  615. if info_dict.get('formats') is None:
  616. # There's only one format available
  617. formats = [info_dict]
  618. else:
  619. formats = info_dict['formats']
  620. # We check that all the formats have the format and format_id fields
  621. for (i, format) in enumerate(formats):
  622. if format.get('format_id') is None:
  623. format['format_id'] = compat_str(i)
  624. if format.get('format') is None:
  625. format['format'] = '{id} - {res}{note}'.format(
  626. id=format['format_id'],
  627. res=self.format_resolution(format),
  628. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  629. )
  630. # Automatically determine file extension if missing
  631. if 'ext' not in format:
  632. format['ext'] = determine_ext(format['url'])
  633. format_limit = self.params.get('format_limit', None)
  634. if format_limit:
  635. formats = list(takewhile_inclusive(
  636. lambda f: f['format_id'] != format_limit, formats
  637. ))
  638. # TODO Central sorting goes here
  639. if formats[0] is not info_dict:
  640. # only set the 'formats' fields if the original info_dict list them
  641. # otherwise we end up with a circular reference, the first (and unique)
  642. # element in the 'formats' field in info_dict is info_dict itself,
  643. # wich can't be exported to json
  644. info_dict['formats'] = formats
  645. if self.params.get('listformats', None):
  646. self.list_formats(info_dict)
  647. return
  648. req_format = self.params.get('format')
  649. if req_format is None:
  650. req_format = 'best'
  651. formats_to_download = []
  652. # The -1 is for supporting YoutubeIE
  653. if req_format in ('-1', 'all'):
  654. formats_to_download = formats
  655. else:
  656. # We can accept formats requested in the format: 34/5/best, we pick
  657. # the first that is available, starting from left
  658. req_formats = req_format.split('/')
  659. for rf in req_formats:
  660. if re.match(r'.+?\+.+?', rf) is not None:
  661. # Two formats have been requested like '137+139'
  662. format_1, format_2 = rf.split('+')
  663. formats_info = (self.select_format(format_1, formats),
  664. self.select_format(format_2, formats))
  665. if all(formats_info):
  666. selected_format = {
  667. 'requested_formats': formats_info,
  668. 'format': rf,
  669. 'ext': formats_info[0]['ext'],
  670. }
  671. else:
  672. selected_format = None
  673. else:
  674. selected_format = self.select_format(rf, formats)
  675. if selected_format is not None:
  676. formats_to_download = [selected_format]
  677. break
  678. if not formats_to_download:
  679. raise ExtractorError('requested format not available',
  680. expected=True)
  681. if download:
  682. if len(formats_to_download) > 1:
  683. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  684. for format in formats_to_download:
  685. new_info = dict(info_dict)
  686. new_info.update(format)
  687. self.process_info(new_info)
  688. # We update the info dict with the best quality format (backwards compatibility)
  689. info_dict.update(formats_to_download[-1])
  690. return info_dict
  691. def process_info(self, info_dict):
  692. """Process a single resolved IE result."""
  693. assert info_dict.get('_type', 'video') == 'video'
  694. #We increment the download the download count here to match the previous behaviour.
  695. self.increment_downloads()
  696. info_dict['fulltitle'] = info_dict['title']
  697. if len(info_dict['title']) > 200:
  698. info_dict['title'] = info_dict['title'][:197] + '...'
  699. # Keep for backwards compatibility
  700. info_dict['stitle'] = info_dict['title']
  701. if not 'format' in info_dict:
  702. info_dict['format'] = info_dict['ext']
  703. reason = self._match_entry(info_dict)
  704. if reason is not None:
  705. self.to_screen('[download] ' + reason)
  706. return
  707. max_downloads = self.params.get('max_downloads')
  708. if max_downloads is not None:
  709. if self._num_downloads > int(max_downloads):
  710. raise MaxDownloadsReached()
  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('vcodec') is not None and
  989. fdict.get('vcodec') != 'none'):
  990. res += '%-5s' % fdict['vcodec']
  991. if fdict.get('vbr') is not None:
  992. res += '@'
  993. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  994. res += 'video@'
  995. if fdict.get('vbr') is not None:
  996. res += '%4dk' % fdict['vbr']
  997. if fdict.get('acodec') is not None:
  998. if res:
  999. res += ', '
  1000. res += '%-5s' % fdict['acodec']
  1001. elif fdict.get('abr') is not None:
  1002. if res:
  1003. res += ', '
  1004. res += 'audio'
  1005. if fdict.get('abr') is not None:
  1006. res += '@%3dk' % fdict['abr']
  1007. if fdict.get('asr') is not None:
  1008. res += ' (%5dHz)' % fdict['asr']
  1009. if fdict.get('filesize') is not None:
  1010. if res:
  1011. res += ', '
  1012. res += format_bytes(fdict['filesize'])
  1013. return res
  1014. def line(format, idlen=20):
  1015. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1016. format['format_id'],
  1017. format['ext'],
  1018. self.format_resolution(format),
  1019. format_note(format),
  1020. ))
  1021. formats = info_dict.get('formats', [info_dict])
  1022. idlen = max(len('format code'),
  1023. max(len(f['format_id']) for f in formats))
  1024. formats_s = [line(f, idlen) for f in formats]
  1025. if len(formats) > 1:
  1026. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1027. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1028. header_line = line({
  1029. 'format_id': 'format code', 'ext': 'extension',
  1030. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1031. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1032. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1033. def urlopen(self, req):
  1034. """ Start an HTTP download """
  1035. return self._opener.open(req)
  1036. def print_debug_header(self):
  1037. if not self.params.get('verbose'):
  1038. return
  1039. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1040. try:
  1041. sp = subprocess.Popen(
  1042. ['git', 'rev-parse', '--short', 'HEAD'],
  1043. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1044. cwd=os.path.dirname(os.path.abspath(__file__)))
  1045. out, err = sp.communicate()
  1046. out = out.decode().strip()
  1047. if re.match('[0-9a-f]+', out):
  1048. write_string('[debug] Git HEAD: ' + out + '\n')
  1049. except:
  1050. try:
  1051. sys.exc_clear()
  1052. except:
  1053. pass
  1054. write_string('[debug] Python version %s - %s' %
  1055. (platform.python_version(), platform_name()) + '\n')
  1056. proxy_map = {}
  1057. for handler in self._opener.handlers:
  1058. if hasattr(handler, 'proxies'):
  1059. proxy_map.update(handler.proxies)
  1060. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1061. def _setup_opener(self):
  1062. timeout_val = self.params.get('socket_timeout')
  1063. timeout = 600 if timeout_val is None else float(timeout_val)
  1064. opts_cookiefile = self.params.get('cookiefile')
  1065. opts_proxy = self.params.get('proxy')
  1066. if opts_cookiefile is None:
  1067. self.cookiejar = compat_cookiejar.CookieJar()
  1068. else:
  1069. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1070. opts_cookiefile)
  1071. if os.access(opts_cookiefile, os.R_OK):
  1072. self.cookiejar.load()
  1073. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1074. self.cookiejar)
  1075. if opts_proxy is not None:
  1076. if opts_proxy == '':
  1077. proxies = {}
  1078. else:
  1079. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1080. else:
  1081. proxies = compat_urllib_request.getproxies()
  1082. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1083. if 'http' in proxies and 'https' not in proxies:
  1084. proxies['https'] = proxies['http']
  1085. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1086. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1087. https_handler = make_HTTPS_handler(
  1088. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1089. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1090. opener = compat_urllib_request.build_opener(
  1091. https_handler, proxy_handler, cookie_processor, ydlh)
  1092. # Delete the default user-agent header, which would otherwise apply in
  1093. # cases where our custom HTTP handler doesn't come into play
  1094. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1095. opener.addheaders = []
  1096. self._opener = opener
  1097. # TODO remove this global modification
  1098. compat_urllib_request.install_opener(opener)
  1099. socket.setdefaulttimeout(timeout)