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.

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