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.

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