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.

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