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.

1145 lines
49 KiB

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