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.

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