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.

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