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', -1)
  499. if playlistend == -1:
  500. entries = ie_result['entries'][playliststart:]
  501. else:
  502. entries = ie_result['entries'][playliststart:playlistend]
  503. n_entries = len(entries)
  504. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  505. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  506. for i, entry in enumerate(entries, 1):
  507. self.to_screen(u'[download] Downloading video #%s of %s' % (i, n_entries))
  508. extra = {
  509. 'playlist': playlist,
  510. 'playlist_index': i + playliststart,
  511. 'extractor': ie_result['extractor'],
  512. 'webpage_url': ie_result['webpage_url'],
  513. 'extractor_key': ie_result['extractor_key'],
  514. }
  515. reason = self._match_entry(entry)
  516. if reason is not None:
  517. self.to_screen(u'[download] ' + reason)
  518. continue
  519. entry_result = self.process_ie_result(entry,
  520. download=download,
  521. extra_info=extra)
  522. playlist_results.append(entry_result)
  523. ie_result['entries'] = playlist_results
  524. return ie_result
  525. elif result_type == 'compat_list':
  526. def _fixup(r):
  527. self.add_extra_info(r,
  528. {
  529. 'extractor': ie_result['extractor'],
  530. 'webpage_url': ie_result['webpage_url'],
  531. 'extractor_key': ie_result['extractor_key'],
  532. })
  533. return r
  534. ie_result['entries'] = [
  535. self.process_ie_result(_fixup(r), download, extra_info)
  536. for r in ie_result['entries']
  537. ]
  538. return ie_result
  539. else:
  540. raise Exception('Invalid result type: %s' % result_type)
  541. def select_format(self, format_spec, available_formats):
  542. if format_spec == 'best' or format_spec is None:
  543. return available_formats[-1]
  544. elif format_spec == 'worst':
  545. return available_formats[0]
  546. else:
  547. extensions = [u'mp4', u'flv', u'webm', u'3gp']
  548. if format_spec in extensions:
  549. filter_f = lambda f: f['ext'] == format_spec
  550. else:
  551. filter_f = lambda f: f['format_id'] == format_spec
  552. matches = list(filter(filter_f, available_formats))
  553. if matches:
  554. return matches[-1]
  555. return None
  556. def process_video_result(self, info_dict, download=True):
  557. assert info_dict.get('_type', 'video') == 'video'
  558. if 'playlist' not in info_dict:
  559. # It isn't part of a playlist
  560. info_dict['playlist'] = None
  561. info_dict['playlist_index'] = None
  562. # This extractors handle format selection themselves
  563. if info_dict['extractor'] in [u'youtube', u'Youku']:
  564. if download:
  565. self.process_info(info_dict)
  566. return info_dict
  567. # We now pick which formats have to be downloaded
  568. if info_dict.get('formats') is None:
  569. # There's only one format available
  570. formats = [info_dict]
  571. else:
  572. formats = info_dict['formats']
  573. # We check that all the formats have the format and format_id fields
  574. for (i, format) in enumerate(formats):
  575. if format.get('format_id') is None:
  576. format['format_id'] = compat_str(i)
  577. if format.get('format') is None:
  578. format['format'] = u'{id} - {res}{note}'.format(
  579. id=format['format_id'],
  580. res=self.format_resolution(format),
  581. note=u' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  582. )
  583. # Automatically determine file extension if missing
  584. if 'ext' not in format:
  585. format['ext'] = determine_ext(format['url'])
  586. if self.params.get('listformats', None):
  587. self.list_formats(info_dict)
  588. return
  589. format_limit = self.params.get('format_limit', None)
  590. if format_limit:
  591. formats = list(takewhile_inclusive(
  592. lambda f: f['format_id'] != format_limit, formats
  593. ))
  594. if self.params.get('prefer_free_formats'):
  595. def _free_formats_key(f):
  596. try:
  597. ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
  598. except ValueError:
  599. ext_ord = -1
  600. # We only compare the extension if they have the same height and width
  601. return (f.get('height'), f.get('width'), ext_ord)
  602. formats = sorted(formats, key=_free_formats_key)
  603. req_format = self.params.get('format', 'best')
  604. if req_format is None:
  605. req_format = 'best'
  606. formats_to_download = []
  607. # The -1 is for supporting YoutubeIE
  608. if req_format in ('-1', 'all'):
  609. formats_to_download = formats
  610. else:
  611. # We can accept formats requestd in the format: 34/5/best, we pick
  612. # the first that is available, starting from left
  613. req_formats = req_format.split('/')
  614. for rf in req_formats:
  615. selected_format = self.select_format(rf, formats)
  616. if selected_format is not None:
  617. formats_to_download = [selected_format]
  618. break
  619. if not formats_to_download:
  620. raise ExtractorError(u'requested format not available',
  621. expected=True)
  622. if download:
  623. if len(formats_to_download) > 1:
  624. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  625. for format in formats_to_download:
  626. new_info = dict(info_dict)
  627. new_info.update(format)
  628. self.process_info(new_info)
  629. # We update the info dict with the best quality format (backwards compatibility)
  630. info_dict.update(formats_to_download[-1])
  631. return info_dict
  632. def process_info(self, info_dict):
  633. """Process a single resolved IE result."""
  634. assert info_dict.get('_type', 'video') == 'video'
  635. #We increment the download the download count here to match the previous behaviour.
  636. self.increment_downloads()
  637. info_dict['fulltitle'] = info_dict['title']
  638. if len(info_dict['title']) > 200:
  639. info_dict['title'] = info_dict['title'][:197] + u'...'
  640. # Keep for backwards compatibility
  641. info_dict['stitle'] = info_dict['title']
  642. if not 'format' in info_dict:
  643. info_dict['format'] = info_dict['ext']
  644. reason = self._match_entry(info_dict)
  645. if reason is not None:
  646. self.to_screen(u'[download] ' + reason)
  647. return
  648. max_downloads = self.params.get('max_downloads')
  649. if max_downloads is not None:
  650. if self._num_downloads > int(max_downloads):
  651. raise MaxDownloadsReached()
  652. filename = self.prepare_filename(info_dict)
  653. # Forced printings
  654. if self.params.get('forcetitle', False):
  655. self.to_stdout(info_dict['fulltitle'])
  656. if self.params.get('forceid', False):
  657. self.to_stdout(info_dict['id'])
  658. if self.params.get('forceurl', False):
  659. # For RTMP URLs, also include the playpath
  660. self.to_stdout(info_dict['url'] + info_dict.get('play_path', u''))
  661. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  662. self.to_stdout(info_dict['thumbnail'])
  663. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  664. self.to_stdout(info_dict['description'])
  665. if self.params.get('forcefilename', False) and filename is not None:
  666. self.to_stdout(filename)
  667. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  668. self.to_stdout(formatSeconds(info_dict['duration']))
  669. if self.params.get('forceformat', False):
  670. self.to_stdout(info_dict['format'])
  671. if self.params.get('forcejson', False):
  672. info_dict['_filename'] = filename
  673. self.to_stdout(json.dumps(info_dict))
  674. # Do nothing else if in simulate mode
  675. if self.params.get('simulate', False):
  676. return
  677. if filename is None:
  678. return
  679. try:
  680. dn = os.path.dirname(encodeFilename(filename))
  681. if dn != '' and not os.path.exists(dn):
  682. os.makedirs(dn)
  683. except (OSError, IOError) as err:
  684. self.report_error(u'unable to create directory ' + compat_str(err))
  685. return
  686. if self.params.get('writedescription', False):
  687. descfn = filename + u'.description'
  688. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  689. self.to_screen(u'[info] Video description is already present')
  690. else:
  691. try:
  692. self.to_screen(u'[info] Writing video description to: ' + descfn)
  693. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  694. descfile.write(info_dict['description'])
  695. except (KeyError, TypeError):
  696. self.report_warning(u'There\'s no description to write.')
  697. except (OSError, IOError):
  698. self.report_error(u'Cannot write description file ' + descfn)
  699. return
  700. if self.params.get('writeannotations', False):
  701. annofn = filename + u'.annotations.xml'
  702. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  703. self.to_screen(u'[info] Video annotations are already present')
  704. else:
  705. try:
  706. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  707. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  708. annofile.write(info_dict['annotations'])
  709. except (KeyError, TypeError):
  710. self.report_warning(u'There are no annotations to write.')
  711. except (OSError, IOError):
  712. self.report_error(u'Cannot write annotations file: ' + annofn)
  713. return
  714. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  715. self.params.get('writeautomaticsub')])
  716. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  717. # subtitles download errors are already managed as troubles in relevant IE
  718. # that way it will silently go on when used with unsupporting IE
  719. subtitles = info_dict['subtitles']
  720. sub_format = self.params.get('subtitlesformat', 'srt')
  721. for sub_lang in subtitles.keys():
  722. sub = subtitles[sub_lang]
  723. if sub is None:
  724. continue
  725. try:
  726. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  727. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  728. self.to_screen(u'[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  729. else:
  730. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  731. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  732. subfile.write(sub)
  733. except (OSError, IOError):
  734. self.report_error(u'Cannot write subtitles file ' + descfn)
  735. return
  736. if self.params.get('writeinfojson', False):
  737. infofn = os.path.splitext(filename)[0] + u'.info.json'
  738. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  739. self.to_screen(u'[info] Video description metadata is already present')
  740. else:
  741. self.to_screen(u'[info] Writing video description metadata as JSON to: ' + infofn)
  742. try:
  743. json_info_dict = dict((k, v) for k, v in info_dict.items() if not k in ['urlhandle'])
  744. write_json_file(json_info_dict, encodeFilename(infofn))
  745. except (OSError, IOError):
  746. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  747. return
  748. if self.params.get('writethumbnail', False):
  749. if info_dict.get('thumbnail') is not None:
  750. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  751. thumb_filename = os.path.splitext(filename)[0] + u'.' + thumb_format
  752. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  753. self.to_screen(u'[%s] %s: Thumbnail is already present' %
  754. (info_dict['extractor'], info_dict['id']))
  755. else:
  756. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  757. (info_dict['extractor'], info_dict['id']))
  758. try:
  759. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  760. with open(thumb_filename, 'wb') as thumbf:
  761. shutil.copyfileobj(uf, thumbf)
  762. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  763. (info_dict['extractor'], info_dict['id'], thumb_filename))
  764. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  765. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  766. (info_dict['thumbnail'], compat_str(err)))
  767. if not self.params.get('skip_download', False):
  768. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  769. success = True
  770. else:
  771. try:
  772. success = self.fd._do_download(filename, info_dict)
  773. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  774. self.report_error(u'unable to download video data: %s' % str(err))
  775. return
  776. except (OSError, IOError) as err:
  777. raise UnavailableVideoError(err)
  778. except (ContentTooShortError, ) as err:
  779. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  780. return
  781. if success:
  782. try:
  783. self.post_process(filename, info_dict)
  784. except (PostProcessingError) as err:
  785. self.report_error(u'postprocessing: %s' % str(err))
  786. return
  787. self.record_download_archive(info_dict)
  788. def download(self, url_list):
  789. """Download a given list of URLs."""
  790. if (len(url_list) > 1 and
  791. '%' not in self.params['outtmpl']
  792. and self.params.get('max_downloads') != 1):
  793. raise SameFileError(self.params['outtmpl'])
  794. for url in url_list:
  795. try:
  796. #It also downloads the videos
  797. self.extract_info(url)
  798. except UnavailableVideoError:
  799. self.report_error(u'unable to download video')
  800. except MaxDownloadsReached:
  801. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  802. raise
  803. return self._download_retcode
  804. def download_with_info_file(self, info_filename):
  805. with io.open(info_filename, 'r', encoding='utf-8') as f:
  806. info = json.load(f)
  807. try:
  808. self.process_ie_result(info, download=True)
  809. except DownloadError:
  810. webpage_url = info.get('webpage_url')
  811. if webpage_url is not None:
  812. self.report_warning(u'The info failed to download, trying with "%s"' % webpage_url)
  813. return self.download([webpage_url])
  814. else:
  815. raise
  816. return self._download_retcode
  817. def post_process(self, filename, ie_info):
  818. """Run all the postprocessors on the given file."""
  819. info = dict(ie_info)
  820. info['filepath'] = filename
  821. keep_video = None
  822. for pp in self._pps:
  823. try:
  824. keep_video_wish, new_info = pp.run(info)
  825. if keep_video_wish is not None:
  826. if keep_video_wish:
  827. keep_video = keep_video_wish
  828. elif keep_video is None:
  829. # No clear decision yet, let IE decide
  830. keep_video = keep_video_wish
  831. except PostProcessingError as e:
  832. self.report_error(e.msg)
  833. if keep_video is False and not self.params.get('keepvideo', False):
  834. try:
  835. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  836. os.remove(encodeFilename(filename))
  837. except (IOError, OSError):
  838. self.report_warning(u'Unable to remove downloaded video file')
  839. def _make_archive_id(self, info_dict):
  840. # Future-proof against any change in case
  841. # and backwards compatibility with prior versions
  842. extractor = info_dict.get('extractor_key')
  843. if extractor is None:
  844. if 'id' in info_dict:
  845. extractor = info_dict.get('ie_key') # key in a playlist
  846. if extractor is None:
  847. return None # Incomplete video information
  848. return extractor.lower() + u' ' + info_dict['id']
  849. def in_download_archive(self, info_dict):
  850. fn = self.params.get('download_archive')
  851. if fn is None:
  852. return False
  853. vid_id = self._make_archive_id(info_dict)
  854. if vid_id is None:
  855. return False # Incomplete video information
  856. try:
  857. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  858. for line in archive_file:
  859. if line.strip() == vid_id:
  860. return True
  861. except IOError as ioe:
  862. if ioe.errno != errno.ENOENT:
  863. raise
  864. return False
  865. def record_download_archive(self, info_dict):
  866. fn = self.params.get('download_archive')
  867. if fn is None:
  868. return
  869. vid_id = self._make_archive_id(info_dict)
  870. assert vid_id
  871. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  872. archive_file.write(vid_id + u'\n')
  873. @staticmethod
  874. def format_resolution(format, default='unknown'):
  875. if format.get('vcodec') == 'none':
  876. return 'audio only'
  877. if format.get('_resolution') is not None:
  878. return format['_resolution']
  879. if format.get('height') is not None:
  880. if format.get('width') is not None:
  881. res = u'%sx%s' % (format['width'], format['height'])
  882. else:
  883. res = u'%sp' % format['height']
  884. else:
  885. res = default
  886. return res
  887. def list_formats(self, info_dict):
  888. def format_note(fdict):
  889. res = u''
  890. if fdict.get('format_note') is not None:
  891. res += fdict['format_note'] + u' '
  892. if (fdict.get('vcodec') is not None and
  893. fdict.get('vcodec') != 'none'):
  894. res += u'%-5s' % fdict['vcodec']
  895. elif fdict.get('vbr') is not None:
  896. res += u'video'
  897. if fdict.get('vbr') is not None:
  898. res += u'@%4dk' % fdict['vbr']
  899. if fdict.get('acodec') is not None:
  900. if res:
  901. res += u', '
  902. res += u'%-5s' % fdict['acodec']
  903. elif fdict.get('abr') is not None:
  904. if res:
  905. res += u', '
  906. res += 'audio'
  907. if fdict.get('abr') is not None:
  908. res += u'@%3dk' % fdict['abr']
  909. if fdict.get('filesize') is not None:
  910. if res:
  911. res += u', '
  912. res += format_bytes(fdict['filesize'])
  913. return res
  914. def line(format, idlen=20):
  915. return ((u'%-' + compat_str(idlen + 1) + u's%-10s%-12s%s') % (
  916. format['format_id'],
  917. format['ext'],
  918. self.format_resolution(format),
  919. format_note(format),
  920. ))
  921. formats = info_dict.get('formats', [info_dict])
  922. idlen = max(len(u'format code'),
  923. max(len(f['format_id']) for f in formats))
  924. formats_s = [line(f, idlen) for f in formats]
  925. if len(formats) > 1:
  926. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  927. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  928. header_line = line({
  929. 'format_id': u'format code', 'ext': u'extension',
  930. '_resolution': u'resolution', 'format_note': u'note'}, idlen=idlen)
  931. self.to_screen(u'[info] Available formats for %s:\n%s\n%s' %
  932. (info_dict['id'], header_line, u"\n".join(formats_s)))
  933. def urlopen(self, req):
  934. """ Start an HTTP download """
  935. return self._opener.open(req)
  936. def print_debug_header(self):
  937. if not self.params.get('verbose'):
  938. return
  939. write_string(u'[debug] youtube-dl version ' + __version__ + u'\n')
  940. try:
  941. sp = subprocess.Popen(
  942. ['git', 'rev-parse', '--short', 'HEAD'],
  943. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  944. cwd=os.path.dirname(os.path.abspath(__file__)))
  945. out, err = sp.communicate()
  946. out = out.decode().strip()
  947. if re.match('[0-9a-f]+', out):
  948. write_string(u'[debug] Git HEAD: ' + out + u'\n')
  949. except:
  950. try:
  951. sys.exc_clear()
  952. except:
  953. pass
  954. write_string(u'[debug] Python version %s - %s' %
  955. (platform.python_version(), platform_name()) + u'\n')
  956. proxy_map = {}
  957. for handler in self._opener.handlers:
  958. if hasattr(handler, 'proxies'):
  959. proxy_map.update(handler.proxies)
  960. write_string(u'[debug] Proxy map: ' + compat_str(proxy_map) + u'\n')
  961. def _setup_opener(self):
  962. timeout_val = self.params.get('socket_timeout')
  963. timeout = 600 if timeout_val is None else float(timeout_val)
  964. opts_cookiefile = self.params.get('cookiefile')
  965. opts_proxy = self.params.get('proxy')
  966. if opts_cookiefile is None:
  967. self.cookiejar = compat_cookiejar.CookieJar()
  968. else:
  969. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  970. opts_cookiefile)
  971. if os.access(opts_cookiefile, os.R_OK):
  972. self.cookiejar.load()
  973. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  974. self.cookiejar)
  975. if opts_proxy is not None:
  976. if opts_proxy == '':
  977. proxies = {}
  978. else:
  979. proxies = {'http': opts_proxy, 'https': opts_proxy}
  980. else:
  981. proxies = compat_urllib_request.getproxies()
  982. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  983. if 'http' in proxies and 'https' not in proxies:
  984. proxies['https'] = proxies['http']
  985. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  986. https_handler = make_HTTPS_handler(
  987. self.params.get('nocheckcertificate', False))
  988. opener = compat_urllib_request.build_opener(
  989. https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  990. # Delete the default user-agent header, which would otherwise apply in
  991. # cases where our custom HTTP handler doesn't come into play
  992. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  993. opener.addheaders = []
  994. self._opener = opener
  995. # TODO remove this global modification
  996. compat_urllib_request.install_opener(opener)
  997. socket.setdefaulttimeout(timeout)