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.

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