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.

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