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.

1635 lines
72 KiB

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