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.

1356 lines
56 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
  1. from __future__ import unicode_literals
  2. import base64
  3. import datetime
  4. import hashlib
  5. import json
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import sys
  11. import time
  12. import xml.etree.ElementTree
  13. from ..compat import (
  14. compat_cookiejar,
  15. compat_cookies,
  16. compat_getpass,
  17. compat_HTTPError,
  18. compat_http_client,
  19. compat_urllib_error,
  20. compat_urllib_parse,
  21. compat_urllib_parse_urlparse,
  22. compat_urllib_request,
  23. compat_urlparse,
  24. compat_str,
  25. )
  26. from ..utils import (
  27. NO_DEFAULT,
  28. age_restricted,
  29. bug_reports_message,
  30. clean_html,
  31. compiled_regex_type,
  32. determine_ext,
  33. ExtractorError,
  34. fix_xml_ampersands,
  35. float_or_none,
  36. int_or_none,
  37. RegexNotFoundError,
  38. sanitize_filename,
  39. unescapeHTML,
  40. url_basename,
  41. xpath_text,
  42. xpath_with_ns,
  43. )
  44. class InfoExtractor(object):
  45. """Information Extractor class.
  46. Information extractors are the classes that, given a URL, extract
  47. information about the video (or videos) the URL refers to. This
  48. information includes the real video URL, the video title, author and
  49. others. The information is stored in a dictionary which is then
  50. passed to the YoutubeDL. The YoutubeDL processes this
  51. information possibly downloading the video to the file system, among
  52. other possible outcomes.
  53. The type field determines the type of the result.
  54. By far the most common value (and the default if _type is missing) is
  55. "video", which indicates a single video.
  56. For a video, the dictionaries must include the following fields:
  57. id: Video identifier.
  58. title: Video title, unescaped.
  59. Additionally, it must contain either a formats entry or a url one:
  60. formats: A list of dictionaries for each format available, ordered
  61. from worst to best quality.
  62. Potential fields:
  63. * url Mandatory. The URL of the video file
  64. * ext Will be calculated from URL if missing
  65. * format A human-readable description of the format
  66. ("mp4 container with h264/opus").
  67. Calculated from the format_id, width, height.
  68. and format_note fields if missing.
  69. * format_id A short description of the format
  70. ("mp4_h264_opus" or "19").
  71. Technically optional, but strongly recommended.
  72. * format_note Additional info about the format
  73. ("3D" or "DASH video")
  74. * width Width of the video, if known
  75. * height Height of the video, if known
  76. * resolution Textual description of width and height
  77. * tbr Average bitrate of audio and video in KBit/s
  78. * abr Average audio bitrate in KBit/s
  79. * acodec Name of the audio codec in use
  80. * asr Audio sampling rate in Hertz
  81. * vbr Average video bitrate in KBit/s
  82. * fps Frame rate
  83. * vcodec Name of the video codec in use
  84. * container Name of the container format
  85. * filesize The number of bytes, if known in advance
  86. * filesize_approx An estimate for the number of bytes
  87. * player_url SWF Player URL (used for rtmpdump).
  88. * protocol The protocol that will be used for the actual
  89. download, lower-case.
  90. "http", "https", "rtsp", "rtmp", "rtmpe",
  91. "m3u8", or "m3u8_native".
  92. * preference Order number of this format. If this field is
  93. present and not None, the formats get sorted
  94. by this field, regardless of all other values.
  95. -1 for default (order by other properties),
  96. -2 or smaller for less than default.
  97. < -1000 to hide the format (if there is
  98. another one which is strictly better)
  99. * language_preference Is this in the correct requested
  100. language?
  101. 10 if it's what the URL is about,
  102. -1 for default (don't know),
  103. -10 otherwise, other values reserved for now.
  104. * quality Order number of the video quality of this
  105. format, irrespective of the file format.
  106. -1 for default (order by other properties),
  107. -2 or smaller for less than default.
  108. * source_preference Order number for this video source
  109. (quality takes higher priority)
  110. -1 for default (order by other properties),
  111. -2 or smaller for less than default.
  112. * http_headers A dictionary of additional HTTP headers
  113. to add to the request.
  114. * stretched_ratio If given and not 1, indicates that the
  115. video's pixels are not square.
  116. width : height ratio as float.
  117. * no_resume The server does not support resuming the
  118. (HTTP or RTMP) download. Boolean.
  119. url: Final video URL.
  120. ext: Video filename extension.
  121. format: The video format, defaults to ext (used for --get-format)
  122. player_url: SWF Player URL (used for rtmpdump).
  123. The following fields are optional:
  124. alt_title: A secondary title of the video.
  125. display_id An alternative identifier for the video, not necessarily
  126. unique, but available before title. Typically, id is
  127. something like "4234987", title "Dancing naked mole rats",
  128. and display_id "dancing-naked-mole-rats"
  129. thumbnails: A list of dictionaries, with the following entries:
  130. * "id" (optional, string) - Thumbnail format ID
  131. * "url"
  132. * "preference" (optional, int) - quality of the image
  133. * "width" (optional, int)
  134. * "height" (optional, int)
  135. * "resolution" (optional, string "{width}x{height"},
  136. deprecated)
  137. thumbnail: Full URL to a video thumbnail image.
  138. description: Full video description.
  139. uploader: Full name of the video uploader.
  140. creator: The main artist who created the video.
  141. timestamp: UNIX timestamp of the moment the video became available.
  142. upload_date: Video upload date (YYYYMMDD).
  143. If not explicitly set, calculated from timestamp.
  144. uploader_id: Nickname or id of the video uploader.
  145. location: Physical location where the video was filmed.
  146. subtitles: The available subtitles as a dictionary in the format
  147. {language: subformats}. "subformats" is a list sorted from
  148. lower to higher preference, each element is a dictionary
  149. with the "ext" entry and one of:
  150. * "data": The subtitles file contents
  151. * "url": A URL pointing to the subtitles file
  152. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  153. automatically generated captions
  154. duration: Length of the video in seconds, as an integer.
  155. view_count: How many users have watched the video on the platform.
  156. like_count: Number of positive ratings of the video
  157. dislike_count: Number of negative ratings of the video
  158. average_rating: Average rating give by users, the scale used depends on the webpage
  159. comment_count: Number of comments on the video
  160. comments: A list of comments, each with one or more of the following
  161. properties (all but one of text or html optional):
  162. * "author" - human-readable name of the comment author
  163. * "author_id" - user ID of the comment author
  164. * "id" - Comment ID
  165. * "html" - Comment as HTML
  166. * "text" - Plain text of the comment
  167. * "timestamp" - UNIX timestamp of comment
  168. * "parent" - ID of the comment this one is replying to.
  169. Set to "root" to indicate that this is a
  170. comment to the original video.
  171. age_limit: Age restriction for the video, as an integer (years)
  172. webpage_url: The URL to the video webpage, if given to youtube-dl it
  173. should allow to get the same result again. (It will be set
  174. by YoutubeDL if it's missing)
  175. categories: A list of categories that the video falls in, for example
  176. ["Sports", "Berlin"]
  177. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  178. is_live: True, False, or None (=unknown). Whether this video is a
  179. live stream that goes on instead of a fixed-length video.
  180. start_time: Time in seconds where the reproduction should start, as
  181. specified in the URL.
  182. end_time: Time in seconds where the reproduction should end, as
  183. specified in the URL.
  184. Unless mentioned otherwise, the fields should be Unicode strings.
  185. Unless mentioned otherwise, None is equivalent to absence of information.
  186. _type "playlist" indicates multiple videos.
  187. There must be a key "entries", which is a list, an iterable, or a PagedList
  188. object, each element of which is a valid dictionary by this specification.
  189. Additionally, playlists can have "title", "description" and "id" attributes
  190. with the same semantics as videos (see above).
  191. _type "multi_video" indicates that there are multiple videos that
  192. form a single show, for examples multiple acts of an opera or TV episode.
  193. It must have an entries key like a playlist and contain all the keys
  194. required for a video at the same time.
  195. _type "url" indicates that the video must be extracted from another
  196. location, possibly by a different extractor. Its only required key is:
  197. "url" - the next URL to extract.
  198. The key "ie_key" can be set to the class name (minus the trailing "IE",
  199. e.g. "Youtube") if the extractor class is known in advance.
  200. Additionally, the dictionary may have any properties of the resolved entity
  201. known in advance, for example "title" if the title of the referred video is
  202. known ahead of time.
  203. _type "url_transparent" entities have the same specification as "url", but
  204. indicate that the given additional information is more precise than the one
  205. associated with the resolved URL.
  206. This is useful when a site employs a video service that hosts the video and
  207. its technical metadata, but that video service does not embed a useful
  208. title, description etc.
  209. Subclasses of this one should re-define the _real_initialize() and
  210. _real_extract() methods and define a _VALID_URL regexp.
  211. Probably, they should also be added to the list of extractors.
  212. Finally, the _WORKING attribute should be set to False for broken IEs
  213. in order to warn the users and skip the tests.
  214. """
  215. _ready = False
  216. _downloader = None
  217. _WORKING = True
  218. def __init__(self, downloader=None):
  219. """Constructor. Receives an optional downloader."""
  220. self._ready = False
  221. self.set_downloader(downloader)
  222. @classmethod
  223. def suitable(cls, url):
  224. """Receives a URL and returns True if suitable for this IE."""
  225. # This does not use has/getattr intentionally - we want to know whether
  226. # we have cached the regexp for *this* class, whereas getattr would also
  227. # match the superclass
  228. if '_VALID_URL_RE' not in cls.__dict__:
  229. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  230. return cls._VALID_URL_RE.match(url) is not None
  231. @classmethod
  232. def _match_id(cls, url):
  233. if '_VALID_URL_RE' not in cls.__dict__:
  234. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  235. m = cls._VALID_URL_RE.match(url)
  236. assert m
  237. return m.group('id')
  238. @classmethod
  239. def working(cls):
  240. """Getter method for _WORKING."""
  241. return cls._WORKING
  242. def initialize(self):
  243. """Initializes an instance (authentication, etc)."""
  244. if not self._ready:
  245. self._real_initialize()
  246. self._ready = True
  247. def extract(self, url):
  248. """Extracts URL information and returns it in list of dicts."""
  249. try:
  250. self.initialize()
  251. return self._real_extract(url)
  252. except ExtractorError:
  253. raise
  254. except compat_http_client.IncompleteRead as e:
  255. raise ExtractorError('A network error has occured.', cause=e, expected=True)
  256. except (KeyError, StopIteration) as e:
  257. raise ExtractorError('An extractor error has occured.', cause=e)
  258. def set_downloader(self, downloader):
  259. """Sets the downloader for this IE."""
  260. self._downloader = downloader
  261. def _real_initialize(self):
  262. """Real initialization process. Redefine in subclasses."""
  263. pass
  264. def _real_extract(self, url):
  265. """Real extraction process. Redefine in subclasses."""
  266. pass
  267. @classmethod
  268. def ie_key(cls):
  269. """A string for getting the InfoExtractor with get_info_extractor"""
  270. return cls.__name__[:-2]
  271. @property
  272. def IE_NAME(self):
  273. return type(self).__name__[:-2]
  274. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  275. """ Returns the response handle """
  276. if note is None:
  277. self.report_download_webpage(video_id)
  278. elif note is not False:
  279. if video_id is None:
  280. self.to_screen('%s' % (note,))
  281. else:
  282. self.to_screen('%s: %s' % (video_id, note))
  283. try:
  284. return self._downloader.urlopen(url_or_request)
  285. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  286. if errnote is False:
  287. return False
  288. if errnote is None:
  289. errnote = 'Unable to download webpage'
  290. errmsg = '%s: %s' % (errnote, compat_str(err))
  291. if fatal:
  292. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  293. else:
  294. self._downloader.report_warning(errmsg)
  295. return False
  296. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None):
  297. """ Returns a tuple (page content as string, URL handle) """
  298. # Strip hashes from the URL (#1038)
  299. if isinstance(url_or_request, (compat_str, str)):
  300. url_or_request = url_or_request.partition('#')[0]
  301. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
  302. if urlh is False:
  303. assert not fatal
  304. return False
  305. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  306. return (content, urlh)
  307. @staticmethod
  308. def _guess_encoding_from_content(content_type, webpage_bytes):
  309. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  310. if m:
  311. encoding = m.group(1)
  312. else:
  313. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  314. webpage_bytes[:1024])
  315. if m:
  316. encoding = m.group(1).decode('ascii')
  317. elif webpage_bytes.startswith(b'\xff\xfe'):
  318. encoding = 'utf-16'
  319. else:
  320. encoding = 'utf-8'
  321. return encoding
  322. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  323. content_type = urlh.headers.get('Content-Type', '')
  324. webpage_bytes = urlh.read()
  325. if prefix is not None:
  326. webpage_bytes = prefix + webpage_bytes
  327. if not encoding:
  328. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  329. if self._downloader.params.get('dump_intermediate_pages', False):
  330. try:
  331. url = url_or_request.get_full_url()
  332. except AttributeError:
  333. url = url_or_request
  334. self.to_screen('Dumping request to ' + url)
  335. dump = base64.b64encode(webpage_bytes).decode('ascii')
  336. self._downloader.to_screen(dump)
  337. if self._downloader.params.get('write_pages', False):
  338. try:
  339. url = url_or_request.get_full_url()
  340. except AttributeError:
  341. url = url_or_request
  342. basen = '%s_%s' % (video_id, url)
  343. if len(basen) > 240:
  344. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  345. basen = basen[:240 - len(h)] + h
  346. raw_filename = basen + '.dump'
  347. filename = sanitize_filename(raw_filename, restricted=True)
  348. self.to_screen('Saving request to ' + filename)
  349. # Working around MAX_PATH limitation on Windows (see
  350. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  351. if os.name == 'nt':
  352. absfilepath = os.path.abspath(filename)
  353. if len(absfilepath) > 259:
  354. filename = '\\\\?\\' + absfilepath
  355. with open(filename, 'wb') as outf:
  356. outf.write(webpage_bytes)
  357. try:
  358. content = webpage_bytes.decode(encoding, 'replace')
  359. except LookupError:
  360. content = webpage_bytes.decode('utf-8', 'replace')
  361. if ('<title>Access to this site is blocked</title>' in content and
  362. 'Websense' in content[:512]):
  363. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  364. blocked_iframe = self._html_search_regex(
  365. r'<iframe src="([^"]+)"', content,
  366. 'Websense information URL', default=None)
  367. if blocked_iframe:
  368. msg += ' Visit %s for more details' % blocked_iframe
  369. raise ExtractorError(msg, expected=True)
  370. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  371. msg = (
  372. 'Access to this webpage has been blocked by Indian censorship. '
  373. 'Use a VPN or proxy server (with --proxy) to route around it.')
  374. block_msg = self._html_search_regex(
  375. r'</h1><p>(.*?)</p>',
  376. content, 'block message', default=None)
  377. if block_msg:
  378. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  379. raise ExtractorError(msg, expected=True)
  380. return content
  381. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None):
  382. """ Returns the data of the page as a string """
  383. success = False
  384. try_count = 0
  385. while success is False:
  386. try:
  387. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  388. success = True
  389. except compat_http_client.IncompleteRead as e:
  390. try_count += 1
  391. if try_count >= tries:
  392. raise e
  393. self._sleep(timeout, video_id)
  394. if res is False:
  395. return res
  396. else:
  397. content, _ = res
  398. return content
  399. def _download_xml(self, url_or_request, video_id,
  400. note='Downloading XML', errnote='Unable to download XML',
  401. transform_source=None, fatal=True, encoding=None):
  402. """Return the xml as an xml.etree.ElementTree.Element"""
  403. xml_string = self._download_webpage(
  404. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding)
  405. if xml_string is False:
  406. return xml_string
  407. if transform_source:
  408. xml_string = transform_source(xml_string)
  409. return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
  410. def _download_json(self, url_or_request, video_id,
  411. note='Downloading JSON metadata',
  412. errnote='Unable to download JSON metadata',
  413. transform_source=None,
  414. fatal=True, encoding=None):
  415. json_string = self._download_webpage(
  416. url_or_request, video_id, note, errnote, fatal=fatal,
  417. encoding=encoding)
  418. if (not fatal) and json_string is False:
  419. return None
  420. return self._parse_json(
  421. json_string, video_id, transform_source=transform_source, fatal=fatal)
  422. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  423. if transform_source:
  424. json_string = transform_source(json_string)
  425. try:
  426. return json.loads(json_string)
  427. except ValueError as ve:
  428. errmsg = '%s: Failed to parse JSON ' % video_id
  429. if fatal:
  430. raise ExtractorError(errmsg, cause=ve)
  431. else:
  432. self.report_warning(errmsg + str(ve))
  433. def report_warning(self, msg, video_id=None):
  434. idstr = '' if video_id is None else '%s: ' % video_id
  435. self._downloader.report_warning(
  436. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  437. def to_screen(self, msg):
  438. """Print msg to screen, prefixing it with '[ie_name]'"""
  439. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  440. def report_extraction(self, id_or_name):
  441. """Report information extraction."""
  442. self.to_screen('%s: Extracting information' % id_or_name)
  443. def report_download_webpage(self, video_id):
  444. """Report webpage download."""
  445. self.to_screen('%s: Downloading webpage' % video_id)
  446. def report_age_confirmation(self):
  447. """Report attempt to confirm age."""
  448. self.to_screen('Confirming age')
  449. def report_login(self):
  450. """Report attempt to log in."""
  451. self.to_screen('Logging in')
  452. @staticmethod
  453. def raise_login_required(msg='This video is only available for registered users'):
  454. raise ExtractorError(
  455. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  456. expected=True)
  457. # Methods for following #608
  458. @staticmethod
  459. def url_result(url, ie=None, video_id=None, video_title=None):
  460. """Returns a URL that points to a page that should be processed"""
  461. # TODO: ie should be the class used for getting the info
  462. video_info = {'_type': 'url',
  463. 'url': url,
  464. 'ie_key': ie}
  465. if video_id is not None:
  466. video_info['id'] = video_id
  467. if video_title is not None:
  468. video_info['title'] = video_title
  469. return video_info
  470. @staticmethod
  471. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  472. """Returns a playlist"""
  473. video_info = {'_type': 'playlist',
  474. 'entries': entries}
  475. if playlist_id:
  476. video_info['id'] = playlist_id
  477. if playlist_title:
  478. video_info['title'] = playlist_title
  479. if playlist_description:
  480. video_info['description'] = playlist_description
  481. return video_info
  482. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  483. """
  484. Perform a regex search on the given string, using a single or a list of
  485. patterns returning the first matching group.
  486. In case of failure return a default value or raise a WARNING or a
  487. RegexNotFoundError, depending on fatal, specifying the field name.
  488. """
  489. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  490. mobj = re.search(pattern, string, flags)
  491. else:
  492. for p in pattern:
  493. mobj = re.search(p, string, flags)
  494. if mobj:
  495. break
  496. if not self._downloader.params.get('no_color') and os.name != 'nt' and sys.stderr.isatty():
  497. _name = '\033[0;34m%s\033[0m' % name
  498. else:
  499. _name = name
  500. if mobj:
  501. if group is None:
  502. # return the first matching group
  503. return next(g for g in mobj.groups() if g is not None)
  504. else:
  505. return mobj.group(group)
  506. elif default is not NO_DEFAULT:
  507. return default
  508. elif fatal:
  509. raise RegexNotFoundError('Unable to extract %s' % _name)
  510. else:
  511. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  512. return None
  513. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  514. """
  515. Like _search_regex, but strips HTML tags and unescapes entities.
  516. """
  517. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  518. if res:
  519. return clean_html(res).strip()
  520. else:
  521. return res
  522. def _get_login_info(self):
  523. """
  524. Get the login info as (username, password)
  525. It will look in the netrc file using the _NETRC_MACHINE value
  526. If there's no info available, return (None, None)
  527. """
  528. if self._downloader is None:
  529. return (None, None)
  530. username = None
  531. password = None
  532. downloader_params = self._downloader.params
  533. # Attempt to use provided username and password or .netrc data
  534. if downloader_params.get('username', None) is not None:
  535. username = downloader_params['username']
  536. password = downloader_params['password']
  537. elif downloader_params.get('usenetrc', False):
  538. try:
  539. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  540. if info is not None:
  541. username = info[0]
  542. password = info[2]
  543. else:
  544. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  545. except (IOError, netrc.NetrcParseError) as err:
  546. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  547. return (username, password)
  548. def _get_tfa_info(self, note='two-factor verification code'):
  549. """
  550. Get the two-factor authentication info
  551. TODO - asking the user will be required for sms/phone verify
  552. currently just uses the command line option
  553. If there's no info available, return None
  554. """
  555. if self._downloader is None:
  556. return None
  557. downloader_params = self._downloader.params
  558. if downloader_params.get('twofactor', None) is not None:
  559. return downloader_params['twofactor']
  560. return compat_getpass('Type %s and press [Return]: ' % note)
  561. # Helper functions for extracting OpenGraph info
  562. @staticmethod
  563. def _og_regexes(prop):
  564. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  565. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  566. template = r'<meta[^>]+?%s[^>]+?%s'
  567. return [
  568. template % (property_re, content_re),
  569. template % (content_re, property_re),
  570. ]
  571. @staticmethod
  572. def _meta_regex(prop):
  573. return r'''(?isx)<meta
  574. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  575. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  576. def _og_search_property(self, prop, html, name=None, **kargs):
  577. if name is None:
  578. name = 'OpenGraph %s' % prop
  579. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  580. if escaped is None:
  581. return None
  582. return unescapeHTML(escaped)
  583. def _og_search_thumbnail(self, html, **kargs):
  584. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  585. def _og_search_description(self, html, **kargs):
  586. return self._og_search_property('description', html, fatal=False, **kargs)
  587. def _og_search_title(self, html, **kargs):
  588. return self._og_search_property('title', html, **kargs)
  589. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  590. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  591. if secure:
  592. regexes = self._og_regexes('video:secure_url') + regexes
  593. return self._html_search_regex(regexes, html, name, **kargs)
  594. def _og_search_url(self, html, **kargs):
  595. return self._og_search_property('url', html, **kargs)
  596. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  597. if display_name is None:
  598. display_name = name
  599. return self._html_search_regex(
  600. self._meta_regex(name),
  601. html, display_name, fatal=fatal, group='content', **kwargs)
  602. def _dc_search_uploader(self, html):
  603. return self._html_search_meta('dc.creator', html, 'uploader')
  604. def _rta_search(self, html):
  605. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  606. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  607. r' content="RTA-5042-1996-1400-1577-RTA"',
  608. html):
  609. return 18
  610. return 0
  611. def _media_rating_search(self, html):
  612. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  613. rating = self._html_search_meta('rating', html)
  614. if not rating:
  615. return None
  616. RATING_TABLE = {
  617. 'safe for kids': 0,
  618. 'general': 8,
  619. '14 years': 14,
  620. 'mature': 17,
  621. 'restricted': 19,
  622. }
  623. return RATING_TABLE.get(rating.lower(), None)
  624. def _family_friendly_search(self, html):
  625. # See http://schema.org/VideoObject
  626. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  627. if not family_friendly:
  628. return None
  629. RATING_TABLE = {
  630. '1': 0,
  631. 'true': 0,
  632. '0': 18,
  633. 'false': 18,
  634. }
  635. return RATING_TABLE.get(family_friendly.lower(), None)
  636. def _twitter_search_player(self, html):
  637. return self._html_search_meta('twitter:player', html,
  638. 'twitter card player')
  639. @staticmethod
  640. def _hidden_inputs(html):
  641. hidden_inputs = {}
  642. for input in re.findall(r'<input([^>]+)>', html):
  643. if not re.search(r'type=(["\'])hidden\1', input):
  644. continue
  645. name = re.search(r'name=(["\'])(?P<value>.+?)\1', input)
  646. if not name:
  647. continue
  648. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  649. if not value:
  650. continue
  651. hidden_inputs[name.group('value')] = value.group('value')
  652. return hidden_inputs
  653. def _form_hidden_inputs(self, form_id, html):
  654. form = self._search_regex(
  655. r'(?s)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  656. html, '%s form' % form_id, group='form')
  657. return self._hidden_inputs(form)
  658. def _sort_formats(self, formats, field_preference=None):
  659. if not formats:
  660. raise ExtractorError('No video formats found')
  661. def _formats_key(f):
  662. # TODO remove the following workaround
  663. from ..utils import determine_ext
  664. if not f.get('ext') and 'url' in f:
  665. f['ext'] = determine_ext(f['url'])
  666. if isinstance(field_preference, (list, tuple)):
  667. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  668. preference = f.get('preference')
  669. if preference is None:
  670. proto = f.get('protocol')
  671. if proto is None:
  672. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  673. preference = 0 if proto in ['http', 'https'] else -0.1
  674. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  675. preference -= 0.5
  676. if f.get('vcodec') == 'none': # audio only
  677. if self._downloader.params.get('prefer_free_formats'):
  678. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  679. else:
  680. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  681. ext_preference = 0
  682. try:
  683. audio_ext_preference = ORDER.index(f['ext'])
  684. except ValueError:
  685. audio_ext_preference = -1
  686. else:
  687. if self._downloader.params.get('prefer_free_formats'):
  688. ORDER = ['flv', 'mp4', 'webm']
  689. else:
  690. ORDER = ['webm', 'flv', 'mp4']
  691. try:
  692. ext_preference = ORDER.index(f['ext'])
  693. except ValueError:
  694. ext_preference = -1
  695. audio_ext_preference = 0
  696. return (
  697. preference,
  698. f.get('language_preference') if f.get('language_preference') is not None else -1,
  699. f.get('quality') if f.get('quality') is not None else -1,
  700. f.get('tbr') if f.get('tbr') is not None else -1,
  701. f.get('filesize') if f.get('filesize') is not None else -1,
  702. f.get('vbr') if f.get('vbr') is not None else -1,
  703. f.get('height') if f.get('height') is not None else -1,
  704. f.get('width') if f.get('width') is not None else -1,
  705. ext_preference,
  706. f.get('abr') if f.get('abr') is not None else -1,
  707. audio_ext_preference,
  708. f.get('fps') if f.get('fps') is not None else -1,
  709. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  710. f.get('source_preference') if f.get('source_preference') is not None else -1,
  711. f.get('format_id') if f.get('format_id') is not None else '',
  712. )
  713. formats.sort(key=_formats_key)
  714. def _check_formats(self, formats, video_id):
  715. if formats:
  716. formats[:] = filter(
  717. lambda f: self._is_valid_url(
  718. f['url'], video_id,
  719. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  720. formats)
  721. def _is_valid_url(self, url, video_id, item='video'):
  722. url = self._proto_relative_url(url, scheme='http:')
  723. # For now assume non HTTP(S) URLs always valid
  724. if not (url.startswith('http://') or url.startswith('https://')):
  725. return True
  726. try:
  727. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  728. return True
  729. except ExtractorError as e:
  730. if isinstance(e.cause, compat_HTTPError):
  731. self.to_screen(
  732. '%s: %s URL is invalid, skipping' % (video_id, item))
  733. return False
  734. raise
  735. def http_scheme(self):
  736. """ Either "http:" or "https:", depending on the user's preferences """
  737. return (
  738. 'http:'
  739. if self._downloader.params.get('prefer_insecure', False)
  740. else 'https:')
  741. def _proto_relative_url(self, url, scheme=None):
  742. if url is None:
  743. return url
  744. if url.startswith('//'):
  745. if scheme is None:
  746. scheme = self.http_scheme()
  747. return scheme + url
  748. else:
  749. return url
  750. def _sleep(self, timeout, video_id, msg_template=None):
  751. if msg_template is None:
  752. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  753. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  754. self.to_screen(msg)
  755. time.sleep(timeout)
  756. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  757. transform_source=lambda s: fix_xml_ampersands(s).strip()):
  758. manifest = self._download_xml(
  759. manifest_url, video_id, 'Downloading f4m manifest',
  760. 'Unable to download f4m manifest',
  761. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  762. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  763. transform_source=transform_source)
  764. formats = []
  765. manifest_version = '1.0'
  766. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  767. if not media_nodes:
  768. manifest_version = '2.0'
  769. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  770. for i, media_el in enumerate(media_nodes):
  771. if manifest_version == '2.0':
  772. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  773. if not media_url:
  774. continue
  775. manifest_url = (
  776. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  777. else ('/'.join(manifest_url.split('/')[:-1]) + '/' + media_url))
  778. # If media_url is itself a f4m manifest do the recursive extraction
  779. # since bitrates in parent manifest (this one) and media_url manifest
  780. # may differ leading to inability to resolve the format by requested
  781. # bitrate in f4m downloader
  782. if determine_ext(manifest_url) == 'f4m':
  783. formats.extend(self._extract_f4m_formats(manifest_url, video_id, preference, f4m_id))
  784. continue
  785. tbr = int_or_none(media_el.attrib.get('bitrate'))
  786. formats.append({
  787. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  788. 'url': manifest_url,
  789. 'ext': 'flv',
  790. 'tbr': tbr,
  791. 'width': int_or_none(media_el.attrib.get('width')),
  792. 'height': int_or_none(media_el.attrib.get('height')),
  793. 'preference': preference,
  794. })
  795. self._sort_formats(formats)
  796. return formats
  797. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  798. entry_protocol='m3u8', preference=None,
  799. m3u8_id=None, note=None, errnote=None,
  800. fatal=True):
  801. formats = [{
  802. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  803. 'url': m3u8_url,
  804. 'ext': ext,
  805. 'protocol': 'm3u8',
  806. 'preference': preference - 1 if preference else -1,
  807. 'resolution': 'multiple',
  808. 'format_note': 'Quality selection URL',
  809. }]
  810. format_url = lambda u: (
  811. u
  812. if re.match(r'^https?://', u)
  813. else compat_urlparse.urljoin(m3u8_url, u))
  814. m3u8_doc = self._download_webpage(
  815. m3u8_url, video_id,
  816. note=note or 'Downloading m3u8 information',
  817. errnote=errnote or 'Failed to download m3u8 information',
  818. fatal=fatal)
  819. if m3u8_doc is False:
  820. return m3u8_doc
  821. last_info = None
  822. last_media = None
  823. kv_rex = re.compile(
  824. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  825. for line in m3u8_doc.splitlines():
  826. if line.startswith('#EXT-X-STREAM-INF:'):
  827. last_info = {}
  828. for m in kv_rex.finditer(line):
  829. v = m.group('val')
  830. if v.startswith('"'):
  831. v = v[1:-1]
  832. last_info[m.group('key')] = v
  833. elif line.startswith('#EXT-X-MEDIA:'):
  834. last_media = {}
  835. for m in kv_rex.finditer(line):
  836. v = m.group('val')
  837. if v.startswith('"'):
  838. v = v[1:-1]
  839. last_media[m.group('key')] = v
  840. elif line.startswith('#') or not line.strip():
  841. continue
  842. else:
  843. if last_info is None:
  844. formats.append({'url': format_url(line)})
  845. continue
  846. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  847. format_id = []
  848. if m3u8_id:
  849. format_id.append(m3u8_id)
  850. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  851. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  852. f = {
  853. 'format_id': '-'.join(format_id),
  854. 'url': format_url(line.strip()),
  855. 'tbr': tbr,
  856. 'ext': ext,
  857. 'protocol': entry_protocol,
  858. 'preference': preference,
  859. }
  860. codecs = last_info.get('CODECS')
  861. if codecs:
  862. # TODO: looks like video codec is not always necessarily goes first
  863. va_codecs = codecs.split(',')
  864. if va_codecs[0]:
  865. f['vcodec'] = va_codecs[0].partition('.')[0]
  866. if len(va_codecs) > 1 and va_codecs[1]:
  867. f['acodec'] = va_codecs[1].partition('.')[0]
  868. resolution = last_info.get('RESOLUTION')
  869. if resolution:
  870. width_str, height_str = resolution.split('x')
  871. f['width'] = int(width_str)
  872. f['height'] = int(height_str)
  873. if last_media is not None:
  874. f['m3u8_media'] = last_media
  875. last_media = None
  876. formats.append(f)
  877. last_info = {}
  878. self._sort_formats(formats)
  879. return formats
  880. @staticmethod
  881. def _xpath_ns(path, namespace=None):
  882. if not namespace:
  883. return path
  884. out = []
  885. for c in path.split('/'):
  886. if not c or c == '.':
  887. out.append(c)
  888. else:
  889. out.append('{%s}%s' % (namespace, c))
  890. return '/'.join(out)
  891. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  892. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  893. if smil is False:
  894. assert not fatal
  895. return []
  896. namespace = self._parse_smil_namespace(smil)
  897. return self._parse_smil_formats(
  898. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  899. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  900. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  901. if smil is False:
  902. return {}
  903. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  904. def _download_smil(self, smil_url, video_id, fatal=True):
  905. return self._download_xml(
  906. smil_url, video_id, 'Downloading SMIL file',
  907. 'Unable to download SMIL file', fatal=fatal)
  908. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  909. namespace = self._parse_smil_namespace(smil)
  910. formats = self._parse_smil_formats(
  911. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  912. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  913. video_id = os.path.splitext(url_basename(smil_url))[0]
  914. title = None
  915. description = None
  916. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  917. name = meta.attrib.get('name')
  918. content = meta.attrib.get('content')
  919. if not name or not content:
  920. continue
  921. if not title and name == 'title':
  922. title = content
  923. elif not description and name in ('description', 'abstract'):
  924. description = content
  925. return {
  926. 'id': video_id,
  927. 'title': title or video_id,
  928. 'description': description,
  929. 'formats': formats,
  930. 'subtitles': subtitles,
  931. }
  932. def _parse_smil_namespace(self, smil):
  933. return self._search_regex(
  934. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  935. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  936. base = smil_url
  937. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  938. b = meta.get('base') or meta.get('httpBase')
  939. if b:
  940. base = b
  941. break
  942. formats = []
  943. rtmp_count = 0
  944. http_count = 0
  945. videos = smil.findall(self._xpath_ns('.//video', namespace))
  946. for video in videos:
  947. src = video.get('src')
  948. if not src:
  949. continue
  950. bitrate = int_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  951. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  952. width = int_or_none(video.get('width'))
  953. height = int_or_none(video.get('height'))
  954. proto = video.get('proto')
  955. ext = video.get('ext')
  956. src_ext = determine_ext(src)
  957. streamer = video.get('streamer') or base
  958. if proto == 'rtmp' or streamer.startswith('rtmp'):
  959. rtmp_count += 1
  960. formats.append({
  961. 'url': streamer,
  962. 'play_path': src,
  963. 'ext': 'flv',
  964. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  965. 'tbr': bitrate,
  966. 'filesize': filesize,
  967. 'width': width,
  968. 'height': height,
  969. })
  970. if transform_rtmp_url:
  971. streamer, src = transform_rtmp_url(streamer, src)
  972. formats[-1].update({
  973. 'url': streamer,
  974. 'play_path': src,
  975. })
  976. continue
  977. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  978. if proto == 'm3u8' or src_ext == 'm3u8':
  979. formats.extend(self._extract_m3u8_formats(
  980. src_url, video_id, ext or 'mp4', m3u8_id='hls'))
  981. continue
  982. if src_ext == 'f4m':
  983. f4m_url = src_url
  984. if not f4m_params:
  985. f4m_params = {
  986. 'hdcore': '3.2.0',
  987. 'plugin': 'flowplayer-3.2.0.1',
  988. }
  989. f4m_url += '&' if '?' in f4m_url else '?'
  990. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  991. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds'))
  992. continue
  993. if src_url.startswith('http'):
  994. http_count += 1
  995. formats.append({
  996. 'url': src_url,
  997. 'ext': ext or src_ext or 'flv',
  998. 'format_id': 'http-%d' % (bitrate or http_count),
  999. 'tbr': bitrate,
  1000. 'filesize': filesize,
  1001. 'width': width,
  1002. 'height': height,
  1003. })
  1004. continue
  1005. self._sort_formats(formats)
  1006. return formats
  1007. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1008. subtitles = {}
  1009. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1010. src = textstream.get('src')
  1011. if not src:
  1012. continue
  1013. ext = textstream.get('ext') or determine_ext(src)
  1014. if not ext:
  1015. type_ = textstream.get('type')
  1016. SUBTITLES_TYPES = {
  1017. 'text/vtt': 'vtt',
  1018. 'text/srt': 'srt',
  1019. 'application/smptett+xml': 'tt',
  1020. }
  1021. if type_ in SUBTITLES_TYPES:
  1022. ext = SUBTITLES_TYPES[type_]
  1023. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1024. subtitles.setdefault(lang, []).append({
  1025. 'url': src,
  1026. 'ext': ext,
  1027. })
  1028. return subtitles
  1029. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1030. xspf = self._download_xml(
  1031. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1032. 'Unable to download xspf manifest', fatal=fatal)
  1033. if xspf is False:
  1034. return []
  1035. return self._parse_xspf(xspf, playlist_id)
  1036. def _parse_xspf(self, playlist, playlist_id):
  1037. NS_MAP = {
  1038. 'xspf': 'http://xspf.org/ns/0/',
  1039. 's1': 'http://static.streamone.nl/player/ns/0',
  1040. }
  1041. entries = []
  1042. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1043. title = xpath_text(
  1044. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1045. description = xpath_text(
  1046. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1047. thumbnail = xpath_text(
  1048. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1049. duration = float_or_none(
  1050. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1051. formats = [{
  1052. 'url': location.text,
  1053. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1054. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1055. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1056. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1057. self._sort_formats(formats)
  1058. entries.append({
  1059. 'id': playlist_id,
  1060. 'title': title,
  1061. 'description': description,
  1062. 'thumbnail': thumbnail,
  1063. 'duration': duration,
  1064. 'formats': formats,
  1065. })
  1066. return entries
  1067. def _live_title(self, name):
  1068. """ Generate the title for a live video """
  1069. now = datetime.datetime.now()
  1070. now_str = now.strftime("%Y-%m-%d %H:%M")
  1071. return name + ' ' + now_str
  1072. def _int(self, v, name, fatal=False, **kwargs):
  1073. res = int_or_none(v, **kwargs)
  1074. if 'get_attr' in kwargs:
  1075. print(getattr(v, kwargs['get_attr']))
  1076. if res is None:
  1077. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1078. if fatal:
  1079. raise ExtractorError(msg)
  1080. else:
  1081. self._downloader.report_warning(msg)
  1082. return res
  1083. def _float(self, v, name, fatal=False, **kwargs):
  1084. res = float_or_none(v, **kwargs)
  1085. if res is None:
  1086. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1087. if fatal:
  1088. raise ExtractorError(msg)
  1089. else:
  1090. self._downloader.report_warning(msg)
  1091. return res
  1092. def _set_cookie(self, domain, name, value, expire_time=None):
  1093. cookie = compat_cookiejar.Cookie(
  1094. 0, name, value, None, None, domain, None,
  1095. None, '/', True, False, expire_time, '', None, None, None)
  1096. self._downloader.cookiejar.set_cookie(cookie)
  1097. def _get_cookies(self, url):
  1098. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1099. req = compat_urllib_request.Request(url)
  1100. self._downloader.cookiejar.add_cookie_header(req)
  1101. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1102. def get_testcases(self, include_onlymatching=False):
  1103. t = getattr(self, '_TEST', None)
  1104. if t:
  1105. assert not hasattr(self, '_TESTS'), \
  1106. '%s has _TEST and _TESTS' % type(self).__name__
  1107. tests = [t]
  1108. else:
  1109. tests = getattr(self, '_TESTS', [])
  1110. for t in tests:
  1111. if not include_onlymatching and t.get('only_matching', False):
  1112. continue
  1113. t['name'] = type(self).__name__[:-len('IE')]
  1114. yield t
  1115. def is_suitable(self, age_limit):
  1116. """ Test whether the extractor is generally suitable for the given
  1117. age limit (i.e. pornographic sites are not, all others usually are) """
  1118. any_restricted = False
  1119. for tc in self.get_testcases(include_onlymatching=False):
  1120. if 'playlist' in tc:
  1121. tc = tc['playlist'][0]
  1122. is_restricted = age_restricted(
  1123. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1124. if not is_restricted:
  1125. return True
  1126. any_restricted = any_restricted or is_restricted
  1127. return not any_restricted
  1128. def extract_subtitles(self, *args, **kwargs):
  1129. if (self._downloader.params.get('writesubtitles', False) or
  1130. self._downloader.params.get('listsubtitles')):
  1131. return self._get_subtitles(*args, **kwargs)
  1132. return {}
  1133. def _get_subtitles(self, *args, **kwargs):
  1134. raise NotImplementedError("This method must be implemented by subclasses")
  1135. @staticmethod
  1136. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1137. """ Merge subtitle items for one language. Items with duplicated URLs
  1138. will be dropped. """
  1139. list1_urls = set([item['url'] for item in subtitle_list1])
  1140. ret = list(subtitle_list1)
  1141. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1142. return ret
  1143. @classmethod
  1144. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1145. """ Merge two subtitle dictionaries, language by language. """
  1146. ret = dict(subtitle_dict1)
  1147. for lang in subtitle_dict2:
  1148. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1149. return ret
  1150. def extract_automatic_captions(self, *args, **kwargs):
  1151. if (self._downloader.params.get('writeautomaticsub', False) or
  1152. self._downloader.params.get('listsubtitles')):
  1153. return self._get_automatic_captions(*args, **kwargs)
  1154. return {}
  1155. def _get_automatic_captions(self, *args, **kwargs):
  1156. raise NotImplementedError("This method must be implemented by subclasses")
  1157. class SearchInfoExtractor(InfoExtractor):
  1158. """
  1159. Base class for paged search queries extractors.
  1160. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1161. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1162. """
  1163. @classmethod
  1164. def _make_valid_url(cls):
  1165. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1166. @classmethod
  1167. def suitable(cls, url):
  1168. return re.match(cls._make_valid_url(), url) is not None
  1169. def _real_extract(self, query):
  1170. mobj = re.match(self._make_valid_url(), query)
  1171. if mobj is None:
  1172. raise ExtractorError('Invalid search query "%s"' % query)
  1173. prefix = mobj.group('prefix')
  1174. query = mobj.group('query')
  1175. if prefix == '':
  1176. return self._get_n_results(query, 1)
  1177. elif prefix == 'all':
  1178. return self._get_n_results(query, self._MAX_RESULTS)
  1179. else:
  1180. n = int(prefix)
  1181. if n <= 0:
  1182. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1183. elif n > self._MAX_RESULTS:
  1184. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1185. n = self._MAX_RESULTS
  1186. return self._get_n_results(query, n)
  1187. def _get_n_results(self, query, n):
  1188. """Get a specified number of results for a query"""
  1189. raise NotImplementedError("This method must be implemented by subclasses")
  1190. @property
  1191. def SEARCH_KEY(self):
  1192. return self._SEARCH_KEY