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.

1645 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. @staticmethod
  792. def _remove_duplicate_formats(formats):
  793. format_urls = set()
  794. unique_formats = []
  795. for f in formats:
  796. if f['url'] not in format_urls:
  797. format_urls.add(f['url'])
  798. unique_formats.append(f)
  799. formats[:] = unique_formats
  800. def _is_valid_url(self, url, video_id, item='video'):
  801. url = self._proto_relative_url(url, scheme='http:')
  802. # For now assume non HTTP(S) URLs always valid
  803. if not (url.startswith('http://') or url.startswith('https://')):
  804. return True
  805. try:
  806. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  807. return True
  808. except ExtractorError as e:
  809. if isinstance(e.cause, compat_urllib_error.URLError):
  810. self.to_screen(
  811. '%s: %s URL is invalid, skipping' % (video_id, item))
  812. return False
  813. raise
  814. def http_scheme(self):
  815. """ Either "http:" or "https:", depending on the user's preferences """
  816. return (
  817. 'http:'
  818. if self._downloader.params.get('prefer_insecure', False)
  819. else 'https:')
  820. def _proto_relative_url(self, url, scheme=None):
  821. if url is None:
  822. return url
  823. if url.startswith('//'):
  824. if scheme is None:
  825. scheme = self.http_scheme()
  826. return scheme + url
  827. else:
  828. return url
  829. def _sleep(self, timeout, video_id, msg_template=None):
  830. if msg_template is None:
  831. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  832. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  833. self.to_screen(msg)
  834. time.sleep(timeout)
  835. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  836. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  837. fatal=True):
  838. manifest = self._download_xml(
  839. manifest_url, video_id, 'Downloading f4m manifest',
  840. 'Unable to download f4m manifest',
  841. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  842. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  843. transform_source=transform_source,
  844. fatal=fatal)
  845. if manifest is False:
  846. return []
  847. formats = []
  848. manifest_version = '1.0'
  849. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  850. if not media_nodes:
  851. manifest_version = '2.0'
  852. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  853. base_url = xpath_text(
  854. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  855. 'base URL', default=None)
  856. if base_url:
  857. base_url = base_url.strip()
  858. for i, media_el in enumerate(media_nodes):
  859. if manifest_version == '2.0':
  860. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  861. if not media_url:
  862. continue
  863. manifest_url = (
  864. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  865. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  866. # If media_url is itself a f4m manifest do the recursive extraction
  867. # since bitrates in parent manifest (this one) and media_url manifest
  868. # may differ leading to inability to resolve the format by requested
  869. # bitrate in f4m downloader
  870. if determine_ext(manifest_url) == 'f4m':
  871. formats.extend(self._extract_f4m_formats(
  872. manifest_url, video_id, preference, f4m_id, fatal=fatal))
  873. continue
  874. tbr = int_or_none(media_el.attrib.get('bitrate'))
  875. formats.append({
  876. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  877. 'url': manifest_url,
  878. 'ext': 'flv',
  879. 'tbr': tbr,
  880. 'width': int_or_none(media_el.attrib.get('width')),
  881. 'height': int_or_none(media_el.attrib.get('height')),
  882. 'preference': preference,
  883. })
  884. self._sort_formats(formats)
  885. return formats
  886. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  887. entry_protocol='m3u8', preference=None,
  888. m3u8_id=None, note=None, errnote=None,
  889. fatal=True):
  890. formats = [{
  891. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  892. 'url': m3u8_url,
  893. 'ext': ext,
  894. 'protocol': 'm3u8',
  895. 'preference': preference - 1 if preference else -1,
  896. 'resolution': 'multiple',
  897. 'format_note': 'Quality selection URL',
  898. }]
  899. format_url = lambda u: (
  900. u
  901. if re.match(r'^https?://', u)
  902. else compat_urlparse.urljoin(m3u8_url, u))
  903. res = self._download_webpage_handle(
  904. m3u8_url, video_id,
  905. note=note or 'Downloading m3u8 information',
  906. errnote=errnote or 'Failed to download m3u8 information',
  907. fatal=fatal)
  908. if res is False:
  909. return []
  910. m3u8_doc, urlh = res
  911. m3u8_url = urlh.geturl()
  912. # A Media Playlist Tag MUST NOT appear in a Master Playlist
  913. # https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  914. # The EXT-X-TARGETDURATION tag is REQUIRED for every M3U8 Media Playlists
  915. # https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  916. if '#EXT-X-TARGETDURATION' in m3u8_doc:
  917. return [{
  918. 'url': m3u8_url,
  919. 'format_id': m3u8_id,
  920. 'ext': ext,
  921. 'protocol': entry_protocol,
  922. 'preference': preference,
  923. }]
  924. last_info = None
  925. last_media = None
  926. kv_rex = re.compile(
  927. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  928. for line in m3u8_doc.splitlines():
  929. if line.startswith('#EXT-X-STREAM-INF:'):
  930. last_info = {}
  931. for m in kv_rex.finditer(line):
  932. v = m.group('val')
  933. if v.startswith('"'):
  934. v = v[1:-1]
  935. last_info[m.group('key')] = v
  936. elif line.startswith('#EXT-X-MEDIA:'):
  937. last_media = {}
  938. for m in kv_rex.finditer(line):
  939. v = m.group('val')
  940. if v.startswith('"'):
  941. v = v[1:-1]
  942. last_media[m.group('key')] = v
  943. elif line.startswith('#') or not line.strip():
  944. continue
  945. else:
  946. if last_info is None:
  947. formats.append({'url': format_url(line)})
  948. continue
  949. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  950. format_id = []
  951. if m3u8_id:
  952. format_id.append(m3u8_id)
  953. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  954. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  955. f = {
  956. 'format_id': '-'.join(format_id),
  957. 'url': format_url(line.strip()),
  958. 'tbr': tbr,
  959. 'ext': ext,
  960. 'protocol': entry_protocol,
  961. 'preference': preference,
  962. }
  963. codecs = last_info.get('CODECS')
  964. if codecs:
  965. # TODO: looks like video codec is not always necessarily goes first
  966. va_codecs = codecs.split(',')
  967. if va_codecs[0]:
  968. f['vcodec'] = va_codecs[0]
  969. if len(va_codecs) > 1 and va_codecs[1]:
  970. f['acodec'] = va_codecs[1]
  971. resolution = last_info.get('RESOLUTION')
  972. if resolution:
  973. width_str, height_str = resolution.split('x')
  974. f['width'] = int(width_str)
  975. f['height'] = int(height_str)
  976. if last_media is not None:
  977. f['m3u8_media'] = last_media
  978. last_media = None
  979. formats.append(f)
  980. last_info = {}
  981. self._sort_formats(formats)
  982. return formats
  983. @staticmethod
  984. def _xpath_ns(path, namespace=None):
  985. if not namespace:
  986. return path
  987. out = []
  988. for c in path.split('/'):
  989. if not c or c == '.':
  990. out.append(c)
  991. else:
  992. out.append('{%s}%s' % (namespace, c))
  993. return '/'.join(out)
  994. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  995. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  996. if smil is False:
  997. assert not fatal
  998. return []
  999. namespace = self._parse_smil_namespace(smil)
  1000. return self._parse_smil_formats(
  1001. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1002. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1003. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1004. if smil is False:
  1005. return {}
  1006. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1007. def _download_smil(self, smil_url, video_id, fatal=True):
  1008. return self._download_xml(
  1009. smil_url, video_id, 'Downloading SMIL file',
  1010. 'Unable to download SMIL file', fatal=fatal)
  1011. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1012. namespace = self._parse_smil_namespace(smil)
  1013. formats = self._parse_smil_formats(
  1014. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1015. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1016. video_id = os.path.splitext(url_basename(smil_url))[0]
  1017. title = None
  1018. description = None
  1019. upload_date = None
  1020. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1021. name = meta.attrib.get('name')
  1022. content = meta.attrib.get('content')
  1023. if not name or not content:
  1024. continue
  1025. if not title and name == 'title':
  1026. title = content
  1027. elif not description and name in ('description', 'abstract'):
  1028. description = content
  1029. elif not upload_date and name == 'date':
  1030. upload_date = unified_strdate(content)
  1031. thumbnails = [{
  1032. 'id': image.get('type'),
  1033. 'url': image.get('src'),
  1034. 'width': int_or_none(image.get('width')),
  1035. 'height': int_or_none(image.get('height')),
  1036. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1037. return {
  1038. 'id': video_id,
  1039. 'title': title or video_id,
  1040. 'description': description,
  1041. 'upload_date': upload_date,
  1042. 'thumbnails': thumbnails,
  1043. 'formats': formats,
  1044. 'subtitles': subtitles,
  1045. }
  1046. def _parse_smil_namespace(self, smil):
  1047. return self._search_regex(
  1048. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1049. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1050. base = smil_url
  1051. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1052. b = meta.get('base') or meta.get('httpBase')
  1053. if b:
  1054. base = b
  1055. break
  1056. formats = []
  1057. rtmp_count = 0
  1058. http_count = 0
  1059. m3u8_count = 0
  1060. srcs = []
  1061. videos = smil.findall(self._xpath_ns('.//video', namespace))
  1062. for video in videos:
  1063. src = video.get('src')
  1064. if not src or src in srcs:
  1065. continue
  1066. srcs.append(src)
  1067. bitrate = float_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  1068. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  1069. width = int_or_none(video.get('width'))
  1070. height = int_or_none(video.get('height'))
  1071. proto = video.get('proto')
  1072. ext = video.get('ext')
  1073. src_ext = determine_ext(src)
  1074. streamer = video.get('streamer') or base
  1075. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1076. rtmp_count += 1
  1077. formats.append({
  1078. 'url': streamer,
  1079. 'play_path': src,
  1080. 'ext': 'flv',
  1081. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1082. 'tbr': bitrate,
  1083. 'filesize': filesize,
  1084. 'width': width,
  1085. 'height': height,
  1086. })
  1087. if transform_rtmp_url:
  1088. streamer, src = transform_rtmp_url(streamer, src)
  1089. formats[-1].update({
  1090. 'url': streamer,
  1091. 'play_path': src,
  1092. })
  1093. continue
  1094. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1095. src_url = src_url.strip()
  1096. if proto == 'm3u8' or src_ext == 'm3u8':
  1097. m3u8_formats = self._extract_m3u8_formats(
  1098. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1099. if len(m3u8_formats) == 1:
  1100. m3u8_count += 1
  1101. m3u8_formats[0].update({
  1102. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1103. 'tbr': bitrate,
  1104. 'width': width,
  1105. 'height': height,
  1106. })
  1107. formats.extend(m3u8_formats)
  1108. continue
  1109. if src_ext == 'f4m':
  1110. f4m_url = src_url
  1111. if not f4m_params:
  1112. f4m_params = {
  1113. 'hdcore': '3.2.0',
  1114. 'plugin': 'flowplayer-3.2.0.1',
  1115. }
  1116. f4m_url += '&' if '?' in f4m_url else '?'
  1117. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  1118. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1119. continue
  1120. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1121. http_count += 1
  1122. formats.append({
  1123. 'url': src_url,
  1124. 'ext': ext or src_ext or 'flv',
  1125. 'format_id': 'http-%d' % (bitrate or http_count),
  1126. 'tbr': bitrate,
  1127. 'filesize': filesize,
  1128. 'width': width,
  1129. 'height': height,
  1130. })
  1131. continue
  1132. self._sort_formats(formats)
  1133. return formats
  1134. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1135. urls = []
  1136. subtitles = {}
  1137. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1138. src = textstream.get('src')
  1139. if not src or src in urls:
  1140. continue
  1141. urls.append(src)
  1142. ext = textstream.get('ext') or determine_ext(src) or mimetype2ext(textstream.get('type'))
  1143. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1144. subtitles.setdefault(lang, []).append({
  1145. 'url': src,
  1146. 'ext': ext,
  1147. })
  1148. return subtitles
  1149. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1150. xspf = self._download_xml(
  1151. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1152. 'Unable to download xspf manifest', fatal=fatal)
  1153. if xspf is False:
  1154. return []
  1155. return self._parse_xspf(xspf, playlist_id)
  1156. def _parse_xspf(self, playlist, playlist_id):
  1157. NS_MAP = {
  1158. 'xspf': 'http://xspf.org/ns/0/',
  1159. 's1': 'http://static.streamone.nl/player/ns/0',
  1160. }
  1161. entries = []
  1162. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1163. title = xpath_text(
  1164. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1165. description = xpath_text(
  1166. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1167. thumbnail = xpath_text(
  1168. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1169. duration = float_or_none(
  1170. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1171. formats = [{
  1172. 'url': location.text,
  1173. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1174. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1175. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1176. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1177. self._sort_formats(formats)
  1178. entries.append({
  1179. 'id': playlist_id,
  1180. 'title': title,
  1181. 'description': description,
  1182. 'thumbnail': thumbnail,
  1183. 'duration': duration,
  1184. 'formats': formats,
  1185. })
  1186. return entries
  1187. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1188. res = self._download_webpage_handle(
  1189. mpd_url, video_id,
  1190. note=note or 'Downloading MPD manifest',
  1191. errnote=errnote or 'Failed to download MPD manifest',
  1192. fatal=fatal)
  1193. if res is False:
  1194. return []
  1195. mpd, urlh = res
  1196. mpd_base_url = re.match(r'https?://.+/', urlh.geturl()).group()
  1197. return self._parse_mpd_formats(
  1198. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url, formats_dict=formats_dict)
  1199. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}):
  1200. if mpd_doc.get('type') == 'dynamic':
  1201. return []
  1202. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1203. def _add_ns(path):
  1204. return self._xpath_ns(path, namespace)
  1205. def is_drm_protected(element):
  1206. return element.find(_add_ns('ContentProtection')) is not None
  1207. def extract_multisegment_info(element, ms_parent_info):
  1208. ms_info = ms_parent_info.copy()
  1209. segment_list = element.find(_add_ns('SegmentList'))
  1210. if segment_list is not None:
  1211. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1212. if segment_urls_e:
  1213. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1214. initialization = segment_list.find(_add_ns('Initialization'))
  1215. if initialization is not None:
  1216. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1217. else:
  1218. segment_template = element.find(_add_ns('SegmentTemplate'))
  1219. if segment_template is not None:
  1220. start_number = segment_template.get('startNumber')
  1221. if start_number:
  1222. ms_info['start_number'] = int(start_number)
  1223. segment_timeline = segment_template.find(_add_ns('SegmentTimeline'))
  1224. if segment_timeline is not None:
  1225. s_e = segment_timeline.findall(_add_ns('S'))
  1226. if s_e:
  1227. ms_info['total_number'] = 0
  1228. for s in s_e:
  1229. ms_info['total_number'] += 1 + int(s.get('r', '0'))
  1230. else:
  1231. timescale = segment_template.get('timescale')
  1232. if timescale:
  1233. ms_info['timescale'] = int(timescale)
  1234. segment_duration = segment_template.get('duration')
  1235. if segment_duration:
  1236. ms_info['segment_duration'] = int(segment_duration)
  1237. media_template = segment_template.get('media')
  1238. if media_template:
  1239. ms_info['media_template'] = media_template
  1240. initialization = segment_template.get('initialization')
  1241. if initialization:
  1242. ms_info['initialization_url'] = initialization
  1243. else:
  1244. initialization = segment_template.find(_add_ns('Initialization'))
  1245. if initialization is not None:
  1246. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1247. return ms_info
  1248. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1249. formats = []
  1250. for period in mpd_doc.findall(_add_ns('Period')):
  1251. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1252. period_ms_info = extract_multisegment_info(period, {
  1253. 'start_number': 1,
  1254. 'timescale': 1,
  1255. })
  1256. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1257. if is_drm_protected(adaptation_set):
  1258. continue
  1259. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1260. for representation in adaptation_set.findall(_add_ns('Representation')):
  1261. if is_drm_protected(representation):
  1262. continue
  1263. representation_attrib = adaptation_set.attrib.copy()
  1264. representation_attrib.update(representation.attrib)
  1265. mime_type = representation_attrib.get('mimeType')
  1266. content_type = mime_type.split('/')[0] if mime_type else representation_attrib.get('contentType')
  1267. if content_type == 'text':
  1268. # TODO implement WebVTT downloading
  1269. pass
  1270. elif content_type == 'video' or content_type == 'audio':
  1271. base_url = ''
  1272. for element in (representation, adaptation_set, period, mpd_doc):
  1273. base_url_e = element.find(_add_ns('BaseURL'))
  1274. if base_url_e is not None:
  1275. base_url = base_url_e.text + base_url
  1276. if re.match(r'^https?://', base_url):
  1277. break
  1278. if mpd_base_url and not re.match(r'^https?://', base_url):
  1279. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1280. mpd_base_url += '/'
  1281. base_url = mpd_base_url + base_url
  1282. representation_id = representation_attrib.get('id')
  1283. lang = representation_attrib.get('lang')
  1284. url_el = representation.find(_add_ns('BaseURL'))
  1285. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1286. f = {
  1287. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1288. 'url': base_url,
  1289. 'width': int_or_none(representation_attrib.get('width')),
  1290. 'height': int_or_none(representation_attrib.get('height')),
  1291. 'tbr': int_or_none(representation_attrib.get('bandwidth'), 1000),
  1292. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1293. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1294. 'vcodec': 'none' if content_type == 'audio' else representation_attrib.get('codecs'),
  1295. 'acodec': 'none' if content_type == 'video' else representation_attrib.get('codecs'),
  1296. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1297. 'format_note': 'DASH %s' % content_type,
  1298. 'filesize': filesize,
  1299. }
  1300. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1301. if 'segment_urls' not in representation_ms_info and 'media_template' in representation_ms_info:
  1302. if 'total_number' not in representation_ms_info and 'segment_duration':
  1303. segment_duration = float(representation_ms_info['segment_duration']) / float(representation_ms_info['timescale'])
  1304. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1305. media_template = representation_ms_info['media_template']
  1306. media_template = media_template.replace('$RepresentationID$', representation_id)
  1307. media_template = re.sub(r'\$(Number|Bandwidth)(?:%(0\d+)d)?\$', r'%(\1)\2d', media_template)
  1308. media_template.replace('$$', '$')
  1309. 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'])]
  1310. if 'segment_urls' in representation_ms_info:
  1311. f.update({
  1312. 'segment_urls': representation_ms_info['segment_urls'],
  1313. 'protocol': 'http_dash_segments',
  1314. })
  1315. if 'initialization_url' in representation_ms_info:
  1316. initialization_url = representation_ms_info['initialization_url'].replace('$RepresentationID$', representation_id)
  1317. f.update({
  1318. 'initialization_url': initialization_url,
  1319. })
  1320. if not f.get('url'):
  1321. f['url'] = initialization_url
  1322. try:
  1323. existing_format = next(
  1324. fo for fo in formats
  1325. if fo['format_id'] == representation_id)
  1326. except StopIteration:
  1327. full_info = formats_dict.get(representation_id, {}).copy()
  1328. full_info.update(f)
  1329. formats.append(full_info)
  1330. else:
  1331. existing_format.update(f)
  1332. else:
  1333. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1334. self._sort_formats(formats)
  1335. return formats
  1336. def _live_title(self, name):
  1337. """ Generate the title for a live video """
  1338. now = datetime.datetime.now()
  1339. now_str = now.strftime('%Y-%m-%d %H:%M')
  1340. return name + ' ' + now_str
  1341. def _int(self, v, name, fatal=False, **kwargs):
  1342. res = int_or_none(v, **kwargs)
  1343. if 'get_attr' in kwargs:
  1344. print(getattr(v, kwargs['get_attr']))
  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 _float(self, v, name, fatal=False, **kwargs):
  1353. res = float_or_none(v, **kwargs)
  1354. if res is None:
  1355. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1356. if fatal:
  1357. raise ExtractorError(msg)
  1358. else:
  1359. self._downloader.report_warning(msg)
  1360. return res
  1361. def _set_cookie(self, domain, name, value, expire_time=None):
  1362. cookie = compat_cookiejar.Cookie(
  1363. 0, name, value, None, None, domain, None,
  1364. None, '/', True, False, expire_time, '', None, None, None)
  1365. self._downloader.cookiejar.set_cookie(cookie)
  1366. def _get_cookies(self, url):
  1367. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1368. req = sanitized_Request(url)
  1369. self._downloader.cookiejar.add_cookie_header(req)
  1370. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1371. def get_testcases(self, include_onlymatching=False):
  1372. t = getattr(self, '_TEST', None)
  1373. if t:
  1374. assert not hasattr(self, '_TESTS'), \
  1375. '%s has _TEST and _TESTS' % type(self).__name__
  1376. tests = [t]
  1377. else:
  1378. tests = getattr(self, '_TESTS', [])
  1379. for t in tests:
  1380. if not include_onlymatching and t.get('only_matching', False):
  1381. continue
  1382. t['name'] = type(self).__name__[:-len('IE')]
  1383. yield t
  1384. def is_suitable(self, age_limit):
  1385. """ Test whether the extractor is generally suitable for the given
  1386. age limit (i.e. pornographic sites are not, all others usually are) """
  1387. any_restricted = False
  1388. for tc in self.get_testcases(include_onlymatching=False):
  1389. if 'playlist' in tc:
  1390. tc = tc['playlist'][0]
  1391. is_restricted = age_restricted(
  1392. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1393. if not is_restricted:
  1394. return True
  1395. any_restricted = any_restricted or is_restricted
  1396. return not any_restricted
  1397. def extract_subtitles(self, *args, **kwargs):
  1398. if (self._downloader.params.get('writesubtitles', False) or
  1399. self._downloader.params.get('listsubtitles')):
  1400. return self._get_subtitles(*args, **kwargs)
  1401. return {}
  1402. def _get_subtitles(self, *args, **kwargs):
  1403. raise NotImplementedError('This method must be implemented by subclasses')
  1404. @staticmethod
  1405. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1406. """ Merge subtitle items for one language. Items with duplicated URLs
  1407. will be dropped. """
  1408. list1_urls = set([item['url'] for item in subtitle_list1])
  1409. ret = list(subtitle_list1)
  1410. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1411. return ret
  1412. @classmethod
  1413. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  1414. """ Merge two subtitle dictionaries, language by language. """
  1415. ret = dict(subtitle_dict1)
  1416. for lang in subtitle_dict2:
  1417. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1418. return ret
  1419. def extract_automatic_captions(self, *args, **kwargs):
  1420. if (self._downloader.params.get('writeautomaticsub', False) or
  1421. self._downloader.params.get('listsubtitles')):
  1422. return self._get_automatic_captions(*args, **kwargs)
  1423. return {}
  1424. def _get_automatic_captions(self, *args, **kwargs):
  1425. raise NotImplementedError('This method must be implemented by subclasses')
  1426. class SearchInfoExtractor(InfoExtractor):
  1427. """
  1428. Base class for paged search queries extractors.
  1429. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1430. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1431. """
  1432. @classmethod
  1433. def _make_valid_url(cls):
  1434. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1435. @classmethod
  1436. def suitable(cls, url):
  1437. return re.match(cls._make_valid_url(), url) is not None
  1438. def _real_extract(self, query):
  1439. mobj = re.match(self._make_valid_url(), query)
  1440. if mobj is None:
  1441. raise ExtractorError('Invalid search query "%s"' % query)
  1442. prefix = mobj.group('prefix')
  1443. query = mobj.group('query')
  1444. if prefix == '':
  1445. return self._get_n_results(query, 1)
  1446. elif prefix == 'all':
  1447. return self._get_n_results(query, self._MAX_RESULTS)
  1448. else:
  1449. n = int(prefix)
  1450. if n <= 0:
  1451. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1452. elif n > self._MAX_RESULTS:
  1453. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1454. n = self._MAX_RESULTS
  1455. return self._get_n_results(query, n)
  1456. def _get_n_results(self, query, n):
  1457. """Get a specified number of results for a query"""
  1458. raise NotImplementedError('This method must be implemented by subclasses')
  1459. @property
  1460. def SEARCH_KEY(self):
  1461. return self._SEARCH_KEY