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.

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