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.

1184 lines
51 KiB

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