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.

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