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.

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