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.

1363 lines
56 KiB

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