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.

1350 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. # Methods for following #608
  453. @staticmethod
  454. def url_result(url, ie=None, video_id=None, video_title=None):
  455. """Returns a URL that points to a page that should be processed"""
  456. # TODO: ie should be the class used for getting the info
  457. video_info = {'_type': 'url',
  458. 'url': url,
  459. 'ie_key': ie}
  460. if video_id is not None:
  461. video_info['id'] = video_id
  462. if video_title is not None:
  463. video_info['title'] = video_title
  464. return video_info
  465. @staticmethod
  466. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  467. """Returns a playlist"""
  468. video_info = {'_type': 'playlist',
  469. 'entries': entries}
  470. if playlist_id:
  471. video_info['id'] = playlist_id
  472. if playlist_title:
  473. video_info['title'] = playlist_title
  474. if playlist_description:
  475. video_info['description'] = playlist_description
  476. return video_info
  477. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  478. """
  479. Perform a regex search on the given string, using a single or a list of
  480. patterns returning the first matching group.
  481. In case of failure return a default value or raise a WARNING or a
  482. RegexNotFoundError, depending on fatal, specifying the field name.
  483. """
  484. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  485. mobj = re.search(pattern, string, flags)
  486. else:
  487. for p in pattern:
  488. mobj = re.search(p, string, flags)
  489. if mobj:
  490. break
  491. if not self._downloader.params.get('no_color') and os.name != 'nt' and sys.stderr.isatty():
  492. _name = '\033[0;34m%s\033[0m' % name
  493. else:
  494. _name = name
  495. if mobj:
  496. if group is None:
  497. # return the first matching group
  498. return next(g for g in mobj.groups() if g is not None)
  499. else:
  500. return mobj.group(group)
  501. elif default is not NO_DEFAULT:
  502. return default
  503. elif fatal:
  504. raise RegexNotFoundError('Unable to extract %s' % _name)
  505. else:
  506. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  507. return None
  508. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  509. """
  510. Like _search_regex, but strips HTML tags and unescapes entities.
  511. """
  512. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  513. if res:
  514. return clean_html(res).strip()
  515. else:
  516. return res
  517. def _get_login_info(self):
  518. """
  519. Get the login info as (username, password)
  520. It will look in the netrc file using the _NETRC_MACHINE value
  521. If there's no info available, return (None, None)
  522. """
  523. if self._downloader is None:
  524. return (None, None)
  525. username = None
  526. password = None
  527. downloader_params = self._downloader.params
  528. # Attempt to use provided username and password or .netrc data
  529. if downloader_params.get('username', None) is not None:
  530. username = downloader_params['username']
  531. password = downloader_params['password']
  532. elif downloader_params.get('usenetrc', False):
  533. try:
  534. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  535. if info is not None:
  536. username = info[0]
  537. password = info[2]
  538. else:
  539. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  540. except (IOError, netrc.NetrcParseError) as err:
  541. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  542. return (username, password)
  543. def _get_tfa_info(self, note='two-factor verification code'):
  544. """
  545. Get the two-factor authentication info
  546. TODO - asking the user will be required for sms/phone verify
  547. currently just uses the command line option
  548. If there's no info available, return None
  549. """
  550. if self._downloader is None:
  551. return None
  552. downloader_params = self._downloader.params
  553. if downloader_params.get('twofactor', None) is not None:
  554. return downloader_params['twofactor']
  555. return compat_getpass('Type %s and press [Return]: ' % note)
  556. # Helper functions for extracting OpenGraph info
  557. @staticmethod
  558. def _og_regexes(prop):
  559. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  560. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  561. template = r'<meta[^>]+?%s[^>]+?%s'
  562. return [
  563. template % (property_re, content_re),
  564. template % (content_re, property_re),
  565. ]
  566. @staticmethod
  567. def _meta_regex(prop):
  568. return r'''(?isx)<meta
  569. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  570. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  571. def _og_search_property(self, prop, html, name=None, **kargs):
  572. if name is None:
  573. name = 'OpenGraph %s' % prop
  574. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  575. if escaped is None:
  576. return None
  577. return unescapeHTML(escaped)
  578. def _og_search_thumbnail(self, html, **kargs):
  579. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  580. def _og_search_description(self, html, **kargs):
  581. return self._og_search_property('description', html, fatal=False, **kargs)
  582. def _og_search_title(self, html, **kargs):
  583. return self._og_search_property('title', html, **kargs)
  584. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  585. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  586. if secure:
  587. regexes = self._og_regexes('video:secure_url') + regexes
  588. return self._html_search_regex(regexes, html, name, **kargs)
  589. def _og_search_url(self, html, **kargs):
  590. return self._og_search_property('url', html, **kargs)
  591. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  592. if display_name is None:
  593. display_name = name
  594. return self._html_search_regex(
  595. self._meta_regex(name),
  596. html, display_name, fatal=fatal, group='content', **kwargs)
  597. def _dc_search_uploader(self, html):
  598. return self._html_search_meta('dc.creator', html, 'uploader')
  599. def _rta_search(self, html):
  600. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  601. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  602. r' content="RTA-5042-1996-1400-1577-RTA"',
  603. html):
  604. return 18
  605. return 0
  606. def _media_rating_search(self, html):
  607. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  608. rating = self._html_search_meta('rating', html)
  609. if not rating:
  610. return None
  611. RATING_TABLE = {
  612. 'safe for kids': 0,
  613. 'general': 8,
  614. '14 years': 14,
  615. 'mature': 17,
  616. 'restricted': 19,
  617. }
  618. return RATING_TABLE.get(rating.lower(), None)
  619. def _family_friendly_search(self, html):
  620. # See http://schema.org/VideoObject
  621. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  622. if not family_friendly:
  623. return None
  624. RATING_TABLE = {
  625. '1': 0,
  626. 'true': 0,
  627. '0': 18,
  628. 'false': 18,
  629. }
  630. return RATING_TABLE.get(family_friendly.lower(), None)
  631. def _twitter_search_player(self, html):
  632. return self._html_search_meta('twitter:player', html,
  633. 'twitter card player')
  634. @staticmethod
  635. def _hidden_inputs(html):
  636. hidden_inputs = {}
  637. for input in re.findall(r'<input([^>]+)>', html):
  638. if not re.search(r'type=(["\'])hidden\1', input):
  639. continue
  640. name = re.search(r'name=(["\'])(?P<value>.+?)\1', input)
  641. if not name:
  642. continue
  643. value = re.search(r'value=(["\'])(?P<value>.*?)\1', input)
  644. if not value:
  645. continue
  646. hidden_inputs[name.group('value')] = value.group('value')
  647. return hidden_inputs
  648. def _form_hidden_inputs(self, form_id, html):
  649. form = self._search_regex(
  650. r'(?s)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  651. html, '%s form' % form_id, group='form')
  652. return self._hidden_inputs(form)
  653. def _sort_formats(self, formats, field_preference=None):
  654. if not formats:
  655. raise ExtractorError('No video formats found')
  656. def _formats_key(f):
  657. # TODO remove the following workaround
  658. from ..utils import determine_ext
  659. if not f.get('ext') and 'url' in f:
  660. f['ext'] = determine_ext(f['url'])
  661. if isinstance(field_preference, (list, tuple)):
  662. return tuple(f.get(field) if f.get(field) is not None else -1 for field in field_preference)
  663. preference = f.get('preference')
  664. if preference is None:
  665. proto = f.get('protocol')
  666. if proto is None:
  667. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  668. preference = 0 if proto in ['http', 'https'] else -0.1
  669. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  670. preference -= 0.5
  671. if f.get('vcodec') == 'none': # audio only
  672. if self._downloader.params.get('prefer_free_formats'):
  673. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  674. else:
  675. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  676. ext_preference = 0
  677. try:
  678. audio_ext_preference = ORDER.index(f['ext'])
  679. except ValueError:
  680. audio_ext_preference = -1
  681. else:
  682. if self._downloader.params.get('prefer_free_formats'):
  683. ORDER = ['flv', 'mp4', 'webm']
  684. else:
  685. ORDER = ['webm', 'flv', 'mp4']
  686. try:
  687. ext_preference = ORDER.index(f['ext'])
  688. except ValueError:
  689. ext_preference = -1
  690. audio_ext_preference = 0
  691. return (
  692. preference,
  693. f.get('language_preference') if f.get('language_preference') is not None else -1,
  694. f.get('quality') if f.get('quality') is not None else -1,
  695. f.get('tbr') if f.get('tbr') is not None else -1,
  696. f.get('filesize') if f.get('filesize') is not None else -1,
  697. f.get('vbr') if f.get('vbr') is not None else -1,
  698. f.get('height') if f.get('height') is not None else -1,
  699. f.get('width') if f.get('width') is not None else -1,
  700. ext_preference,
  701. f.get('abr') if f.get('abr') is not None else -1,
  702. audio_ext_preference,
  703. f.get('fps') if f.get('fps') is not None else -1,
  704. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  705. f.get('source_preference') if f.get('source_preference') is not None else -1,
  706. f.get('format_id') if f.get('format_id') is not None else '',
  707. )
  708. formats.sort(key=_formats_key)
  709. def _check_formats(self, formats, video_id):
  710. if formats:
  711. formats[:] = filter(
  712. lambda f: self._is_valid_url(
  713. f['url'], video_id,
  714. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  715. formats)
  716. def _is_valid_url(self, url, video_id, item='video'):
  717. url = self._proto_relative_url(url, scheme='http:')
  718. # For now assume non HTTP(S) URLs always valid
  719. if not (url.startswith('http://') or url.startswith('https://')):
  720. return True
  721. try:
  722. self._request_webpage(url, video_id, 'Checking %s URL' % item)
  723. return True
  724. except ExtractorError as e:
  725. if isinstance(e.cause, compat_HTTPError):
  726. self.to_screen(
  727. '%s: %s URL is invalid, skipping' % (video_id, item))
  728. return False
  729. raise
  730. def http_scheme(self):
  731. """ Either "http:" or "https:", depending on the user's preferences """
  732. return (
  733. 'http:'
  734. if self._downloader.params.get('prefer_insecure', False)
  735. else 'https:')
  736. def _proto_relative_url(self, url, scheme=None):
  737. if url is None:
  738. return url
  739. if url.startswith('//'):
  740. if scheme is None:
  741. scheme = self.http_scheme()
  742. return scheme + url
  743. else:
  744. return url
  745. def _sleep(self, timeout, video_id, msg_template=None):
  746. if msg_template is None:
  747. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  748. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  749. self.to_screen(msg)
  750. time.sleep(timeout)
  751. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  752. transform_source=lambda s: fix_xml_ampersands(s).strip()):
  753. manifest = self._download_xml(
  754. manifest_url, video_id, 'Downloading f4m manifest',
  755. 'Unable to download f4m manifest',
  756. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  757. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  758. transform_source=transform_source)
  759. formats = []
  760. manifest_version = '1.0'
  761. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  762. if not media_nodes:
  763. manifest_version = '2.0'
  764. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  765. for i, media_el in enumerate(media_nodes):
  766. if manifest_version == '2.0':
  767. media_url = media_el.attrib.get('href') or media_el.attrib.get('url')
  768. if not media_url:
  769. continue
  770. manifest_url = (
  771. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  772. else ('/'.join(manifest_url.split('/')[:-1]) + '/' + media_url))
  773. # If media_url is itself a f4m manifest do the recursive extraction
  774. # since bitrates in parent manifest (this one) and media_url manifest
  775. # may differ leading to inability to resolve the format by requested
  776. # bitrate in f4m downloader
  777. if determine_ext(manifest_url) == 'f4m':
  778. formats.extend(self._extract_f4m_formats(manifest_url, video_id, preference, f4m_id))
  779. continue
  780. tbr = int_or_none(media_el.attrib.get('bitrate'))
  781. formats.append({
  782. 'format_id': '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)])),
  783. 'url': manifest_url,
  784. 'ext': 'flv',
  785. 'tbr': tbr,
  786. 'width': int_or_none(media_el.attrib.get('width')),
  787. 'height': int_or_none(media_el.attrib.get('height')),
  788. 'preference': preference,
  789. })
  790. self._sort_formats(formats)
  791. return formats
  792. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  793. entry_protocol='m3u8', preference=None,
  794. m3u8_id=None, note=None, errnote=None,
  795. fatal=True):
  796. formats = [{
  797. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  798. 'url': m3u8_url,
  799. 'ext': ext,
  800. 'protocol': 'm3u8',
  801. 'preference': preference - 1 if preference else -1,
  802. 'resolution': 'multiple',
  803. 'format_note': 'Quality selection URL',
  804. }]
  805. format_url = lambda u: (
  806. u
  807. if re.match(r'^https?://', u)
  808. else compat_urlparse.urljoin(m3u8_url, u))
  809. m3u8_doc = self._download_webpage(
  810. m3u8_url, video_id,
  811. note=note or 'Downloading m3u8 information',
  812. errnote=errnote or 'Failed to download m3u8 information',
  813. fatal=fatal)
  814. if m3u8_doc is False:
  815. return m3u8_doc
  816. last_info = None
  817. last_media = None
  818. kv_rex = re.compile(
  819. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  820. for line in m3u8_doc.splitlines():
  821. if line.startswith('#EXT-X-STREAM-INF:'):
  822. last_info = {}
  823. for m in kv_rex.finditer(line):
  824. v = m.group('val')
  825. if v.startswith('"'):
  826. v = v[1:-1]
  827. last_info[m.group('key')] = v
  828. elif line.startswith('#EXT-X-MEDIA:'):
  829. last_media = {}
  830. for m in kv_rex.finditer(line):
  831. v = m.group('val')
  832. if v.startswith('"'):
  833. v = v[1:-1]
  834. last_media[m.group('key')] = v
  835. elif line.startswith('#') or not line.strip():
  836. continue
  837. else:
  838. if last_info is None:
  839. formats.append({'url': format_url(line)})
  840. continue
  841. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  842. format_id = []
  843. if m3u8_id:
  844. format_id.append(m3u8_id)
  845. last_media_name = last_media.get('NAME') if last_media and last_media.get('TYPE') != 'SUBTITLES' else None
  846. format_id.append(last_media_name if last_media_name else '%d' % (tbr if tbr else len(formats)))
  847. f = {
  848. 'format_id': '-'.join(format_id),
  849. 'url': format_url(line.strip()),
  850. 'tbr': tbr,
  851. 'ext': ext,
  852. 'protocol': entry_protocol,
  853. 'preference': preference,
  854. }
  855. codecs = last_info.get('CODECS')
  856. if codecs:
  857. # TODO: looks like video codec is not always necessarily goes first
  858. va_codecs = codecs.split(',')
  859. if va_codecs[0]:
  860. f['vcodec'] = va_codecs[0].partition('.')[0]
  861. if len(va_codecs) > 1 and va_codecs[1]:
  862. f['acodec'] = va_codecs[1].partition('.')[0]
  863. resolution = last_info.get('RESOLUTION')
  864. if resolution:
  865. width_str, height_str = resolution.split('x')
  866. f['width'] = int(width_str)
  867. f['height'] = int(height_str)
  868. if last_media is not None:
  869. f['m3u8_media'] = last_media
  870. last_media = None
  871. formats.append(f)
  872. last_info = {}
  873. self._sort_formats(formats)
  874. return formats
  875. @staticmethod
  876. def _xpath_ns(path, namespace=None):
  877. if not namespace:
  878. return path
  879. out = []
  880. for c in path.split('/'):
  881. if not c or c == '.':
  882. out.append(c)
  883. else:
  884. out.append('{%s}%s' % (namespace, c))
  885. return '/'.join(out)
  886. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None):
  887. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  888. if smil is False:
  889. assert not fatal
  890. return []
  891. namespace = self._parse_smil_namespace(smil)
  892. return self._parse_smil_formats(
  893. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  894. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  895. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  896. if smil is False:
  897. return {}
  898. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  899. def _download_smil(self, smil_url, video_id, fatal=True):
  900. return self._download_xml(
  901. smil_url, video_id, 'Downloading SMIL file',
  902. 'Unable to download SMIL file', fatal=fatal)
  903. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  904. namespace = self._parse_smil_namespace(smil)
  905. formats = self._parse_smil_formats(
  906. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  907. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  908. video_id = os.path.splitext(url_basename(smil_url))[0]
  909. title = None
  910. description = None
  911. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  912. name = meta.attrib.get('name')
  913. content = meta.attrib.get('content')
  914. if not name or not content:
  915. continue
  916. if not title and name == 'title':
  917. title = content
  918. elif not description and name in ('description', 'abstract'):
  919. description = content
  920. return {
  921. 'id': video_id,
  922. 'title': title or video_id,
  923. 'description': description,
  924. 'formats': formats,
  925. 'subtitles': subtitles,
  926. }
  927. def _parse_smil_namespace(self, smil):
  928. return self._search_regex(
  929. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  930. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  931. base = smil_url
  932. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  933. b = meta.get('base') or meta.get('httpBase')
  934. if b:
  935. base = b
  936. break
  937. formats = []
  938. rtmp_count = 0
  939. http_count = 0
  940. videos = smil.findall(self._xpath_ns('.//video', namespace))
  941. for video in videos:
  942. src = video.get('src')
  943. if not src:
  944. continue
  945. bitrate = int_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
  946. filesize = int_or_none(video.get('size') or video.get('fileSize'))
  947. width = int_or_none(video.get('width'))
  948. height = int_or_none(video.get('height'))
  949. proto = video.get('proto')
  950. ext = video.get('ext')
  951. src_ext = determine_ext(src)
  952. streamer = video.get('streamer') or base
  953. if proto == 'rtmp' or streamer.startswith('rtmp'):
  954. rtmp_count += 1
  955. formats.append({
  956. 'url': streamer,
  957. 'play_path': src,
  958. 'ext': 'flv',
  959. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  960. 'tbr': bitrate,
  961. 'filesize': filesize,
  962. 'width': width,
  963. 'height': height,
  964. })
  965. if transform_rtmp_url:
  966. streamer, src = transform_rtmp_url(streamer, src)
  967. formats[-1].update({
  968. 'url': streamer,
  969. 'play_path': src,
  970. })
  971. continue
  972. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  973. if proto == 'm3u8' or src_ext == 'm3u8':
  974. formats.extend(self._extract_m3u8_formats(
  975. src_url, video_id, ext or 'mp4', m3u8_id='hls'))
  976. continue
  977. if src_ext == 'f4m':
  978. f4m_url = src_url
  979. if not f4m_params:
  980. f4m_params = {
  981. 'hdcore': '3.2.0',
  982. 'plugin': 'flowplayer-3.2.0.1',
  983. }
  984. f4m_url += '&' if '?' in f4m_url else '?'
  985. f4m_url += compat_urllib_parse.urlencode(f4m_params)
  986. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds'))
  987. continue
  988. if src_url.startswith('http'):
  989. http_count += 1
  990. formats.append({
  991. 'url': src_url,
  992. 'ext': ext or src_ext or 'flv',
  993. 'format_id': 'http-%d' % (bitrate or http_count),
  994. 'tbr': bitrate,
  995. 'filesize': filesize,
  996. 'width': width,
  997. 'height': height,
  998. })
  999. continue
  1000. self._sort_formats(formats)
  1001. return formats
  1002. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1003. subtitles = {}
  1004. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1005. src = textstream.get('src')
  1006. if not src:
  1007. continue
  1008. ext = textstream.get('ext') or determine_ext(src)
  1009. if not ext:
  1010. type_ = textstream.get('type')
  1011. SUBTITLES_TYPES = {
  1012. 'text/vtt': 'vtt',
  1013. 'text/srt': 'srt',
  1014. 'application/smptett+xml': 'tt',
  1015. }
  1016. if type_ in SUBTITLES_TYPES:
  1017. ext = SUBTITLES_TYPES[type_]
  1018. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1019. subtitles.setdefault(lang, []).append({
  1020. 'url': src,
  1021. 'ext': ext,
  1022. })
  1023. return subtitles
  1024. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1025. xspf = self._download_xml(
  1026. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1027. 'Unable to download xspf manifest', fatal=fatal)
  1028. if xspf is False:
  1029. return []
  1030. return self._parse_xspf(xspf, playlist_id)
  1031. def _parse_xspf(self, playlist, playlist_id):
  1032. NS_MAP = {
  1033. 'xspf': 'http://xspf.org/ns/0/',
  1034. 's1': 'http://static.streamone.nl/player/ns/0',
  1035. }
  1036. entries = []
  1037. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1038. title = xpath_text(
  1039. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1040. description = xpath_text(
  1041. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1042. thumbnail = xpath_text(
  1043. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1044. duration = float_or_none(
  1045. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1046. formats = [{
  1047. 'url': location.text,
  1048. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1049. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1050. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1051. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1052. self._sort_formats(formats)
  1053. entries.append({
  1054. 'id': playlist_id,
  1055. 'title': title,
  1056. 'description': description,
  1057. 'thumbnail': thumbnail,
  1058. 'duration': duration,
  1059. 'formats': formats,
  1060. })
  1061. return entries
  1062. def _live_title(self, name):
  1063. """ Generate the title for a live video """
  1064. now = datetime.datetime.now()
  1065. now_str = now.strftime("%Y-%m-%d %H:%M")
  1066. return name + ' ' + now_str
  1067. def _int(self, v, name, fatal=False, **kwargs):
  1068. res = int_or_none(v, **kwargs)
  1069. if 'get_attr' in kwargs:
  1070. print(getattr(v, kwargs['get_attr']))
  1071. if res is None:
  1072. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1073. if fatal:
  1074. raise ExtractorError(msg)
  1075. else:
  1076. self._downloader.report_warning(msg)
  1077. return res
  1078. def _float(self, v, name, fatal=False, **kwargs):
  1079. res = float_or_none(v, **kwargs)
  1080. if res is None:
  1081. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  1082. if fatal:
  1083. raise ExtractorError(msg)
  1084. else:
  1085. self._downloader.report_warning(msg)
  1086. return res
  1087. def _set_cookie(self, domain, name, value, expire_time=None):
  1088. cookie = compat_cookiejar.Cookie(
  1089. 0, name, value, None, None, domain, None,
  1090. None, '/', True, False, expire_time, '', None, None, None)
  1091. self._downloader.cookiejar.set_cookie(cookie)
  1092. def _get_cookies(self, url):
  1093. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  1094. req = compat_urllib_request.Request(url)
  1095. self._downloader.cookiejar.add_cookie_header(req)
  1096. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  1097. def get_testcases(self, include_onlymatching=False):
  1098. t = getattr(self, '_TEST', None)
  1099. if t:
  1100. assert not hasattr(self, '_TESTS'), \
  1101. '%s has _TEST and _TESTS' % type(self).__name__
  1102. tests = [t]
  1103. else:
  1104. tests = getattr(self, '_TESTS', [])
  1105. for t in tests:
  1106. if not include_onlymatching and t.get('only_matching', False):
  1107. continue
  1108. t['name'] = type(self).__name__[:-len('IE')]
  1109. yield t
  1110. def is_suitable(self, age_limit):
  1111. """ Test whether the extractor is generally suitable for the given
  1112. age limit (i.e. pornographic sites are not, all others usually are) """
  1113. any_restricted = False
  1114. for tc in self.get_testcases(include_onlymatching=False):
  1115. if 'playlist' in tc:
  1116. tc = tc['playlist'][0]
  1117. is_restricted = age_restricted(
  1118. tc.get('info_dict', {}).get('age_limit'), age_limit)
  1119. if not is_restricted:
  1120. return True
  1121. any_restricted = any_restricted or is_restricted
  1122. return not any_restricted
  1123. def extract_subtitles(self, *args, **kwargs):
  1124. if (self._downloader.params.get('writesubtitles', False) or
  1125. self._downloader.params.get('listsubtitles')):
  1126. return self._get_subtitles(*args, **kwargs)
  1127. return {}
  1128. def _get_subtitles(self, *args, **kwargs):
  1129. raise NotImplementedError("This method must be implemented by subclasses")
  1130. @staticmethod
  1131. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  1132. """ Merge subtitle items for one language. Items with duplicated URLs
  1133. will be dropped. """
  1134. list1_urls = set([item['url'] for item in subtitle_list1])
  1135. ret = list(subtitle_list1)
  1136. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  1137. return ret
  1138. @classmethod
  1139. def _merge_subtitles(kls, subtitle_dict1, subtitle_dict2):
  1140. """ Merge two subtitle dictionaries, language by language. """
  1141. ret = dict(subtitle_dict1)
  1142. for lang in subtitle_dict2:
  1143. ret[lang] = kls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  1144. return ret
  1145. def extract_automatic_captions(self, *args, **kwargs):
  1146. if (self._downloader.params.get('writeautomaticsub', False) or
  1147. self._downloader.params.get('listsubtitles')):
  1148. return self._get_automatic_captions(*args, **kwargs)
  1149. return {}
  1150. def _get_automatic_captions(self, *args, **kwargs):
  1151. raise NotImplementedError("This method must be implemented by subclasses")
  1152. class SearchInfoExtractor(InfoExtractor):
  1153. """
  1154. Base class for paged search queries extractors.
  1155. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  1156. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  1157. """
  1158. @classmethod
  1159. def _make_valid_url(cls):
  1160. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  1161. @classmethod
  1162. def suitable(cls, url):
  1163. return re.match(cls._make_valid_url(), url) is not None
  1164. def _real_extract(self, query):
  1165. mobj = re.match(self._make_valid_url(), query)
  1166. if mobj is None:
  1167. raise ExtractorError('Invalid search query "%s"' % query)
  1168. prefix = mobj.group('prefix')
  1169. query = mobj.group('query')
  1170. if prefix == '':
  1171. return self._get_n_results(query, 1)
  1172. elif prefix == 'all':
  1173. return self._get_n_results(query, self._MAX_RESULTS)
  1174. else:
  1175. n = int(prefix)
  1176. if n <= 0:
  1177. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  1178. elif n > self._MAX_RESULTS:
  1179. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  1180. n = self._MAX_RESULTS
  1181. return self._get_n_results(query, n)
  1182. def _get_n_results(self, query, n):
  1183. """Get a specified number of results for a query"""
  1184. raise NotImplementedError("This method must be implemented by subclasses")
  1185. @property
  1186. def SEARCH_KEY(self):
  1187. return self._SEARCH_KEY