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.

1357 lines
56 KiB

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