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.

1319 lines
54 KiB

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