logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

common.py (159729B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import collections
  5. import datetime
  6. import functools
  7. import hashlib
  8. import json
  9. import netrc
  10. import os
  11. import random
  12. import re
  13. import socket
  14. import ssl
  15. import sys
  16. import time
  17. import math
  18. from ..compat import (
  19. compat_cookiejar_Cookie,
  20. compat_cookies_SimpleCookie,
  21. compat_etree_Element,
  22. compat_etree_fromstring,
  23. compat_getpass,
  24. compat_integer_types,
  25. compat_http_client,
  26. compat_kwargs,
  27. compat_map as map,
  28. compat_open as open,
  29. compat_os_name,
  30. compat_str,
  31. compat_urllib_error,
  32. compat_urllib_parse_unquote,
  33. compat_urllib_parse_urlencode,
  34. compat_urllib_request,
  35. compat_urlparse,
  36. compat_xml_parse_error,
  37. compat_zip as zip,
  38. )
  39. from ..downloader.f4m import (
  40. get_base_url,
  41. remove_encrypted_media,
  42. )
  43. from ..utils import (
  44. NO_DEFAULT,
  45. age_restricted,
  46. base_url,
  47. bug_reports_message,
  48. clean_html,
  49. compiled_regex_type,
  50. determine_ext,
  51. determine_protocol,
  52. dict_get,
  53. error_to_compat_str,
  54. ExtractorError,
  55. extract_attributes,
  56. fix_xml_ampersands,
  57. float_or_none,
  58. GeoRestrictedError,
  59. GeoUtils,
  60. int_or_none,
  61. join_nonempty,
  62. js_to_json,
  63. JSON_LD_RE,
  64. mimetype2ext,
  65. orderedSet,
  66. parse_bitrate,
  67. parse_codecs,
  68. parse_duration,
  69. parse_iso8601,
  70. parse_m3u8_attributes,
  71. parse_resolution,
  72. RegexNotFoundError,
  73. sanitized_Request,
  74. sanitize_filename,
  75. str_or_none,
  76. str_to_int,
  77. strip_or_none,
  78. T,
  79. traverse_obj,
  80. try_get,
  81. unescapeHTML,
  82. unified_strdate,
  83. unified_timestamp,
  84. update_Request,
  85. update_url_query,
  86. urljoin,
  87. url_basename,
  88. url_or_none,
  89. variadic,
  90. xpath_element,
  91. xpath_text,
  92. xpath_with_ns,
  93. )
  94. class InfoExtractor(object):
  95. """Information Extractor class.
  96. Information extractors are the classes that, given a URL, extract
  97. information about the video (or videos) the URL refers to. This
  98. information includes the real video URL, the video title, author and
  99. others. The information is stored in a dictionary which is then
  100. passed to the YoutubeDL. The YoutubeDL processes this
  101. information possibly downloading the video to the file system, among
  102. other possible outcomes.
  103. The type field determines the type of the result.
  104. By far the most common value (and the default if _type is missing) is
  105. "video", which indicates a single video.
  106. For a video, the dictionaries must include the following fields:
  107. id: Video identifier.
  108. title: Video title, unescaped.
  109. Additionally, it must contain either a formats entry or a url one:
  110. formats: A list of dictionaries for each format available, ordered
  111. from worst to best quality.
  112. Potential fields:
  113. * url The mandatory URL representing the media:
  114. for plain file media - HTTP URL of this file,
  115. for RTMP - RTMP URL,
  116. for HLS - URL of the M3U8 media playlist,
  117. for HDS - URL of the F4M manifest,
  118. for DASH
  119. - HTTP URL to plain file media (in case of
  120. unfragmented media)
  121. - URL of the MPD manifest or base URL
  122. representing the media if MPD manifest
  123. is parsed from a string (in case of
  124. fragmented media)
  125. for MSS - URL of the ISM manifest.
  126. * manifest_url
  127. The URL of the manifest file in case of
  128. fragmented media:
  129. for HLS - URL of the M3U8 master playlist,
  130. for HDS - URL of the F4M manifest,
  131. for DASH - URL of the MPD manifest,
  132. for MSS - URL of the ISM manifest.
  133. * ext Will be calculated from URL if missing
  134. * format A human-readable description of the format
  135. ("mp4 container with h264/opus").
  136. Calculated from the format_id, width, height.
  137. and format_note fields if missing.
  138. * format_id A short description of the format
  139. ("mp4_h264_opus" or "19").
  140. Technically optional, but strongly recommended.
  141. * format_note Additional info about the format
  142. ("3D" or "DASH video")
  143. * width Width of the video, if known
  144. * height Height of the video, if known
  145. * resolution Textual description of width and height
  146. * tbr Average bitrate of audio and video in KBit/s
  147. * abr Average audio bitrate in KBit/s
  148. * acodec Name of the audio codec in use
  149. * asr Audio sampling rate in Hertz
  150. * vbr Average video bitrate in KBit/s
  151. * fps Frame rate
  152. * vcodec Name of the video codec in use
  153. * container Name of the container format
  154. * filesize The number of bytes, if known in advance
  155. * filesize_approx An estimate for the number of bytes
  156. * player_url SWF Player URL (used for rtmpdump).
  157. * protocol The protocol that will be used for the actual
  158. download, lower-case.
  159. "http", "https", "rtsp", "rtmp", "rtmpe",
  160. "m3u8", "m3u8_native" or "http_dash_segments".
  161. * fragment_base_url
  162. Base URL for fragments. Each fragment's path
  163. value (if present) will be relative to
  164. this URL.
  165. * fragments A list of fragments of a fragmented media.
  166. Each fragment entry must contain either an url
  167. or a path. If an url is present it should be
  168. considered by a client. Otherwise both path and
  169. fragment_base_url must be present. Here is
  170. the list of all potential fields:
  171. * "url" - fragment's URL
  172. * "path" - fragment's path relative to
  173. fragment_base_url
  174. * "duration" (optional, int or float)
  175. * "filesize" (optional, int)
  176. * "range" (optional, str of the form "start-end"
  177. to use in HTTP Range header)
  178. * preference Order number of this format. If this field is
  179. present and not None, the formats get sorted
  180. by this field, regardless of all other values.
  181. -1 for default (order by other properties),
  182. -2 or smaller for less than default.
  183. < -1000 to hide the format (if there is
  184. another one which is strictly better)
  185. * language Language code, e.g. "de" or "en-US".
  186. * language_preference Is this in the language mentioned in
  187. the URL?
  188. 10 if it's what the URL is about,
  189. -1 for default (don't know),
  190. -10 otherwise, other values reserved for now.
  191. * quality Order number of the video quality of this
  192. format, irrespective of the file format.
  193. -1 for default (order by other properties),
  194. -2 or smaller for less than default.
  195. * source_preference Order number for this video source
  196. (quality takes higher priority)
  197. -1 for default (order by other properties),
  198. -2 or smaller for less than default.
  199. * http_headers A dictionary of additional HTTP headers
  200. to add to the request.
  201. * stretched_ratio If given and not 1, indicates that the
  202. video's pixels are not square.
  203. width : height ratio as float.
  204. * no_resume The server does not support resuming the
  205. (HTTP or RTMP) download. Boolean.
  206. * downloader_options A dictionary of downloader options as
  207. described in FileDownloader
  208. url: Final video URL.
  209. ext: Video filename extension.
  210. format: The video format, defaults to ext (used for --get-format)
  211. player_url: SWF Player URL (used for rtmpdump).
  212. The following fields are optional:
  213. alt_title: A secondary title of the video.
  214. display_id An alternative identifier for the video, not necessarily
  215. unique, but available before title. Typically, id is
  216. something like "4234987", title "Dancing naked mole rats",
  217. and display_id "dancing-naked-mole-rats"
  218. thumbnails: A list of dictionaries, with the following entries:
  219. * "id" (optional, string) - Thumbnail format ID
  220. * "url"
  221. * "preference" (optional, int) - quality of the image
  222. * "width" (optional, int)
  223. * "height" (optional, int)
  224. * "resolution" (optional, string "{width}x{height}",
  225. deprecated)
  226. * "filesize" (optional, int)
  227. thumbnail: Full URL to a video thumbnail image.
  228. description: Full video description.
  229. uploader: Full name of the video uploader.
  230. license: License name the video is licensed under.
  231. creator: The creator of the video.
  232. release_timestamp: UNIX timestamp of the moment the video was released.
  233. release_date: The date (YYYYMMDD) when the video was released.
  234. timestamp: UNIX timestamp of the moment the video became available
  235. (uploaded).
  236. upload_date: Video upload date (YYYYMMDD).
  237. If not explicitly set, calculated from timestamp.
  238. uploader_id: Nickname or id of the video uploader.
  239. uploader_url: Full URL to a personal webpage of the video uploader.
  240. channel: Full name of the channel the video is uploaded on.
  241. Note that channel fields may or may not repeat uploader
  242. fields. This depends on a particular extractor.
  243. channel_id: Id of the channel.
  244. channel_url: Full URL to a channel webpage.
  245. location: Physical location where the video was filmed.
  246. subtitles: The available subtitles as a dictionary in the format
  247. {tag: subformats}. "tag" is usually a language code, and
  248. "subformats" is a list sorted from lower to higher
  249. preference, each element is a dictionary with the "ext"
  250. entry and one of:
  251. * "data": The subtitles file contents
  252. * "url": A URL pointing to the subtitles file
  253. "ext" will be calculated from URL if missing
  254. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  255. automatically generated captions
  256. duration: Length of the video in seconds, as an integer or float.
  257. view_count: How many users have watched the video on the platform.
  258. like_count: Number of positive ratings of the video
  259. dislike_count: Number of negative ratings of the video
  260. repost_count: Number of reposts of the video
  261. average_rating: Average rating give by users, the scale used depends on the webpage
  262. comment_count: Number of comments on the video
  263. comments: A list of comments, each with one or more of the following
  264. properties (all but one of text or html optional):
  265. * "author" - human-readable name of the comment author
  266. * "author_id" - user ID of the comment author
  267. * "id" - Comment ID
  268. * "html" - Comment as HTML
  269. * "text" - Plain text of the comment
  270. * "timestamp" - UNIX timestamp of comment
  271. * "parent" - ID of the comment this one is replying to.
  272. Set to "root" to indicate that this is a
  273. comment to the original video.
  274. age_limit: Age restriction for the video, as an integer (years)
  275. webpage_url: The URL to the video webpage, if given to youtube-dl it
  276. should allow to get the same result again. (It will be set
  277. by YoutubeDL if it's missing)
  278. categories: A list of categories that the video falls in, for example
  279. ["Sports", "Berlin"]
  280. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  281. is_live: True, False, or None (=unknown). Whether this video is a
  282. live stream that goes on instead of a fixed-length video.
  283. start_time: Time in seconds where the reproduction should start, as
  284. specified in the URL.
  285. end_time: Time in seconds where the reproduction should end, as
  286. specified in the URL.
  287. chapters: A list of dictionaries, with the following entries:
  288. * "start_time" - The start time of the chapter in seconds
  289. * "end_time" - The end time of the chapter in seconds
  290. * "title" (optional, string)
  291. The following fields should only be used when the video belongs to some logical
  292. chapter or section:
  293. chapter: Name or title of the chapter the video belongs to.
  294. chapter_number: Number of the chapter the video belongs to, as an integer.
  295. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  296. The following fields should only be used when the video is an episode of some
  297. series, programme or podcast:
  298. series: Title of the series or programme the video episode belongs to.
  299. season: Title of the season the video episode belongs to.
  300. season_number: Number of the season the video episode belongs to, as an integer.
  301. season_id: Id of the season the video episode belongs to, as a unicode string.
  302. episode: Title of the video episode. Unlike mandatory video title field,
  303. this field should denote the exact title of the video episode
  304. without any kind of decoration.
  305. episode_number: Number of the video episode within a season, as an integer.
  306. episode_id: Id of the video episode, as a unicode string.
  307. The following fields should only be used when the media is a track or a part of
  308. a music album:
  309. track: Title of the track.
  310. track_number: Number of the track within an album or a disc, as an integer.
  311. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  312. as a unicode string.
  313. artist: Artist(s) of the track.
  314. genre: Genre(s) of the track.
  315. album: Title of the album the track belongs to.
  316. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  317. album_artist: List of all artists appeared on the album (e.g.
  318. "Ash Borer / Fell Voices" or "Various Artists", useful for splits
  319. and compilations).
  320. disc_number: Number of the disc or other physical medium the track belongs to,
  321. as an integer.
  322. release_year: Year (YYYY) when the album was released.
  323. Unless mentioned otherwise, the fields should be Unicode strings.
  324. Unless mentioned otherwise, None is equivalent to absence of information.
  325. _type "playlist" indicates multiple videos.
  326. There must be a key "entries", which is a list, an iterable, or a PagedList
  327. object, each element of which is a valid dictionary by this specification.
  328. Additionally, playlists can have "id", "title", "description", "uploader",
  329. "uploader_id", "uploader_url", "duration" attributes with the same semantics
  330. as videos (see above).
  331. _type "multi_video" indicates that there are multiple videos that
  332. form a single show, for examples multiple acts of an opera or TV episode.
  333. It must have an entries key like a playlist and contain all the keys
  334. required for a video at the same time.
  335. _type "url" indicates that the video must be extracted from another
  336. location, possibly by a different extractor. Its only required key is:
  337. "url" - the next URL to extract.
  338. The key "ie_key" can be set to the class name (minus the trailing "IE",
  339. e.g. "Youtube") if the extractor class is known in advance.
  340. Additionally, the dictionary may have any properties of the resolved entity
  341. known in advance, for example "title" if the title of the referred video is
  342. known ahead of time.
  343. _type "url_transparent" entities have the same specification as "url", but
  344. indicate that the given additional information is more precise than the one
  345. associated with the resolved URL.
  346. This is useful when a site employs a video service that hosts the video and
  347. its technical metadata, but that video service does not embed a useful
  348. title, description etc.
  349. A subclass of InfoExtractor must be defined to handle each specific site (or
  350. several sites). Such a concrete subclass should be added to the list of
  351. extractors. It should also:
  352. * define its _VALID_URL attribute as a regexp, or a Sequence of alternative
  353. regexps (but see below)
  354. * re-define the _real_extract() method
  355. * optionally re-define the _real_initialize() method.
  356. An extractor subclass may also override suitable() if necessary, but the
  357. function signature must be preserved and the function must import everything
  358. it needs (except other extractors), so that lazy_extractors works correctly.
  359. If the subclass's suitable() and _real_extract() functions avoid using
  360. _VALID_URL, the subclass need not set that class attribute.
  361. An abstract subclass of InfoExtractor may be used to simplify implementation
  362. within an extractor module; it should not be added to the list of extractors.
  363. _GEO_BYPASS attribute may be set to False in order to disable
  364. geo restriction bypass mechanisms for a particular extractor.
  365. Though it won't disable explicit geo restriction bypass based on
  366. country code provided with geo_bypass_country.
  367. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  368. countries for this extractor. One of these countries will be used by
  369. geo restriction bypass mechanism right away in order to bypass
  370. geo restriction, of course, if the mechanism is not disabled.
  371. _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
  372. IP blocks in CIDR notation for this extractor. One of these IP blocks
  373. will be used by geo restriction bypass mechanism similarly
  374. to _GEO_COUNTRIES.
  375. Finally, the _WORKING attribute should be set to False for broken IEs
  376. in order to warn the users and skip the tests.
  377. """
  378. _ready = False
  379. _downloader = None
  380. _x_forwarded_for_ip = None
  381. _GEO_BYPASS = True
  382. _GEO_COUNTRIES = None
  383. _GEO_IP_BLOCKS = None
  384. _WORKING = True
  385. # supply this in public subclasses: used in supported sites list, etc
  386. # IE_DESC = 'short description of IE'
  387. def __init__(self, downloader=None):
  388. """Constructor. Receives an optional downloader."""
  389. self._ready = False
  390. self._x_forwarded_for_ip = None
  391. self.set_downloader(downloader)
  392. @classmethod
  393. def __match_valid_url(cls, url):
  394. # This does not use has/getattr intentionally - we want to know whether
  395. # we have cached the regexp for cls, whereas getattr would also
  396. # match its superclass
  397. if '_VALID_URL_RE' not in cls.__dict__:
  398. # _VALID_URL can now be a list/tuple of patterns
  399. cls._VALID_URL_RE = tuple(map(re.compile, variadic(cls._VALID_URL)))
  400. # 20% faster than next(filter(None, (p.match(url) for p in cls._VALID_URL_RE)), None) in 2.7
  401. for p in cls._VALID_URL_RE:
  402. p = p.match(url)
  403. if p:
  404. return p
  405. # The public alias can safely be overridden, as in some back-ports
  406. _match_valid_url = __match_valid_url
  407. @classmethod
  408. def suitable(cls, url):
  409. """Receives a URL and returns True if suitable for this IE."""
  410. # This function must import everything it needs (except other extractors),
  411. # so that lazy_extractors works correctly
  412. return cls.__match_valid_url(url) is not None
  413. @classmethod
  414. def _match_id(cls, url):
  415. m = cls.__match_valid_url(url)
  416. assert m
  417. return compat_str(m.group('id'))
  418. @classmethod
  419. def working(cls):
  420. """Getter method for _WORKING."""
  421. return cls._WORKING
  422. def initialize(self):
  423. """Initializes an instance (authentication, etc)."""
  424. self._initialize_geo_bypass({
  425. 'countries': self._GEO_COUNTRIES,
  426. 'ip_blocks': self._GEO_IP_BLOCKS,
  427. })
  428. if not self._ready:
  429. self._real_initialize()
  430. self._ready = True
  431. def _initialize_geo_bypass(self, geo_bypass_context):
  432. """
  433. Initialize geo restriction bypass mechanism.
  434. This method is used to initialize geo bypass mechanism based on faking
  435. X-Forwarded-For HTTP header. A random country from provided country list
  436. is selected and a random IP belonging to this country is generated. This
  437. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  438. HTTP requests.
  439. This method will be used for initial geo bypass mechanism initialization
  440. during the instance initialization with _GEO_COUNTRIES and
  441. _GEO_IP_BLOCKS.
  442. You may also manually call it from extractor's code if geo bypass
  443. information is not available beforehand (e.g. obtained during
  444. extraction) or due to some other reason. In this case you should pass
  445. this information in geo bypass context passed as first argument. It may
  446. contain following fields:
  447. countries: List of geo unrestricted countries (similar
  448. to _GEO_COUNTRIES)
  449. ip_blocks: List of geo unrestricted IP blocks in CIDR notation
  450. (similar to _GEO_IP_BLOCKS)
  451. """
  452. if not self._x_forwarded_for_ip:
  453. # Geo bypass mechanism is explicitly disabled by user
  454. if not self.get_param('geo_bypass', True):
  455. return
  456. if not geo_bypass_context:
  457. geo_bypass_context = {}
  458. # Backward compatibility: previously _initialize_geo_bypass
  459. # expected a list of countries, some 3rd party code may still use
  460. # it this way
  461. if isinstance(geo_bypass_context, (list, tuple)):
  462. geo_bypass_context = {
  463. 'countries': geo_bypass_context,
  464. }
  465. # The whole point of geo bypass mechanism is to fake IP
  466. # as X-Forwarded-For HTTP header based on some IP block or
  467. # country code.
  468. # Path 1: bypassing based on IP block in CIDR notation
  469. # Explicit IP block specified by user, use it right away
  470. # regardless of whether extractor is geo bypassable or not
  471. ip_block = self.get_param('geo_bypass_ip_block', None)
  472. # Otherwise use random IP block from geo bypass context but only
  473. # if extractor is known as geo bypassable
  474. if not ip_block:
  475. ip_blocks = geo_bypass_context.get('ip_blocks')
  476. if self._GEO_BYPASS and ip_blocks:
  477. ip_block = random.choice(ip_blocks)
  478. if ip_block:
  479. self._x_forwarded_for_ip = GeoUtils.random_ipv4(ip_block)
  480. if self.get_param('verbose', False):
  481. self.to_screen(
  482. '[debug] Using fake IP %s as X-Forwarded-For.'
  483. % self._x_forwarded_for_ip)
  484. return
  485. # Path 2: bypassing based on country code
  486. # Explicit country code specified by user, use it right away
  487. # regardless of whether extractor is geo bypassable or not
  488. country = self.get_param('geo_bypass_country', None)
  489. # Otherwise use random country code from geo bypass context but
  490. # only if extractor is known as geo bypassable
  491. if not country:
  492. countries = geo_bypass_context.get('countries')
  493. if self._GEO_BYPASS and countries:
  494. country = random.choice(countries)
  495. if country:
  496. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country)
  497. if self.get_param('verbose', False):
  498. self.to_screen(
  499. '[debug] Using fake IP %s (%s) as X-Forwarded-For.'
  500. % (self._x_forwarded_for_ip, country.upper()))
  501. def extract(self, url):
  502. """Extracts URL information and returns it in list of dicts."""
  503. try:
  504. for _ in range(2):
  505. try:
  506. self.initialize()
  507. ie_result = self._real_extract(url)
  508. if self._x_forwarded_for_ip:
  509. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  510. return ie_result
  511. except GeoRestrictedError as e:
  512. if self.__maybe_fake_ip_and_retry(e.countries):
  513. continue
  514. raise
  515. except ExtractorError:
  516. raise
  517. except compat_http_client.IncompleteRead as e:
  518. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  519. except (KeyError, StopIteration) as e:
  520. raise ExtractorError('An extractor error has occurred.', cause=e)
  521. def __maybe_fake_ip_and_retry(self, countries):
  522. if (not self.get_param('geo_bypass_country', None)
  523. and self._GEO_BYPASS
  524. and self.get_param('geo_bypass', True)
  525. and not self._x_forwarded_for_ip
  526. and countries):
  527. country_code = random.choice(countries)
  528. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  529. if self._x_forwarded_for_ip:
  530. self.report_warning(
  531. 'Video is geo restricted. Retrying extraction with fake IP %s (%s) as X-Forwarded-For.'
  532. % (self._x_forwarded_for_ip, country_code.upper()))
  533. return True
  534. return False
  535. def set_downloader(self, downloader):
  536. """Sets the downloader for this IE."""
  537. self._downloader = downloader
  538. @property
  539. def cache(self):
  540. return self._downloader.cache
  541. @property
  542. def cookiejar(self):
  543. return self._downloader.cookiejar
  544. def _real_initialize(self):
  545. """Real initialization process. Redefine in subclasses."""
  546. pass
  547. def _real_extract(self, url):
  548. """Real extraction process. Redefine in subclasses."""
  549. pass
  550. @classmethod
  551. def ie_key(cls):
  552. """A string for getting the InfoExtractor with get_info_extractor"""
  553. return compat_str(cls.__name__[:-2])
  554. @property
  555. def IE_NAME(self):
  556. return compat_str(type(self).__name__[:-2])
  557. @staticmethod
  558. def __can_accept_status_code(err, expected_status):
  559. assert isinstance(err, compat_urllib_error.HTTPError)
  560. if expected_status is None:
  561. return False
  562. if isinstance(expected_status, compat_integer_types):
  563. return err.code == expected_status
  564. elif isinstance(expected_status, (list, tuple)):
  565. return err.code in expected_status
  566. elif callable(expected_status):
  567. return expected_status(err.code) is True
  568. else:
  569. assert False
  570. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}, expected_status=None):
  571. """
  572. Return the response handle.
  573. See _download_webpage docstring for arguments specification.
  574. """
  575. if note is None:
  576. self.report_download_webpage(video_id)
  577. elif note is not False:
  578. if video_id is None:
  579. self.to_screen('%s' % (note,))
  580. else:
  581. self.to_screen('%s: %s' % (video_id, note))
  582. # Some sites check X-Forwarded-For HTTP header in order to figure out
  583. # the origin of the client behind proxy. This allows bypassing geo
  584. # restriction by faking this header's value to IP that belongs to some
  585. # geo unrestricted country. We will do so once we encounter any
  586. # geo restriction error.
  587. if self._x_forwarded_for_ip:
  588. if 'X-Forwarded-For' not in headers:
  589. headers['X-Forwarded-For'] = self._x_forwarded_for_ip
  590. if isinstance(url_or_request, compat_urllib_request.Request):
  591. url_or_request = update_Request(
  592. url_or_request, data=data, headers=headers, query=query)
  593. else:
  594. if query:
  595. url_or_request = update_url_query(url_or_request, query)
  596. if data is not None or headers:
  597. url_or_request = sanitized_Request(url_or_request, data, headers)
  598. exceptions = [compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error]
  599. if hasattr(ssl, 'CertificateError'):
  600. exceptions.append(ssl.CertificateError)
  601. try:
  602. return self._downloader.urlopen(url_or_request)
  603. except tuple(exceptions) as err:
  604. if isinstance(err, compat_urllib_error.HTTPError):
  605. if self.__can_accept_status_code(err, expected_status):
  606. # Retain reference to error to prevent file object from
  607. # being closed before it can be read. Works around the
  608. # effects of <https://bugs.python.org/issue15002>
  609. # introduced in Python 3.4.1.
  610. err.fp._error = err
  611. return err.fp
  612. if errnote is False:
  613. return False
  614. if errnote is None:
  615. errnote = 'Unable to download webpage'
  616. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  617. if fatal:
  618. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  619. else:
  620. self.report_warning(errmsg)
  621. return False
  622. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None):
  623. """
  624. Return a tuple (page content as string, URL handle).
  625. See _download_webpage docstring for arguments specification.
  626. """
  627. # Strip hashes from the URL (#1038)
  628. if isinstance(url_or_request, (compat_str, str)):
  629. url_or_request = url_or_request.partition('#')[0]
  630. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query, expected_status=expected_status)
  631. if urlh is False:
  632. assert not fatal
  633. return False
  634. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  635. return (content, urlh)
  636. @staticmethod
  637. def _guess_encoding_from_content(content_type, webpage_bytes):
  638. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  639. if m:
  640. encoding = m.group(1)
  641. else:
  642. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  643. webpage_bytes[:1024])
  644. if m:
  645. encoding = m.group(1).decode('ascii')
  646. elif webpage_bytes.startswith(b'\xff\xfe'):
  647. encoding = 'utf-16'
  648. else:
  649. encoding = 'utf-8'
  650. return encoding
  651. def __check_blocked(self, content):
  652. first_block = content[:512]
  653. if ('<title>Access to this site is blocked</title>' in content
  654. and 'Websense' in first_block):
  655. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  656. blocked_iframe = self._html_search_regex(
  657. r'<iframe src="([^"]+)"', content,
  658. 'Websense information URL', default=None)
  659. if blocked_iframe:
  660. msg += ' Visit %s for more details' % blocked_iframe
  661. raise ExtractorError(msg, expected=True)
  662. if '<title>The URL you requested has been blocked</title>' in first_block:
  663. msg = (
  664. 'Access to this webpage has been blocked by Indian censorship. '
  665. 'Use a VPN or proxy server (with --proxy) to route around it.')
  666. block_msg = self._html_search_regex(
  667. r'</h1><p>(.*?)</p>',
  668. content, 'block message', default=None)
  669. if block_msg:
  670. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  671. raise ExtractorError(msg, expected=True)
  672. if ('<title>TTK :: Доступ к ресурсу ограничен</title>' in content
  673. and 'blocklist.rkn.gov.ru' in content):
  674. raise ExtractorError(
  675. 'Access to this webpage has been blocked by decision of the Russian government. '
  676. 'Visit http://blocklist.rkn.gov.ru/ for a block reason.',
  677. expected=True)
  678. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  679. content_type = urlh.headers.get('Content-Type', '')
  680. webpage_bytes = urlh.read()
  681. if prefix is not None:
  682. webpage_bytes = prefix + webpage_bytes
  683. if not encoding:
  684. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  685. if self.get_param('dump_intermediate_pages', False):
  686. self.to_screen('Dumping request to ' + urlh.geturl())
  687. dump = base64.b64encode(webpage_bytes).decode('ascii')
  688. self.to_screen(dump)
  689. if self.get_param('write_pages', False):
  690. basen = '%s_%s' % (video_id, urlh.geturl())
  691. if len(basen) > 240:
  692. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  693. basen = basen[:240 - len(h)] + h
  694. raw_filename = basen + '.dump'
  695. filename = sanitize_filename(raw_filename, restricted=True)
  696. self.to_screen('Saving request to ' + filename)
  697. # Working around MAX_PATH limitation on Windows (see
  698. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  699. if compat_os_name == 'nt':
  700. absfilepath = os.path.abspath(filename)
  701. if len(absfilepath) > 259:
  702. filename = '\\\\?\\' + absfilepath
  703. with open(filename, 'wb') as outf:
  704. outf.write(webpage_bytes)
  705. try:
  706. content = webpage_bytes.decode(encoding, 'replace')
  707. except LookupError:
  708. content = webpage_bytes.decode('utf-8', 'replace')
  709. self.__check_blocked(content)
  710. return content
  711. def _download_webpage(
  712. self, url_or_request, video_id, note=None, errnote=None,
  713. fatal=True, tries=1, timeout=5, encoding=None, data=None,
  714. headers={}, query={}, expected_status=None):
  715. """
  716. Return the data of the page as a string.
  717. Arguments:
  718. url_or_request -- plain text URL as a string or
  719. a compat_urllib_request.Requestobject
  720. video_id -- Video/playlist/item identifier (string)
  721. Keyword arguments:
  722. note -- note printed before downloading (string)
  723. errnote -- note printed in case of an error (string)
  724. fatal -- flag denoting whether error should be considered fatal,
  725. i.e. whether it should cause ExtractionError to be raised,
  726. otherwise a warning will be reported and extraction continued
  727. tries -- number of tries
  728. timeout -- sleep interval between tries
  729. encoding -- encoding for a page content decoding, guessed automatically
  730. when not explicitly specified
  731. data -- POST data (bytes)
  732. headers -- HTTP headers (dict)
  733. query -- URL query (dict)
  734. expected_status -- allows to accept failed HTTP requests (non 2xx
  735. status code) by explicitly specifying a set of accepted status
  736. codes. Can be any of the following entities:
  737. - an integer type specifying an exact failed status code to
  738. accept
  739. - a list or a tuple of integer types specifying a list of
  740. failed status codes to accept
  741. - a callable accepting an actual failed status code and
  742. returning True if it should be accepted
  743. Note that this argument does not affect success status codes (2xx)
  744. which are always accepted.
  745. """
  746. success = False
  747. try_count = 0
  748. while success is False:
  749. try:
  750. res = self._download_webpage_handle(
  751. url_or_request, video_id, note, errnote, fatal,
  752. encoding=encoding, data=data, headers=headers, query=query,
  753. expected_status=expected_status)
  754. success = True
  755. except compat_http_client.IncompleteRead as e:
  756. try_count += 1
  757. if try_count >= tries:
  758. raise e
  759. self._sleep(timeout, video_id)
  760. if res is False:
  761. return res
  762. else:
  763. content, _ = res
  764. return content
  765. def _download_xml_handle(
  766. self, url_or_request, video_id, note='Downloading XML',
  767. errnote='Unable to download XML', transform_source=None,
  768. fatal=True, encoding=None, data=None, headers={}, query={},
  769. expected_status=None):
  770. """
  771. Return a tuple (xml as an compat_etree_Element, URL handle).
  772. See _download_webpage docstring for arguments specification.
  773. """
  774. res = self._download_webpage_handle(
  775. url_or_request, video_id, note, errnote, fatal=fatal,
  776. encoding=encoding, data=data, headers=headers, query=query,
  777. expected_status=expected_status)
  778. if res is False:
  779. return res
  780. xml_string, urlh = res
  781. return self._parse_xml(
  782. xml_string, video_id, transform_source=transform_source,
  783. fatal=fatal), urlh
  784. def _download_xml(
  785. self, url_or_request, video_id,
  786. note='Downloading XML', errnote='Unable to download XML',
  787. transform_source=None, fatal=True, encoding=None,
  788. data=None, headers={}, query={}, expected_status=None):
  789. """
  790. Return the xml as an compat_etree_Element.
  791. See _download_webpage docstring for arguments specification.
  792. """
  793. res = self._download_xml_handle(
  794. url_or_request, video_id, note=note, errnote=errnote,
  795. transform_source=transform_source, fatal=fatal, encoding=encoding,
  796. data=data, headers=headers, query=query,
  797. expected_status=expected_status)
  798. return res if res is False else res[0]
  799. def _parse_xml(self, xml_string, video_id, transform_source=None, fatal=True):
  800. if transform_source:
  801. xml_string = transform_source(xml_string)
  802. try:
  803. return compat_etree_fromstring(xml_string.encode('utf-8'))
  804. except compat_xml_parse_error as ve:
  805. errmsg = '%s: Failed to parse XML ' % video_id
  806. if fatal:
  807. raise ExtractorError(errmsg, cause=ve)
  808. else:
  809. self.report_warning(errmsg + str(ve))
  810. def _download_json_handle(
  811. self, url_or_request, video_id, note='Downloading JSON metadata',
  812. errnote='Unable to download JSON metadata', transform_source=None,
  813. fatal=True, encoding=None, data=None, headers={}, query={},
  814. expected_status=None):
  815. """
  816. Return a tuple (JSON object, URL handle).
  817. See _download_webpage docstring for arguments specification.
  818. """
  819. res = self._download_webpage_handle(
  820. url_or_request, video_id, note, errnote, fatal=fatal,
  821. encoding=encoding, data=data, headers=headers, query=query,
  822. expected_status=expected_status)
  823. if res is False:
  824. return res
  825. json_string, urlh = res
  826. return self._parse_json(
  827. json_string, video_id, transform_source=transform_source,
  828. fatal=fatal), urlh
  829. def _download_json(
  830. self, url_or_request, video_id, note='Downloading JSON metadata',
  831. errnote='Unable to download JSON metadata', transform_source=None,
  832. fatal=True, encoding=None, data=None, headers={}, query={},
  833. expected_status=None):
  834. """
  835. Return the JSON object as a dict.
  836. See _download_webpage docstring for arguments specification.
  837. """
  838. res = self._download_json_handle(
  839. url_or_request, video_id, note=note, errnote=errnote,
  840. transform_source=transform_source, fatal=fatal, encoding=encoding,
  841. data=data, headers=headers, query=query,
  842. expected_status=expected_status)
  843. return res if res is False else res[0]
  844. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  845. if transform_source:
  846. json_string = transform_source(json_string)
  847. try:
  848. return json.loads(json_string)
  849. except ValueError as ve:
  850. errmsg = '%s: Failed to parse JSON ' % video_id
  851. if fatal:
  852. raise ExtractorError(errmsg, cause=ve)
  853. else:
  854. self.report_warning(errmsg + str(ve))
  855. def __ie_msg(self, *msg):
  856. return '[{0}] {1}'.format(self.IE_NAME, ''.join(msg))
  857. # msg, video_id=None, *args, only_once=False, **kwargs
  858. def report_warning(self, msg, *args, **kwargs):
  859. if len(args) > 0:
  860. video_id = args[0]
  861. args = args[1:]
  862. else:
  863. video_id = kwargs.pop('video_id', None)
  864. idstr = '' if video_id is None else '%s: ' % video_id
  865. self._downloader.report_warning(
  866. self.__ie_msg(idstr, msg), *args, **kwargs)
  867. def to_screen(self, msg):
  868. """Print msg to screen, prefixing it with '[ie_name]'"""
  869. self._downloader.to_screen(self.__ie_msg(msg))
  870. def write_debug(self, msg, only_once=False):
  871. '''Log debug message or Print message to stderr'''
  872. self._downloader.write_debug(self.__ie_msg(msg), only_once=only_once)
  873. # name, default=None, *args, **kwargs
  874. def get_param(self, name, *args, **kwargs):
  875. default, args = (args[0], args[1:]) if len(args) > 0 else (kwargs.pop('default', None), args)
  876. if self._downloader:
  877. return self._downloader.params.get(name, default, *args, **kwargs)
  878. return default
  879. def report_drm(self, video_id):
  880. self.raise_no_formats('This video is DRM protected', expected=True, video_id=video_id)
  881. def report_extraction(self, id_or_name):
  882. """Report information extraction."""
  883. self.to_screen('%s: Extracting information' % id_or_name)
  884. def report_download_webpage(self, video_id):
  885. """Report webpage download."""
  886. self.to_screen('%s: Downloading webpage' % video_id)
  887. def report_age_confirmation(self):
  888. """Report attempt to confirm age."""
  889. self.to_screen('Confirming age')
  890. def report_login(self):
  891. """Report attempt to log in."""
  892. self.to_screen('Logging in')
  893. @staticmethod
  894. def raise_login_required(msg='This video is only available for registered users'):
  895. raise ExtractorError(
  896. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  897. expected=True)
  898. @staticmethod
  899. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction', countries=None):
  900. raise GeoRestrictedError(msg, countries=countries)
  901. def raise_no_formats(self, msg, expected=False, video_id=None):
  902. if expected and (
  903. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  904. self.report_warning(msg, video_id)
  905. elif isinstance(msg, ExtractorError):
  906. raise msg
  907. else:
  908. raise ExtractorError(msg, expected=expected, video_id=video_id)
  909. # Methods for following #608
  910. @staticmethod
  911. def url_result(url, ie=None, video_id=None, video_title=None):
  912. """Returns a URL that points to a page that should be processed"""
  913. # TODO: ie should be the class used for getting the info
  914. video_info = {'_type': 'url',
  915. 'url': url,
  916. 'ie_key': ie}
  917. if video_id is not None:
  918. video_info['id'] = video_id
  919. if video_title is not None:
  920. video_info['title'] = video_title
  921. return video_info
  922. def playlist_from_matches(self, matches, playlist_id=None, playlist_title=None, getter=None, ie=None):
  923. urls = orderedSet(
  924. self.url_result(self._proto_relative_url(getter(m) if getter else m), ie)
  925. for m in matches)
  926. return self.playlist_result(
  927. urls, playlist_id=playlist_id, playlist_title=playlist_title)
  928. @staticmethod
  929. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  930. """Returns a playlist"""
  931. video_info = {'_type': 'playlist',
  932. 'entries': entries}
  933. if playlist_id:
  934. video_info['id'] = playlist_id
  935. if playlist_title:
  936. video_info['title'] = playlist_title
  937. if playlist_description:
  938. video_info['description'] = playlist_description
  939. return video_info
  940. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  941. """
  942. Perform a regex search on the given string, using a single or a list of
  943. patterns returning the first matching group.
  944. In case of failure return a default value or raise a WARNING or a
  945. RegexNotFoundError, depending on fatal, specifying the field name.
  946. """
  947. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  948. mobj = re.search(pattern, string, flags)
  949. else:
  950. for p in pattern:
  951. mobj = re.search(p, string, flags)
  952. if mobj:
  953. break
  954. if not self.get_param('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  955. _name = '\033[0;34m%s\033[0m' % name
  956. else:
  957. _name = name
  958. if mobj:
  959. if group is None:
  960. # return the first matching group
  961. return next(g for g in mobj.groups() if g is not None)
  962. elif isinstance(group, (list, tuple)):
  963. return tuple(mobj.group(g) for g in group)
  964. else:
  965. return mobj.group(group)
  966. elif default is not NO_DEFAULT:
  967. return default
  968. elif fatal:
  969. raise RegexNotFoundError('Unable to extract %s' % _name)
  970. else:
  971. self.report_warning('unable to extract %s' % _name + bug_reports_message())
  972. return None
  973. def _search_json(self, start_pattern, string, name, video_id, **kwargs):
  974. """Searches string for the JSON object specified by start_pattern"""
  975. # self, start_pattern, string, name, video_id, *, end_pattern='',
  976. # contains_pattern=r'{(?s:.+)}', fatal=True, default=NO_DEFAULT
  977. # NB: end_pattern is only used to reduce the size of the initial match
  978. end_pattern = kwargs.pop('end_pattern', '')
  979. # (?:[\s\S]) simulates (?(s):.) (eg)
  980. contains_pattern = kwargs.pop('contains_pattern', r'{[\s\S]+}')
  981. fatal = kwargs.pop('fatal', True)
  982. default = kwargs.pop('default', NO_DEFAULT)
  983. if default is NO_DEFAULT:
  984. default, has_default = {}, False
  985. else:
  986. fatal, has_default = False, True
  987. json_string = self._search_regex(
  988. r'(?:{0})\s*(?P<json>{1})\s*(?:{2})'.format(
  989. start_pattern, contains_pattern, end_pattern),
  990. string, name, group='json', fatal=fatal, default=None if has_default else NO_DEFAULT)
  991. if not json_string:
  992. return default
  993. # yt-dlp has a special JSON parser that allows trailing text.
  994. # Until that arrives here, the diagnostic from the exception
  995. # raised by json.loads() is used to extract the wanted text.
  996. # Either way, it's a problem if a transform_source() can't
  997. # handle the trailing text.
  998. # force an exception
  999. kwargs['fatal'] = True
  1000. # self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1001. for _ in range(2):
  1002. try:
  1003. # return self._parse_json(json_string, video_id, ignore_extra=True, **kwargs)
  1004. transform_source = kwargs.pop('transform_source', None)
  1005. if transform_source:
  1006. json_string = transform_source(json_string)
  1007. return self._parse_json(json_string, video_id, **compat_kwargs(kwargs))
  1008. except ExtractorError as e:
  1009. end = int_or_none(self._search_regex(r'\(char\s+(\d+)', error_to_compat_str(e), 'end', default=None))
  1010. if end is not None:
  1011. json_string = json_string[:end]
  1012. continue
  1013. msg = 'Unable to extract {0} - Failed to parse JSON'.format(name)
  1014. if fatal:
  1015. raise ExtractorError(msg, cause=e.cause, video_id=video_id)
  1016. elif not has_default:
  1017. self.report_warning(
  1018. '{0}: {1}'.format(msg, error_to_compat_str(e)), video_id=video_id)
  1019. return default
  1020. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1021. """
  1022. Like _search_regex, but strips HTML tags and unescapes entities.
  1023. """
  1024. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  1025. if isinstance(res, tuple):
  1026. return tuple(map(clean_html, res))
  1027. return clean_html(res)
  1028. def _get_netrc_login_info(self, netrc_machine=None):
  1029. username = None
  1030. password = None
  1031. if self.get_param('usenetrc', False):
  1032. try:
  1033. netrc_machine = netrc_machine or self._NETRC_MACHINE
  1034. info = netrc.netrc().authenticators(netrc_machine)
  1035. if info is not None:
  1036. username = info[0]
  1037. password = info[2]
  1038. else:
  1039. raise netrc.NetrcParseError(
  1040. 'No authenticators for %s' % netrc_machine)
  1041. except (AttributeError, IOError, netrc.NetrcParseError) as err:
  1042. self.report_warning(
  1043. 'parsing .netrc: %s' % error_to_compat_str(err))
  1044. return username, password
  1045. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  1046. """
  1047. Get the login info as (username, password)
  1048. First look for the manually specified credentials using username_option
  1049. and password_option as keys in params dictionary. If no such credentials
  1050. available look in the netrc file using the netrc_machine or _NETRC_MACHINE
  1051. value.
  1052. If there's no info available, return (None, None)
  1053. """
  1054. if self._downloader is None:
  1055. return (None, None)
  1056. downloader_params = self._downloader.params
  1057. # Attempt to use provided username and password or .netrc data
  1058. if downloader_params.get(username_option) is not None:
  1059. username = downloader_params[username_option]
  1060. password = downloader_params[password_option]
  1061. else:
  1062. username, password = self._get_netrc_login_info(netrc_machine)
  1063. return username, password
  1064. def _get_tfa_info(self, note='two-factor verification code'):
  1065. """
  1066. Get the two-factor authentication info
  1067. TODO - asking the user will be required for sms/phone verify
  1068. currently just uses the command line option
  1069. If there's no info available, return None
  1070. """
  1071. if self._downloader is None:
  1072. return None
  1073. twofactor = self.get_param('twofactor')
  1074. if twofactor is not None:
  1075. return twofactor
  1076. return compat_getpass('Type %s and press [Return]: ' % note)
  1077. # Helper functions for extracting OpenGraph info
  1078. @staticmethod
  1079. def _og_regexes(prop):
  1080. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))'
  1081. property_re = (r'(?:name|property)=(?:\'og[:-]%(prop)s\'|"og[:-]%(prop)s"|\s*og[:-]%(prop)s\b)'
  1082. % {'prop': re.escape(prop)})
  1083. template = r'<meta[^>]+?%s[^>]+?%s'
  1084. return [
  1085. template % (property_re, content_re),
  1086. template % (content_re, property_re),
  1087. ]
  1088. @staticmethod
  1089. def _meta_regex(prop):
  1090. return r'''(?isx)<meta
  1091. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  1092. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  1093. def _og_search_property(self, prop, html, name=None, **kargs):
  1094. if not isinstance(prop, (list, tuple)):
  1095. prop = [prop]
  1096. if name is None:
  1097. name = 'OpenGraph %s' % prop[0]
  1098. og_regexes = []
  1099. for p in prop:
  1100. og_regexes.extend(self._og_regexes(p))
  1101. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  1102. if escaped is None:
  1103. return None
  1104. return unescapeHTML(escaped)
  1105. def _og_search_thumbnail(self, html, **kargs):
  1106. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  1107. def _og_search_description(self, html, **kargs):
  1108. return self._og_search_property('description', html, fatal=False, **kargs)
  1109. def _og_search_title(self, html, **kargs):
  1110. return self._og_search_property('title', html, **kargs)
  1111. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  1112. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  1113. if secure:
  1114. regexes = self._og_regexes('video:secure_url') + regexes
  1115. return self._html_search_regex(regexes, html, name, **kargs)
  1116. def _og_search_url(self, html, **kargs):
  1117. return self._og_search_property('url', html, **kargs)
  1118. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  1119. if not isinstance(name, (list, tuple)):
  1120. name = [name]
  1121. if display_name is None:
  1122. display_name = name[0]
  1123. return self._html_search_regex(
  1124. [self._meta_regex(n) for n in name],
  1125. html, display_name, fatal=fatal, group='content', **kwargs)
  1126. def _dc_search_uploader(self, html):
  1127. return self._html_search_meta('dc.creator', html, 'uploader')
  1128. def _rta_search(self, html):
  1129. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  1130. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  1131. r' content="RTA-5042-1996-1400-1577-RTA"',
  1132. html):
  1133. return 18
  1134. return 0
  1135. def _media_rating_search(self, html):
  1136. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  1137. rating = self._html_search_meta('rating', html)
  1138. if not rating:
  1139. return None
  1140. RATING_TABLE = {
  1141. 'safe for kids': 0,
  1142. 'general': 8,
  1143. '14 years': 14,
  1144. 'mature': 17,
  1145. 'restricted': 19,
  1146. }
  1147. return RATING_TABLE.get(rating.lower())
  1148. def _family_friendly_search(self, html):
  1149. # See http://schema.org/VideoObject
  1150. family_friendly = self._html_search_meta(
  1151. 'isFamilyFriendly', html, default=None)
  1152. if not family_friendly:
  1153. return None
  1154. RATING_TABLE = {
  1155. '1': 0,
  1156. 'true': 0,
  1157. '0': 18,
  1158. 'false': 18,
  1159. }
  1160. return RATING_TABLE.get(family_friendly.lower())
  1161. def _twitter_search_player(self, html):
  1162. return self._html_search_meta('twitter:player', html,
  1163. 'twitter card player')
  1164. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  1165. json_ld_list = list(re.finditer(JSON_LD_RE, html))
  1166. default = kwargs.get('default', NO_DEFAULT)
  1167. # JSON-LD may be malformed and thus `fatal` should be respected.
  1168. # At the same time `default` may be passed that assumes `fatal=False`
  1169. # for _search_regex. Let's simulate the same behavior here as well.
  1170. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  1171. json_ld = []
  1172. for mobj in json_ld_list:
  1173. json_ld_item = self._parse_json(
  1174. mobj.group('json_ld'), video_id, fatal=fatal)
  1175. if not json_ld_item:
  1176. continue
  1177. if isinstance(json_ld_item, dict):
  1178. json_ld.append(json_ld_item)
  1179. elif isinstance(json_ld_item, (list, tuple)):
  1180. json_ld.extend(json_ld_item)
  1181. if json_ld:
  1182. json_ld = self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  1183. if json_ld:
  1184. return json_ld
  1185. if default is not NO_DEFAULT:
  1186. return default
  1187. elif fatal:
  1188. raise RegexNotFoundError('Unable to extract JSON-LD')
  1189. else:
  1190. self.report_warning('unable to extract JSON-LD %s' % bug_reports_message())
  1191. return {}
  1192. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  1193. if isinstance(json_ld, compat_str):
  1194. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  1195. if not json_ld:
  1196. return {}
  1197. info = {}
  1198. if not isinstance(json_ld, (list, tuple, dict)):
  1199. return info
  1200. if isinstance(json_ld, dict):
  1201. json_ld = [json_ld]
  1202. INTERACTION_TYPE_MAP = {
  1203. 'CommentAction': 'comment',
  1204. 'AgreeAction': 'like',
  1205. 'DisagreeAction': 'dislike',
  1206. 'LikeAction': 'like',
  1207. 'DislikeAction': 'dislike',
  1208. 'ListenAction': 'view',
  1209. 'WatchAction': 'view',
  1210. 'ViewAction': 'view',
  1211. }
  1212. def extract_interaction_type(e):
  1213. interaction_type = e.get('interactionType')
  1214. if isinstance(interaction_type, dict):
  1215. interaction_type = interaction_type.get('@type')
  1216. return str_or_none(interaction_type)
  1217. def extract_interaction_statistic(e):
  1218. interaction_statistic = e.get('interactionStatistic')
  1219. if isinstance(interaction_statistic, dict):
  1220. interaction_statistic = [interaction_statistic]
  1221. if not isinstance(interaction_statistic, list):
  1222. return
  1223. for is_e in interaction_statistic:
  1224. if not isinstance(is_e, dict):
  1225. continue
  1226. if is_e.get('@type') != 'InteractionCounter':
  1227. continue
  1228. interaction_type = extract_interaction_type(is_e)
  1229. if not interaction_type:
  1230. continue
  1231. # For interaction count some sites provide string instead of
  1232. # an integer (as per spec) with non digit characters (e.g. ",")
  1233. # so extracting count with more relaxed str_to_int
  1234. interaction_count = str_to_int(is_e.get('userInteractionCount'))
  1235. if interaction_count is None:
  1236. continue
  1237. count_kind = INTERACTION_TYPE_MAP.get(interaction_type.split('/')[-1])
  1238. if not count_kind:
  1239. continue
  1240. count_key = '%s_count' % count_kind
  1241. if info.get(count_key) is not None:
  1242. continue
  1243. info[count_key] = interaction_count
  1244. def extract_video_object(e):
  1245. assert e['@type'] == 'VideoObject'
  1246. author = e.get('author')
  1247. info.update({
  1248. 'url': url_or_none(e.get('contentUrl')),
  1249. 'title': unescapeHTML(e.get('name')),
  1250. 'description': unescapeHTML(e.get('description')),
  1251. 'thumbnail': url_or_none(e.get('thumbnailUrl') or e.get('thumbnailURL')),
  1252. 'duration': parse_duration(e.get('duration')),
  1253. 'timestamp': unified_timestamp(e.get('uploadDate')),
  1254. # author can be an instance of 'Organization' or 'Person' types.
  1255. # both types can have 'name' property(inherited from 'Thing' type). [1]
  1256. # however some websites are using 'Text' type instead.
  1257. # 1. https://schema.org/VideoObject
  1258. 'uploader': author.get('name') if isinstance(author, dict) else author if isinstance(author, compat_str) else None,
  1259. 'filesize': float_or_none(e.get('contentSize')),
  1260. 'tbr': int_or_none(e.get('bitrate')),
  1261. 'width': int_or_none(e.get('width')),
  1262. 'height': int_or_none(e.get('height')),
  1263. 'view_count': int_or_none(e.get('interactionCount')),
  1264. })
  1265. extract_interaction_statistic(e)
  1266. for e in json_ld:
  1267. if '@context' in e:
  1268. item_type = e.get('@type')
  1269. if expected_type is not None and expected_type != item_type:
  1270. continue
  1271. if item_type in ('TVEpisode', 'Episode'):
  1272. episode_name = unescapeHTML(e.get('name'))
  1273. info.update({
  1274. 'episode': episode_name,
  1275. 'episode_number': int_or_none(e.get('episodeNumber')),
  1276. 'description': unescapeHTML(e.get('description')),
  1277. })
  1278. if not info.get('title') and episode_name:
  1279. info['title'] = episode_name
  1280. part_of_season = e.get('partOfSeason')
  1281. if isinstance(part_of_season, dict) and part_of_season.get('@type') in ('TVSeason', 'Season', 'CreativeWorkSeason'):
  1282. info.update({
  1283. 'season': unescapeHTML(part_of_season.get('name')),
  1284. 'season_number': int_or_none(part_of_season.get('seasonNumber')),
  1285. })
  1286. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  1287. if isinstance(part_of_series, dict) and part_of_series.get('@type') in ('TVSeries', 'Series', 'CreativeWorkSeries'):
  1288. info['series'] = unescapeHTML(part_of_series.get('name'))
  1289. elif item_type == 'Movie':
  1290. info.update({
  1291. 'title': unescapeHTML(e.get('name')),
  1292. 'description': unescapeHTML(e.get('description')),
  1293. 'duration': parse_duration(e.get('duration')),
  1294. 'timestamp': unified_timestamp(e.get('dateCreated')),
  1295. })
  1296. elif item_type in ('Article', 'NewsArticle'):
  1297. info.update({
  1298. 'timestamp': parse_iso8601(e.get('datePublished')),
  1299. 'title': unescapeHTML(e.get('headline')),
  1300. 'description': unescapeHTML(e.get('articleBody')),
  1301. })
  1302. elif item_type == 'VideoObject':
  1303. extract_video_object(e)
  1304. if expected_type is None:
  1305. continue
  1306. else:
  1307. break
  1308. video = e.get('video')
  1309. if isinstance(video, dict) and video.get('@type') == 'VideoObject':
  1310. extract_video_object(video)
  1311. if expected_type is None:
  1312. continue
  1313. else:
  1314. break
  1315. return dict((k, v) for k, v in info.items() if v is not None)
  1316. def _search_nextjs_data(self, webpage, video_id, **kw):
  1317. # ..., *, transform_source=None, fatal=True, default=NO_DEFAULT
  1318. # TODO: remove this backward compat
  1319. default = kw.get('default', NO_DEFAULT)
  1320. if default == '{}':
  1321. kw['default'] = {}
  1322. kw = compat_kwargs(kw)
  1323. return self._search_json(
  1324. r'''<script\s[^>]*?\bid\s*=\s*('|")__NEXT_DATA__\1[^>]*>''',
  1325. webpage, 'next.js data', video_id, end_pattern='</script>',
  1326. **kw)
  1327. def _search_nuxt_data(self, webpage, video_id, *args, **kwargs):
  1328. """Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure function"""
  1329. # self, webpage, video_id, context_name='__NUXT__', *, fatal=True, traverse=('data', 0)
  1330. context_name = args[0] if len(args) > 0 else kwargs.get('context_name', '__NUXT__')
  1331. fatal = kwargs.get('fatal', True)
  1332. traverse = kwargs.get('traverse', ('data', 0))
  1333. re_ctx = re.escape(context_name)
  1334. FUNCTION_RE = (r'\(\s*function\s*\((?P<arg_keys>[\s\S]*?)\)\s*\{\s*'
  1335. r'return\s+(?P<js>\{[\s\S]*?})\s*;?\s*}\s*\((?P<arg_vals>[\s\S]*?)\)')
  1336. js, arg_keys, arg_vals = self._search_regex(
  1337. (p.format(re_ctx, FUNCTION_RE) for p in
  1338. (r'<script>\s*window\s*\.\s*{0}\s*=\s*{1}\s*\)\s*;?\s*</script>',
  1339. r'{0}\s*\([\s\S]*?{1}')),
  1340. webpage, context_name, group=('js', 'arg_keys', 'arg_vals'),
  1341. default=NO_DEFAULT if fatal else (None, None, None))
  1342. if js is None:
  1343. return {}
  1344. args = dict(zip(arg_keys.split(','), map(json.dumps, self._parse_json(
  1345. '[{0}]'.format(arg_vals), video_id, transform_source=js_to_json, fatal=fatal) or ())))
  1346. ret = self._parse_json(js, video_id, transform_source=functools.partial(js_to_json, vars=args), fatal=fatal)
  1347. return traverse_obj(ret, traverse) or {}
  1348. @staticmethod
  1349. def _hidden_inputs(html):
  1350. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  1351. hidden_inputs = {}
  1352. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  1353. attrs = extract_attributes(input)
  1354. if not input:
  1355. continue
  1356. if attrs.get('type') not in ('hidden', 'submit'):
  1357. continue
  1358. name = attrs.get('name') or attrs.get('id')
  1359. value = attrs.get('value')
  1360. if name and value is not None:
  1361. hidden_inputs[name] = value
  1362. return hidden_inputs
  1363. def _form_hidden_inputs(self, form_id, html):
  1364. form = self._search_regex(
  1365. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  1366. html, '%s form' % form_id, group='form')
  1367. return self._hidden_inputs(form)
  1368. def _sort_formats(self, formats, field_preference=None):
  1369. if not formats:
  1370. raise ExtractorError('No video formats found')
  1371. for f in formats:
  1372. # Automatically determine tbr when missing based on abr and vbr (improves
  1373. # formats sorting in some cases)
  1374. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  1375. f['tbr'] = f['abr'] + f['vbr']
  1376. def _formats_key(f):
  1377. # TODO remove the following workaround
  1378. from ..utils import determine_ext
  1379. if not f.get('ext') and 'url' in f:
  1380. f['ext'] = determine_ext(f['url'])
  1381. if isinstance(field_preference, (list, tuple)):
  1382. return tuple(
  1383. f.get(field)
  1384. if f.get(field) is not None
  1385. else ('' if field == 'format_id' else -1)
  1386. for field in field_preference)
  1387. preference = f.get('preference')
  1388. if preference is None:
  1389. preference = 0
  1390. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  1391. preference -= 0.5
  1392. protocol = f.get('protocol') or determine_protocol(f)
  1393. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  1394. if f.get('vcodec') == 'none': # audio only
  1395. preference -= 50
  1396. if self.get_param('prefer_free_formats'):
  1397. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  1398. else:
  1399. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  1400. ext_preference = 0
  1401. try:
  1402. audio_ext_preference = ORDER.index(f['ext'])
  1403. except ValueError:
  1404. audio_ext_preference = -1
  1405. else:
  1406. if f.get('acodec') == 'none': # video only
  1407. preference -= 40
  1408. if self.get_param('prefer_free_formats'):
  1409. ORDER = ['flv', 'mp4', 'webm']
  1410. else:
  1411. ORDER = ['webm', 'flv', 'mp4']
  1412. try:
  1413. ext_preference = ORDER.index(f['ext'])
  1414. except ValueError:
  1415. ext_preference = -1
  1416. audio_ext_preference = 0
  1417. return (
  1418. preference,
  1419. f.get('language_preference') if f.get('language_preference') is not None else -1,
  1420. f.get('quality') if f.get('quality') is not None else -1,
  1421. f.get('tbr') if f.get('tbr') is not None else -1,
  1422. f.get('filesize') if f.get('filesize') is not None else -1,
  1423. f.get('vbr') if f.get('vbr') is not None else -1,
  1424. f.get('height') if f.get('height') is not None else -1,
  1425. f.get('width') if f.get('width') is not None else -1,
  1426. proto_preference,
  1427. ext_preference,
  1428. f.get('abr') if f.get('abr') is not None else -1,
  1429. audio_ext_preference,
  1430. f.get('fps') if f.get('fps') is not None else -1,
  1431. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  1432. f.get('source_preference') if f.get('source_preference') is not None else -1,
  1433. f.get('format_id') if f.get('format_id') is not None else '',
  1434. )
  1435. formats.sort(key=_formats_key)
  1436. def _check_formats(self, formats, video_id):
  1437. if formats:
  1438. formats[:] = filter(
  1439. lambda f: self._is_valid_url(
  1440. f['url'], video_id,
  1441. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  1442. formats)
  1443. @staticmethod
  1444. def _remove_duplicate_formats(formats):
  1445. format_urls = set()
  1446. unique_formats = []
  1447. for f in formats:
  1448. if f['url'] not in format_urls:
  1449. format_urls.add(f['url'])
  1450. unique_formats.append(f)
  1451. formats[:] = unique_formats
  1452. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1453. url = self._proto_relative_url(url, scheme='http:')
  1454. # For now assume non HTTP(S) URLs always valid
  1455. if not (url.startswith('http://') or url.startswith('https://')):
  1456. return True
  1457. try:
  1458. self._request_webpage(url, video_id, 'Checking %s URL' % item, headers=headers)
  1459. return True
  1460. except ExtractorError as e:
  1461. self.to_screen(
  1462. '%s: %s URL is invalid, skipping: %s'
  1463. % (video_id, item, error_to_compat_str(e.cause)))
  1464. return False
  1465. def http_scheme(self):
  1466. """ Either "http:" or "https:", depending on the user's preferences """
  1467. return (
  1468. 'http:'
  1469. if self.get_param('prefer_insecure', False)
  1470. else 'https:')
  1471. def _proto_relative_url(self, url, scheme=None):
  1472. if url is None:
  1473. return url
  1474. if url.startswith('//'):
  1475. if scheme is None:
  1476. scheme = self.http_scheme()
  1477. return scheme + url
  1478. else:
  1479. return url
  1480. def _sleep(self, timeout, video_id, msg_template=None):
  1481. if msg_template is None:
  1482. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1483. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1484. self.to_screen(msg)
  1485. time.sleep(timeout)
  1486. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  1487. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1488. fatal=True, m3u8_id=None, data=None, headers={}, query={}):
  1489. manifest = self._download_xml(
  1490. manifest_url, video_id, 'Downloading f4m manifest',
  1491. 'Unable to download f4m manifest',
  1492. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1493. # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244)
  1494. transform_source=transform_source,
  1495. fatal=fatal, data=data, headers=headers, query=query)
  1496. if manifest is False:
  1497. return []
  1498. return self._parse_f4m_formats(
  1499. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1500. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1501. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  1502. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1503. fatal=True, m3u8_id=None):
  1504. if not isinstance(manifest, compat_etree_Element) and not fatal:
  1505. return []
  1506. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1507. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1508. if akamai_pv is not None and ';' in akamai_pv.text:
  1509. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  1510. if playerVerificationChallenge.strip() != '':
  1511. return []
  1512. formats = []
  1513. manifest_version = '1.0'
  1514. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1515. if not media_nodes:
  1516. manifest_version = '2.0'
  1517. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1518. # Remove unsupported DRM protected media from final formats
  1519. # rendition (see https://github.com/ytdl-org/youtube-dl/issues/8573).
  1520. media_nodes = remove_encrypted_media(media_nodes)
  1521. if not media_nodes:
  1522. return formats
  1523. manifest_base_url = get_base_url(manifest)
  1524. bootstrap_info = xpath_element(
  1525. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1526. 'bootstrap info', default=None)
  1527. vcodec = None
  1528. mime_type = xpath_text(
  1529. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1530. 'base URL', default=None)
  1531. if mime_type and mime_type.startswith('audio/'):
  1532. vcodec = 'none'
  1533. for i, media_el in enumerate(media_nodes):
  1534. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1535. width = int_or_none(media_el.attrib.get('width'))
  1536. height = int_or_none(media_el.attrib.get('height'))
  1537. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  1538. # If <bootstrapInfo> is present, the specified f4m is a
  1539. # stream-level manifest, and only set-level manifests may refer to
  1540. # external resources. See section 11.4 and section 4 of F4M spec
  1541. if bootstrap_info is None:
  1542. media_url = None
  1543. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1544. if manifest_version == '2.0':
  1545. media_url = media_el.attrib.get('href')
  1546. if media_url is None:
  1547. media_url = media_el.attrib.get('url')
  1548. if not media_url:
  1549. continue
  1550. manifest_url = (
  1551. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1552. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1553. # If media_url is itself a f4m manifest do the recursive extraction
  1554. # since bitrates in parent manifest (this one) and media_url manifest
  1555. # may differ leading to inability to resolve the format by requested
  1556. # bitrate in f4m downloader
  1557. ext = determine_ext(manifest_url)
  1558. if ext == 'f4m':
  1559. f4m_formats = self._extract_f4m_formats(
  1560. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1561. transform_source=transform_source, fatal=fatal)
  1562. # Sometimes stream-level manifest contains single media entry that
  1563. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1564. # At the same time parent's media entry in set-level manifest may
  1565. # contain it. We will copy it from parent in such cases.
  1566. if len(f4m_formats) == 1:
  1567. f = f4m_formats[0]
  1568. f.update({
  1569. 'tbr': f.get('tbr') or tbr,
  1570. 'width': f.get('width') or width,
  1571. 'height': f.get('height') or height,
  1572. 'format_id': f.get('format_id') if not tbr else format_id,
  1573. 'vcodec': vcodec,
  1574. })
  1575. formats.extend(f4m_formats)
  1576. continue
  1577. elif ext == 'm3u8':
  1578. formats.extend(self._extract_m3u8_formats(
  1579. manifest_url, video_id, 'mp4', preference=preference,
  1580. m3u8_id=m3u8_id, fatal=fatal))
  1581. continue
  1582. formats.append({
  1583. 'format_id': format_id,
  1584. 'url': manifest_url,
  1585. 'manifest_url': manifest_url,
  1586. 'ext': 'flv' if bootstrap_info is not None else None,
  1587. 'protocol': 'f4m',
  1588. 'tbr': tbr,
  1589. 'width': width,
  1590. 'height': height,
  1591. 'vcodec': vcodec,
  1592. 'preference': preference,
  1593. })
  1594. return formats
  1595. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1596. return {
  1597. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1598. 'url': m3u8_url,
  1599. 'ext': ext,
  1600. 'protocol': 'm3u8',
  1601. 'preference': preference - 100 if preference else -100,
  1602. 'resolution': 'multiple',
  1603. 'format_note': 'Quality selection URL',
  1604. }
  1605. def _report_ignoring_subs(self, name):
  1606. self.report_warning(bug_reports_message(
  1607. 'Ignoring subtitle tracks found in the {0} manifest; '
  1608. 'if any subtitle tracks are missing,'.format(name)
  1609. ), only_once=True)
  1610. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1611. entry_protocol='m3u8', preference=None,
  1612. m3u8_id=None, note=None, errnote=None,
  1613. fatal=True, live=False, data=None, headers={},
  1614. query={}):
  1615. res = self._download_webpage_handle(
  1616. m3u8_url, video_id,
  1617. note=note or 'Downloading m3u8 information',
  1618. errnote=errnote or 'Failed to download m3u8 information',
  1619. fatal=fatal, data=data, headers=headers, query=query)
  1620. if res is False:
  1621. return []
  1622. m3u8_doc, urlh = res
  1623. m3u8_url = urlh.geturl()
  1624. return self._parse_m3u8_formats(
  1625. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1626. preference=preference, m3u8_id=m3u8_id, live=live)
  1627. def _parse_m3u8_formats(self, m3u8_doc, m3u8_url, ext=None,
  1628. entry_protocol='m3u8', preference=None,
  1629. m3u8_id=None, live=False):
  1630. if '#EXT-X-FAXS-CM:' in m3u8_doc: # Adobe Flash Access
  1631. return []
  1632. if re.search(r'#EXT-X-SESSION-KEY:.*?URI="skd://', m3u8_doc): # Apple FairPlay
  1633. return []
  1634. formats = []
  1635. format_url = lambda u: (
  1636. u
  1637. if re.match(r'^https?://', u)
  1638. else compat_urlparse.urljoin(m3u8_url, u))
  1639. # References:
  1640. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1641. # 2. https://github.com/ytdl-org/youtube-dl/issues/12211
  1642. # 3. https://github.com/ytdl-org/youtube-dl/issues/18923
  1643. # We should try extracting formats only from master playlists [1, 4.3.4],
  1644. # i.e. playlists that describe available qualities. On the other hand
  1645. # media playlists [1, 4.3.3] should be returned as is since they contain
  1646. # just the media without qualities renditions.
  1647. # Fortunately, master playlist can be easily distinguished from media
  1648. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1649. # master playlist tags MUST NOT appear in a media playlist and vice versa.
  1650. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1651. # media playlist and MUST NOT appear in master playlist thus we can
  1652. # clearly detect media playlist with this criterion.
  1653. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1654. return [{
  1655. 'url': m3u8_url,
  1656. 'format_id': m3u8_id,
  1657. 'ext': ext,
  1658. 'protocol': entry_protocol,
  1659. 'preference': preference,
  1660. }]
  1661. groups = {}
  1662. last_stream_inf = {}
  1663. def extract_media(x_media_line):
  1664. media = parse_m3u8_attributes(x_media_line)
  1665. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1666. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1667. if not (media_type and group_id and name):
  1668. return
  1669. groups.setdefault(group_id, []).append(media)
  1670. if media_type not in ('VIDEO', 'AUDIO'):
  1671. return
  1672. media_url = media.get('URI')
  1673. if media_url:
  1674. format_id = []
  1675. for v in (m3u8_id, group_id, name):
  1676. if v:
  1677. format_id.append(v)
  1678. f = {
  1679. 'format_id': '-'.join(format_id),
  1680. 'url': format_url(media_url),
  1681. 'manifest_url': m3u8_url,
  1682. 'language': media.get('LANGUAGE'),
  1683. 'ext': ext,
  1684. 'protocol': entry_protocol,
  1685. 'preference': preference,
  1686. }
  1687. if media_type == 'AUDIO':
  1688. f['vcodec'] = 'none'
  1689. formats.append(f)
  1690. def build_stream_name():
  1691. # Despite specification does not mention NAME attribute for
  1692. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1693. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1694. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1695. stream_name = last_stream_inf.get('NAME')
  1696. if stream_name:
  1697. return stream_name
  1698. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1699. # from corresponding rendition group
  1700. stream_group_id = last_stream_inf.get('VIDEO')
  1701. if not stream_group_id:
  1702. return
  1703. stream_group = groups.get(stream_group_id)
  1704. if not stream_group:
  1705. return stream_group_id
  1706. rendition = stream_group[0]
  1707. return rendition.get('NAME') or stream_group_id
  1708. # parse EXT-X-MEDIA tags before EXT-X-STREAM-INF in order to have the
  1709. # chance to detect video only formats when EXT-X-STREAM-INF tags
  1710. # precede EXT-X-MEDIA tags in HLS manifest such as [3].
  1711. for line in m3u8_doc.splitlines():
  1712. if line.startswith('#EXT-X-MEDIA:'):
  1713. extract_media(line)
  1714. for line in m3u8_doc.splitlines():
  1715. if line.startswith('#EXT-X-STREAM-INF:'):
  1716. last_stream_inf = parse_m3u8_attributes(line)
  1717. elif line.startswith('#') or not line.strip():
  1718. continue
  1719. else:
  1720. tbr = float_or_none(
  1721. last_stream_inf.get('AVERAGE-BANDWIDTH')
  1722. or last_stream_inf.get('BANDWIDTH'), scale=1000)
  1723. format_id = []
  1724. if m3u8_id:
  1725. format_id.append(m3u8_id)
  1726. stream_name = build_stream_name()
  1727. # Bandwidth of live streams may differ over time thus making
  1728. # format_id unpredictable. So it's better to keep provided
  1729. # format_id intact.
  1730. if not live:
  1731. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1732. manifest_url = format_url(line.strip())
  1733. f = {
  1734. 'format_id': '-'.join(format_id),
  1735. 'url': manifest_url,
  1736. 'manifest_url': m3u8_url,
  1737. 'tbr': tbr,
  1738. 'ext': ext,
  1739. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  1740. 'protocol': entry_protocol,
  1741. 'preference': preference,
  1742. }
  1743. resolution = last_stream_inf.get('RESOLUTION')
  1744. if resolution:
  1745. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1746. if mobj:
  1747. f['width'] = int(mobj.group('width'))
  1748. f['height'] = int(mobj.group('height'))
  1749. # Unified Streaming Platform
  1750. mobj = re.search(
  1751. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1752. if mobj:
  1753. abr, vbr = mobj.groups()
  1754. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1755. f.update({
  1756. 'vbr': vbr,
  1757. 'abr': abr,
  1758. })
  1759. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  1760. f.update(codecs)
  1761. audio_group_id = last_stream_inf.get('AUDIO')
  1762. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  1763. # references a rendition group MUST have a CODECS attribute.
  1764. # However, this is not always respected, for example, [2]
  1765. # contains EXT-X-STREAM-INF tag which references AUDIO
  1766. # rendition group but does not have CODECS and despite
  1767. # referencing an audio group it represents a complete
  1768. # (with audio and video) format. So, for such cases we will
  1769. # ignore references to rendition groups and treat them
  1770. # as complete formats.
  1771. if audio_group_id and codecs and f.get('vcodec') != 'none':
  1772. audio_group = groups.get(audio_group_id)
  1773. if audio_group and audio_group[0].get('URI'):
  1774. # TODO: update acodec for audio only formats with
  1775. # the same GROUP-ID
  1776. f['acodec'] = 'none'
  1777. formats.append(f)
  1778. # for DailyMotion
  1779. progressive_uri = last_stream_inf.get('PROGRESSIVE-URI')
  1780. if progressive_uri:
  1781. http_f = f.copy()
  1782. del http_f['manifest_url']
  1783. http_f.update({
  1784. 'format_id': f['format_id'].replace('hls-', 'http-'),
  1785. 'protocol': 'http',
  1786. 'url': progressive_uri,
  1787. })
  1788. formats.append(http_f)
  1789. last_stream_inf = {}
  1790. return formats
  1791. @staticmethod
  1792. def _xpath_ns(path, namespace=None):
  1793. if not namespace:
  1794. return path
  1795. out = []
  1796. for c in path.split('/'):
  1797. if not c or c == '.':
  1798. out.append(c)
  1799. else:
  1800. out.append('{%s}%s' % (namespace, c))
  1801. return '/'.join(out)
  1802. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1803. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1804. if smil is False:
  1805. assert not fatal
  1806. return []
  1807. namespace = self._parse_smil_namespace(smil)
  1808. return self._parse_smil_formats(
  1809. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1810. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1811. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1812. if smil is False:
  1813. return {}
  1814. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1815. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1816. return self._download_xml(
  1817. smil_url, video_id, 'Downloading SMIL file',
  1818. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1819. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1820. namespace = self._parse_smil_namespace(smil)
  1821. formats = self._parse_smil_formats(
  1822. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1823. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1824. video_id = os.path.splitext(url_basename(smil_url))[0]
  1825. title = None
  1826. description = None
  1827. upload_date = None
  1828. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1829. name = meta.attrib.get('name')
  1830. content = meta.attrib.get('content')
  1831. if not name or not content:
  1832. continue
  1833. if not title and name == 'title':
  1834. title = content
  1835. elif not description and name in ('description', 'abstract'):
  1836. description = content
  1837. elif not upload_date and name == 'date':
  1838. upload_date = unified_strdate(content)
  1839. thumbnails = [{
  1840. 'id': image.get('type'),
  1841. 'url': image.get('src'),
  1842. 'width': int_or_none(image.get('width')),
  1843. 'height': int_or_none(image.get('height')),
  1844. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1845. return {
  1846. 'id': video_id,
  1847. 'title': title or video_id,
  1848. 'description': description,
  1849. 'upload_date': upload_date,
  1850. 'thumbnails': thumbnails,
  1851. 'formats': formats,
  1852. 'subtitles': subtitles,
  1853. }
  1854. def _parse_smil_namespace(self, smil):
  1855. return self._search_regex(
  1856. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1857. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1858. base = smil_url
  1859. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1860. b = meta.get('base') or meta.get('httpBase')
  1861. if b:
  1862. base = b
  1863. break
  1864. formats = []
  1865. rtmp_count = 0
  1866. http_count = 0
  1867. m3u8_count = 0
  1868. srcs = []
  1869. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1870. for medium in media:
  1871. src = medium.get('src')
  1872. if not src or src in srcs:
  1873. continue
  1874. srcs.append(src)
  1875. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1876. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1877. width = int_or_none(medium.get('width'))
  1878. height = int_or_none(medium.get('height'))
  1879. proto = medium.get('proto')
  1880. ext = medium.get('ext')
  1881. src_ext = determine_ext(src)
  1882. streamer = medium.get('streamer') or base
  1883. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1884. rtmp_count += 1
  1885. formats.append({
  1886. 'url': streamer,
  1887. 'play_path': src,
  1888. 'ext': 'flv',
  1889. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1890. 'tbr': bitrate,
  1891. 'filesize': filesize,
  1892. 'width': width,
  1893. 'height': height,
  1894. })
  1895. if transform_rtmp_url:
  1896. streamer, src = transform_rtmp_url(streamer, src)
  1897. formats[-1].update({
  1898. 'url': streamer,
  1899. 'play_path': src,
  1900. })
  1901. continue
  1902. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1903. src_url = src_url.strip()
  1904. if proto == 'm3u8' or src_ext == 'm3u8':
  1905. m3u8_formats = self._extract_m3u8_formats(
  1906. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1907. if len(m3u8_formats) == 1:
  1908. m3u8_count += 1
  1909. m3u8_formats[0].update({
  1910. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1911. 'tbr': bitrate,
  1912. 'width': width,
  1913. 'height': height,
  1914. })
  1915. formats.extend(m3u8_formats)
  1916. elif src_ext == 'f4m':
  1917. f4m_url = src_url
  1918. if not f4m_params:
  1919. f4m_params = {
  1920. 'hdcore': '3.2.0',
  1921. 'plugin': 'flowplayer-3.2.0.1',
  1922. }
  1923. f4m_url += '&' if '?' in f4m_url else '?'
  1924. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1925. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1926. elif src_ext == 'mpd':
  1927. formats.extend(self._extract_mpd_formats(
  1928. src_url, video_id, mpd_id='dash', fatal=False))
  1929. elif re.search(r'\.ism/[Mm]anifest', src_url):
  1930. formats.extend(self._extract_ism_formats(
  1931. src_url, video_id, ism_id='mss', fatal=False))
  1932. elif src_url.startswith('http') and self._is_valid_url(src, video_id):
  1933. http_count += 1
  1934. formats.append({
  1935. 'url': src_url,
  1936. 'ext': ext or src_ext or 'flv',
  1937. 'format_id': 'http-%d' % (bitrate or http_count),
  1938. 'tbr': bitrate,
  1939. 'filesize': filesize,
  1940. 'width': width,
  1941. 'height': height,
  1942. })
  1943. return formats
  1944. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1945. urls = []
  1946. subtitles = {}
  1947. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1948. src = textstream.get('src')
  1949. if not src or src in urls:
  1950. continue
  1951. urls.append(src)
  1952. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1953. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1954. subtitles.setdefault(lang, []).append({
  1955. 'url': src,
  1956. 'ext': ext,
  1957. })
  1958. return subtitles
  1959. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  1960. xspf = self._download_xml(
  1961. xspf_url, playlist_id, 'Downloading xpsf playlist',
  1962. 'Unable to download xspf manifest', fatal=fatal)
  1963. if xspf is False:
  1964. return []
  1965. return self._parse_xspf(
  1966. xspf, playlist_id, xspf_url=xspf_url,
  1967. xspf_base_url=base_url(xspf_url))
  1968. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  1969. NS_MAP = {
  1970. 'xspf': 'http://xspf.org/ns/0/',
  1971. 's1': 'http://static.streamone.nl/player/ns/0',
  1972. }
  1973. entries = []
  1974. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1975. title = xpath_text(
  1976. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1977. description = xpath_text(
  1978. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1979. thumbnail = xpath_text(
  1980. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1981. duration = float_or_none(
  1982. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1983. formats = []
  1984. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  1985. format_url = urljoin(xspf_base_url, location.text)
  1986. if not format_url:
  1987. continue
  1988. formats.append({
  1989. 'url': format_url,
  1990. 'manifest_url': xspf_url,
  1991. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1992. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1993. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1994. })
  1995. self._sort_formats(formats)
  1996. entries.append({
  1997. 'id': playlist_id,
  1998. 'title': title,
  1999. 'description': description,
  2000. 'thumbnail': thumbnail,
  2001. 'duration': duration,
  2002. 'formats': formats,
  2003. })
  2004. return entries
  2005. def _extract_mpd_formats(self, *args, **kwargs):
  2006. fmts, subs = self._extract_mpd_formats_and_subtitles(*args, **kwargs)
  2007. if subs:
  2008. self._report_ignoring_subs('DASH')
  2009. return fmts
  2010. def _extract_mpd_formats_and_subtitles(
  2011. self, mpd_url, video_id, mpd_id=None, note=None, errnote=None,
  2012. fatal=True, data=None, headers=None, query=None):
  2013. # TODO: or not? param not yet implemented
  2014. if self.get_param('ignore_no_formats_error'):
  2015. fatal = False
  2016. res = self._download_xml_handle(
  2017. mpd_url, video_id,
  2018. note='Downloading MPD manifest' if note is None else note,
  2019. errnote='Failed to download MPD manifest' if errnote is None else errnote,
  2020. fatal=fatal, data=data, headers=headers or {}, query=query or {})
  2021. if res is False:
  2022. return [], {}
  2023. mpd_doc, urlh = res
  2024. if mpd_doc is None:
  2025. return [], {}
  2026. # We could have been redirected to a new url when we retrieved our mpd file.
  2027. mpd_url = urlh.geturl()
  2028. mpd_base_url = base_url(mpd_url)
  2029. return self._parse_mpd_formats_and_subtitles(
  2030. mpd_doc, mpd_id, mpd_base_url, mpd_url)
  2031. def _parse_mpd_formats(self, *args, **kwargs):
  2032. fmts, subs = self._parse_mpd_formats_and_subtitles(*args, **kwargs)
  2033. if subs:
  2034. self._report_ignoring_subs('DASH')
  2035. return fmts
  2036. def _parse_mpd_formats_and_subtitles(
  2037. self, mpd_doc, mpd_id=None, mpd_base_url='', mpd_url=None):
  2038. """
  2039. Parse formats from MPD manifest.
  2040. References:
  2041. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  2042. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  2043. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  2044. """
  2045. # TODO: param not yet implemented: default like previous yt-dl logic
  2046. if not self.get_param('dynamic_mpd', False):
  2047. if mpd_doc.get('type') == 'dynamic':
  2048. return [], {}
  2049. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  2050. def _add_ns(path):
  2051. return self._xpath_ns(path, namespace)
  2052. def is_drm_protected(element):
  2053. return element.find(_add_ns('ContentProtection')) is not None
  2054. from ..utils import YoutubeDLHandler
  2055. fix_path = YoutubeDLHandler._fix_path
  2056. def resolve_base_url(element, parent_base_url=None):
  2057. # TODO: use native XML traversal when ready
  2058. b_url = traverse_obj(element, (
  2059. T(lambda e: e.find(_add_ns('BaseURL')).text)))
  2060. if parent_base_url and b_url:
  2061. if not parent_base_url[-1] in ('/', ':'):
  2062. parent_base_url += '/'
  2063. b_url = compat_urlparse.urljoin(parent_base_url, b_url)
  2064. if b_url:
  2065. b_url = fix_path(b_url)
  2066. return b_url or parent_base_url
  2067. def extract_multisegment_info(element, ms_parent_info):
  2068. ms_info = ms_parent_info.copy()
  2069. base_url = ms_info['base_url'] = resolve_base_url(element, ms_info.get('base_url'))
  2070. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  2071. # common attributes and elements. We will only extract relevant
  2072. # for us.
  2073. def extract_common(source):
  2074. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  2075. if segment_timeline is not None:
  2076. s_e = segment_timeline.findall(_add_ns('S'))
  2077. if s_e:
  2078. ms_info['total_number'] = 0
  2079. ms_info['s'] = []
  2080. for s in s_e:
  2081. r = int(s.get('r', 0))
  2082. ms_info['total_number'] += 1 + r
  2083. ms_info['s'].append({
  2084. 't': int(s.get('t', 0)),
  2085. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  2086. 'd': int(s.attrib['d']),
  2087. 'r': r,
  2088. })
  2089. start_number = source.get('startNumber')
  2090. if start_number:
  2091. ms_info['start_number'] = int(start_number)
  2092. timescale = source.get('timescale')
  2093. if timescale:
  2094. ms_info['timescale'] = int(timescale)
  2095. segment_duration = source.get('duration')
  2096. if segment_duration:
  2097. ms_info['segment_duration'] = float(segment_duration)
  2098. def extract_Initialization(source):
  2099. initialization = source.find(_add_ns('Initialization'))
  2100. if initialization is not None:
  2101. ms_info['initialization_url'] = initialization.get('sourceURL') or base_url
  2102. initialization_url_range = initialization.get('range')
  2103. if initialization_url_range:
  2104. ms_info['initialization_url_range'] = initialization_url_range
  2105. segment_list = element.find(_add_ns('SegmentList'))
  2106. if segment_list is not None:
  2107. extract_common(segment_list)
  2108. extract_Initialization(segment_list)
  2109. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  2110. segment_urls = traverse_obj(segment_urls_e, (
  2111. Ellipsis, T(lambda e: e.attrib), 'media'))
  2112. if segment_urls:
  2113. ms_info['segment_urls'] = segment_urls
  2114. segment_urls_range = traverse_obj(segment_urls_e, (
  2115. Ellipsis, T(lambda e: e.attrib), 'mediaRange',
  2116. T(lambda r: re.findall(r'^\d+-\d+$', r)), 0))
  2117. if segment_urls_range:
  2118. ms_info['segment_urls_range'] = segment_urls_range
  2119. if not segment_urls:
  2120. ms_info['segment_urls'] = [base_url for _ in segment_urls_range]
  2121. else:
  2122. segment_template = element.find(_add_ns('SegmentTemplate'))
  2123. if segment_template is not None:
  2124. extract_common(segment_template)
  2125. media = segment_template.get('media')
  2126. if media:
  2127. ms_info['media'] = media
  2128. initialization = segment_template.get('initialization')
  2129. if initialization:
  2130. ms_info['initialization'] = initialization
  2131. else:
  2132. extract_Initialization(segment_template)
  2133. return ms_info
  2134. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  2135. formats, subtitles = [], {}
  2136. stream_numbers = collections.defaultdict(int)
  2137. mpd_base_url = resolve_base_url(mpd_doc, mpd_base_url or mpd_url)
  2138. for period in mpd_doc.findall(_add_ns('Period')):
  2139. period_duration = parse_duration(period.get('duration')) or mpd_duration
  2140. period_ms_info = extract_multisegment_info(period, {
  2141. 'start_number': 1,
  2142. 'timescale': 1,
  2143. 'base_url': mpd_base_url,
  2144. })
  2145. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  2146. if is_drm_protected(adaptation_set):
  2147. continue
  2148. adaptation_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  2149. for representation in adaptation_set.findall(_add_ns('Representation')):
  2150. if is_drm_protected(representation):
  2151. continue
  2152. representation_attrib = adaptation_set.attrib.copy()
  2153. representation_attrib.update(representation.attrib)
  2154. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  2155. mime_type = representation_attrib['mimeType']
  2156. content_type = representation_attrib.get('contentType') or mime_type.split('/')[0]
  2157. codec_str = representation_attrib.get('codecs', '')
  2158. # Some kind of binary subtitle found in some youtube livestreams
  2159. if mime_type == 'application/x-rawcc':
  2160. codecs = {'scodec': codec_str}
  2161. else:
  2162. codecs = parse_codecs(codec_str)
  2163. if content_type not in ('video', 'audio', 'text'):
  2164. if mime_type == 'image/jpeg':
  2165. content_type = mime_type
  2166. elif codecs.get('vcodec', 'none') != 'none':
  2167. content_type = 'video'
  2168. elif codecs.get('acodec', 'none') != 'none':
  2169. content_type = 'audio'
  2170. elif codecs.get('scodec', 'none') != 'none':
  2171. content_type = 'text'
  2172. elif mimetype2ext(mime_type) in ('tt', 'dfxp', 'ttml', 'xml', 'json'):
  2173. content_type = 'text'
  2174. else:
  2175. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  2176. continue
  2177. representation_id = representation_attrib.get('id')
  2178. lang = representation_attrib.get('lang')
  2179. url_el = representation.find(_add_ns('BaseURL'))
  2180. filesize = int_or_none(url_el.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  2181. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  2182. format_id = join_nonempty(representation_id or content_type, mpd_id)
  2183. if content_type in ('video', 'audio'):
  2184. f = {
  2185. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  2186. 'manifest_url': mpd_url,
  2187. 'ext': mimetype2ext(mime_type),
  2188. 'width': int_or_none(representation_attrib.get('width')),
  2189. 'height': int_or_none(representation_attrib.get('height')),
  2190. 'tbr': float_or_none(bandwidth, 1000),
  2191. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  2192. 'fps': int_or_none(representation_attrib.get('frameRate')),
  2193. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  2194. 'format_note': 'DASH %s' % content_type,
  2195. 'filesize': filesize,
  2196. 'container': mimetype2ext(mime_type) + '_dash',
  2197. }
  2198. f.update(codecs)
  2199. elif content_type == 'text':
  2200. f = {
  2201. 'ext': mimetype2ext(mime_type),
  2202. 'manifest_url': mpd_url,
  2203. 'filesize': filesize,
  2204. }
  2205. elif content_type == 'image/jpeg':
  2206. # See test case in VikiIE
  2207. # https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1
  2208. f = {
  2209. 'format_id': format_id,
  2210. 'ext': 'mhtml',
  2211. 'manifest_url': mpd_url,
  2212. 'format_note': 'DASH storyboards (jpeg)',
  2213. 'acodec': 'none',
  2214. 'vcodec': 'none',
  2215. }
  2216. if is_drm_protected(adaptation_set) or is_drm_protected(representation):
  2217. f['has_drm'] = True
  2218. representation_ms_info = extract_multisegment_info(representation, adaptation_set_ms_info)
  2219. def prepare_template(template_name, identifiers):
  2220. tmpl = representation_ms_info[template_name]
  2221. # First of, % characters outside $...$ templates
  2222. # must be escaped by doubling for proper processing
  2223. # by % operator string formatting used further (see
  2224. # https://github.com/ytdl-org/youtube-dl/issues/16867).
  2225. t = ''
  2226. in_template = False
  2227. for c in tmpl:
  2228. t += c
  2229. if c == '$':
  2230. in_template = not in_template
  2231. elif c == '%' and not in_template:
  2232. t += c
  2233. # Next, $...$ templates are translated to their
  2234. # %(...) counterparts to be used with % operator
  2235. t = t.replace('$RepresentationID$', representation_id)
  2236. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  2237. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  2238. t.replace('$$', '$')
  2239. return t
  2240. # @initialization is a regular template like @media one
  2241. # so it should be handled just the same way (see
  2242. # https://github.com/ytdl-org/youtube-dl/issues/11605)
  2243. if 'initialization' in representation_ms_info:
  2244. initialization_template = prepare_template(
  2245. 'initialization',
  2246. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  2247. # $Time$ shall not be included for @initialization thus
  2248. # only $Bandwidth$ remains
  2249. ('Bandwidth', ))
  2250. representation_ms_info['initialization_url'] = initialization_template % {
  2251. 'Bandwidth': bandwidth,
  2252. }
  2253. def location_key(location):
  2254. return 'url' if re.match(r'^https?://', location) else 'path'
  2255. def calc_segment_duration():
  2256. return float_or_none(
  2257. representation_ms_info['segment_duration'],
  2258. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  2259. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  2260. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  2261. media_location_key = location_key(media_template)
  2262. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  2263. # can't be used at the same time
  2264. if '%(Number' in media_template and 's' not in representation_ms_info:
  2265. segment_duration = None
  2266. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  2267. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  2268. representation_ms_info['total_number'] = int(math.ceil(
  2269. float_or_none(period_duration, segment_duration, default=0)))
  2270. representation_ms_info['fragments'] = [{
  2271. media_location_key: media_template % {
  2272. 'Number': segment_number,
  2273. 'Bandwidth': bandwidth,
  2274. },
  2275. 'duration': segment_duration,
  2276. } for segment_number in range(
  2277. representation_ms_info['start_number'],
  2278. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  2279. else:
  2280. # $Number*$ or $Time$ in media template with S list available
  2281. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  2282. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  2283. representation_ms_info['fragments'] = []
  2284. segment_time = 0
  2285. segment_d = None
  2286. segment_number = representation_ms_info['start_number']
  2287. def add_segment_url():
  2288. segment_url = media_template % {
  2289. 'Time': segment_time,
  2290. 'Bandwidth': bandwidth,
  2291. 'Number': segment_number,
  2292. }
  2293. representation_ms_info['fragments'].append({
  2294. media_location_key: segment_url,
  2295. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  2296. })
  2297. for num, s in enumerate(representation_ms_info['s']):
  2298. segment_time = s.get('t') or segment_time
  2299. segment_d = s['d']
  2300. add_segment_url()
  2301. segment_number += 1
  2302. for r in range(s.get('r', 0)):
  2303. segment_time += segment_d
  2304. add_segment_url()
  2305. segment_number += 1
  2306. segment_time += segment_d
  2307. elif 'segment_urls' in representation_ms_info:
  2308. fragments = []
  2309. if 's' in representation_ms_info:
  2310. # No media template
  2311. # Example: https://www.youtube.com/watch?v=iXZV5uAYMJI
  2312. # or any YouTube dashsegments video
  2313. segment_index = 0
  2314. timescale = representation_ms_info['timescale']
  2315. for s in representation_ms_info['s']:
  2316. duration = float_or_none(s['d'], timescale)
  2317. for r in range(s.get('r', 0) + 1):
  2318. segment_uri = representation_ms_info['segment_urls'][segment_index]
  2319. fragments.append({
  2320. location_key(segment_uri): segment_uri,
  2321. 'duration': duration,
  2322. })
  2323. segment_index += 1
  2324. elif 'segment_urls_range' in representation_ms_info:
  2325. # Segment URLs with mediaRange
  2326. # Example: https://kinescope.io/200615537/master.mpd
  2327. # https://github.com/ytdl-org/youtube-dl/issues/30235
  2328. # or any mpd generated with Bento4 `mp4dash --no-split --use-segment-list`
  2329. segment_duration = calc_segment_duration()
  2330. for segment_url, segment_url_range in zip(
  2331. representation_ms_info['segment_urls'], representation_ms_info['segment_urls_range']):
  2332. fragments.append({
  2333. location_key(segment_url): segment_url,
  2334. 'range': segment_url_range,
  2335. 'duration': segment_duration,
  2336. })
  2337. else:
  2338. # Segment URLs with no SegmentTimeline
  2339. # Example: https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  2340. # https://github.com/ytdl-org/youtube-dl/pull/14844
  2341. segment_duration = calc_segment_duration()
  2342. for segment_url in representation_ms_info['segment_urls']:
  2343. fragments.append({
  2344. location_key(segment_url): segment_url,
  2345. 'duration': segment_duration,
  2346. })
  2347. representation_ms_info['fragments'] = fragments
  2348. # If there is a fragments key available then we correctly recognized fragmented media.
  2349. # Otherwise we will assume unfragmented media with direct access. Technically, such
  2350. # assumption is not necessarily correct since we may simply have no support for
  2351. # some forms of fragmented media renditions yet, but for now we'll use this fallback.
  2352. if 'fragments' in representation_ms_info:
  2353. base_url = representation_ms_info['base_url']
  2354. f.update({
  2355. # NB: mpd_url may be empty when MPD manifest is parsed from a string
  2356. 'url': mpd_url or base_url,
  2357. 'fragment_base_url': base_url,
  2358. 'fragments': [],
  2359. 'protocol': 'http_dash_segments',
  2360. })
  2361. if 'initialization_url' in representation_ms_info and 'initialization_url_range' in representation_ms_info:
  2362. # Initialization URL with range (accompanied by Segment URLs with mediaRange above)
  2363. # https://github.com/ytdl-org/youtube-dl/issues/30235
  2364. initialization_url = representation_ms_info['initialization_url']
  2365. f['fragments'].append({
  2366. location_key(initialization_url): initialization_url,
  2367. 'range': representation_ms_info['initialization_url_range'],
  2368. })
  2369. elif 'initialization_url' in representation_ms_info:
  2370. initialization_url = representation_ms_info['initialization_url']
  2371. if not f.get('url'):
  2372. f['url'] = initialization_url
  2373. f['fragments'].append({location_key(initialization_url): initialization_url})
  2374. elif 'initialization_url_range' in representation_ms_info:
  2375. # no Initialization URL but range (accompanied by no Segment URLs but mediaRange above)
  2376. # https://github.com/ytdl-org/youtube-dl/issues/27575
  2377. f['fragments'].append({
  2378. location_key(base_url): base_url,
  2379. 'range': representation_ms_info['initialization_url_range'],
  2380. })
  2381. f['fragments'].extend(representation_ms_info['fragments'])
  2382. if not period_duration:
  2383. period_duration = sum(traverse_obj(representation_ms_info, (
  2384. 'fragments', Ellipsis, 'duration', T(float_or_none))))
  2385. else:
  2386. # Assuming direct URL to unfragmented media.
  2387. f['url'] = representation_ms_info['base_url']
  2388. if content_type in ('video', 'audio', 'image/jpeg'):
  2389. f['manifest_stream_number'] = stream_numbers[f['url']]
  2390. stream_numbers[f['url']] += 1
  2391. formats.append(f)
  2392. elif content_type == 'text':
  2393. subtitles.setdefault(lang or 'und', []).append(f)
  2394. return formats, subtitles
  2395. def _extract_ism_formats(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  2396. res = self._download_xml_handle(
  2397. ism_url, video_id,
  2398. note=note or 'Downloading ISM manifest',
  2399. errnote=errnote or 'Failed to download ISM manifest',
  2400. fatal=fatal, data=data, headers=headers, query=query)
  2401. if res is False:
  2402. return []
  2403. ism_doc, urlh = res
  2404. if ism_doc is None:
  2405. return []
  2406. return self._parse_ism_formats(ism_doc, urlh.geturl(), ism_id)
  2407. def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
  2408. """
  2409. Parse formats from ISM manifest.
  2410. References:
  2411. 1. [MS-SSTR]: Smooth Streaming Protocol,
  2412. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  2413. """
  2414. if ism_doc.get('IsLive') == 'TRUE' or ism_doc.find('Protection') is not None:
  2415. return []
  2416. duration = int(ism_doc.attrib['Duration'])
  2417. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  2418. formats = []
  2419. for stream in ism_doc.findall('StreamIndex'):
  2420. stream_type = stream.get('Type')
  2421. if stream_type not in ('video', 'audio'):
  2422. continue
  2423. url_pattern = stream.attrib['Url']
  2424. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  2425. stream_name = stream.get('Name')
  2426. for track in stream.findall('QualityLevel'):
  2427. fourcc = track.get('FourCC', 'AACL' if track.get('AudioTag') == '255' else None)
  2428. # TODO: add support for WVC1 and WMAP
  2429. if fourcc not in ('H264', 'AVC1', 'AACL'):
  2430. self.report_warning('%s is not a supported codec' % fourcc)
  2431. continue
  2432. tbr = int(track.attrib['Bitrate']) // 1000
  2433. # [1] does not mention Width and Height attributes. However,
  2434. # they're often present while MaxWidth and MaxHeight are
  2435. # missing, so should be used as fallbacks
  2436. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  2437. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  2438. sampling_rate = int_or_none(track.get('SamplingRate'))
  2439. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  2440. track_url_pattern = compat_urlparse.urljoin(ism_url, track_url_pattern)
  2441. fragments = []
  2442. fragment_ctx = {
  2443. 'time': 0,
  2444. }
  2445. stream_fragments = stream.findall('c')
  2446. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  2447. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  2448. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  2449. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  2450. if not fragment_ctx['duration']:
  2451. try:
  2452. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  2453. except IndexError:
  2454. next_fragment_time = duration
  2455. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  2456. for _ in range(fragment_repeat):
  2457. fragments.append({
  2458. 'url': re.sub(r'{start[ _]time}', compat_str(fragment_ctx['time']), track_url_pattern),
  2459. 'duration': fragment_ctx['duration'] / stream_timescale,
  2460. })
  2461. fragment_ctx['time'] += fragment_ctx['duration']
  2462. format_id = []
  2463. if ism_id:
  2464. format_id.append(ism_id)
  2465. if stream_name:
  2466. format_id.append(stream_name)
  2467. format_id.append(compat_str(tbr))
  2468. formats.append({
  2469. 'format_id': '-'.join(format_id),
  2470. 'url': ism_url,
  2471. 'manifest_url': ism_url,
  2472. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  2473. 'width': width,
  2474. 'height': height,
  2475. 'tbr': tbr,
  2476. 'asr': sampling_rate,
  2477. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  2478. 'acodec': 'none' if stream_type == 'video' else fourcc,
  2479. 'protocol': 'ism',
  2480. 'fragments': fragments,
  2481. '_download_params': {
  2482. 'duration': duration,
  2483. 'timescale': stream_timescale,
  2484. 'width': width or 0,
  2485. 'height': height or 0,
  2486. 'fourcc': fourcc,
  2487. 'codec_private_data': track.get('CodecPrivateData'),
  2488. 'sampling_rate': sampling_rate,
  2489. 'channels': int_or_none(track.get('Channels', 2)),
  2490. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  2491. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  2492. },
  2493. })
  2494. return formats
  2495. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8', mpd_id=None, preference=None):
  2496. def absolute_url(item_url):
  2497. return urljoin(base_url, item_url)
  2498. def parse_content_type(content_type):
  2499. if not content_type:
  2500. return {}
  2501. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  2502. if ctr:
  2503. mimetype, codecs = ctr.groups()
  2504. f = parse_codecs(codecs)
  2505. f['ext'] = mimetype2ext(mimetype)
  2506. return f
  2507. return {}
  2508. def _media_formats(src, cur_media_type, type_info=None):
  2509. type_info = type_info or {}
  2510. full_url = absolute_url(src)
  2511. ext = type_info.get('ext') or determine_ext(full_url)
  2512. if ext == 'm3u8':
  2513. is_plain_url = False
  2514. formats = self._extract_m3u8_formats(
  2515. full_url, video_id, ext='mp4',
  2516. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  2517. preference=preference, fatal=False)
  2518. elif ext == 'mpd':
  2519. is_plain_url = False
  2520. formats = self._extract_mpd_formats(
  2521. full_url, video_id, mpd_id=mpd_id, fatal=False)
  2522. else:
  2523. is_plain_url = True
  2524. formats = [{
  2525. 'url': full_url,
  2526. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  2527. 'ext': ext,
  2528. }]
  2529. return is_plain_url, formats
  2530. entries = []
  2531. # amp-video and amp-audio are very similar to their HTML5 counterparts
  2532. # so we wll include them right here (see
  2533. # https://www.ampproject.org/docs/reference/components/amp-video)
  2534. # For dl8-* tags see https://delight-vr.com/documentation/dl8-video/
  2535. _MEDIA_TAG_NAME_RE = r'(?:(?:amp|dl8(?:-live)?)-)?(video(?:-js)?|audio)'
  2536. media_tags = [(media_tag, media_tag_name, media_type, '')
  2537. for media_tag, media_tag_name, media_type
  2538. in re.findall(r'(?s)(<(%s)[^>]*/>)' % _MEDIA_TAG_NAME_RE, webpage)]
  2539. media_tags.extend(re.findall(
  2540. # We only allow video|audio followed by a whitespace or '>'.
  2541. # Allowing more characters may end up in significant slow down (see
  2542. # https://github.com/ytdl-org/youtube-dl/issues/11979, example URL:
  2543. # http://www.porntrex.com/maps/videositemap.xml).
  2544. r'(?s)(<(?P<tag>%s)(?:\s+[^>]*)?>)(.*?)</(?P=tag)>' % _MEDIA_TAG_NAME_RE, webpage))
  2545. for media_tag, _, media_type, media_content in media_tags:
  2546. media_info = {
  2547. 'formats': [],
  2548. 'subtitles': {},
  2549. }
  2550. media_attributes = extract_attributes(media_tag)
  2551. src = strip_or_none(media_attributes.get('src'))
  2552. if src:
  2553. f = parse_content_type(media_attributes.get('type'))
  2554. _, formats = _media_formats(src, media_type, f)
  2555. media_info['formats'].extend(formats)
  2556. media_info['thumbnail'] = absolute_url(media_attributes.get('poster'))
  2557. if media_content:
  2558. for source_tag in re.findall(r'<source[^>]+>', media_content):
  2559. s_attr = extract_attributes(source_tag)
  2560. # data-video-src and data-src are non standard but seen
  2561. # several times in the wild
  2562. src = strip_or_none(dict_get(s_attr, ('src', 'data-video-src', 'data-src')))
  2563. if not src:
  2564. continue
  2565. f = parse_content_type(s_attr.get('type'))
  2566. is_plain_url, formats = _media_formats(src, media_type, f)
  2567. if is_plain_url:
  2568. # width, height, res, label and title attributes are
  2569. # all not standard but seen several times in the wild
  2570. labels = [
  2571. s_attr.get(lbl)
  2572. for lbl in ('label', 'title')
  2573. if str_or_none(s_attr.get(lbl))
  2574. ]
  2575. width = int_or_none(s_attr.get('width'))
  2576. height = (int_or_none(s_attr.get('height'))
  2577. or int_or_none(s_attr.get('res')))
  2578. if not width or not height:
  2579. for lbl in labels:
  2580. resolution = parse_resolution(lbl)
  2581. if not resolution:
  2582. continue
  2583. width = width or resolution.get('width')
  2584. height = height or resolution.get('height')
  2585. for lbl in labels:
  2586. tbr = parse_bitrate(lbl)
  2587. if tbr:
  2588. break
  2589. else:
  2590. tbr = None
  2591. f.update({
  2592. 'width': width,
  2593. 'height': height,
  2594. 'tbr': tbr,
  2595. 'format_id': s_attr.get('label') or s_attr.get('title'),
  2596. })
  2597. f.update(formats[0])
  2598. media_info['formats'].append(f)
  2599. else:
  2600. media_info['formats'].extend(formats)
  2601. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2602. track_attributes = extract_attributes(track_tag)
  2603. kind = track_attributes.get('kind')
  2604. if not kind or kind in ('subtitles', 'captions'):
  2605. src = strip_or_none(track_attributes.get('src'))
  2606. if not src:
  2607. continue
  2608. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2609. media_info['subtitles'].setdefault(lang, []).append({
  2610. 'url': absolute_url(src),
  2611. })
  2612. for f in media_info['formats']:
  2613. f.setdefault('http_headers', {})['Referer'] = base_url
  2614. if media_info['formats'] or media_info['subtitles']:
  2615. entries.append(media_info)
  2616. return entries
  2617. def _extract_akamai_formats(self, manifest_url, video_id, hosts={}):
  2618. signed = 'hdnea=' in manifest_url
  2619. if not signed:
  2620. # https://learn.akamai.com/en-us/webhelp/media-services-on-demand/stream-packaging-user-guide/GUID-BE6C0F73-1E06-483B-B0EA-57984B91B7F9.html
  2621. manifest_url = re.sub(
  2622. r'(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?',
  2623. '', manifest_url).strip('?')
  2624. formats = []
  2625. hdcore_sign = 'hdcore=3.7.0'
  2626. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  2627. hds_host = hosts.get('hds')
  2628. if hds_host:
  2629. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  2630. if 'hdcore=' not in f4m_url:
  2631. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  2632. f4m_formats = self._extract_f4m_formats(
  2633. f4m_url, video_id, f4m_id='hds', fatal=False)
  2634. for entry in f4m_formats:
  2635. entry.update({'extra_param_to_segment_url': hdcore_sign})
  2636. formats.extend(f4m_formats)
  2637. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  2638. hls_host = hosts.get('hls')
  2639. if hls_host:
  2640. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  2641. m3u8_formats = self._extract_m3u8_formats(
  2642. m3u8_url, video_id, 'mp4', 'm3u8_native',
  2643. m3u8_id='hls', fatal=False)
  2644. formats.extend(m3u8_formats)
  2645. http_host = hosts.get('http')
  2646. if http_host and m3u8_formats and not signed:
  2647. REPL_REGEX = r'https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+'
  2648. qualities = re.match(REPL_REGEX, m3u8_url).group(2).split(',')
  2649. qualities_length = len(qualities)
  2650. if len(m3u8_formats) in (qualities_length, qualities_length + 1):
  2651. i = 0
  2652. for f in m3u8_formats:
  2653. if f['vcodec'] != 'none':
  2654. for protocol in ('http', 'https'):
  2655. http_f = f.copy()
  2656. del http_f['manifest_url']
  2657. http_url = re.sub(
  2658. REPL_REGEX, protocol + r'://%s/\g<1>%s\3' % (http_host, qualities[i]), f['url'])
  2659. http_f.update({
  2660. 'format_id': http_f['format_id'].replace('hls-', protocol + '-'),
  2661. 'url': http_url,
  2662. 'protocol': protocol,
  2663. })
  2664. formats.append(http_f)
  2665. i += 1
  2666. return formats
  2667. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  2668. query = compat_urlparse.urlparse(url).query
  2669. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  2670. mobj = re.search(
  2671. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  2672. url_base = mobj.group('url')
  2673. http_base_url = '%s%s:%s' % ('http', mobj.group('s') or '', url_base)
  2674. formats = []
  2675. def manifest_url(manifest):
  2676. m_url = '%s/%s' % (http_base_url, manifest)
  2677. if query:
  2678. m_url += '?%s' % query
  2679. return m_url
  2680. if 'm3u8' not in skip_protocols:
  2681. formats.extend(self._extract_m3u8_formats(
  2682. manifest_url('playlist.m3u8'), video_id, 'mp4',
  2683. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  2684. if 'f4m' not in skip_protocols:
  2685. formats.extend(self._extract_f4m_formats(
  2686. manifest_url('manifest.f4m'),
  2687. video_id, f4m_id='hds', fatal=False))
  2688. if 'dash' not in skip_protocols:
  2689. formats.extend(self._extract_mpd_formats(
  2690. manifest_url('manifest.mpd'),
  2691. video_id, mpd_id='dash', fatal=False))
  2692. if re.search(r'(?:/smil:|\.smil)', url_base):
  2693. if 'smil' not in skip_protocols:
  2694. rtmp_formats = self._extract_smil_formats(
  2695. manifest_url('jwplayer.smil'),
  2696. video_id, fatal=False)
  2697. for rtmp_format in rtmp_formats:
  2698. rtsp_format = rtmp_format.copy()
  2699. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  2700. del rtsp_format['play_path']
  2701. del rtsp_format['ext']
  2702. rtsp_format.update({
  2703. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  2704. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  2705. 'protocol': 'rtsp',
  2706. })
  2707. formats.extend([rtmp_format, rtsp_format])
  2708. else:
  2709. for protocol in ('rtmp', 'rtsp'):
  2710. if protocol not in skip_protocols:
  2711. formats.append({
  2712. 'url': '%s:%s' % (protocol, url_base),
  2713. 'format_id': protocol,
  2714. 'protocol': protocol,
  2715. })
  2716. return formats
  2717. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  2718. return self._search_json(
  2719. r'''(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)''',
  2720. webpage, 'JWPlayer data', video_id,
  2721. # must be a {...} or sequence, ending
  2722. contains_pattern=r'\{[\s\S]*}(?(load)(?:\s*,\s*\{[\s\S]*})*)', end_pattern=r'(?(load)\]|\))',
  2723. transform_source=transform_source, default=None)
  2724. def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
  2725. # allow passing `transform_source` through to _find_jwplayer_data()
  2726. transform_source = kwargs.pop('transform_source', None)
  2727. kwfind = compat_kwargs({'transform_source': transform_source}) if transform_source else {}
  2728. jwplayer_data = self._find_jwplayer_data(webpage, video_id, **kwfind)
  2729. return self._parse_jwplayer_data(jwplayer_data, video_id, *args, **kwargs)
  2730. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  2731. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  2732. flat_pl = try_get(jwplayer_data, lambda x: x.get('playlist') or True)
  2733. if flat_pl is None:
  2734. # not even a dict
  2735. return []
  2736. # JWPlayer backward compatibility: flattened playlists
  2737. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  2738. if flat_pl is True:
  2739. jwplayer_data = {'playlist': [jwplayer_data]}
  2740. entries = []
  2741. # JWPlayer backward compatibility: single playlist item
  2742. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  2743. if not isinstance(jwplayer_data['playlist'], list):
  2744. jwplayer_data['playlist'] = [jwplayer_data['playlist']]
  2745. for video_data in jwplayer_data['playlist']:
  2746. # JWPlayer backward compatibility: flattened sources
  2747. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  2748. if 'sources' not in video_data:
  2749. video_data['sources'] = [video_data]
  2750. this_video_id = video_id or video_data['mediaid']
  2751. formats = self._parse_jwplayer_formats(
  2752. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  2753. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  2754. subtitles = {}
  2755. for track in traverse_obj(video_data, (
  2756. 'tracks', lambda _, t: t.get('kind').lower() in ('captions', 'subtitles'))):
  2757. track_url = urljoin(base_url, track.get('file'))
  2758. if not track_url:
  2759. continue
  2760. subtitles.setdefault(track.get('label') or 'en', []).append({
  2761. 'url': self._proto_relative_url(track_url)
  2762. })
  2763. entry = {
  2764. 'id': this_video_id,
  2765. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  2766. 'description': clean_html(video_data.get('description')),
  2767. 'thumbnail': urljoin(base_url, self._proto_relative_url(video_data.get('image'))),
  2768. 'timestamp': int_or_none(video_data.get('pubdate')),
  2769. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  2770. 'subtitles': subtitles,
  2771. 'alt_title': clean_html(video_data.get('subtitle')), # attributes used e.g. by Tele5 ...
  2772. 'genre': clean_html(video_data.get('genre')),
  2773. 'channel': clean_html(dict_get(video_data, ('category', 'channel'))),
  2774. 'season_number': int_or_none(video_data.get('season')),
  2775. 'episode_number': int_or_none(video_data.get('episode')),
  2776. 'release_year': int_or_none(video_data.get('releasedate')),
  2777. 'age_limit': int_or_none(video_data.get('age_restriction')),
  2778. }
  2779. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  2780. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  2781. entry.update({
  2782. '_type': 'url_transparent',
  2783. 'url': formats[0]['url'],
  2784. })
  2785. else:
  2786. # avoid exception in case of only sttls
  2787. if formats:
  2788. self._sort_formats(formats)
  2789. entry['formats'] = formats
  2790. entries.append(entry)
  2791. if len(entries) == 1:
  2792. return entries[0]
  2793. else:
  2794. return self.playlist_result(entries)
  2795. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  2796. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  2797. urls = set()
  2798. formats = []
  2799. for source in jwplayer_sources_data:
  2800. if not isinstance(source, dict):
  2801. continue
  2802. source_url = urljoin(
  2803. base_url, self._proto_relative_url(source.get('file')))
  2804. if not source_url or source_url in urls:
  2805. continue
  2806. urls.add(source_url)
  2807. source_type = source.get('type') or ''
  2808. ext = mimetype2ext(source_type) or determine_ext(source_url)
  2809. if source_type == 'hls' or ext == 'm3u8' or 'format=m3u8-aapl' in source_url:
  2810. formats.extend(self._extract_m3u8_formats(
  2811. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  2812. m3u8_id=m3u8_id, fatal=False))
  2813. elif source_type == 'dash' or ext == 'mpd' or 'format=mpd-time-csf' in source_url:
  2814. formats.extend(self._extract_mpd_formats(
  2815. source_url, video_id, mpd_id=mpd_id, fatal=False))
  2816. elif ext == 'smil':
  2817. formats.extend(self._extract_smil_formats(
  2818. source_url, video_id, fatal=False))
  2819. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  2820. elif source_type.startswith('audio') or ext in (
  2821. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  2822. formats.append({
  2823. 'url': source_url,
  2824. 'vcodec': 'none',
  2825. 'ext': ext,
  2826. })
  2827. else:
  2828. format_id = str_or_none(source.get('label'))
  2829. height = int_or_none(source.get('height'))
  2830. if height is None and format_id:
  2831. # Often no height is provided but there is a label in
  2832. # format like "1080p", "720p SD", or 1080.
  2833. height = parse_resolution(format_id).get('height')
  2834. a_format = {
  2835. 'url': source_url,
  2836. 'width': int_or_none(source.get('width')),
  2837. 'height': height,
  2838. 'tbr': int_or_none(source.get('bitrate'), scale=1000),
  2839. 'filesize': int_or_none(source.get('filesize')),
  2840. 'ext': ext,
  2841. }
  2842. if format_id:
  2843. a_format['format_id'] = format_id
  2844. if source_url.startswith('rtmp'):
  2845. a_format['ext'] = 'flv'
  2846. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  2847. # of jwplayer.flash.swf
  2848. rtmp_url_parts = re.split(
  2849. r'((?:mp4|mp3|flv):)', source_url, maxsplit=1)
  2850. if len(rtmp_url_parts) == 3:
  2851. rtmp_url, prefix, play_path = rtmp_url_parts
  2852. a_format.update({
  2853. 'url': rtmp_url,
  2854. 'play_path': prefix + play_path,
  2855. })
  2856. if rtmp_params:
  2857. a_format.update(rtmp_params)
  2858. formats.append(a_format)
  2859. return formats
  2860. def _live_title(self, name):
  2861. """ Generate the title for a live video """
  2862. now = datetime.datetime.now()
  2863. now_str = now.strftime('%Y-%m-%d %H:%M')
  2864. return name + ' ' + now_str
  2865. def _int(self, v, name, fatal=False, **kwargs):
  2866. res = int_or_none(v, **kwargs)
  2867. if 'get_attr' in kwargs:
  2868. print(getattr(v, kwargs['get_attr']))
  2869. if res is None:
  2870. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2871. if fatal:
  2872. raise ExtractorError(msg)
  2873. else:
  2874. self.report_warning(msg)
  2875. return res
  2876. def _float(self, v, name, fatal=False, **kwargs):
  2877. res = float_or_none(v, **kwargs)
  2878. if res is None:
  2879. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2880. if fatal:
  2881. raise ExtractorError(msg)
  2882. else:
  2883. self.report_warning(msg)
  2884. return res
  2885. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  2886. path='/', secure=False, discard=False, rest={}, **kwargs):
  2887. cookie = compat_cookiejar_Cookie(
  2888. 0, name, value, port, port is not None, domain, True,
  2889. domain.startswith('.'), path, True, secure, expire_time,
  2890. discard, None, None, rest)
  2891. self.cookiejar.set_cookie(cookie)
  2892. def _get_cookies(self, url):
  2893. """ Return a compat_cookies_SimpleCookie with the cookies for the url """
  2894. req = sanitized_Request(url)
  2895. self.cookiejar.add_cookie_header(req)
  2896. return compat_cookies_SimpleCookie(req.get_header('Cookie'))
  2897. def _apply_first_set_cookie_header(self, url_handle, cookie):
  2898. """
  2899. Apply first Set-Cookie header instead of the last. Experimental.
  2900. Some sites (e.g. [1-3]) may serve two cookies under the same name
  2901. in Set-Cookie header and expect the first (old) one to be set rather
  2902. than second (new). However, as of RFC6265 the newer one cookie
  2903. should be set into cookie store what actually happens.
  2904. We will workaround this issue by resetting the cookie to
  2905. the first one manually.
  2906. 1. https://new.vk.com/
  2907. 2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
  2908. 3. https://learning.oreilly.com/
  2909. """
  2910. for header, cookies in url_handle.headers.items():
  2911. if header.lower() != 'set-cookie':
  2912. continue
  2913. if sys.version_info[0] >= 3:
  2914. cookies = cookies.encode('iso-8859-1')
  2915. cookies = cookies.decode('utf-8')
  2916. cookie_value = re.search(
  2917. r'%s=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)' % cookie, cookies)
  2918. if cookie_value:
  2919. value, domain = cookie_value.groups()
  2920. self._set_cookie(domain, cookie, value)
  2921. break
  2922. def get_testcases(self, include_onlymatching=False):
  2923. t = getattr(self, '_TEST', None)
  2924. if t:
  2925. assert not hasattr(self, '_TESTS'), \
  2926. '%s has _TEST and _TESTS' % type(self).__name__
  2927. tests = [t]
  2928. else:
  2929. tests = getattr(self, '_TESTS', [])
  2930. for t in tests:
  2931. if not include_onlymatching and t.get('only_matching', False):
  2932. continue
  2933. t['name'] = type(self).__name__[:-len('IE')]
  2934. yield t
  2935. def is_suitable(self, age_limit):
  2936. """ Test whether the extractor is generally suitable for the given
  2937. age limit (i.e. pornographic sites are not, all others usually are) """
  2938. any_restricted = False
  2939. for tc in self.get_testcases(include_onlymatching=False):
  2940. if tc.get('playlist', []):
  2941. tc = tc['playlist'][0]
  2942. is_restricted = age_restricted(
  2943. tc.get('info_dict', {}).get('age_limit'), age_limit)
  2944. if not is_restricted:
  2945. return True
  2946. any_restricted = any_restricted or is_restricted
  2947. return not any_restricted
  2948. def extract_subtitles(self, *args, **kwargs):
  2949. if (self.get_param('writesubtitles', False)
  2950. or self.get_param('listsubtitles')):
  2951. return self._get_subtitles(*args, **kwargs)
  2952. return {}
  2953. def _get_subtitles(self, *args, **kwargs):
  2954. raise NotImplementedError('This method must be implemented by subclasses')
  2955. @staticmethod
  2956. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  2957. """ Merge subtitle items for one language. Items with duplicated URLs
  2958. will be dropped. """
  2959. list1_urls = set([item['url'] for item in subtitle_list1])
  2960. ret = list(subtitle_list1)
  2961. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  2962. return ret
  2963. @classmethod
  2964. def _merge_subtitles(cls, subtitle_dict1, *subtitle_dicts, **kwargs):
  2965. """ Merge subtitle dictionaries, language by language. """
  2966. # ..., * , target=None
  2967. target = kwargs.get('target')
  2968. if target is None:
  2969. target = dict(subtitle_dict1)
  2970. else:
  2971. subtitle_dicts = (subtitle_dict1,) + subtitle_dicts
  2972. for subtitle_dict in subtitle_dicts:
  2973. for lang in subtitle_dict:
  2974. target[lang] = cls._merge_subtitle_items(target.get(lang, []), subtitle_dict[lang])
  2975. return target
  2976. def extract_automatic_captions(self, *args, **kwargs):
  2977. if (self.get_param('writeautomaticsub', False)
  2978. or self.get_param('listsubtitles')):
  2979. return self._get_automatic_captions(*args, **kwargs)
  2980. return {}
  2981. def _get_automatic_captions(self, *args, **kwargs):
  2982. raise NotImplementedError('This method must be implemented by subclasses')
  2983. def mark_watched(self, *args, **kwargs):
  2984. if (self.get_param('mark_watched', False)
  2985. and (self._get_login_info()[0] is not None
  2986. or self.get_param('cookiefile') is not None)):
  2987. self._mark_watched(*args, **kwargs)
  2988. def _mark_watched(self, *args, **kwargs):
  2989. raise NotImplementedError('This method must be implemented by subclasses')
  2990. def geo_verification_headers(self):
  2991. headers = {}
  2992. geo_verification_proxy = self.get_param('geo_verification_proxy')
  2993. if geo_verification_proxy:
  2994. headers['Ytdl-request-proxy'] = geo_verification_proxy
  2995. return headers
  2996. def _generic_id(self, url):
  2997. return compat_urllib_parse_unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  2998. def _generic_title(self, url):
  2999. return compat_urllib_parse_unquote(os.path.splitext(url_basename(url))[0])
  3000. def _yes_playlist(self, playlist_id, video_id, *args, **kwargs):
  3001. # smuggled_data=None, *, playlist_label='playlist', video_label='video'
  3002. smuggled_data = args[0] if len(args) == 1 else kwargs.get('smuggled_data')
  3003. playlist_label = kwargs.get('playlist_label', 'playlist')
  3004. video_label = kwargs.get('video_label', 'video')
  3005. if not playlist_id or not video_id:
  3006. return not video_id
  3007. no_playlist = (smuggled_data or {}).get('force_noplaylist')
  3008. if no_playlist is not None:
  3009. return not no_playlist
  3010. video_id = '' if video_id is True else ' ' + video_id
  3011. noplaylist = self.get_param('noplaylist')
  3012. self.to_screen(
  3013. 'Downloading just the {0}{1} because of --no-playlist'.format(video_label, video_id)
  3014. if noplaylist else
  3015. 'Downloading {0}{1} - add --no-playlist to download just the {2}{3}'.format(
  3016. playlist_label, '' if playlist_id is True else ' ' + playlist_id,
  3017. video_label, video_id))
  3018. return not noplaylist
  3019. class SearchInfoExtractor(InfoExtractor):
  3020. """
  3021. Base class for paged search queries extractors.
  3022. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  3023. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  3024. """
  3025. @classmethod
  3026. def _make_valid_url(cls):
  3027. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  3028. @classmethod
  3029. def suitable(cls, url):
  3030. return re.match(cls._make_valid_url(), url) is not None
  3031. def _real_extract(self, query):
  3032. mobj = re.match(self._make_valid_url(), query)
  3033. if mobj is None:
  3034. raise ExtractorError('Invalid search query "%s"' % query)
  3035. prefix = mobj.group('prefix')
  3036. query = mobj.group('query')
  3037. if prefix == '':
  3038. return self._get_n_results(query, 1)
  3039. elif prefix == 'all':
  3040. return self._get_n_results(query, self._MAX_RESULTS)
  3041. else:
  3042. n = int(prefix)
  3043. if n <= 0:
  3044. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  3045. elif n > self._MAX_RESULTS:
  3046. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  3047. n = self._MAX_RESULTS
  3048. return self._get_n_results(query, n)
  3049. def _get_n_results(self, query, n):
  3050. """Get a specified number of results for a query"""
  3051. raise NotImplementedError('This method must be implemented by subclasses')
  3052. @property
  3053. def SEARCH_KEY(self):
  3054. return self._SEARCH_KEY