logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

common.py (194608B)


  1. import base64
  2. import collections
  3. import functools
  4. import getpass
  5. import hashlib
  6. import http.client
  7. import http.cookiejar
  8. import http.cookies
  9. import inspect
  10. import itertools
  11. import json
  12. import math
  13. import netrc
  14. import os
  15. import random
  16. import re
  17. import subprocess
  18. import sys
  19. import time
  20. import types
  21. import urllib.parse
  22. import urllib.request
  23. import xml.etree.ElementTree
  24. from ..compat import (
  25. compat_etree_fromstring,
  26. compat_expanduser,
  27. urllib_req_to_req,
  28. )
  29. from ..cookies import LenientSimpleCookie
  30. from ..downloader.f4m import get_base_url, remove_encrypted_media
  31. from ..downloader.hls import HlsFD
  32. from ..networking import HEADRequest, Request
  33. from ..networking.exceptions import (
  34. HTTPError,
  35. IncompleteRead,
  36. TransportError,
  37. network_exceptions,
  38. )
  39. from ..networking.impersonate import ImpersonateTarget
  40. from ..utils import (
  41. IDENTITY,
  42. JSON_LD_RE,
  43. NO_DEFAULT,
  44. ExtractorError,
  45. FormatSorter,
  46. GeoRestrictedError,
  47. GeoUtils,
  48. ISO639Utils,
  49. LenientJSONDecoder,
  50. Popen,
  51. RegexNotFoundError,
  52. RetryManager,
  53. UnsupportedError,
  54. age_restricted,
  55. base_url,
  56. bug_reports_message,
  57. classproperty,
  58. clean_html,
  59. deprecation_warning,
  60. determine_ext,
  61. dict_get,
  62. encode_data_uri,
  63. extract_attributes,
  64. filter_dict,
  65. fix_xml_ampersands,
  66. float_or_none,
  67. format_field,
  68. int_or_none,
  69. join_nonempty,
  70. js_to_json,
  71. mimetype2ext,
  72. netrc_from_content,
  73. orderedSet,
  74. parse_bitrate,
  75. parse_codecs,
  76. parse_duration,
  77. parse_iso8601,
  78. parse_m3u8_attributes,
  79. parse_resolution,
  80. sanitize_filename,
  81. sanitize_url,
  82. smuggle_url,
  83. str_or_none,
  84. str_to_int,
  85. strip_or_none,
  86. traverse_obj,
  87. truncate_string,
  88. try_call,
  89. try_get,
  90. unescapeHTML,
  91. unified_strdate,
  92. unified_timestamp,
  93. url_basename,
  94. url_or_none,
  95. urlhandle_detect_ext,
  96. urljoin,
  97. variadic,
  98. xpath_element,
  99. xpath_text,
  100. xpath_with_ns,
  101. )
  102. class InfoExtractor:
  103. """Information Extractor class.
  104. Information extractors are the classes that, given a URL, extract
  105. information about the video (or videos) the URL refers to. This
  106. information includes the real video URL, the video title, author and
  107. others. The information is stored in a dictionary which is then
  108. passed to the YoutubeDL. The YoutubeDL processes this
  109. information possibly downloading the video to the file system, among
  110. other possible outcomes.
  111. The type field determines the type of the result.
  112. By far the most common value (and the default if _type is missing) is
  113. "video", which indicates a single video.
  114. For a video, the dictionaries must include the following fields:
  115. id: Video identifier.
  116. title: Video title, unescaped. Set to an empty string if video has
  117. no title as opposed to "None" which signifies that the
  118. extractor failed to obtain a title
  119. Additionally, it must contain either a formats entry or a url one:
  120. formats: A list of dictionaries for each format available, ordered
  121. from worst to best quality.
  122. Potential fields:
  123. * url The mandatory URL representing the media:
  124. for plain file media - HTTP URL of this file,
  125. for RTMP - RTMP URL,
  126. for HLS - URL of the M3U8 media playlist,
  127. for HDS - URL of the F4M manifest,
  128. for DASH
  129. - HTTP URL to plain file media (in case of
  130. unfragmented media)
  131. - URL of the MPD manifest or base URL
  132. representing the media if MPD manifest
  133. is parsed from a string (in case of
  134. fragmented media)
  135. for MSS - URL of the ISM manifest.
  136. * request_data Data to send in POST request to the URL
  137. * manifest_url
  138. The URL of the manifest file in case of
  139. fragmented media:
  140. for HLS - URL of the M3U8 master playlist,
  141. for HDS - URL of the F4M manifest,
  142. for DASH - URL of the MPD manifest,
  143. for MSS - URL of the ISM manifest.
  144. * manifest_stream_number (For internal use only)
  145. The index of the stream in the manifest file
  146. * ext Will be calculated from URL if missing
  147. * format A human-readable description of the format
  148. ("mp4 container with h264/opus").
  149. Calculated from the format_id, width, height.
  150. and format_note fields if missing.
  151. * format_id A short description of the format
  152. ("mp4_h264_opus" or "19").
  153. Technically optional, but strongly recommended.
  154. * format_note Additional info about the format
  155. ("3D" or "DASH video")
  156. * width Width of the video, if known
  157. * height Height of the video, if known
  158. * aspect_ratio Aspect ratio of the video, if known
  159. Automatically calculated from width and height
  160. * resolution Textual description of width and height
  161. Automatically calculated from width and height
  162. * dynamic_range The dynamic range of the video. One of:
  163. "SDR" (None), "HDR10", "HDR10+, "HDR12", "HLG, "DV"
  164. * tbr Average bitrate of audio and video in kbps (1000 bits/sec)
  165. * abr Average audio bitrate in kbps (1000 bits/sec)
  166. * acodec Name of the audio codec in use
  167. * asr Audio sampling rate in Hertz
  168. * audio_channels Number of audio channels
  169. * vbr Average video bitrate in kbps (1000 bits/sec)
  170. * fps Frame rate
  171. * vcodec Name of the video codec in use
  172. * container Name of the container format
  173. * filesize The number of bytes, if known in advance
  174. * filesize_approx An estimate for the number of bytes
  175. * player_url SWF Player URL (used for rtmpdump).
  176. * protocol The protocol that will be used for the actual
  177. download, lower-case. One of "http", "https" or
  178. one of the protocols defined in downloader.PROTOCOL_MAP
  179. * fragment_base_url
  180. Base URL for fragments. Each fragment's path
  181. value (if present) will be relative to
  182. this URL.
  183. * fragments A list of fragments of a fragmented media.
  184. Each fragment entry must contain either an url
  185. or a path. If an url is present it should be
  186. considered by a client. Otherwise both path and
  187. fragment_base_url must be present. Here is
  188. the list of all potential fields:
  189. * "url" - fragment's URL
  190. * "path" - fragment's path relative to
  191. fragment_base_url
  192. * "duration" (optional, int or float)
  193. * "filesize" (optional, int)
  194. * is_from_start Is a live format that can be downloaded
  195. from the start. Boolean
  196. * preference Order number of this format. If this field is
  197. present and not None, the formats get sorted
  198. by this field, regardless of all other values.
  199. -1 for default (order by other properties),
  200. -2 or smaller for less than default.
  201. < -1000 to hide the format (if there is
  202. another one which is strictly better)
  203. * language Language code, e.g. "de" or "en-US".
  204. * language_preference Is this in the language mentioned in
  205. the URL?
  206. 10 if it's what the URL is about,
  207. -1 for default (don't know),
  208. -10 otherwise, other values reserved for now.
  209. * quality Order number of the video quality of this
  210. format, irrespective of the file format.
  211. -1 for default (order by other properties),
  212. -2 or smaller for less than default.
  213. * source_preference Order number for this video source
  214. (quality takes higher priority)
  215. -1 for default (order by other properties),
  216. -2 or smaller for less than default.
  217. * http_headers A dictionary of additional HTTP headers
  218. to add to the request.
  219. * stretched_ratio If given and not 1, indicates that the
  220. video's pixels are not square.
  221. width : height ratio as float.
  222. * no_resume The server does not support resuming the
  223. (HTTP or RTMP) download. Boolean.
  224. * has_drm True if the format has DRM and cannot be downloaded.
  225. 'maybe' if the format may have DRM and has to be tested before download.
  226. * extra_param_to_segment_url A query string to append to each
  227. fragment's URL, or to update each existing query string
  228. with. If it is an HLS stream with an AES-128 decryption key,
  229. the query paramaters will be passed to the key URI as well,
  230. unless there is an `extra_param_to_key_url` given,
  231. or unless an external key URI is provided via `hls_aes`.
  232. Only applied by the native HLS/DASH downloaders.
  233. * extra_param_to_key_url A query string to append to the URL
  234. of the format's HLS AES-128 decryption key.
  235. Only applied by the native HLS downloader.
  236. * hls_aes A dictionary of HLS AES-128 decryption information
  237. used by the native HLS downloader to override the
  238. values in the media playlist when an '#EXT-X-KEY' tag
  239. is present in the playlist:
  240. * uri The URI from which the key will be downloaded
  241. * key The key (as hex) used to decrypt fragments.
  242. If `key` is given, any key URI will be ignored
  243. * iv The IV (as hex) used to decrypt fragments
  244. * downloader_options A dictionary of downloader options
  245. (For internal use only)
  246. * http_chunk_size Chunk size for HTTP downloads
  247. * ffmpeg_args Extra arguments for ffmpeg downloader (input)
  248. * ffmpeg_args_out Extra arguments for ffmpeg downloader (output)
  249. * is_dash_periods Whether the format is a result of merging
  250. multiple DASH periods.
  251. RTMP formats can also have the additional fields: page_url,
  252. app, play_path, tc_url, flash_version, rtmp_live, rtmp_conn,
  253. rtmp_protocol, rtmp_real_time
  254. url: Final video URL.
  255. ext: Video filename extension.
  256. format: The video format, defaults to ext (used for --get-format)
  257. player_url: SWF Player URL (used for rtmpdump).
  258. The following fields are optional:
  259. direct: True if a direct video file was given (must only be set by GenericIE)
  260. alt_title: A secondary title of the video.
  261. display_id: An alternative identifier for the video, not necessarily
  262. unique, but available before title. Typically, id is
  263. something like "4234987", title "Dancing naked mole rats",
  264. and display_id "dancing-naked-mole-rats"
  265. thumbnails: A list of dictionaries, with the following entries:
  266. * "id" (optional, string) - Thumbnail format ID
  267. * "url"
  268. * "ext" (optional, string) - actual image extension if not given in URL
  269. * "preference" (optional, int) - quality of the image
  270. * "width" (optional, int)
  271. * "height" (optional, int)
  272. * "resolution" (optional, string "{width}x{height}",
  273. deprecated)
  274. * "filesize" (optional, int)
  275. * "http_headers" (dict) - HTTP headers for the request
  276. thumbnail: Full URL to a video thumbnail image.
  277. description: Full video description.
  278. uploader: Full name of the video uploader.
  279. license: License name the video is licensed under.
  280. creators: List of creators of the video.
  281. timestamp: UNIX timestamp of the moment the video was uploaded
  282. upload_date: Video upload date in UTC (YYYYMMDD).
  283. If not explicitly set, calculated from timestamp
  284. release_timestamp: UNIX timestamp of the moment the video was released.
  285. If it is not clear whether to use timestamp or this, use the former
  286. release_date: The date (YYYYMMDD) when the video was released in UTC.
  287. If not explicitly set, calculated from release_timestamp
  288. release_year: Year (YYYY) as integer when the video or album was released.
  289. To be used if no exact release date is known.
  290. If not explicitly set, calculated from release_date.
  291. modified_timestamp: UNIX timestamp of the moment the video was last modified.
  292. modified_date: The date (YYYYMMDD) when the video was last modified in UTC.
  293. If not explicitly set, calculated from modified_timestamp
  294. uploader_id: Nickname or id of the video uploader.
  295. uploader_url: Full URL to a personal webpage of the video uploader.
  296. channel: Full name of the channel the video is uploaded on.
  297. Note that channel fields may or may not repeat uploader
  298. fields. This depends on a particular extractor.
  299. channel_id: Id of the channel.
  300. channel_url: Full URL to a channel webpage.
  301. channel_follower_count: Number of followers of the channel.
  302. channel_is_verified: Whether the channel is verified on the platform.
  303. location: Physical location where the video was filmed.
  304. subtitles: The available subtitles as a dictionary in the format
  305. {tag: subformats}. "tag" is usually a language code, and
  306. "subformats" is a list sorted from lower to higher
  307. preference, each element is a dictionary with the "ext"
  308. entry and one of:
  309. * "data": The subtitles file contents
  310. * "url": A URL pointing to the subtitles file
  311. It can optionally also have:
  312. * "name": Name or description of the subtitles
  313. * "http_headers": A dictionary of additional HTTP headers
  314. to add to the request.
  315. "ext" will be calculated from URL if missing
  316. automatic_captions: Like 'subtitles'; contains automatically generated
  317. captions instead of normal subtitles
  318. duration: Length of the video in seconds, as an integer or float.
  319. view_count: How many users have watched the video on the platform.
  320. concurrent_view_count: How many users are currently watching the video on the platform.
  321. like_count: Number of positive ratings of the video
  322. dislike_count: Number of negative ratings of the video
  323. repost_count: Number of reposts of the video
  324. average_rating: Average rating given by users, the scale used depends on the webpage
  325. comment_count: Number of comments on the video
  326. comments: A list of comments, each with one or more of the following
  327. properties (all but one of text or html optional):
  328. * "author" - human-readable name of the comment author
  329. * "author_id" - user ID of the comment author
  330. * "author_thumbnail" - The thumbnail of the comment author
  331. * "author_url" - The url to the comment author's page
  332. * "author_is_verified" - Whether the author is verified
  333. on the platform
  334. * "author_is_uploader" - Whether the comment is made by
  335. the video uploader
  336. * "id" - Comment ID
  337. * "html" - Comment as HTML
  338. * "text" - Plain text of the comment
  339. * "timestamp" - UNIX timestamp of comment
  340. * "parent" - ID of the comment this one is replying to.
  341. Set to "root" to indicate that this is a
  342. comment to the original video.
  343. * "like_count" - Number of positive ratings of the comment
  344. * "dislike_count" - Number of negative ratings of the comment
  345. * "is_favorited" - Whether the comment is marked as
  346. favorite by the video uploader
  347. * "is_pinned" - Whether the comment is pinned to
  348. the top of the comments
  349. age_limit: Age restriction for the video, as an integer (years)
  350. webpage_url: The URL to the video webpage, if given to yt-dlp it
  351. should allow to get the same result again. (It will be set
  352. by YoutubeDL if it's missing)
  353. categories: A list of categories that the video falls in, for example
  354. ["Sports", "Berlin"]
  355. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  356. cast: A list of the video cast
  357. is_live: True, False, or None (=unknown). Whether this video is a
  358. live stream that goes on instead of a fixed-length video.
  359. was_live: True, False, or None (=unknown). Whether this video was
  360. originally a live stream.
  361. live_status: None (=unknown), 'is_live', 'is_upcoming', 'was_live', 'not_live',
  362. or 'post_live' (was live, but VOD is not yet processed)
  363. If absent, automatically set from is_live, was_live
  364. start_time: Time in seconds where the reproduction should start, as
  365. specified in the URL.
  366. end_time: Time in seconds where the reproduction should end, as
  367. specified in the URL.
  368. chapters: A list of dictionaries, with the following entries:
  369. * "start_time" - The start time of the chapter in seconds
  370. * "end_time" - The end time of the chapter in seconds
  371. * "title" (optional, string)
  372. heatmap: A list of dictionaries, with the following entries:
  373. * "start_time" - The start time of the data point in seconds
  374. * "end_time" - The end time of the data point in seconds
  375. * "value" - The normalized value of the data point (float between 0 and 1)
  376. playable_in_embed: Whether this video is allowed to play in embedded
  377. players on other sites. Can be True (=always allowed),
  378. False (=never allowed), None (=unknown), or a string
  379. specifying the criteria for embedability; e.g. 'whitelist'
  380. availability: Under what condition the video is available. One of
  381. 'private', 'premium_only', 'subscriber_only', 'needs_auth',
  382. 'unlisted' or 'public'. Use 'InfoExtractor._availability'
  383. to set it
  384. media_type: The type of media as classified by the site, e.g. "episode", "clip", "trailer"
  385. _old_archive_ids: A list of old archive ids needed for backward compatibility
  386. _format_sort_fields: A list of fields to use for sorting formats
  387. __post_extractor: A function to be called just before the metadata is
  388. written to either disk, logger or console. The function
  389. must return a dict which will be added to the info_dict.
  390. This is usefull for additional information that is
  391. time-consuming to extract. Note that the fields thus
  392. extracted will not be available to output template and
  393. match_filter. So, only "comments" and "comment_count" are
  394. currently allowed to be extracted via this method.
  395. The following fields should only be used when the video belongs to some logical
  396. chapter or section:
  397. chapter: Name or title of the chapter the video belongs to.
  398. chapter_number: Number of the chapter the video belongs to, as an integer.
  399. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  400. The following fields should only be used when the video is an episode of some
  401. series, programme or podcast:
  402. series: Title of the series or programme the video episode belongs to.
  403. series_id: Id of the series or programme the video episode belongs to, as a unicode string.
  404. season: Title of the season the video episode belongs to.
  405. season_number: Number of the season the video episode belongs to, as an integer.
  406. season_id: Id of the season the video episode belongs to, as a unicode string.
  407. episode: Title of the video episode. Unlike mandatory video title field,
  408. this field should denote the exact title of the video episode
  409. without any kind of decoration.
  410. episode_number: Number of the video episode within a season, as an integer.
  411. episode_id: Id of the video episode, as a unicode string.
  412. The following fields should only be used when the media is a track or a part of
  413. a music album:
  414. track: Title of the track.
  415. track_number: Number of the track within an album or a disc, as an integer.
  416. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  417. as a unicode string.
  418. artists: List of artists of the track.
  419. composers: List of composers of the piece.
  420. genres: List of genres of the track.
  421. album: Title of the album the track belongs to.
  422. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  423. album_artists: List of all artists appeared on the album.
  424. E.g. ["Ash Borer", "Fell Voices"] or ["Various Artists"].
  425. Useful for splits and compilations.
  426. disc_number: Number of the disc or other physical medium the track belongs to,
  427. as an integer.
  428. The following fields should only be set for clips that should be cut from the original video:
  429. section_start: Start time of the section in seconds
  430. section_end: End time of the section in seconds
  431. The following fields should only be set for storyboards:
  432. rows: Number of rows in each storyboard fragment, as an integer
  433. columns: Number of columns in each storyboard fragment, as an integer
  434. The following fields are deprecated and should not be set by new code:
  435. composer: Use "composers" instead.
  436. Composer(s) of the piece, comma-separated.
  437. artist: Use "artists" instead.
  438. Artist(s) of the track, comma-separated.
  439. genre: Use "genres" instead.
  440. Genre(s) of the track, comma-separated.
  441. album_artist: Use "album_artists" instead.
  442. All artists appeared on the album, comma-separated.
  443. creator: Use "creators" instead.
  444. The creator of the video.
  445. Unless mentioned otherwise, the fields should be Unicode strings.
  446. Unless mentioned otherwise, None is equivalent to absence of information.
  447. _type "playlist" indicates multiple videos.
  448. There must be a key "entries", which is a list, an iterable, or a PagedList
  449. object, each element of which is a valid dictionary by this specification.
  450. Additionally, playlists can have "id", "title", and any other relevant
  451. attributes with the same semantics as videos (see above).
  452. It can also have the following optional fields:
  453. playlist_count: The total number of videos in a playlist. If not given,
  454. YoutubeDL tries to calculate it from "entries"
  455. _type "multi_video" indicates that there are multiple videos that
  456. form a single show, for examples multiple acts of an opera or TV episode.
  457. It must have an entries key like a playlist and contain all the keys
  458. required for a video at the same time.
  459. _type "url" indicates that the video must be extracted from another
  460. location, possibly by a different extractor. Its only required key is:
  461. "url" - the next URL to extract.
  462. The key "ie_key" can be set to the class name (minus the trailing "IE",
  463. e.g. "Youtube") if the extractor class is known in advance.
  464. Additionally, the dictionary may have any properties of the resolved entity
  465. known in advance, for example "title" if the title of the referred video is
  466. known ahead of time.
  467. _type "url_transparent" entities have the same specification as "url", but
  468. indicate that the given additional information is more precise than the one
  469. associated with the resolved URL.
  470. This is useful when a site employs a video service that hosts the video and
  471. its technical metadata, but that video service does not embed a useful
  472. title, description etc.
  473. Subclasses of this should also be added to the list of extractors and
  474. should define _VALID_URL as a regexp or a Sequence of regexps, and
  475. re-define the _real_extract() and (optionally) _real_initialize() methods.
  476. Subclasses may also override suitable() if necessary, but ensure the function
  477. signature is preserved and that this function imports everything it needs
  478. (except other extractors), so that lazy_extractors works correctly.
  479. Subclasses can define a list of _EMBED_REGEX, which will be searched for in
  480. the HTML of Generic webpages. It may also override _extract_embed_urls
  481. or _extract_from_webpage as necessary. While these are normally classmethods,
  482. _extract_from_webpage is allowed to be an instance method.
  483. _extract_from_webpage may raise self.StopExtraction to stop further
  484. processing of the webpage and obtain exclusive rights to it. This is useful
  485. when the extractor cannot reliably be matched using just the URL,
  486. e.g. invidious/peertube instances
  487. Embed-only extractors can be defined by setting _VALID_URL = False.
  488. To support username + password (or netrc) login, the extractor must define a
  489. _NETRC_MACHINE and re-define _perform_login(username, password) and
  490. (optionally) _initialize_pre_login() methods. The _perform_login method will
  491. be called between _initialize_pre_login and _real_initialize if credentials
  492. are passed by the user. In cases where it is necessary to have the login
  493. process as part of the extraction rather than initialization, _perform_login
  494. can be left undefined.
  495. _GEO_BYPASS attribute may be set to False in order to disable
  496. geo restriction bypass mechanisms for a particular extractor.
  497. Though it won't disable explicit geo restriction bypass based on
  498. country code provided with geo_bypass_country.
  499. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  500. countries for this extractor. One of these countries will be used by
  501. geo restriction bypass mechanism right away in order to bypass
  502. geo restriction, of course, if the mechanism is not disabled.
  503. _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
  504. IP blocks in CIDR notation for this extractor. One of these IP blocks
  505. will be used by geo restriction bypass mechanism similarly
  506. to _GEO_COUNTRIES.
  507. The _ENABLED attribute should be set to False for IEs that
  508. are disabled by default and must be explicitly enabled.
  509. The _WORKING attribute should be set to False for broken IEs
  510. in order to warn the users and skip the tests.
  511. """
  512. _ready = False
  513. _downloader = None
  514. _x_forwarded_for_ip = None
  515. _GEO_BYPASS = True
  516. _GEO_COUNTRIES = None
  517. _GEO_IP_BLOCKS = None
  518. _WORKING = True
  519. _ENABLED = True
  520. _NETRC_MACHINE = None
  521. IE_DESC = None
  522. SEARCH_KEY = None
  523. _VALID_URL = None
  524. _EMBED_REGEX = []
  525. def _login_hint(self, method=NO_DEFAULT, netrc=None):
  526. password_hint = f'--username and --password, --netrc-cmd, or --netrc ({netrc or self._NETRC_MACHINE}) to provide account credentials'
  527. cookies_hint = 'See https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp for how to manually pass cookies'
  528. return {
  529. None: '',
  530. 'any': f'Use --cookies, --cookies-from-browser, {password_hint}. {cookies_hint}',
  531. 'password': f'Use {password_hint}',
  532. 'cookies': f'Use --cookies-from-browser or --cookies for the authentication. {cookies_hint}',
  533. 'session_cookies': f'Use --cookies for the authentication (--cookies-from-browser might not work). {cookies_hint}',
  534. }[method if method is not NO_DEFAULT else 'any' if self.supports_login() else 'cookies']
  535. def __init__(self, downloader=None):
  536. """Constructor. Receives an optional downloader (a YoutubeDL instance).
  537. If a downloader is not passed during initialization,
  538. it must be set using "set_downloader()" before "extract()" is called"""
  539. self._ready = False
  540. self._x_forwarded_for_ip = None
  541. self._printed_messages = set()
  542. self.set_downloader(downloader)
  543. @classmethod
  544. def _match_valid_url(cls, url):
  545. if cls._VALID_URL is False:
  546. return None
  547. # This does not use has/getattr intentionally - we want to know whether
  548. # we have cached the regexp for *this* class, whereas getattr would also
  549. # match the superclass
  550. if '_VALID_URL_RE' not in cls.__dict__:
  551. cls._VALID_URL_RE = tuple(map(re.compile, variadic(cls._VALID_URL)))
  552. return next(filter(None, (regex.match(url) for regex in cls._VALID_URL_RE)), None)
  553. @classmethod
  554. def suitable(cls, url):
  555. """Receives a URL and returns True if suitable for this IE."""
  556. # This function must import everything it needs (except other extractors),
  557. # so that lazy_extractors works correctly
  558. return cls._match_valid_url(url) is not None
  559. @classmethod
  560. def _match_id(cls, url):
  561. return cls._match_valid_url(url).group('id')
  562. @classmethod
  563. def get_temp_id(cls, url):
  564. try:
  565. return cls._match_id(url)
  566. except (IndexError, AttributeError):
  567. return None
  568. @classmethod
  569. def working(cls):
  570. """Getter method for _WORKING."""
  571. return cls._WORKING
  572. @classmethod
  573. def supports_login(cls):
  574. return bool(cls._NETRC_MACHINE)
  575. def initialize(self):
  576. """Initializes an instance (authentication, etc)."""
  577. self._printed_messages = set()
  578. self._initialize_geo_bypass({
  579. 'countries': self._GEO_COUNTRIES,
  580. 'ip_blocks': self._GEO_IP_BLOCKS,
  581. })
  582. if not self._ready:
  583. self._initialize_pre_login()
  584. if self.supports_login():
  585. username, password = self._get_login_info()
  586. if username:
  587. self._perform_login(username, password)
  588. elif self.get_param('username') and False not in (self.IE_DESC, self._NETRC_MACHINE):
  589. self.report_warning(f'Login with password is not supported for this website. {self._login_hint("cookies")}')
  590. self._real_initialize()
  591. self._ready = True
  592. def _initialize_geo_bypass(self, geo_bypass_context):
  593. """
  594. Initialize geo restriction bypass mechanism.
  595. This method is used to initialize geo bypass mechanism based on faking
  596. X-Forwarded-For HTTP header. A random country from provided country list
  597. is selected and a random IP belonging to this country is generated. This
  598. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  599. HTTP requests.
  600. This method will be used for initial geo bypass mechanism initialization
  601. during the instance initialization with _GEO_COUNTRIES and
  602. _GEO_IP_BLOCKS.
  603. You may also manually call it from extractor's code if geo bypass
  604. information is not available beforehand (e.g. obtained during
  605. extraction) or due to some other reason. In this case you should pass
  606. this information in geo bypass context passed as first argument. It may
  607. contain following fields:
  608. countries: List of geo unrestricted countries (similar
  609. to _GEO_COUNTRIES)
  610. ip_blocks: List of geo unrestricted IP blocks in CIDR notation
  611. (similar to _GEO_IP_BLOCKS)
  612. """
  613. if not self._x_forwarded_for_ip:
  614. # Geo bypass mechanism is explicitly disabled by user
  615. if not self.get_param('geo_bypass', True):
  616. return
  617. if not geo_bypass_context:
  618. geo_bypass_context = {}
  619. # Backward compatibility: previously _initialize_geo_bypass
  620. # expected a list of countries, some 3rd party code may still use
  621. # it this way
  622. if isinstance(geo_bypass_context, (list, tuple)):
  623. geo_bypass_context = {
  624. 'countries': geo_bypass_context,
  625. }
  626. # The whole point of geo bypass mechanism is to fake IP
  627. # as X-Forwarded-For HTTP header based on some IP block or
  628. # country code.
  629. # Path 1: bypassing based on IP block in CIDR notation
  630. # Explicit IP block specified by user, use it right away
  631. # regardless of whether extractor is geo bypassable or not
  632. ip_block = self.get_param('geo_bypass_ip_block', None)
  633. # Otherwise use random IP block from geo bypass context but only
  634. # if extractor is known as geo bypassable
  635. if not ip_block:
  636. ip_blocks = geo_bypass_context.get('ip_blocks')
  637. if self._GEO_BYPASS and ip_blocks:
  638. ip_block = random.choice(ip_blocks)
  639. if ip_block:
  640. self._x_forwarded_for_ip = GeoUtils.random_ipv4(ip_block)
  641. self.write_debug(f'Using fake IP {self._x_forwarded_for_ip} as X-Forwarded-For')
  642. return
  643. # Path 2: bypassing based on country code
  644. # Explicit country code specified by user, use it right away
  645. # regardless of whether extractor is geo bypassable or not
  646. country = self.get_param('geo_bypass_country', None)
  647. # Otherwise use random country code from geo bypass context but
  648. # only if extractor is known as geo bypassable
  649. if not country:
  650. countries = geo_bypass_context.get('countries')
  651. if self._GEO_BYPASS and countries:
  652. country = random.choice(countries)
  653. if country:
  654. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country)
  655. self._downloader.write_debug(
  656. f'Using fake IP {self._x_forwarded_for_ip} ({country.upper()}) as X-Forwarded-For')
  657. def extract(self, url):
  658. """Extracts URL information and returns it in list of dicts."""
  659. try:
  660. for _ in range(2):
  661. try:
  662. self.initialize()
  663. self.to_screen('Extracting URL: %s' % (
  664. url if self.get_param('verbose') else truncate_string(url, 100, 20)))
  665. ie_result = self._real_extract(url)
  666. if ie_result is None:
  667. return None
  668. if self._x_forwarded_for_ip:
  669. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  670. subtitles = ie_result.get('subtitles') or {}
  671. if 'no-live-chat' in self.get_param('compat_opts'):
  672. for lang in ('live_chat', 'comments', 'danmaku'):
  673. subtitles.pop(lang, None)
  674. return ie_result
  675. except GeoRestrictedError as e:
  676. if self.__maybe_fake_ip_and_retry(e.countries):
  677. continue
  678. raise
  679. except UnsupportedError:
  680. raise
  681. except ExtractorError as e:
  682. e.video_id = e.video_id or self.get_temp_id(url)
  683. e.ie = e.ie or self.IE_NAME
  684. e.traceback = e.traceback or sys.exc_info()[2]
  685. raise
  686. except IncompleteRead as e:
  687. raise ExtractorError('A network error has occurred.', cause=e, expected=True, video_id=self.get_temp_id(url))
  688. except (KeyError, StopIteration) as e:
  689. raise ExtractorError('An extractor error has occurred.', cause=e, video_id=self.get_temp_id(url))
  690. def __maybe_fake_ip_and_retry(self, countries):
  691. if (not self.get_param('geo_bypass_country', None)
  692. and self._GEO_BYPASS
  693. and self.get_param('geo_bypass', True)
  694. and not self._x_forwarded_for_ip
  695. and countries):
  696. country_code = random.choice(countries)
  697. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  698. if self._x_forwarded_for_ip:
  699. self.report_warning(
  700. 'Video is geo restricted. Retrying extraction with fake IP '
  701. f'{self._x_forwarded_for_ip} ({country_code.upper()}) as X-Forwarded-For.')
  702. return True
  703. return False
  704. def set_downloader(self, downloader):
  705. """Sets a YoutubeDL instance as the downloader for this IE."""
  706. self._downloader = downloader
  707. @property
  708. def cache(self):
  709. return self._downloader.cache
  710. @property
  711. def cookiejar(self):
  712. return self._downloader.cookiejar
  713. def _initialize_pre_login(self):
  714. """ Initialization before login. Redefine in subclasses."""
  715. pass
  716. def _perform_login(self, username, password):
  717. """ Login with username and password. Redefine in subclasses."""
  718. pass
  719. def _real_initialize(self):
  720. """Real initialization process. Redefine in subclasses."""
  721. pass
  722. def _real_extract(self, url):
  723. """Real extraction process. Redefine in subclasses."""
  724. raise NotImplementedError('This method must be implemented by subclasses')
  725. @classmethod
  726. def ie_key(cls):
  727. """A string for getting the InfoExtractor with get_info_extractor"""
  728. return cls.__name__[:-2]
  729. @classproperty
  730. def IE_NAME(cls):
  731. return cls.__name__[:-2]
  732. @staticmethod
  733. def __can_accept_status_code(err, expected_status):
  734. assert isinstance(err, HTTPError)
  735. if expected_status is None:
  736. return False
  737. elif callable(expected_status):
  738. return expected_status(err.status) is True
  739. else:
  740. return err.status in variadic(expected_status)
  741. def _create_request(self, url_or_request, data=None, headers=None, query=None, extensions=None):
  742. if isinstance(url_or_request, urllib.request.Request):
  743. self._downloader.deprecation_warning(
  744. 'Passing a urllib.request.Request to _create_request() is deprecated. '
  745. 'Use yt_dlp.networking.common.Request instead.')
  746. url_or_request = urllib_req_to_req(url_or_request)
  747. elif not isinstance(url_or_request, Request):
  748. url_or_request = Request(url_or_request)
  749. url_or_request.update(data=data, headers=headers, query=query, extensions=extensions)
  750. return url_or_request
  751. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None,
  752. headers=None, query=None, expected_status=None, impersonate=None, require_impersonation=False):
  753. """
  754. Return the response handle.
  755. See _download_webpage docstring for arguments specification.
  756. """
  757. if not self._downloader._first_webpage_request:
  758. sleep_interval = self.get_param('sleep_interval_requests') or 0
  759. if sleep_interval > 0:
  760. self.to_screen(f'Sleeping {sleep_interval} seconds ...')
  761. time.sleep(sleep_interval)
  762. else:
  763. self._downloader._first_webpage_request = False
  764. if note is None:
  765. self.report_download_webpage(video_id)
  766. elif note is not False:
  767. if video_id is None:
  768. self.to_screen(str(note))
  769. else:
  770. self.to_screen(f'{video_id}: {note}')
  771. # Some sites check X-Forwarded-For HTTP header in order to figure out
  772. # the origin of the client behind proxy. This allows bypassing geo
  773. # restriction by faking this header's value to IP that belongs to some
  774. # geo unrestricted country. We will do so once we encounter any
  775. # geo restriction error.
  776. if self._x_forwarded_for_ip:
  777. headers = (headers or {}).copy()
  778. headers.setdefault('X-Forwarded-For', self._x_forwarded_for_ip)
  779. extensions = {}
  780. if impersonate in (True, ''):
  781. impersonate = ImpersonateTarget()
  782. requested_targets = [
  783. t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t)
  784. for t in variadic(impersonate)
  785. ] if impersonate else []
  786. available_target = next(filter(self._downloader._impersonate_target_available, requested_targets), None)
  787. if available_target:
  788. extensions['impersonate'] = available_target
  789. elif requested_targets:
  790. message = 'The extractor is attempting impersonation, but '
  791. message += (
  792. 'no impersonate target is available' if not str(impersonate)
  793. else f'none of these impersonate targets are available: "{", ".join(map(str, requested_targets))}"')
  794. info_msg = ('see https://github.com/yt-dlp/yt-dlp#impersonation '
  795. 'for information on installing the required dependencies')
  796. if require_impersonation:
  797. raise ExtractorError(f'{message}; {info_msg}', expected=True)
  798. self.report_warning(f'{message}; if you encounter errors, then {info_msg}', only_once=True)
  799. try:
  800. return self._downloader.urlopen(self._create_request(url_or_request, data, headers, query, extensions))
  801. except network_exceptions as err:
  802. if isinstance(err, HTTPError):
  803. if self.__can_accept_status_code(err, expected_status):
  804. return err.response
  805. if errnote is False:
  806. return False
  807. if errnote is None:
  808. errnote = 'Unable to download webpage'
  809. errmsg = f'{errnote}: {err}'
  810. if fatal:
  811. raise ExtractorError(errmsg, cause=err)
  812. else:
  813. self.report_warning(errmsg)
  814. return False
  815. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True,
  816. encoding=None, data=None, headers={}, query={}, expected_status=None,
  817. impersonate=None, require_impersonation=False):
  818. """
  819. Return a tuple (page content as string, URL handle).
  820. Arguments:
  821. url_or_request -- plain text URL as a string or
  822. a yt_dlp.networking.Request object
  823. video_id -- Video/playlist/item identifier (string)
  824. Keyword arguments:
  825. note -- note printed before downloading (string)
  826. errnote -- note printed in case of an error (string)
  827. fatal -- flag denoting whether error should be considered fatal,
  828. i.e. whether it should cause ExtractionError to be raised,
  829. otherwise a warning will be reported and extraction continued
  830. encoding -- encoding for a page content decoding, guessed automatically
  831. when not explicitly specified
  832. data -- POST data (bytes)
  833. headers -- HTTP headers (dict)
  834. query -- URL query (dict)
  835. expected_status -- allows to accept failed HTTP requests (non 2xx
  836. status code) by explicitly specifying a set of accepted status
  837. codes. Can be any of the following entities:
  838. - an integer type specifying an exact failed status code to
  839. accept
  840. - a list or a tuple of integer types specifying a list of
  841. failed status codes to accept
  842. - a callable accepting an actual failed status code and
  843. returning True if it should be accepted
  844. Note that this argument does not affect success status codes (2xx)
  845. which are always accepted.
  846. impersonate -- the impersonate target. Can be any of the following entities:
  847. - an instance of yt_dlp.networking.impersonate.ImpersonateTarget
  848. - a string in the format of CLIENT[:OS]
  849. - a list or a tuple of CLIENT[:OS] strings or ImpersonateTarget instances
  850. - a boolean value; True means any impersonate target is sufficient
  851. require_impersonation -- flag to toggle whether the request should raise an error
  852. if impersonation is not possible (bool, default: False)
  853. """
  854. # Strip hashes from the URL (#1038)
  855. if isinstance(url_or_request, str):
  856. url_or_request = url_or_request.partition('#')[0]
  857. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data,
  858. headers=headers, query=query, expected_status=expected_status,
  859. impersonate=impersonate, require_impersonation=require_impersonation)
  860. if urlh is False:
  861. assert not fatal
  862. return False
  863. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal,
  864. encoding=encoding, data=data)
  865. if content is False:
  866. assert not fatal
  867. return False
  868. return (content, urlh)
  869. @staticmethod
  870. def _guess_encoding_from_content(content_type, webpage_bytes):
  871. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  872. if m:
  873. encoding = m.group(1)
  874. else:
  875. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  876. webpage_bytes[:1024])
  877. if m:
  878. encoding = m.group(1).decode('ascii')
  879. elif webpage_bytes.startswith(b'\xff\xfe'):
  880. encoding = 'utf-16'
  881. else:
  882. encoding = 'utf-8'
  883. return encoding
  884. def __check_blocked(self, content):
  885. first_block = content[:512]
  886. if ('<title>Access to this site is blocked</title>' in content
  887. and 'Websense' in first_block):
  888. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  889. blocked_iframe = self._html_search_regex(
  890. r'<iframe src="([^"]+)"', content,
  891. 'Websense information URL', default=None)
  892. if blocked_iframe:
  893. msg += f' Visit {blocked_iframe} for more details'
  894. raise ExtractorError(msg, expected=True)
  895. if '<title>The URL you requested has been blocked</title>' in first_block:
  896. msg = (
  897. 'Access to this webpage has been blocked by Indian censorship. '
  898. 'Use a VPN or proxy server (with --proxy) to route around it.')
  899. block_msg = self._html_search_regex(
  900. r'</h1><p>(.*?)</p>',
  901. content, 'block message', default=None)
  902. if block_msg:
  903. msg += ' (Message: "{}")'.format(block_msg.replace('\n', ' '))
  904. raise ExtractorError(msg, expected=True)
  905. if ('<title>TTK :: Доступ к ресурсу ограничен</title>' in content
  906. and 'blocklist.rkn.gov.ru' in content):
  907. raise ExtractorError(
  908. 'Access to this webpage has been blocked by decision of the Russian government. '
  909. 'Visit http://blocklist.rkn.gov.ru/ for a block reason.',
  910. expected=True)
  911. def _request_dump_filename(self, url, video_id, data=None):
  912. if data is not None:
  913. data = hashlib.md5(data).hexdigest()
  914. basen = join_nonempty(video_id, data, url, delim='_')
  915. trim_length = self.get_param('trim_file_name') or 240
  916. if len(basen) > trim_length:
  917. h = '___' + hashlib.md5(basen.encode()).hexdigest()
  918. basen = basen[:trim_length - len(h)] + h
  919. filename = sanitize_filename(f'{basen}.dump', restricted=True)
  920. # Working around MAX_PATH limitation on Windows (see
  921. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  922. if os.name == 'nt':
  923. absfilepath = os.path.abspath(filename)
  924. if len(absfilepath) > 259:
  925. filename = fR'\\?\{absfilepath}'
  926. return filename
  927. def __decode_webpage(self, webpage_bytes, encoding, headers):
  928. if not encoding:
  929. encoding = self._guess_encoding_from_content(headers.get('Content-Type', ''), webpage_bytes)
  930. try:
  931. return webpage_bytes.decode(encoding, 'replace')
  932. except LookupError:
  933. return webpage_bytes.decode('utf-8', 'replace')
  934. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True,
  935. prefix=None, encoding=None, data=None):
  936. try:
  937. webpage_bytes = urlh.read()
  938. except TransportError as err:
  939. errmsg = f'{video_id}: Error reading response: {err.msg}'
  940. if fatal:
  941. raise ExtractorError(errmsg, cause=err)
  942. self.report_warning(errmsg)
  943. return False
  944. if prefix is not None:
  945. webpage_bytes = prefix + webpage_bytes
  946. if self.get_param('dump_intermediate_pages', False):
  947. self.to_screen('Dumping request to ' + urlh.url)
  948. dump = base64.b64encode(webpage_bytes).decode('ascii')
  949. self._downloader.to_screen(dump)
  950. if self.get_param('write_pages'):
  951. if isinstance(url_or_request, Request):
  952. data = self._create_request(url_or_request, data).data
  953. filename = self._request_dump_filename(urlh.url, video_id, data)
  954. self.to_screen(f'Saving request to {filename}')
  955. with open(filename, 'wb') as outf:
  956. outf.write(webpage_bytes)
  957. content = self.__decode_webpage(webpage_bytes, encoding, urlh.headers)
  958. self.__check_blocked(content)
  959. return content
  960. def __print_error(self, errnote, fatal, video_id, err):
  961. if fatal:
  962. raise ExtractorError(f'{video_id}: {errnote}', cause=err)
  963. elif errnote:
  964. self.report_warning(f'{video_id}: {errnote}: {err}')
  965. def _parse_xml(self, xml_string, video_id, transform_source=None, fatal=True, errnote=None):
  966. if transform_source:
  967. xml_string = transform_source(xml_string)
  968. try:
  969. return compat_etree_fromstring(xml_string.encode())
  970. except xml.etree.ElementTree.ParseError as ve:
  971. self.__print_error('Failed to parse XML' if errnote is None else errnote, fatal, video_id, ve)
  972. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True, errnote=None, **parser_kwargs):
  973. try:
  974. return json.loads(
  975. json_string, cls=LenientJSONDecoder, strict=False, transform_source=transform_source, **parser_kwargs)
  976. except ValueError as ve:
  977. self.__print_error('Failed to parse JSON' if errnote is None else errnote, fatal, video_id, ve)
  978. def _parse_socket_response_as_json(self, data, *args, **kwargs):
  979. return self._parse_json(data[data.find('{'):data.rfind('}') + 1], *args, **kwargs)
  980. def __create_download_methods(name, parser, note, errnote, return_value):
  981. def parse(ie, content, *args, errnote=errnote, **kwargs):
  982. if parser is None:
  983. return content
  984. if errnote is False:
  985. kwargs['errnote'] = errnote
  986. # parser is fetched by name so subclasses can override it
  987. return getattr(ie, parser)(content, *args, **kwargs)
  988. def download_handle(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  989. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  990. impersonate=None, require_impersonation=False):
  991. res = self._download_webpage_handle(
  992. url_or_request, video_id, note=note, errnote=errnote, fatal=fatal, encoding=encoding,
  993. data=data, headers=headers, query=query, expected_status=expected_status,
  994. impersonate=impersonate, require_impersonation=require_impersonation)
  995. if res is False:
  996. return res
  997. content, urlh = res
  998. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote), urlh
  999. def download_content(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  1000. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  1001. impersonate=None, require_impersonation=False):
  1002. if self.get_param('load_pages'):
  1003. url_or_request = self._create_request(url_or_request, data, headers, query)
  1004. filename = self._request_dump_filename(url_or_request.url, video_id, url_or_request.data)
  1005. self.to_screen(f'Loading request from {filename}')
  1006. try:
  1007. with open(filename, 'rb') as dumpf:
  1008. webpage_bytes = dumpf.read()
  1009. except OSError as e:
  1010. self.report_warning(f'Unable to load request from disk: {e}')
  1011. else:
  1012. content = self.__decode_webpage(webpage_bytes, encoding, url_or_request.headers)
  1013. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote)
  1014. kwargs = {
  1015. 'note': note,
  1016. 'errnote': errnote,
  1017. 'transform_source': transform_source,
  1018. 'fatal': fatal,
  1019. 'encoding': encoding,
  1020. 'data': data,
  1021. 'headers': headers,
  1022. 'query': query,
  1023. 'expected_status': expected_status,
  1024. 'impersonate': impersonate,
  1025. 'require_impersonation': require_impersonation,
  1026. }
  1027. if parser is None:
  1028. kwargs.pop('transform_source')
  1029. # The method is fetched by name so subclasses can override _download_..._handle
  1030. res = getattr(self, download_handle.__name__)(url_or_request, video_id, **kwargs)
  1031. return res if res is False else res[0]
  1032. def impersonate(func, name, return_value):
  1033. func.__name__, func.__qualname__ = name, f'InfoExtractor.{name}'
  1034. func.__doc__ = f'''
  1035. @param transform_source Apply this transformation before parsing
  1036. @returns {return_value}
  1037. See _download_webpage_handle docstring for other arguments specification
  1038. '''
  1039. impersonate(download_handle, f'_download_{name}_handle', f'({return_value}, URL handle)')
  1040. impersonate(download_content, f'_download_{name}', f'{return_value}')
  1041. return download_handle, download_content
  1042. _download_xml_handle, _download_xml = __create_download_methods(
  1043. 'xml', '_parse_xml', 'Downloading XML', 'Unable to download XML', 'xml as an xml.etree.ElementTree.Element')
  1044. _download_json_handle, _download_json = __create_download_methods(
  1045. 'json', '_parse_json', 'Downloading JSON metadata', 'Unable to download JSON metadata', 'JSON object as a dict')
  1046. _download_socket_json_handle, _download_socket_json = __create_download_methods(
  1047. 'socket_json', '_parse_socket_response_as_json', 'Polling socket', 'Unable to poll socket', 'JSON object as a dict')
  1048. __download_webpage = __create_download_methods('webpage', None, None, None, 'data of the page as a string')[1]
  1049. def _download_webpage(
  1050. self, url_or_request, video_id, note=None, errnote=None,
  1051. fatal=True, tries=1, timeout=NO_DEFAULT, *args, **kwargs):
  1052. """
  1053. Return the data of the page as a string.
  1054. Keyword arguments:
  1055. tries -- number of tries
  1056. timeout -- sleep interval between tries
  1057. See _download_webpage_handle docstring for other arguments specification.
  1058. """
  1059. R''' # NB: These are unused; should they be deprecated?
  1060. if tries != 1:
  1061. self._downloader.deprecation_warning('tries argument is deprecated in InfoExtractor._download_webpage')
  1062. if timeout is NO_DEFAULT:
  1063. timeout = 5
  1064. else:
  1065. self._downloader.deprecation_warning('timeout argument is deprecated in InfoExtractor._download_webpage')
  1066. '''
  1067. try_count = 0
  1068. while True:
  1069. try:
  1070. return self.__download_webpage(url_or_request, video_id, note, errnote, None, fatal, *args, **kwargs)
  1071. except IncompleteRead as e:
  1072. try_count += 1
  1073. if try_count >= tries:
  1074. raise e
  1075. self._sleep(timeout, video_id)
  1076. def report_warning(self, msg, video_id=None, *args, only_once=False, **kwargs):
  1077. idstr = format_field(video_id, None, '%s: ')
  1078. msg = f'[{self.IE_NAME}] {idstr}{msg}'
  1079. if only_once:
  1080. if f'WARNING: {msg}' in self._printed_messages:
  1081. return
  1082. self._printed_messages.add(f'WARNING: {msg}')
  1083. self._downloader.report_warning(msg, *args, **kwargs)
  1084. def to_screen(self, msg, *args, **kwargs):
  1085. """Print msg to screen, prefixing it with '[ie_name]'"""
  1086. self._downloader.to_screen(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1087. def write_debug(self, msg, *args, **kwargs):
  1088. self._downloader.write_debug(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1089. def get_param(self, name, default=None, *args, **kwargs):
  1090. if self._downloader:
  1091. return self._downloader.params.get(name, default, *args, **kwargs)
  1092. return default
  1093. def report_drm(self, video_id, partial=NO_DEFAULT):
  1094. if partial is not NO_DEFAULT:
  1095. self._downloader.deprecation_warning('InfoExtractor.report_drm no longer accepts the argument partial')
  1096. self.raise_no_formats('This video is DRM protected', expected=True, video_id=video_id)
  1097. def report_extraction(self, id_or_name):
  1098. """Report information extraction."""
  1099. self.to_screen(f'{id_or_name}: Extracting information')
  1100. def report_download_webpage(self, video_id):
  1101. """Report webpage download."""
  1102. self.to_screen(f'{video_id}: Downloading webpage')
  1103. def report_age_confirmation(self):
  1104. """Report attempt to confirm age."""
  1105. self.to_screen('Confirming age')
  1106. def report_login(self):
  1107. """Report attempt to log in."""
  1108. self.to_screen('Logging in')
  1109. def raise_login_required(
  1110. self, msg='This video is only available for registered users',
  1111. metadata_available=False, method=NO_DEFAULT):
  1112. if metadata_available and (
  1113. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1114. self.report_warning(msg)
  1115. return
  1116. msg += format_field(self._login_hint(method), None, '. %s')
  1117. raise ExtractorError(msg, expected=True)
  1118. def raise_geo_restricted(
  1119. self, msg='This video is not available from your location due to geo restriction',
  1120. countries=None, metadata_available=False):
  1121. if metadata_available and (
  1122. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1123. self.report_warning(msg)
  1124. else:
  1125. raise GeoRestrictedError(msg, countries=countries)
  1126. def raise_no_formats(self, msg, expected=False, video_id=None):
  1127. if expected and (
  1128. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1129. self.report_warning(msg, video_id)
  1130. elif isinstance(msg, ExtractorError):
  1131. raise msg
  1132. else:
  1133. raise ExtractorError(msg, expected=expected, video_id=video_id)
  1134. # Methods for following #608
  1135. @staticmethod
  1136. def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs):
  1137. """Returns a URL that points to a page that should be processed"""
  1138. if ie is not None:
  1139. kwargs['ie_key'] = ie if isinstance(ie, str) else ie.ie_key()
  1140. if video_id is not None:
  1141. kwargs['id'] = video_id
  1142. if video_title is not None:
  1143. kwargs['title'] = video_title
  1144. return {
  1145. **kwargs,
  1146. '_type': 'url_transparent' if url_transparent else 'url',
  1147. 'url': url,
  1148. }
  1149. @classmethod
  1150. def playlist_from_matches(cls, matches, playlist_id=None, playlist_title=None,
  1151. getter=IDENTITY, ie=None, video_kwargs=None, **kwargs):
  1152. return cls.playlist_result(
  1153. (cls.url_result(m, ie, **(video_kwargs or {})) for m in orderedSet(map(getter, matches), lazy=True)),
  1154. playlist_id, playlist_title, **kwargs)
  1155. @staticmethod
  1156. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None, *, multi_video=False, **kwargs):
  1157. """Returns a playlist"""
  1158. if playlist_id:
  1159. kwargs['id'] = playlist_id
  1160. if playlist_title:
  1161. kwargs['title'] = playlist_title
  1162. if playlist_description is not None:
  1163. kwargs['description'] = playlist_description
  1164. return {
  1165. **kwargs,
  1166. '_type': 'multi_video' if multi_video else 'playlist',
  1167. 'entries': entries,
  1168. }
  1169. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1170. """
  1171. Perform a regex search on the given string, using a single or a list of
  1172. patterns returning the first matching group.
  1173. In case of failure return a default value or raise a WARNING or a
  1174. RegexNotFoundError, depending on fatal, specifying the field name.
  1175. """
  1176. if string is None:
  1177. mobj = None
  1178. elif isinstance(pattern, (str, re.Pattern)):
  1179. mobj = re.search(pattern, string, flags)
  1180. else:
  1181. for p in pattern:
  1182. mobj = re.search(p, string, flags)
  1183. if mobj:
  1184. break
  1185. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1186. if mobj:
  1187. if group is None:
  1188. # return the first matching group
  1189. return next(g for g in mobj.groups() if g is not None)
  1190. elif isinstance(group, (list, tuple)):
  1191. return tuple(mobj.group(g) for g in group)
  1192. else:
  1193. return mobj.group(group)
  1194. elif default is not NO_DEFAULT:
  1195. return default
  1196. elif fatal:
  1197. raise RegexNotFoundError(f'Unable to extract {_name}')
  1198. else:
  1199. self.report_warning(f'unable to extract {_name}' + bug_reports_message())
  1200. return None
  1201. def _search_json(self, start_pattern, string, name, video_id, *, end_pattern='',
  1202. contains_pattern=r'{(?s:.+)}', fatal=True, default=NO_DEFAULT, **kwargs):
  1203. """Searches string for the JSON object specified by start_pattern"""
  1204. # NB: end_pattern is only used to reduce the size of the initial match
  1205. if default is NO_DEFAULT:
  1206. default, has_default = {}, False
  1207. else:
  1208. fatal, has_default = False, True
  1209. json_string = self._search_regex(
  1210. rf'(?:{start_pattern})\s*(?P<json>{contains_pattern})\s*(?:{end_pattern})',
  1211. string, name, group='json', fatal=fatal, default=None if has_default else NO_DEFAULT)
  1212. if not json_string:
  1213. return default
  1214. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1215. try:
  1216. return self._parse_json(json_string, video_id, ignore_extra=True, **kwargs)
  1217. except ExtractorError as e:
  1218. if fatal:
  1219. raise ExtractorError(
  1220. f'Unable to extract {_name} - Failed to parse JSON', cause=e.cause, video_id=video_id)
  1221. elif not has_default:
  1222. self.report_warning(
  1223. f'Unable to extract {_name} - Failed to parse JSON: {e}', video_id=video_id)
  1224. return default
  1225. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1226. """
  1227. Like _search_regex, but strips HTML tags and unescapes entities.
  1228. """
  1229. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  1230. if isinstance(res, tuple):
  1231. return tuple(map(clean_html, res))
  1232. return clean_html(res)
  1233. def _get_netrc_login_info(self, netrc_machine=None):
  1234. netrc_machine = netrc_machine or self._NETRC_MACHINE
  1235. cmd = self.get_param('netrc_cmd')
  1236. if cmd:
  1237. cmd = cmd.replace('{}', netrc_machine)
  1238. self.to_screen(f'Executing command: {cmd}')
  1239. stdout, _, ret = Popen.run(cmd, text=True, shell=True, stdout=subprocess.PIPE)
  1240. if ret != 0:
  1241. raise OSError(f'Command returned error code {ret}')
  1242. info = netrc_from_content(stdout).authenticators(netrc_machine)
  1243. elif self.get_param('usenetrc', False):
  1244. netrc_file = compat_expanduser(self.get_param('netrc_location') or '~')
  1245. if os.path.isdir(netrc_file):
  1246. netrc_file = os.path.join(netrc_file, '.netrc')
  1247. info = netrc.netrc(netrc_file).authenticators(netrc_machine)
  1248. else:
  1249. return None, None
  1250. if not info:
  1251. self.to_screen(f'No authenticators for {netrc_machine}')
  1252. return None, None
  1253. self.write_debug(f'Using netrc for {netrc_machine} authentication')
  1254. # compat: <=py3.10: netrc cannot parse tokens as empty strings, will return `""` instead
  1255. # Ref: https://github.com/yt-dlp/yt-dlp/issues/11413
  1256. # https://github.com/python/cpython/commit/15409c720be0503131713e3d3abc1acd0da07378
  1257. if sys.version_info < (3, 11):
  1258. return tuple(x if x != '""' else '' for x in info[::2])
  1259. return info[0], info[2]
  1260. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  1261. """
  1262. Get the login info as (username, password)
  1263. First look for the manually specified credentials using username_option
  1264. and password_option as keys in params dictionary. If no such credentials
  1265. are available try the netrc_cmd if it is defined or look in the
  1266. netrc file using the netrc_machine or _NETRC_MACHINE value.
  1267. If there's no info available, return (None, None)
  1268. """
  1269. username = self.get_param(username_option)
  1270. if username is not None:
  1271. password = self.get_param(password_option)
  1272. else:
  1273. try:
  1274. username, password = self._get_netrc_login_info(netrc_machine)
  1275. except (OSError, netrc.NetrcParseError) as err:
  1276. self.report_warning(f'Failed to parse .netrc: {err}')
  1277. return None, None
  1278. return username, password
  1279. def _get_tfa_info(self, note='two-factor verification code'):
  1280. """
  1281. Get the two-factor authentication info
  1282. TODO - asking the user will be required for sms/phone verify
  1283. currently just uses the command line option
  1284. If there's no info available, return None
  1285. """
  1286. tfa = self.get_param('twofactor')
  1287. if tfa is not None:
  1288. return tfa
  1289. return getpass.getpass(f'Type {note} and press [Return]: ')
  1290. # Helper functions for extracting OpenGraph info
  1291. @staticmethod
  1292. def _og_regexes(prop):
  1293. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))'
  1294. property_re = r'(?:name|property)=(?:\'og{sep}{prop}\'|"og{sep}{prop}"|\s*og{sep}{prop}\b)'.format(
  1295. prop=re.escape(prop), sep='(?:&#x3A;|[:-])')
  1296. template = r'<meta[^>]+?%s[^>]+?%s'
  1297. return [
  1298. template % (property_re, content_re),
  1299. template % (content_re, property_re),
  1300. ]
  1301. @staticmethod
  1302. def _meta_regex(prop):
  1303. return rf'''(?isx)<meta
  1304. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?){re.escape(prop)}\1)
  1305. [^>]+?content=(["\'])(?P<content>.*?)\2'''
  1306. def _og_search_property(self, prop, html, name=None, **kargs):
  1307. prop = variadic(prop)
  1308. if name is None:
  1309. name = f'OpenGraph {prop[0]}'
  1310. og_regexes = []
  1311. for p in prop:
  1312. og_regexes.extend(self._og_regexes(p))
  1313. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  1314. if escaped is None:
  1315. return None
  1316. return unescapeHTML(escaped)
  1317. def _og_search_thumbnail(self, html, **kargs):
  1318. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  1319. def _og_search_description(self, html, **kargs):
  1320. return self._og_search_property('description', html, fatal=False, **kargs)
  1321. def _og_search_title(self, html, *, fatal=False, **kargs):
  1322. return self._og_search_property('title', html, fatal=fatal, **kargs)
  1323. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  1324. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  1325. if secure:
  1326. regexes = self._og_regexes('video:secure_url') + regexes
  1327. return self._html_search_regex(regexes, html, name, **kargs)
  1328. def _og_search_url(self, html, **kargs):
  1329. return self._og_search_property('url', html, **kargs)
  1330. def _html_extract_title(self, html, name='title', *, fatal=False, **kwargs):
  1331. return self._html_search_regex(r'(?s)<title\b[^>]*>([^<]+)</title>', html, name, fatal=fatal, **kwargs)
  1332. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  1333. name = variadic(name)
  1334. if display_name is None:
  1335. display_name = name[0]
  1336. return self._html_search_regex(
  1337. [self._meta_regex(n) for n in name],
  1338. html, display_name, fatal=fatal, group='content', **kwargs)
  1339. def _dc_search_uploader(self, html):
  1340. return self._html_search_meta('dc.creator', html, 'uploader')
  1341. @staticmethod
  1342. def _rta_search(html):
  1343. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  1344. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  1345. r' content="RTA-5042-1996-1400-1577-RTA"',
  1346. html):
  1347. return 18
  1348. # And then there are the jokers who advertise that they use RTA, but actually don't.
  1349. AGE_LIMIT_MARKERS = [
  1350. r'Proudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>',
  1351. r'>[^<]*you acknowledge you are at least (\d+) years old',
  1352. r'>\s*(?:18\s+U(?:\.S\.C\.|SC)\s+)?(?:§+\s*)?2257\b',
  1353. ]
  1354. age_limit = 0
  1355. for marker in AGE_LIMIT_MARKERS:
  1356. mobj = re.search(marker, html)
  1357. if mobj:
  1358. age_limit = max(age_limit, int(traverse_obj(mobj, 1, default=18)))
  1359. return age_limit
  1360. def _media_rating_search(self, html):
  1361. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  1362. rating = self._html_search_meta('rating', html)
  1363. if not rating:
  1364. return None
  1365. RATING_TABLE = {
  1366. 'safe for kids': 0,
  1367. 'general': 8,
  1368. '14 years': 14,
  1369. 'mature': 17,
  1370. 'restricted': 19,
  1371. }
  1372. return RATING_TABLE.get(rating.lower())
  1373. def _family_friendly_search(self, html):
  1374. # See http://schema.org/VideoObject
  1375. family_friendly = self._html_search_meta(
  1376. 'isFamilyFriendly', html, default=None)
  1377. if not family_friendly:
  1378. return None
  1379. RATING_TABLE = {
  1380. '1': 0,
  1381. 'true': 0,
  1382. '0': 18,
  1383. 'false': 18,
  1384. }
  1385. return RATING_TABLE.get(family_friendly.lower())
  1386. def _twitter_search_player(self, html):
  1387. return self._html_search_meta('twitter:player', html,
  1388. 'twitter card player')
  1389. def _yield_json_ld(self, html, video_id, *, fatal=True, default=NO_DEFAULT):
  1390. """Yield all json ld objects in the html"""
  1391. if default is not NO_DEFAULT:
  1392. fatal = False
  1393. for mobj in re.finditer(JSON_LD_RE, html):
  1394. json_ld_item = self._parse_json(
  1395. mobj.group('json_ld'), video_id, fatal=fatal,
  1396. errnote=False if default is not NO_DEFAULT else None)
  1397. for json_ld in variadic(json_ld_item):
  1398. if isinstance(json_ld, dict):
  1399. yield json_ld
  1400. def _search_json_ld(self, html, video_id, expected_type=None, *, fatal=True, default=NO_DEFAULT):
  1401. """Search for a video in any json ld in the html"""
  1402. if default is not NO_DEFAULT:
  1403. fatal = False
  1404. info = self._json_ld(
  1405. list(self._yield_json_ld(html, video_id, fatal=fatal, default=default)),
  1406. video_id, fatal=fatal, expected_type=expected_type)
  1407. if info:
  1408. return info
  1409. if default is not NO_DEFAULT:
  1410. return default
  1411. elif fatal:
  1412. raise RegexNotFoundError('Unable to extract JSON-LD')
  1413. else:
  1414. self.report_warning(f'unable to extract JSON-LD {bug_reports_message()}')
  1415. return {}
  1416. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  1417. if isinstance(json_ld, str):
  1418. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  1419. if not json_ld:
  1420. return {}
  1421. info = {}
  1422. INTERACTION_TYPE_MAP = {
  1423. 'CommentAction': 'comment',
  1424. 'AgreeAction': 'like',
  1425. 'DisagreeAction': 'dislike',
  1426. 'LikeAction': 'like',
  1427. 'DislikeAction': 'dislike',
  1428. 'ListenAction': 'view',
  1429. 'WatchAction': 'view',
  1430. 'ViewAction': 'view',
  1431. }
  1432. def is_type(e, *expected_types):
  1433. type_ = variadic(traverse_obj(e, '@type'))
  1434. return any(x in type_ for x in expected_types)
  1435. def extract_interaction_type(e):
  1436. interaction_type = e.get('interactionType')
  1437. if isinstance(interaction_type, dict):
  1438. interaction_type = interaction_type.get('@type')
  1439. return str_or_none(interaction_type)
  1440. def extract_interaction_statistic(e):
  1441. interaction_statistic = e.get('interactionStatistic')
  1442. if isinstance(interaction_statistic, dict):
  1443. interaction_statistic = [interaction_statistic]
  1444. if not isinstance(interaction_statistic, list):
  1445. return
  1446. for is_e in interaction_statistic:
  1447. if not is_type(is_e, 'InteractionCounter'):
  1448. continue
  1449. interaction_type = extract_interaction_type(is_e)
  1450. if not interaction_type:
  1451. continue
  1452. # For interaction count some sites provide string instead of
  1453. # an integer (as per spec) with non digit characters (e.g. ",")
  1454. # so extracting count with more relaxed str_to_int
  1455. interaction_count = str_to_int(is_e.get('userInteractionCount'))
  1456. if interaction_count is None:
  1457. continue
  1458. count_kind = INTERACTION_TYPE_MAP.get(interaction_type.split('/')[-1])
  1459. if not count_kind:
  1460. continue
  1461. count_key = f'{count_kind}_count'
  1462. if info.get(count_key) is not None:
  1463. continue
  1464. info[count_key] = interaction_count
  1465. def extract_chapter_information(e):
  1466. chapters = [{
  1467. 'title': part.get('name'),
  1468. 'start_time': part.get('startOffset'),
  1469. 'end_time': part.get('endOffset'),
  1470. } for part in variadic(e.get('hasPart') or []) if part.get('@type') == 'Clip']
  1471. for idx, (last_c, current_c, next_c) in enumerate(zip(
  1472. [{'end_time': 0}, *chapters], chapters, chapters[1:])):
  1473. current_c['end_time'] = current_c['end_time'] or next_c['start_time']
  1474. current_c['start_time'] = current_c['start_time'] or last_c['end_time']
  1475. if None in current_c.values():
  1476. self.report_warning(f'Chapter {idx} contains broken data. Not extracting chapters')
  1477. return
  1478. if chapters:
  1479. chapters[-1]['end_time'] = chapters[-1]['end_time'] or info['duration']
  1480. info['chapters'] = chapters
  1481. def extract_video_object(e):
  1482. author = e.get('author')
  1483. info.update({
  1484. 'url': url_or_none(e.get('contentUrl')),
  1485. 'ext': mimetype2ext(e.get('encodingFormat')),
  1486. 'title': unescapeHTML(e.get('name')),
  1487. 'description': unescapeHTML(e.get('description')),
  1488. 'thumbnails': [{'url': unescapeHTML(url)}
  1489. for url in variadic(traverse_obj(e, 'thumbnailUrl', 'thumbnailURL'))
  1490. if url_or_none(url)],
  1491. 'duration': parse_duration(e.get('duration')),
  1492. 'timestamp': unified_timestamp(e.get('uploadDate')),
  1493. # author can be an instance of 'Organization' or 'Person' types.
  1494. # both types can have 'name' property(inherited from 'Thing' type). [1]
  1495. # however some websites are using 'Text' type instead.
  1496. # 1. https://schema.org/VideoObject
  1497. 'uploader': author.get('name') if isinstance(author, dict) else author if isinstance(author, str) else None,
  1498. 'artist': traverse_obj(e, ('byArtist', 'name'), expected_type=str),
  1499. 'filesize': int_or_none(float_or_none(e.get('contentSize'))),
  1500. 'tbr': int_or_none(e.get('bitrate')),
  1501. 'width': int_or_none(e.get('width')),
  1502. 'height': int_or_none(e.get('height')),
  1503. 'view_count': int_or_none(e.get('interactionCount')),
  1504. 'tags': try_call(lambda: e.get('keywords').split(',')),
  1505. })
  1506. if is_type(e, 'AudioObject'):
  1507. info.update({
  1508. 'vcodec': 'none',
  1509. 'abr': int_or_none(e.get('bitrate')),
  1510. })
  1511. extract_interaction_statistic(e)
  1512. extract_chapter_information(e)
  1513. def traverse_json_ld(json_ld, at_top_level=True):
  1514. for e in variadic(json_ld):
  1515. if not isinstance(e, dict):
  1516. continue
  1517. if at_top_level and '@context' not in e:
  1518. continue
  1519. if at_top_level and set(e.keys()) == {'@context', '@graph'}:
  1520. traverse_json_ld(e['@graph'], at_top_level=False)
  1521. continue
  1522. if expected_type is not None and not is_type(e, expected_type):
  1523. continue
  1524. rating = traverse_obj(e, ('aggregateRating', 'ratingValue'), expected_type=float_or_none)
  1525. if rating is not None:
  1526. info['average_rating'] = rating
  1527. if is_type(e, 'TVEpisode', 'Episode', 'PodcastEpisode'):
  1528. episode_name = unescapeHTML(e.get('name'))
  1529. info.update({
  1530. 'episode': episode_name,
  1531. 'episode_number': int_or_none(e.get('episodeNumber')),
  1532. 'description': unescapeHTML(e.get('description')),
  1533. })
  1534. if not info.get('title') and episode_name:
  1535. info['title'] = episode_name
  1536. part_of_season = e.get('partOfSeason')
  1537. if is_type(part_of_season, 'TVSeason', 'Season', 'CreativeWorkSeason'):
  1538. info.update({
  1539. 'season': unescapeHTML(part_of_season.get('name')),
  1540. 'season_number': int_or_none(part_of_season.get('seasonNumber')),
  1541. })
  1542. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  1543. if is_type(part_of_series, 'TVSeries', 'Series', 'CreativeWorkSeries'):
  1544. info['series'] = unescapeHTML(part_of_series.get('name'))
  1545. elif is_type(e, 'Movie'):
  1546. info.update({
  1547. 'title': unescapeHTML(e.get('name')),
  1548. 'description': unescapeHTML(e.get('description')),
  1549. 'duration': parse_duration(e.get('duration')),
  1550. 'timestamp': unified_timestamp(e.get('dateCreated')),
  1551. })
  1552. elif is_type(e, 'Article', 'NewsArticle'):
  1553. info.update({
  1554. 'timestamp': parse_iso8601(e.get('datePublished')),
  1555. 'title': unescapeHTML(e.get('headline')),
  1556. 'description': unescapeHTML(e.get('articleBody') or e.get('description')),
  1557. })
  1558. if is_type(traverse_obj(e, ('video', 0)), 'VideoObject'):
  1559. extract_video_object(e['video'][0])
  1560. elif is_type(traverse_obj(e, ('subjectOf', 0)), 'VideoObject'):
  1561. extract_video_object(e['subjectOf'][0])
  1562. elif is_type(e, 'VideoObject', 'AudioObject'):
  1563. extract_video_object(e)
  1564. if expected_type is None:
  1565. continue
  1566. else:
  1567. break
  1568. video = e.get('video')
  1569. if is_type(video, 'VideoObject'):
  1570. extract_video_object(video)
  1571. if expected_type is None:
  1572. continue
  1573. else:
  1574. break
  1575. traverse_json_ld(json_ld)
  1576. return filter_dict(info)
  1577. def _search_nextjs_data(self, webpage, video_id, *, fatal=True, default=NO_DEFAULT, **kw):
  1578. if default == '{}':
  1579. self._downloader.deprecation_warning('using `default=\'{}\'` is deprecated, use `default={}` instead')
  1580. default = {}
  1581. if default is not NO_DEFAULT:
  1582. fatal = False
  1583. return self._search_json(
  1584. r'<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>', webpage, 'next.js data',
  1585. video_id, end_pattern='</script>', fatal=fatal, default=default, **kw)
  1586. def _search_nuxt_data(self, webpage, video_id, context_name='__NUXT__', *, fatal=True, traverse=('data', 0)):
  1587. """Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure function"""
  1588. rectx = re.escape(context_name)
  1589. FUNCTION_RE = r'\(function\((?P<arg_keys>.*?)\){.*?\breturn\s+(?P<js>{.*?})\s*;?\s*}\((?P<arg_vals>.*?)\)'
  1590. js, arg_keys, arg_vals = self._search_regex(
  1591. (rf'<script>\s*window\.{rectx}={FUNCTION_RE}\s*\)\s*;?\s*</script>', rf'{rectx}\(.*?{FUNCTION_RE}'),
  1592. webpage, context_name, group=('js', 'arg_keys', 'arg_vals'),
  1593. default=NO_DEFAULT if fatal else (None, None, None))
  1594. if js is None:
  1595. return {}
  1596. args = dict(zip(arg_keys.split(','), map(json.dumps, self._parse_json(
  1597. f'[{arg_vals}]', video_id, transform_source=js_to_json, fatal=fatal) or ())))
  1598. ret = self._parse_json(js, video_id, transform_source=functools.partial(js_to_json, vars=args), fatal=fatal)
  1599. return traverse_obj(ret, traverse) or {}
  1600. @staticmethod
  1601. def _hidden_inputs(html):
  1602. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  1603. hidden_inputs = {}
  1604. for input_el in re.findall(r'(?i)(<input[^>]+>)', html):
  1605. attrs = extract_attributes(input_el)
  1606. if not input_el:
  1607. continue
  1608. if attrs.get('type') not in ('hidden', 'submit'):
  1609. continue
  1610. name = attrs.get('name') or attrs.get('id')
  1611. value = attrs.get('value')
  1612. if name and value is not None:
  1613. hidden_inputs[name] = value
  1614. return hidden_inputs
  1615. def _form_hidden_inputs(self, form_id, html):
  1616. form = self._search_regex(
  1617. rf'(?is)<form[^>]+?id=(["\']){form_id}\1[^>]*>(?P<form>.+?)</form>',
  1618. html, f'{form_id} form', group='form')
  1619. return self._hidden_inputs(form)
  1620. @classproperty(cache=True)
  1621. def FormatSort(cls):
  1622. class FormatSort(FormatSorter):
  1623. def __init__(ie, *args, **kwargs):
  1624. super().__init__(ie._downloader, *args, **kwargs)
  1625. deprecation_warning(
  1626. 'yt_dlp.InfoExtractor.FormatSort is deprecated and may be removed in the future. '
  1627. 'Use yt_dlp.utils.FormatSorter instead')
  1628. return FormatSort
  1629. def _sort_formats(self, formats, field_preference=[]):
  1630. if not field_preference:
  1631. self._downloader.deprecation_warning(
  1632. 'yt_dlp.InfoExtractor._sort_formats is deprecated and is no longer required')
  1633. return
  1634. self._downloader.deprecation_warning(
  1635. 'yt_dlp.InfoExtractor._sort_formats is deprecated and no longer works as expected. '
  1636. 'Return _format_sort_fields in the info_dict instead')
  1637. if formats:
  1638. formats[0]['__sort_fields'] = field_preference
  1639. def _check_formats(self, formats, video_id):
  1640. if formats:
  1641. formats[:] = filter(
  1642. lambda f: self._is_valid_url(
  1643. f['url'], video_id,
  1644. item='{} video format'.format(f.get('format_id')) if f.get('format_id') else 'video'),
  1645. formats)
  1646. @staticmethod
  1647. def _remove_duplicate_formats(formats):
  1648. seen_urls = set()
  1649. seen_fragment_urls = set()
  1650. unique_formats = []
  1651. for f in formats:
  1652. fragments = f.get('fragments')
  1653. if callable(fragments):
  1654. unique_formats.append(f)
  1655. elif fragments:
  1656. fragment_urls = frozenset(
  1657. fragment.get('url') or urljoin(f['fragment_base_url'], fragment['path'])
  1658. for fragment in fragments)
  1659. if fragment_urls not in seen_fragment_urls:
  1660. seen_fragment_urls.add(fragment_urls)
  1661. unique_formats.append(f)
  1662. elif f['url'] not in seen_urls:
  1663. seen_urls.add(f['url'])
  1664. unique_formats.append(f)
  1665. formats[:] = unique_formats
  1666. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1667. url = self._proto_relative_url(url, scheme='http:')
  1668. # For now assume non HTTP(S) URLs always valid
  1669. if not url.startswith(('http://', 'https://')):
  1670. return True
  1671. try:
  1672. self._request_webpage(url, video_id, f'Checking {item} URL', headers=headers)
  1673. return True
  1674. except ExtractorError as e:
  1675. self.to_screen(
  1676. f'{video_id}: {item} URL is invalid, skipping: {e.cause!s}')
  1677. return False
  1678. def http_scheme(self):
  1679. """ Either "http:" or "https:", depending on the user's preferences """
  1680. return (
  1681. 'http:'
  1682. if self.get_param('prefer_insecure', False)
  1683. else 'https:')
  1684. def _proto_relative_url(self, url, scheme=None):
  1685. scheme = scheme or self.http_scheme()
  1686. assert scheme.endswith(':')
  1687. return sanitize_url(url, scheme=scheme[:-1])
  1688. def _sleep(self, timeout, video_id, msg_template=None):
  1689. if msg_template is None:
  1690. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1691. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1692. self.to_screen(msg)
  1693. time.sleep(timeout)
  1694. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1695. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1696. fatal=True, m3u8_id=None, data=None, headers={}, query={}):
  1697. if self.get_param('ignore_no_formats_error'):
  1698. fatal = False
  1699. res = self._download_xml_handle(
  1700. manifest_url, video_id, 'Downloading f4m manifest',
  1701. 'Unable to download f4m manifest',
  1702. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1703. # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244)
  1704. transform_source=transform_source,
  1705. fatal=fatal, data=data, headers=headers, query=query)
  1706. if res is False:
  1707. return []
  1708. manifest, urlh = res
  1709. manifest_url = urlh.url
  1710. return self._parse_f4m_formats(
  1711. manifest, manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1712. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1713. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1714. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1715. fatal=True, m3u8_id=None):
  1716. if not isinstance(manifest, xml.etree.ElementTree.Element) and not fatal:
  1717. return []
  1718. # currently yt-dlp cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1719. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1720. if akamai_pv is not None and ';' in akamai_pv.text:
  1721. player_verification_challenge = akamai_pv.text.split(';')[0]
  1722. if player_verification_challenge.strip() != '':
  1723. return []
  1724. formats = []
  1725. manifest_version = '1.0'
  1726. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1727. if not media_nodes:
  1728. manifest_version = '2.0'
  1729. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1730. # Remove unsupported DRM protected media from final formats
  1731. # rendition (see https://github.com/ytdl-org/youtube-dl/issues/8573).
  1732. media_nodes = remove_encrypted_media(media_nodes)
  1733. if not media_nodes:
  1734. return formats
  1735. manifest_base_url = get_base_url(manifest)
  1736. bootstrap_info = xpath_element(
  1737. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1738. 'bootstrap info', default=None)
  1739. vcodec = None
  1740. mime_type = xpath_text(
  1741. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1742. 'base URL', default=None)
  1743. if mime_type and mime_type.startswith('audio/'):
  1744. vcodec = 'none'
  1745. for i, media_el in enumerate(media_nodes):
  1746. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1747. width = int_or_none(media_el.attrib.get('width'))
  1748. height = int_or_none(media_el.attrib.get('height'))
  1749. format_id = join_nonempty(f4m_id, tbr or i)
  1750. # If <bootstrapInfo> is present, the specified f4m is a
  1751. # stream-level manifest, and only set-level manifests may refer to
  1752. # external resources. See section 11.4 and section 4 of F4M spec
  1753. if bootstrap_info is None:
  1754. media_url = None
  1755. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1756. if manifest_version == '2.0':
  1757. media_url = media_el.attrib.get('href')
  1758. if media_url is None:
  1759. media_url = media_el.attrib.get('url')
  1760. if not media_url:
  1761. continue
  1762. manifest_url = (
  1763. media_url if media_url.startswith(('http://', 'https://'))
  1764. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1765. # If media_url is itself a f4m manifest do the recursive extraction
  1766. # since bitrates in parent manifest (this one) and media_url manifest
  1767. # may differ leading to inability to resolve the format by requested
  1768. # bitrate in f4m downloader
  1769. ext = determine_ext(manifest_url)
  1770. if ext == 'f4m':
  1771. f4m_formats = self._extract_f4m_formats(
  1772. manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1773. transform_source=transform_source, fatal=fatal)
  1774. # Sometimes stream-level manifest contains single media entry that
  1775. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1776. # At the same time parent's media entry in set-level manifest may
  1777. # contain it. We will copy it from parent in such cases.
  1778. if len(f4m_formats) == 1:
  1779. f = f4m_formats[0]
  1780. f.update({
  1781. 'tbr': f.get('tbr') or tbr,
  1782. 'width': f.get('width') or width,
  1783. 'height': f.get('height') or height,
  1784. 'format_id': f.get('format_id') if not tbr else format_id,
  1785. 'vcodec': vcodec,
  1786. })
  1787. formats.extend(f4m_formats)
  1788. continue
  1789. elif ext == 'm3u8':
  1790. formats.extend(self._extract_m3u8_formats(
  1791. manifest_url, video_id, 'mp4', preference=preference,
  1792. quality=quality, m3u8_id=m3u8_id, fatal=fatal))
  1793. continue
  1794. formats.append({
  1795. 'format_id': format_id,
  1796. 'url': manifest_url,
  1797. 'manifest_url': manifest_url,
  1798. 'ext': 'flv' if bootstrap_info is not None else None,
  1799. 'protocol': 'f4m',
  1800. 'tbr': tbr,
  1801. 'width': width,
  1802. 'height': height,
  1803. 'vcodec': vcodec,
  1804. 'preference': preference,
  1805. 'quality': quality,
  1806. })
  1807. return formats
  1808. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, quality=None, m3u8_id=None):
  1809. return {
  1810. 'format_id': join_nonempty(m3u8_id, 'meta'),
  1811. 'url': m3u8_url,
  1812. 'ext': ext,
  1813. 'protocol': 'm3u8',
  1814. 'preference': preference - 100 if preference else -100,
  1815. 'quality': quality,
  1816. 'resolution': 'multiple',
  1817. 'format_note': 'Quality selection URL',
  1818. }
  1819. def _report_ignoring_subs(self, name):
  1820. self.report_warning(bug_reports_message(
  1821. f'Ignoring subtitle tracks found in the {name} manifest; '
  1822. 'if any subtitle tracks are missing,',
  1823. ), only_once=True)
  1824. def _extract_m3u8_formats(self, *args, **kwargs):
  1825. fmts, subs = self._extract_m3u8_formats_and_subtitles(*args, **kwargs)
  1826. if subs:
  1827. self._report_ignoring_subs('HLS')
  1828. return fmts
  1829. def _extract_m3u8_formats_and_subtitles(
  1830. self, m3u8_url, video_id, ext=None, entry_protocol='m3u8_native',
  1831. preference=None, quality=None, m3u8_id=None, note=None,
  1832. errnote=None, fatal=True, live=False, data=None, headers={},
  1833. query={}):
  1834. if self.get_param('ignore_no_formats_error'):
  1835. fatal = False
  1836. if not m3u8_url:
  1837. if errnote is not False:
  1838. errnote = errnote or 'Failed to obtain m3u8 URL'
  1839. if fatal:
  1840. raise ExtractorError(errnote, video_id=video_id)
  1841. self.report_warning(f'{errnote}{bug_reports_message()}')
  1842. return [], {}
  1843. res = self._download_webpage_handle(
  1844. m3u8_url, video_id,
  1845. note='Downloading m3u8 information' if note is None else note,
  1846. errnote='Failed to download m3u8 information' if errnote is None else errnote,
  1847. fatal=fatal, data=data, headers=headers, query=query)
  1848. if res is False:
  1849. return [], {}
  1850. m3u8_doc, urlh = res
  1851. m3u8_url = urlh.url
  1852. return self._parse_m3u8_formats_and_subtitles(
  1853. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1854. preference=preference, quality=quality, m3u8_id=m3u8_id,
  1855. note=note, errnote=errnote, fatal=fatal, live=live, data=data,
  1856. headers=headers, query=query, video_id=video_id)
  1857. def _parse_m3u8_formats_and_subtitles(
  1858. self, m3u8_doc, m3u8_url=None, ext=None, entry_protocol='m3u8_native',
  1859. preference=None, quality=None, m3u8_id=None, live=False, note=None,
  1860. errnote=None, fatal=True, data=None, headers={}, query={},
  1861. video_id=None):
  1862. formats, subtitles = [], {}
  1863. has_drm = HlsFD._has_drm(m3u8_doc)
  1864. def format_url(url):
  1865. return url if re.match(r'https?://', url) else urllib.parse.urljoin(m3u8_url, url)
  1866. if self.get_param('hls_split_discontinuity', False):
  1867. def _extract_m3u8_playlist_indices(manifest_url=None, m3u8_doc=None):
  1868. if not m3u8_doc:
  1869. if not manifest_url:
  1870. return []
  1871. m3u8_doc = self._download_webpage(
  1872. manifest_url, video_id, fatal=fatal, data=data, headers=headers,
  1873. note=False, errnote='Failed to download m3u8 playlist information')
  1874. if m3u8_doc is False:
  1875. return []
  1876. return range(1 + sum(line.startswith('#EXT-X-DISCONTINUITY') for line in m3u8_doc.splitlines()))
  1877. else:
  1878. def _extract_m3u8_playlist_indices(*args, **kwargs):
  1879. return [None]
  1880. # References:
  1881. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1882. # 2. https://github.com/ytdl-org/youtube-dl/issues/12211
  1883. # 3. https://github.com/ytdl-org/youtube-dl/issues/18923
  1884. # We should try extracting formats only from master playlists [1, 4.3.4],
  1885. # i.e. playlists that describe available qualities. On the other hand
  1886. # media playlists [1, 4.3.3] should be returned as is since they contain
  1887. # just the media without qualities renditions.
  1888. # Fortunately, master playlist can be easily distinguished from media
  1889. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1890. # master playlist tags MUST NOT appear in a media playlist and vice versa.
  1891. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1892. # media playlist and MUST NOT appear in master playlist thus we can
  1893. # clearly detect media playlist with this criterion.
  1894. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1895. formats = [{
  1896. 'format_id': join_nonempty(m3u8_id, idx),
  1897. 'format_index': idx,
  1898. 'url': m3u8_url or encode_data_uri(m3u8_doc.encode(), 'application/x-mpegurl'),
  1899. 'ext': ext,
  1900. 'protocol': entry_protocol,
  1901. 'preference': preference,
  1902. 'quality': quality,
  1903. 'has_drm': has_drm,
  1904. } for idx in _extract_m3u8_playlist_indices(m3u8_doc=m3u8_doc)]
  1905. return formats, subtitles
  1906. groups = {}
  1907. last_stream_inf = {}
  1908. def extract_media(x_media_line):
  1909. media = parse_m3u8_attributes(x_media_line)
  1910. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1911. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1912. if not (media_type and group_id and name):
  1913. return
  1914. groups.setdefault(group_id, []).append(media)
  1915. # <https://tools.ietf.org/html/rfc8216#section-4.3.4.1>
  1916. if media_type == 'SUBTITLES':
  1917. # According to RFC 8216 §4.3.4.2.1, URI is REQUIRED in the
  1918. # EXT-X-MEDIA tag if the media type is SUBTITLES.
  1919. # However, lack of URI has been spotted in the wild.
  1920. # e.g. NebulaIE; see https://github.com/yt-dlp/yt-dlp/issues/339
  1921. if not media.get('URI'):
  1922. return
  1923. url = format_url(media['URI'])
  1924. sub_info = {
  1925. 'url': url,
  1926. 'ext': determine_ext(url),
  1927. }
  1928. if sub_info['ext'] == 'm3u8':
  1929. # Per RFC 8216 §3.1, the only possible subtitle format m3u8
  1930. # files may contain is WebVTT:
  1931. # <https://tools.ietf.org/html/rfc8216#section-3.1>
  1932. sub_info['ext'] = 'vtt'
  1933. sub_info['protocol'] = 'm3u8_native'
  1934. lang = media.get('LANGUAGE') or 'und'
  1935. subtitles.setdefault(lang, []).append(sub_info)
  1936. if media_type not in ('VIDEO', 'AUDIO'):
  1937. return
  1938. media_url = media.get('URI')
  1939. if media_url:
  1940. manifest_url = format_url(media_url)
  1941. formats.extend({
  1942. 'format_id': join_nonempty(m3u8_id, group_id, name, idx),
  1943. 'format_note': name,
  1944. 'format_index': idx,
  1945. 'url': manifest_url,
  1946. 'manifest_url': m3u8_url,
  1947. 'language': media.get('LANGUAGE'),
  1948. 'ext': ext,
  1949. 'protocol': entry_protocol,
  1950. 'preference': preference,
  1951. 'quality': quality,
  1952. 'has_drm': has_drm,
  1953. 'vcodec': 'none' if media_type == 'AUDIO' else None,
  1954. } for idx in _extract_m3u8_playlist_indices(manifest_url))
  1955. def build_stream_name():
  1956. # Despite specification does not mention NAME attribute for
  1957. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1958. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1959. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1960. stream_name = last_stream_inf.get('NAME')
  1961. if stream_name:
  1962. return stream_name
  1963. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1964. # from corresponding rendition group
  1965. stream_group_id = last_stream_inf.get('VIDEO')
  1966. if not stream_group_id:
  1967. return
  1968. stream_group = groups.get(stream_group_id)
  1969. if not stream_group:
  1970. return stream_group_id
  1971. rendition = stream_group[0]
  1972. return rendition.get('NAME') or stream_group_id
  1973. # parse EXT-X-MEDIA tags before EXT-X-STREAM-INF in order to have the
  1974. # chance to detect video only formats when EXT-X-STREAM-INF tags
  1975. # precede EXT-X-MEDIA tags in HLS manifest such as [3].
  1976. for line in m3u8_doc.splitlines():
  1977. if line.startswith('#EXT-X-MEDIA:'):
  1978. extract_media(line)
  1979. for line in m3u8_doc.splitlines():
  1980. if line.startswith('#EXT-X-STREAM-INF:'):
  1981. last_stream_inf = parse_m3u8_attributes(line)
  1982. elif line.startswith('#') or not line.strip():
  1983. continue
  1984. else:
  1985. tbr = float_or_none(
  1986. last_stream_inf.get('AVERAGE-BANDWIDTH')
  1987. or last_stream_inf.get('BANDWIDTH'), scale=1000)
  1988. manifest_url = format_url(line.strip())
  1989. for idx in _extract_m3u8_playlist_indices(manifest_url):
  1990. format_id = [m3u8_id, None, idx]
  1991. # Bandwidth of live streams may differ over time thus making
  1992. # format_id unpredictable. So it's better to keep provided
  1993. # format_id intact.
  1994. if not live:
  1995. stream_name = build_stream_name()
  1996. format_id[1] = stream_name or '%d' % (tbr or len(formats))
  1997. f = {
  1998. 'format_id': join_nonempty(*format_id),
  1999. 'format_index': idx,
  2000. 'url': manifest_url,
  2001. 'manifest_url': m3u8_url,
  2002. 'tbr': tbr,
  2003. 'ext': ext,
  2004. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  2005. 'protocol': entry_protocol,
  2006. 'preference': preference,
  2007. 'quality': quality,
  2008. 'has_drm': has_drm,
  2009. }
  2010. # YouTube-specific
  2011. if yt_audio_content_id := last_stream_inf.get('YT-EXT-AUDIO-CONTENT-ID'):
  2012. f['language'] = yt_audio_content_id.split('.')[0]
  2013. resolution = last_stream_inf.get('RESOLUTION')
  2014. if resolution:
  2015. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  2016. if mobj:
  2017. f['width'] = int(mobj.group('width'))
  2018. f['height'] = int(mobj.group('height'))
  2019. # Unified Streaming Platform
  2020. mobj = re.search(
  2021. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  2022. if mobj:
  2023. abr, vbr = mobj.groups()
  2024. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  2025. f.update({
  2026. 'vbr': vbr,
  2027. 'abr': abr,
  2028. })
  2029. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  2030. f.update(codecs)
  2031. audio_group_id = last_stream_inf.get('AUDIO')
  2032. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  2033. # references a rendition group MUST have a CODECS attribute.
  2034. # However, this is not always respected. E.g. [2]
  2035. # contains EXT-X-STREAM-INF tag which references AUDIO
  2036. # rendition group but does not have CODECS and despite
  2037. # referencing an audio group it represents a complete
  2038. # (with audio and video) format. So, for such cases we will
  2039. # ignore references to rendition groups and treat them
  2040. # as complete formats.
  2041. if audio_group_id and codecs and f.get('vcodec') != 'none':
  2042. audio_group = groups.get(audio_group_id)
  2043. if audio_group and audio_group[0].get('URI'):
  2044. # TODO: update acodec for audio only formats with
  2045. # the same GROUP-ID
  2046. f['acodec'] = 'none'
  2047. if not f.get('ext'):
  2048. f['ext'] = 'm4a' if f.get('vcodec') == 'none' else 'mp4'
  2049. formats.append(f)
  2050. # for DailyMotion
  2051. progressive_uri = last_stream_inf.get('PROGRESSIVE-URI')
  2052. if progressive_uri:
  2053. http_f = f.copy()
  2054. del http_f['manifest_url']
  2055. http_f.update({
  2056. 'format_id': f['format_id'].replace('hls-', 'http-'),
  2057. 'protocol': 'http',
  2058. 'url': progressive_uri,
  2059. })
  2060. formats.append(http_f)
  2061. last_stream_inf = {}
  2062. return formats, subtitles
  2063. def _extract_m3u8_vod_duration(
  2064. self, m3u8_vod_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2065. m3u8_vod = self._download_webpage(
  2066. m3u8_vod_url, video_id,
  2067. note='Downloading m3u8 VOD manifest' if note is None else note,
  2068. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2069. fatal=False, data=data, headers=headers, query=query)
  2070. return self._parse_m3u8_vod_duration(m3u8_vod or '', video_id)
  2071. def _parse_m3u8_vod_duration(self, m3u8_vod, video_id):
  2072. if '#EXT-X-ENDLIST' not in m3u8_vod:
  2073. return None
  2074. return int(sum(
  2075. float(line[len('#EXTINF:'):].split(',')[0])
  2076. for line in m3u8_vod.splitlines() if line.startswith('#EXTINF:'))) or None
  2077. def _extract_mpd_vod_duration(
  2078. self, mpd_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2079. mpd_doc = self._download_xml(
  2080. mpd_url, video_id,
  2081. note='Downloading MPD VOD manifest' if note is None else note,
  2082. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2083. fatal=False, data=data, headers=headers, query=query)
  2084. if not isinstance(mpd_doc, xml.etree.ElementTree.Element):
  2085. return None
  2086. return int_or_none(parse_duration(mpd_doc.get('mediaPresentationDuration')))
  2087. @staticmethod
  2088. def _xpath_ns(path, namespace=None):
  2089. if not namespace:
  2090. return path
  2091. out = []
  2092. for c in path.split('/'):
  2093. if not c or c == '.':
  2094. out.append(c)
  2095. else:
  2096. out.append(f'{{{namespace}}}{c}')
  2097. return '/'.join(out)
  2098. def _extract_smil_formats_and_subtitles(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  2099. if self.get_param('ignore_no_formats_error'):
  2100. fatal = False
  2101. res = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  2102. if res is False:
  2103. assert not fatal
  2104. return [], {}
  2105. smil, urlh = res
  2106. return self._parse_smil_formats_and_subtitles(smil, urlh.url, video_id, f4m_params=f4m_params,
  2107. namespace=self._parse_smil_namespace(smil))
  2108. def _extract_smil_formats(self, *args, **kwargs):
  2109. fmts, subs = self._extract_smil_formats_and_subtitles(*args, **kwargs)
  2110. if subs:
  2111. self._report_ignoring_subs('SMIL')
  2112. return fmts
  2113. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  2114. res = self._download_smil(smil_url, video_id, fatal=fatal)
  2115. if res is False:
  2116. return {}
  2117. smil, urlh = res
  2118. smil_url = urlh.url
  2119. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  2120. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  2121. return self._download_xml_handle(
  2122. smil_url, video_id, 'Downloading SMIL file',
  2123. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  2124. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  2125. namespace = self._parse_smil_namespace(smil)
  2126. formats, subtitles = self._parse_smil_formats_and_subtitles(
  2127. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  2128. video_id = os.path.splitext(url_basename(smil_url))[0]
  2129. title = None
  2130. description = None
  2131. upload_date = None
  2132. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2133. name = meta.attrib.get('name')
  2134. content = meta.attrib.get('content')
  2135. if not name or not content:
  2136. continue
  2137. if not title and name == 'title':
  2138. title = content
  2139. elif not description and name in ('description', 'abstract'):
  2140. description = content
  2141. elif not upload_date and name == 'date':
  2142. upload_date = unified_strdate(content)
  2143. thumbnails = [{
  2144. 'id': image.get('type'),
  2145. 'url': image.get('src'),
  2146. 'width': int_or_none(image.get('width')),
  2147. 'height': int_or_none(image.get('height')),
  2148. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  2149. return {
  2150. 'id': video_id,
  2151. 'title': title or video_id,
  2152. 'description': description,
  2153. 'upload_date': upload_date,
  2154. 'thumbnails': thumbnails,
  2155. 'formats': formats,
  2156. 'subtitles': subtitles,
  2157. }
  2158. def _parse_smil_namespace(self, smil):
  2159. return self._search_regex(
  2160. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  2161. def _parse_smil_formats(self, *args, **kwargs):
  2162. fmts, subs = self._parse_smil_formats_and_subtitles(*args, **kwargs)
  2163. if subs:
  2164. self._report_ignoring_subs('SMIL')
  2165. return fmts
  2166. def _parse_smil_formats_and_subtitles(
  2167. self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  2168. base = smil_url
  2169. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2170. b = meta.get('base') or meta.get('httpBase')
  2171. if b:
  2172. base = b
  2173. break
  2174. formats, subtitles = [], {}
  2175. rtmp_count = 0
  2176. http_count = 0
  2177. m3u8_count = 0
  2178. imgs_count = 0
  2179. srcs = set()
  2180. media = itertools.chain.from_iterable(
  2181. smil.findall(self._xpath_ns(arg, namespace))
  2182. for arg in ['.//video', './/audio', './/media'])
  2183. for medium in media:
  2184. src = medium.get('src')
  2185. if not src or src in srcs:
  2186. continue
  2187. srcs.add(src)
  2188. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  2189. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  2190. width = int_or_none(medium.get('width'))
  2191. height = int_or_none(medium.get('height'))
  2192. proto = medium.get('proto')
  2193. ext = medium.get('ext')
  2194. src_ext = determine_ext(src, default_ext=None) or ext or urlhandle_detect_ext(
  2195. self._request_webpage(HEADRequest(src), video_id, note='Requesting extension info', fatal=False))
  2196. streamer = medium.get('streamer') or base
  2197. if proto == 'rtmp' or streamer.startswith('rtmp'):
  2198. rtmp_count += 1
  2199. formats.append({
  2200. 'url': streamer,
  2201. 'play_path': src,
  2202. 'ext': 'flv',
  2203. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  2204. 'tbr': bitrate,
  2205. 'filesize': filesize,
  2206. 'width': width,
  2207. 'height': height,
  2208. })
  2209. if transform_rtmp_url:
  2210. streamer, src = transform_rtmp_url(streamer, src)
  2211. formats[-1].update({
  2212. 'url': streamer,
  2213. 'play_path': src,
  2214. })
  2215. continue
  2216. src_url = src if src.startswith('http') else urllib.parse.urljoin(f'{base}/', src)
  2217. src_url = src_url.strip()
  2218. if proto == 'm3u8' or src_ext == 'm3u8':
  2219. m3u8_formats, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
  2220. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  2221. self._merge_subtitles(m3u8_subs, target=subtitles)
  2222. if len(m3u8_formats) == 1:
  2223. m3u8_count += 1
  2224. m3u8_formats[0].update({
  2225. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  2226. 'tbr': bitrate,
  2227. 'width': width,
  2228. 'height': height,
  2229. })
  2230. formats.extend(m3u8_formats)
  2231. elif src_ext == 'f4m':
  2232. f4m_url = src_url
  2233. if not f4m_params:
  2234. f4m_params = {
  2235. 'hdcore': '3.2.0',
  2236. 'plugin': 'flowplayer-3.2.0.1',
  2237. }
  2238. f4m_url += '&' if '?' in f4m_url else '?'
  2239. f4m_url += urllib.parse.urlencode(f4m_params)
  2240. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  2241. elif src_ext == 'mpd':
  2242. mpd_formats, mpd_subs = self._extract_mpd_formats_and_subtitles(
  2243. src_url, video_id, mpd_id='dash', fatal=False)
  2244. formats.extend(mpd_formats)
  2245. self._merge_subtitles(mpd_subs, target=subtitles)
  2246. elif re.search(r'\.ism/[Mm]anifest', src_url):
  2247. ism_formats, ism_subs = self._extract_ism_formats_and_subtitles(
  2248. src_url, video_id, ism_id='mss', fatal=False)
  2249. formats.extend(ism_formats)
  2250. self._merge_subtitles(ism_subs, target=subtitles)
  2251. elif src_url.startswith('http') and self._is_valid_url(src, video_id):
  2252. http_count += 1
  2253. formats.append({
  2254. 'url': src_url,
  2255. 'ext': ext or src_ext or 'flv',
  2256. 'format_id': 'http-%d' % (bitrate or http_count),
  2257. 'tbr': bitrate,
  2258. 'filesize': filesize,
  2259. 'width': width,
  2260. 'height': height,
  2261. })
  2262. for medium in smil.findall(self._xpath_ns('.//imagestream', namespace)):
  2263. src = medium.get('src')
  2264. if not src or src in srcs:
  2265. continue
  2266. srcs.add(src)
  2267. imgs_count += 1
  2268. formats.append({
  2269. 'format_id': f'imagestream-{imgs_count}',
  2270. 'url': src,
  2271. 'ext': mimetype2ext(medium.get('type')),
  2272. 'acodec': 'none',
  2273. 'vcodec': 'none',
  2274. 'width': int_or_none(medium.get('width')),
  2275. 'height': int_or_none(medium.get('height')),
  2276. 'format_note': 'SMIL storyboards',
  2277. })
  2278. smil_subs = self._parse_smil_subtitles(smil, namespace=namespace)
  2279. self._merge_subtitles(smil_subs, target=subtitles)
  2280. return formats, subtitles
  2281. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  2282. urls = []
  2283. subtitles = {}
  2284. for textstream in smil.findall(self._xpath_ns('.//textstream', namespace)):
  2285. src = textstream.get('src')
  2286. if not src or src in urls:
  2287. continue
  2288. urls.append(src)
  2289. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  2290. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  2291. subtitles.setdefault(lang, []).append({
  2292. 'url': src,
  2293. 'ext': ext,
  2294. })
  2295. return subtitles
  2296. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  2297. res = self._download_xml_handle(
  2298. xspf_url, playlist_id, 'Downloading xpsf playlist',
  2299. 'Unable to download xspf manifest', fatal=fatal)
  2300. if res is False:
  2301. return []
  2302. xspf, urlh = res
  2303. xspf_url = urlh.url
  2304. return self._parse_xspf(
  2305. xspf, playlist_id, xspf_url=xspf_url,
  2306. xspf_base_url=base_url(xspf_url))
  2307. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  2308. NS_MAP = {
  2309. 'xspf': 'http://xspf.org/ns/0/',
  2310. 's1': 'http://static.streamone.nl/player/ns/0',
  2311. }
  2312. entries = []
  2313. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  2314. title = xpath_text(
  2315. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  2316. description = xpath_text(
  2317. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  2318. thumbnail = xpath_text(
  2319. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  2320. duration = float_or_none(
  2321. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  2322. formats = []
  2323. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  2324. format_url = urljoin(xspf_base_url, location.text)
  2325. if not format_url:
  2326. continue
  2327. formats.append({
  2328. 'url': format_url,
  2329. 'manifest_url': xspf_url,
  2330. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  2331. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  2332. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  2333. })
  2334. entries.append({
  2335. 'id': playlist_id,
  2336. 'title': title,
  2337. 'description': description,
  2338. 'thumbnail': thumbnail,
  2339. 'duration': duration,
  2340. 'formats': formats,
  2341. })
  2342. return entries
  2343. def _extract_mpd_formats(self, *args, **kwargs):
  2344. fmts, subs = self._extract_mpd_formats_and_subtitles(*args, **kwargs)
  2345. if subs:
  2346. self._report_ignoring_subs('DASH')
  2347. return fmts
  2348. def _extract_mpd_formats_and_subtitles(self, *args, **kwargs):
  2349. periods = self._extract_mpd_periods(*args, **kwargs)
  2350. return self._merge_mpd_periods(periods)
  2351. def _extract_mpd_periods(
  2352. self, mpd_url, video_id, mpd_id=None, note=None, errnote=None,
  2353. fatal=True, data=None, headers={}, query={}):
  2354. if self.get_param('ignore_no_formats_error'):
  2355. fatal = False
  2356. res = self._download_xml_handle(
  2357. mpd_url, video_id,
  2358. note='Downloading MPD manifest' if note is None else note,
  2359. errnote='Failed to download MPD manifest' if errnote is None else errnote,
  2360. fatal=fatal, data=data, headers=headers, query=query)
  2361. if res is False:
  2362. return []
  2363. mpd_doc, urlh = res
  2364. if mpd_doc is None:
  2365. return []
  2366. # We could have been redirected to a new url when we retrieved our mpd file.
  2367. mpd_url = urlh.url
  2368. mpd_base_url = base_url(mpd_url)
  2369. return self._parse_mpd_periods(mpd_doc, mpd_id, mpd_base_url, mpd_url)
  2370. def _parse_mpd_formats(self, *args, **kwargs):
  2371. fmts, subs = self._parse_mpd_formats_and_subtitles(*args, **kwargs)
  2372. if subs:
  2373. self._report_ignoring_subs('DASH')
  2374. return fmts
  2375. def _parse_mpd_formats_and_subtitles(self, *args, **kwargs):
  2376. periods = self._parse_mpd_periods(*args, **kwargs)
  2377. return self._merge_mpd_periods(periods)
  2378. def _merge_mpd_periods(self, periods):
  2379. """
  2380. Combine all formats and subtitles from an MPD manifest into a single list,
  2381. by concatenate streams with similar formats.
  2382. """
  2383. formats, subtitles = {}, {}
  2384. for period in periods:
  2385. for f in period['formats']:
  2386. assert 'is_dash_periods' not in f, 'format already processed'
  2387. f['is_dash_periods'] = True
  2388. format_key = tuple(v for k, v in f.items() if k not in (
  2389. ('format_id', 'fragments', 'manifest_stream_number')))
  2390. if format_key not in formats:
  2391. formats[format_key] = f
  2392. elif 'fragments' in f:
  2393. formats[format_key].setdefault('fragments', []).extend(f['fragments'])
  2394. if subtitles and period['subtitles']:
  2395. self.report_warning(bug_reports_message(
  2396. 'Found subtitles in multiple periods in the DASH manifest; '
  2397. 'if part of the subtitles are missing,',
  2398. ), only_once=True)
  2399. for sub_lang, sub_info in period['subtitles'].items():
  2400. subtitles.setdefault(sub_lang, []).extend(sub_info)
  2401. return list(formats.values()), subtitles
  2402. def _parse_mpd_periods(self, mpd_doc, mpd_id=None, mpd_base_url='', mpd_url=None):
  2403. """
  2404. Parse formats from MPD manifest.
  2405. References:
  2406. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  2407. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  2408. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  2409. """
  2410. if not self.get_param('dynamic_mpd', True):
  2411. if mpd_doc.get('type') == 'dynamic':
  2412. return [], {}
  2413. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  2414. def _add_ns(path):
  2415. return self._xpath_ns(path, namespace)
  2416. def is_drm_protected(element):
  2417. return element.find(_add_ns('ContentProtection')) is not None
  2418. def extract_multisegment_info(element, ms_parent_info):
  2419. ms_info = ms_parent_info.copy()
  2420. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  2421. # common attributes and elements. We will only extract relevant
  2422. # for us.
  2423. def extract_common(source):
  2424. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  2425. if segment_timeline is not None:
  2426. s_e = segment_timeline.findall(_add_ns('S'))
  2427. if s_e:
  2428. ms_info['total_number'] = 0
  2429. ms_info['s'] = []
  2430. for s in s_e:
  2431. r = int(s.get('r', 0))
  2432. ms_info['total_number'] += 1 + r
  2433. ms_info['s'].append({
  2434. 't': int(s.get('t', 0)),
  2435. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  2436. 'd': int(s.attrib['d']),
  2437. 'r': r,
  2438. })
  2439. start_number = source.get('startNumber')
  2440. if start_number:
  2441. ms_info['start_number'] = int(start_number)
  2442. timescale = source.get('timescale')
  2443. if timescale:
  2444. ms_info['timescale'] = int(timescale)
  2445. segment_duration = source.get('duration')
  2446. if segment_duration:
  2447. ms_info['segment_duration'] = float(segment_duration)
  2448. def extract_Initialization(source):
  2449. initialization = source.find(_add_ns('Initialization'))
  2450. if initialization is not None:
  2451. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  2452. segment_list = element.find(_add_ns('SegmentList'))
  2453. if segment_list is not None:
  2454. extract_common(segment_list)
  2455. extract_Initialization(segment_list)
  2456. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  2457. if segment_urls_e:
  2458. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  2459. else:
  2460. segment_template = element.find(_add_ns('SegmentTemplate'))
  2461. if segment_template is not None:
  2462. extract_common(segment_template)
  2463. media = segment_template.get('media')
  2464. if media:
  2465. ms_info['media'] = media
  2466. initialization = segment_template.get('initialization')
  2467. if initialization:
  2468. ms_info['initialization'] = initialization
  2469. else:
  2470. extract_Initialization(segment_template)
  2471. return ms_info
  2472. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  2473. stream_numbers = collections.defaultdict(int)
  2474. for period_idx, period in enumerate(mpd_doc.findall(_add_ns('Period'))):
  2475. period_entry = {
  2476. 'id': period.get('id', f'period-{period_idx}'),
  2477. 'formats': [],
  2478. 'subtitles': collections.defaultdict(list),
  2479. }
  2480. period_duration = parse_duration(period.get('duration')) or mpd_duration
  2481. period_ms_info = extract_multisegment_info(period, {
  2482. 'start_number': 1,
  2483. 'timescale': 1,
  2484. })
  2485. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  2486. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  2487. for representation in adaptation_set.findall(_add_ns('Representation')):
  2488. representation_attrib = adaptation_set.attrib.copy()
  2489. representation_attrib.update(representation.attrib)
  2490. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  2491. mime_type = representation_attrib['mimeType']
  2492. content_type = representation_attrib.get('contentType', mime_type.split('/')[0])
  2493. codec_str = representation_attrib.get('codecs', '')
  2494. # Some kind of binary subtitle found in some youtube livestreams
  2495. if mime_type == 'application/x-rawcc':
  2496. codecs = {'scodec': codec_str}
  2497. else:
  2498. codecs = parse_codecs(codec_str)
  2499. if content_type not in ('video', 'audio', 'text'):
  2500. if mime_type == 'image/jpeg':
  2501. content_type = mime_type
  2502. elif codecs.get('vcodec', 'none') != 'none':
  2503. content_type = 'video'
  2504. elif codecs.get('acodec', 'none') != 'none':
  2505. content_type = 'audio'
  2506. elif codecs.get('scodec', 'none') != 'none':
  2507. content_type = 'text'
  2508. elif mimetype2ext(mime_type) in ('tt', 'dfxp', 'ttml', 'xml', 'json'):
  2509. content_type = 'text'
  2510. else:
  2511. self.report_warning(f'Unknown MIME type {mime_type} in DASH manifest')
  2512. continue
  2513. base_url = ''
  2514. for element in (representation, adaptation_set, period, mpd_doc):
  2515. base_url_e = element.find(_add_ns('BaseURL'))
  2516. if try_call(lambda: base_url_e.text) is not None:
  2517. base_url = base_url_e.text + base_url
  2518. if re.match(r'https?://', base_url):
  2519. break
  2520. if mpd_base_url and base_url.startswith('/'):
  2521. base_url = urllib.parse.urljoin(mpd_base_url, base_url)
  2522. elif mpd_base_url and not re.match(r'https?://', base_url):
  2523. if not mpd_base_url.endswith('/'):
  2524. mpd_base_url += '/'
  2525. base_url = mpd_base_url + base_url
  2526. representation_id = representation_attrib.get('id')
  2527. lang = representation_attrib.get('lang')
  2528. url_el = representation.find(_add_ns('BaseURL'))
  2529. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  2530. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  2531. if representation_id is not None:
  2532. format_id = representation_id
  2533. else:
  2534. format_id = content_type
  2535. if mpd_id:
  2536. format_id = mpd_id + '-' + format_id
  2537. if content_type in ('video', 'audio'):
  2538. f = {
  2539. 'format_id': format_id,
  2540. 'manifest_url': mpd_url,
  2541. 'ext': mimetype2ext(mime_type),
  2542. 'width': int_or_none(representation_attrib.get('width')),
  2543. 'height': int_or_none(representation_attrib.get('height')),
  2544. 'tbr': float_or_none(bandwidth, 1000),
  2545. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  2546. 'fps': int_or_none(representation_attrib.get('frameRate')),
  2547. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  2548. 'format_note': f'DASH {content_type}',
  2549. 'filesize': filesize,
  2550. 'container': mimetype2ext(mime_type) + '_dash',
  2551. **codecs,
  2552. }
  2553. elif content_type == 'text':
  2554. f = {
  2555. 'ext': mimetype2ext(mime_type),
  2556. 'manifest_url': mpd_url,
  2557. 'filesize': filesize,
  2558. }
  2559. elif content_type == 'image/jpeg':
  2560. # See test case in VikiIE
  2561. # https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1
  2562. f = {
  2563. 'format_id': format_id,
  2564. 'ext': 'mhtml',
  2565. 'manifest_url': mpd_url,
  2566. 'format_note': 'DASH storyboards (jpeg)',
  2567. 'acodec': 'none',
  2568. 'vcodec': 'none',
  2569. }
  2570. if is_drm_protected(adaptation_set) or is_drm_protected(representation):
  2571. f['has_drm'] = True
  2572. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  2573. def prepare_template(template_name, identifiers):
  2574. tmpl = representation_ms_info[template_name]
  2575. if representation_id is not None:
  2576. tmpl = tmpl.replace('$RepresentationID$', representation_id)
  2577. # First of, % characters outside $...$ templates
  2578. # must be escaped by doubling for proper processing
  2579. # by % operator string formatting used further (see
  2580. # https://github.com/ytdl-org/youtube-dl/issues/16867).
  2581. t = ''
  2582. in_template = False
  2583. for c in tmpl:
  2584. t += c
  2585. if c == '$':
  2586. in_template = not in_template
  2587. elif c == '%' and not in_template:
  2588. t += c
  2589. # Next, $...$ templates are translated to their
  2590. # %(...) counterparts to be used with % operator
  2591. t = re.sub(r'\$({})\$'.format('|'.join(identifiers)), r'%(\1)d', t)
  2592. t = re.sub(r'\$({})%([^$]+)\$'.format('|'.join(identifiers)), r'%(\1)\2', t)
  2593. t.replace('$$', '$')
  2594. return t
  2595. # @initialization is a regular template like @media one
  2596. # so it should be handled just the same way (see
  2597. # https://github.com/ytdl-org/youtube-dl/issues/11605)
  2598. if 'initialization' in representation_ms_info:
  2599. initialization_template = prepare_template(
  2600. 'initialization',
  2601. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  2602. # $Time$ shall not be included for @initialization thus
  2603. # only $Bandwidth$ remains
  2604. ('Bandwidth', ))
  2605. representation_ms_info['initialization_url'] = initialization_template % {
  2606. 'Bandwidth': bandwidth,
  2607. }
  2608. def location_key(location):
  2609. return 'url' if re.match(r'https?://', location) else 'path'
  2610. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  2611. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  2612. media_location_key = location_key(media_template)
  2613. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  2614. # can't be used at the same time
  2615. if '%(Number' in media_template and 's' not in representation_ms_info:
  2616. segment_duration = None
  2617. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  2618. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  2619. representation_ms_info['total_number'] = int(math.ceil(
  2620. float_or_none(period_duration, segment_duration, default=0)))
  2621. representation_ms_info['fragments'] = [{
  2622. media_location_key: media_template % {
  2623. 'Number': segment_number,
  2624. 'Bandwidth': bandwidth,
  2625. },
  2626. 'duration': segment_duration,
  2627. } for segment_number in range(
  2628. representation_ms_info['start_number'],
  2629. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  2630. else:
  2631. # $Number*$ or $Time$ in media template with S list available
  2632. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  2633. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  2634. representation_ms_info['fragments'] = []
  2635. segment_time = 0
  2636. segment_d = None
  2637. segment_number = representation_ms_info['start_number']
  2638. def add_segment_url():
  2639. segment_url = media_template % {
  2640. 'Time': segment_time,
  2641. 'Bandwidth': bandwidth,
  2642. 'Number': segment_number,
  2643. }
  2644. representation_ms_info['fragments'].append({
  2645. media_location_key: segment_url,
  2646. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  2647. })
  2648. for s in representation_ms_info['s']:
  2649. segment_time = s.get('t') or segment_time
  2650. segment_d = s['d']
  2651. add_segment_url()
  2652. segment_number += 1
  2653. for _ in range(s.get('r', 0)):
  2654. segment_time += segment_d
  2655. add_segment_url()
  2656. segment_number += 1
  2657. segment_time += segment_d
  2658. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  2659. # No media template,
  2660. # e.g. https://www.youtube.com/watch?v=iXZV5uAYMJI
  2661. # or any YouTube dashsegments video
  2662. fragments = []
  2663. segment_index = 0
  2664. timescale = representation_ms_info['timescale']
  2665. for s in representation_ms_info['s']:
  2666. duration = float_or_none(s['d'], timescale)
  2667. for _ in range(s.get('r', 0) + 1):
  2668. segment_uri = representation_ms_info['segment_urls'][segment_index]
  2669. fragments.append({
  2670. location_key(segment_uri): segment_uri,
  2671. 'duration': duration,
  2672. })
  2673. segment_index += 1
  2674. representation_ms_info['fragments'] = fragments
  2675. elif 'segment_urls' in representation_ms_info:
  2676. # Segment URLs with no SegmentTimeline
  2677. # E.g. https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  2678. # https://github.com/ytdl-org/youtube-dl/pull/14844
  2679. fragments = []
  2680. segment_duration = float_or_none(
  2681. representation_ms_info['segment_duration'],
  2682. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  2683. for segment_url in representation_ms_info['segment_urls']:
  2684. fragment = {
  2685. location_key(segment_url): segment_url,
  2686. }
  2687. if segment_duration:
  2688. fragment['duration'] = segment_duration
  2689. fragments.append(fragment)
  2690. representation_ms_info['fragments'] = fragments
  2691. # If there is a fragments key available then we correctly recognized fragmented media.
  2692. # Otherwise we will assume unfragmented media with direct access. Technically, such
  2693. # assumption is not necessarily correct since we may simply have no support for
  2694. # some forms of fragmented media renditions yet, but for now we'll use this fallback.
  2695. if 'fragments' in representation_ms_info:
  2696. f.update({
  2697. # NB: mpd_url may be empty when MPD manifest is parsed from a string
  2698. 'url': mpd_url or base_url,
  2699. 'fragment_base_url': base_url,
  2700. 'fragments': [],
  2701. 'protocol': 'http_dash_segments' if mime_type != 'image/jpeg' else 'mhtml',
  2702. })
  2703. if 'initialization_url' in representation_ms_info:
  2704. initialization_url = representation_ms_info['initialization_url']
  2705. if not f.get('url'):
  2706. f['url'] = initialization_url
  2707. f['fragments'].append({location_key(initialization_url): initialization_url})
  2708. f['fragments'].extend(representation_ms_info['fragments'])
  2709. if not period_duration:
  2710. period_duration = try_get(
  2711. representation_ms_info,
  2712. lambda r: sum(frag['duration'] for frag in r['fragments']), float)
  2713. else:
  2714. # Assuming direct URL to unfragmented media.
  2715. f['url'] = base_url
  2716. if content_type in ('video', 'audio', 'image/jpeg'):
  2717. f['manifest_stream_number'] = stream_numbers[f['url']]
  2718. stream_numbers[f['url']] += 1
  2719. period_entry['formats'].append(f)
  2720. elif content_type == 'text':
  2721. period_entry['subtitles'][lang or 'und'].append(f)
  2722. yield period_entry
  2723. def _extract_ism_formats(self, *args, **kwargs):
  2724. fmts, subs = self._extract_ism_formats_and_subtitles(*args, **kwargs)
  2725. if subs:
  2726. self._report_ignoring_subs('ISM')
  2727. return fmts
  2728. def _extract_ism_formats_and_subtitles(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  2729. if self.get_param('ignore_no_formats_error'):
  2730. fatal = False
  2731. res = self._download_xml_handle(
  2732. ism_url, video_id,
  2733. note='Downloading ISM manifest' if note is None else note,
  2734. errnote='Failed to download ISM manifest' if errnote is None else errnote,
  2735. fatal=fatal, data=data, headers=headers, query=query)
  2736. if res is False:
  2737. return [], {}
  2738. ism_doc, urlh = res
  2739. if ism_doc is None:
  2740. return [], {}
  2741. return self._parse_ism_formats_and_subtitles(ism_doc, urlh.url, ism_id)
  2742. def _parse_ism_formats_and_subtitles(self, ism_doc, ism_url, ism_id=None):
  2743. """
  2744. Parse formats from ISM manifest.
  2745. References:
  2746. 1. [MS-SSTR]: Smooth Streaming Protocol,
  2747. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  2748. """
  2749. if ism_doc.get('IsLive') == 'TRUE':
  2750. return [], {}
  2751. duration = int(ism_doc.attrib['Duration'])
  2752. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  2753. formats = []
  2754. subtitles = {}
  2755. for stream in ism_doc.findall('StreamIndex'):
  2756. stream_type = stream.get('Type')
  2757. if stream_type not in ('video', 'audio', 'text'):
  2758. continue
  2759. url_pattern = stream.attrib['Url']
  2760. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  2761. stream_name = stream.get('Name')
  2762. # IsmFD expects ISO 639 Set 2 language codes (3-character length)
  2763. # See: https://github.com/yt-dlp/yt-dlp/issues/11356
  2764. stream_language = stream.get('Language') or 'und'
  2765. if len(stream_language) != 3:
  2766. stream_language = ISO639Utils.short2long(stream_language) or 'und'
  2767. for track in stream.findall('QualityLevel'):
  2768. KNOWN_TAGS = {'255': 'AACL', '65534': 'EC-3'}
  2769. fourcc = track.get('FourCC') or KNOWN_TAGS.get(track.get('AudioTag'))
  2770. # TODO: add support for WVC1 and WMAP
  2771. if fourcc not in ('H264', 'AVC1', 'AACL', 'TTML', 'EC-3'):
  2772. self.report_warning(f'{fourcc} is not a supported codec')
  2773. continue
  2774. tbr = int(track.attrib['Bitrate']) // 1000
  2775. # [1] does not mention Width and Height attributes. However,
  2776. # they're often present while MaxWidth and MaxHeight are
  2777. # missing, so should be used as fallbacks
  2778. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  2779. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  2780. sampling_rate = int_or_none(track.get('SamplingRate'))
  2781. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  2782. track_url_pattern = urllib.parse.urljoin(ism_url, track_url_pattern)
  2783. fragments = []
  2784. fragment_ctx = {
  2785. 'time': 0,
  2786. }
  2787. stream_fragments = stream.findall('c')
  2788. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  2789. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  2790. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  2791. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  2792. if not fragment_ctx['duration']:
  2793. try:
  2794. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  2795. except IndexError:
  2796. next_fragment_time = duration
  2797. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  2798. for _ in range(fragment_repeat):
  2799. fragments.append({
  2800. 'url': re.sub(r'{start[ _]time}', str(fragment_ctx['time']), track_url_pattern),
  2801. 'duration': fragment_ctx['duration'] / stream_timescale,
  2802. })
  2803. fragment_ctx['time'] += fragment_ctx['duration']
  2804. if stream_type == 'text':
  2805. subtitles.setdefault(stream_language, []).append({
  2806. 'ext': 'ismt',
  2807. 'protocol': 'ism',
  2808. 'url': ism_url,
  2809. 'manifest_url': ism_url,
  2810. 'fragments': fragments,
  2811. '_download_params': {
  2812. 'stream_type': stream_type,
  2813. 'duration': duration,
  2814. 'timescale': stream_timescale,
  2815. 'fourcc': fourcc,
  2816. 'language': stream_language,
  2817. 'codec_private_data': track.get('CodecPrivateData'),
  2818. },
  2819. })
  2820. elif stream_type in ('video', 'audio'):
  2821. formats.append({
  2822. 'format_id': join_nonempty(ism_id, stream_name, tbr),
  2823. 'url': ism_url,
  2824. 'manifest_url': ism_url,
  2825. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  2826. 'width': width,
  2827. 'height': height,
  2828. 'tbr': tbr,
  2829. 'asr': sampling_rate,
  2830. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  2831. 'acodec': 'none' if stream_type == 'video' else fourcc,
  2832. 'protocol': 'ism',
  2833. 'fragments': fragments,
  2834. 'has_drm': ism_doc.find('Protection') is not None,
  2835. 'language': stream_language,
  2836. 'audio_channels': int_or_none(track.get('Channels')),
  2837. '_download_params': {
  2838. 'stream_type': stream_type,
  2839. 'duration': duration,
  2840. 'timescale': stream_timescale,
  2841. 'width': width or 0,
  2842. 'height': height or 0,
  2843. 'fourcc': fourcc,
  2844. 'language': stream_language,
  2845. 'codec_private_data': track.get('CodecPrivateData'),
  2846. 'sampling_rate': sampling_rate,
  2847. 'channels': int_or_none(track.get('Channels', 2)),
  2848. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  2849. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  2850. },
  2851. })
  2852. return formats, subtitles
  2853. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8_native', mpd_id=None, preference=None, quality=None, _headers=None):
  2854. def absolute_url(item_url):
  2855. return urljoin(base_url, item_url)
  2856. def parse_content_type(content_type):
  2857. if not content_type:
  2858. return {}
  2859. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  2860. if ctr:
  2861. mimetype, codecs = ctr.groups()
  2862. f = parse_codecs(codecs)
  2863. f['ext'] = mimetype2ext(mimetype)
  2864. return f
  2865. return {}
  2866. def _media_formats(src, cur_media_type, type_info=None):
  2867. type_info = type_info or {}
  2868. full_url = absolute_url(src)
  2869. ext = type_info.get('ext') or determine_ext(full_url)
  2870. if ext == 'm3u8':
  2871. is_plain_url = False
  2872. formats = self._extract_m3u8_formats(
  2873. full_url, video_id, ext='mp4',
  2874. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  2875. preference=preference, quality=quality, fatal=False, headers=_headers)
  2876. elif ext == 'mpd':
  2877. is_plain_url = False
  2878. formats = self._extract_mpd_formats(
  2879. full_url, video_id, mpd_id=mpd_id, fatal=False, headers=_headers)
  2880. else:
  2881. is_plain_url = True
  2882. formats = [{
  2883. 'url': full_url,
  2884. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  2885. 'ext': ext,
  2886. }]
  2887. return is_plain_url, formats
  2888. entries = []
  2889. # amp-video and amp-audio are very similar to their HTML5 counterparts
  2890. # so we will include them right here (see
  2891. # https://www.ampproject.org/docs/reference/components/amp-video)
  2892. # For dl8-* tags see https://delight-vr.com/documentation/dl8-video/
  2893. _MEDIA_TAG_NAME_RE = r'(?:(?:amp|dl8(?:-live)?)-)?(video|audio)'
  2894. media_tags = [(media_tag, media_tag_name, media_type, '')
  2895. for media_tag, media_tag_name, media_type
  2896. in re.findall(rf'(?s)(<({_MEDIA_TAG_NAME_RE})[^>]*/>)', webpage)]
  2897. media_tags.extend(re.findall(
  2898. # We only allow video|audio followed by a whitespace or '>'.
  2899. # Allowing more characters may end up in significant slow down (see
  2900. # https://github.com/ytdl-org/youtube-dl/issues/11979,
  2901. # e.g. http://www.porntrex.com/maps/videositemap.xml).
  2902. rf'(?s)(<(?P<tag>{_MEDIA_TAG_NAME_RE})(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  2903. for media_tag, _, media_type, media_content in media_tags:
  2904. media_info = {
  2905. 'formats': [],
  2906. 'subtitles': {},
  2907. }
  2908. media_attributes = extract_attributes(media_tag)
  2909. src = strip_or_none(dict_get(media_attributes, ('src', 'data-video-src', 'data-src', 'data-source')))
  2910. if src:
  2911. f = parse_content_type(media_attributes.get('type'))
  2912. _, formats = _media_formats(src, media_type, f)
  2913. media_info['formats'].extend(formats)
  2914. media_info['thumbnail'] = absolute_url(media_attributes.get('poster'))
  2915. if media_content:
  2916. for source_tag in re.findall(r'<source[^>]+>', media_content):
  2917. s_attr = extract_attributes(source_tag)
  2918. # data-video-src and data-src are non standard but seen
  2919. # several times in the wild
  2920. src = strip_or_none(dict_get(s_attr, ('src', 'data-video-src', 'data-src', 'data-source')))
  2921. if not src:
  2922. continue
  2923. f = parse_content_type(s_attr.get('type'))
  2924. is_plain_url, formats = _media_formats(src, media_type, f)
  2925. if is_plain_url:
  2926. # width, height, res, label and title attributes are
  2927. # all not standard but seen several times in the wild
  2928. labels = [
  2929. s_attr.get(lbl)
  2930. for lbl in ('label', 'title')
  2931. if str_or_none(s_attr.get(lbl))
  2932. ]
  2933. width = int_or_none(s_attr.get('width'))
  2934. height = (int_or_none(s_attr.get('height'))
  2935. or int_or_none(s_attr.get('res')))
  2936. if not width or not height:
  2937. for lbl in labels:
  2938. resolution = parse_resolution(lbl)
  2939. if not resolution:
  2940. continue
  2941. width = width or resolution.get('width')
  2942. height = height or resolution.get('height')
  2943. for lbl in labels:
  2944. tbr = parse_bitrate(lbl)
  2945. if tbr:
  2946. break
  2947. else:
  2948. tbr = None
  2949. f.update({
  2950. 'width': width,
  2951. 'height': height,
  2952. 'tbr': tbr,
  2953. 'format_id': s_attr.get('label') or s_attr.get('title'),
  2954. })
  2955. f.update(formats[0])
  2956. media_info['formats'].append(f)
  2957. else:
  2958. media_info['formats'].extend(formats)
  2959. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2960. track_attributes = extract_attributes(track_tag)
  2961. kind = track_attributes.get('kind')
  2962. if not kind or kind in ('subtitles', 'captions'):
  2963. src = strip_or_none(track_attributes.get('src'))
  2964. if not src:
  2965. continue
  2966. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2967. media_info['subtitles'].setdefault(lang, []).append({
  2968. 'url': absolute_url(src),
  2969. })
  2970. for f in media_info['formats']:
  2971. f.setdefault('http_headers', {})['Referer'] = base_url
  2972. if _headers:
  2973. f['http_headers'].update(_headers)
  2974. if media_info['formats'] or media_info['subtitles']:
  2975. entries.append(media_info)
  2976. return entries
  2977. def _extract_akamai_formats(self, *args, **kwargs):
  2978. fmts, subs = self._extract_akamai_formats_and_subtitles(*args, **kwargs)
  2979. if subs:
  2980. self._report_ignoring_subs('akamai')
  2981. return fmts
  2982. def _extract_akamai_formats_and_subtitles(self, manifest_url, video_id, hosts={}):
  2983. signed = 'hdnea=' in manifest_url
  2984. if not signed:
  2985. # https://learn.akamai.com/en-us/webhelp/media-services-on-demand/stream-packaging-user-guide/GUID-BE6C0F73-1E06-483B-B0EA-57984B91B7F9.html
  2986. manifest_url = re.sub(
  2987. r'(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?',
  2988. '', manifest_url).strip('?')
  2989. formats = []
  2990. subtitles = {}
  2991. hdcore_sign = 'hdcore=3.7.0'
  2992. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  2993. hds_host = hosts.get('hds')
  2994. if hds_host:
  2995. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  2996. if 'hdcore=' not in f4m_url:
  2997. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  2998. f4m_formats = self._extract_f4m_formats(
  2999. f4m_url, video_id, f4m_id='hds', fatal=False)
  3000. for entry in f4m_formats:
  3001. entry.update({'extra_param_to_segment_url': hdcore_sign})
  3002. formats.extend(f4m_formats)
  3003. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  3004. hls_host = hosts.get('hls')
  3005. if hls_host:
  3006. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  3007. m3u8_formats, m3u8_subtitles = self._extract_m3u8_formats_and_subtitles(
  3008. m3u8_url, video_id, 'mp4', 'm3u8_native',
  3009. m3u8_id='hls', fatal=False)
  3010. formats.extend(m3u8_formats)
  3011. subtitles = self._merge_subtitles(subtitles, m3u8_subtitles)
  3012. http_host = hosts.get('http')
  3013. if http_host and m3u8_formats and not signed:
  3014. REPL_REGEX = r'https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+'
  3015. qualities = re.match(REPL_REGEX, m3u8_url).group(2).split(',')
  3016. qualities_length = len(qualities)
  3017. if len(m3u8_formats) in (qualities_length, qualities_length + 1):
  3018. i = 0
  3019. for f in m3u8_formats:
  3020. if f['vcodec'] != 'none':
  3021. for protocol in ('http', 'https'):
  3022. http_f = f.copy()
  3023. del http_f['manifest_url']
  3024. http_url = re.sub(
  3025. REPL_REGEX, protocol + fr'://{http_host}/\g<1>{qualities[i]}\3', f['url'])
  3026. http_f.update({
  3027. 'format_id': http_f['format_id'].replace('hls-', protocol + '-'),
  3028. 'url': http_url,
  3029. 'protocol': protocol,
  3030. })
  3031. formats.append(http_f)
  3032. i += 1
  3033. return formats, subtitles
  3034. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  3035. query = urllib.parse.urlparse(url).query
  3036. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  3037. mobj = re.search(
  3038. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  3039. url_base = mobj.group('url')
  3040. http_base_url = '{}{}:{}'.format('http', mobj.group('s') or '', url_base)
  3041. formats = []
  3042. def manifest_url(manifest):
  3043. m_url = f'{http_base_url}/{manifest}'
  3044. if query:
  3045. m_url += f'?{query}'
  3046. return m_url
  3047. if 'm3u8' not in skip_protocols:
  3048. formats.extend(self._extract_m3u8_formats(
  3049. manifest_url('playlist.m3u8'), video_id, 'mp4',
  3050. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  3051. if 'f4m' not in skip_protocols:
  3052. formats.extend(self._extract_f4m_formats(
  3053. manifest_url('manifest.f4m'),
  3054. video_id, f4m_id='hds', fatal=False))
  3055. if 'dash' not in skip_protocols:
  3056. formats.extend(self._extract_mpd_formats(
  3057. manifest_url('manifest.mpd'),
  3058. video_id, mpd_id='dash', fatal=False))
  3059. if re.search(r'(?:/smil:|\.smil)', url_base):
  3060. if 'smil' not in skip_protocols:
  3061. rtmp_formats = self._extract_smil_formats(
  3062. manifest_url('jwplayer.smil'),
  3063. video_id, fatal=False)
  3064. for rtmp_format in rtmp_formats:
  3065. rtsp_format = rtmp_format.copy()
  3066. rtsp_format['url'] = '{}/{}'.format(rtmp_format['url'], rtmp_format['play_path'])
  3067. del rtsp_format['play_path']
  3068. del rtsp_format['ext']
  3069. rtsp_format.update({
  3070. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  3071. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  3072. 'protocol': 'rtsp',
  3073. })
  3074. formats.extend([rtmp_format, rtsp_format])
  3075. else:
  3076. for protocol in ('rtmp', 'rtsp'):
  3077. if protocol not in skip_protocols:
  3078. formats.append({
  3079. 'url': f'{protocol}:{url_base}',
  3080. 'format_id': protocol,
  3081. 'protocol': protocol,
  3082. })
  3083. return formats
  3084. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  3085. return self._search_json(
  3086. r'''(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)''',
  3087. webpage, 'JWPlayer data', video_id,
  3088. # must be a {...} or sequence, ending
  3089. contains_pattern=r'\{(?s:.*)}(?(load)(?:\s*,\s*\{(?s:.*)})*)', end_pattern=r'(?(load)\]|\))',
  3090. transform_source=transform_source, default=None)
  3091. def _extract_jwplayer_data(self, webpage, video_id, *args, transform_source=js_to_json, **kwargs):
  3092. jwplayer_data = self._find_jwplayer_data(
  3093. webpage, video_id, transform_source=transform_source)
  3094. return self._parse_jwplayer_data(
  3095. jwplayer_data, video_id, *args, **kwargs)
  3096. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  3097. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3098. entries = []
  3099. if not isinstance(jwplayer_data, dict):
  3100. return entries
  3101. playlist_items = jwplayer_data.get('playlist')
  3102. # JWPlayer backward compatibility: single playlist item/flattened playlists
  3103. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  3104. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  3105. if not isinstance(playlist_items, list):
  3106. playlist_items = (playlist_items or jwplayer_data, )
  3107. for video_data in playlist_items:
  3108. if not isinstance(video_data, dict):
  3109. continue
  3110. # JWPlayer backward compatibility: flattened sources
  3111. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  3112. if 'sources' not in video_data:
  3113. video_data['sources'] = [video_data]
  3114. this_video_id = video_id or video_data['mediaid']
  3115. formats = self._parse_jwplayer_formats(
  3116. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  3117. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  3118. subtitles = {}
  3119. for track in traverse_obj(video_data, (
  3120. 'tracks', lambda _, v: v['kind'].lower() in ('captions', 'subtitles'))):
  3121. track_url = urljoin(base_url, track.get('file'))
  3122. if not track_url:
  3123. continue
  3124. subtitles.setdefault(track.get('label') or 'en', []).append({
  3125. 'url': self._proto_relative_url(track_url),
  3126. })
  3127. entry = {
  3128. 'id': this_video_id,
  3129. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  3130. 'description': clean_html(video_data.get('description')),
  3131. 'thumbnail': urljoin(base_url, self._proto_relative_url(video_data.get('image'))),
  3132. 'timestamp': int_or_none(video_data.get('pubdate')),
  3133. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  3134. 'subtitles': subtitles,
  3135. 'alt_title': clean_html(video_data.get('subtitle')), # attributes used e.g. by Tele5 ...
  3136. 'genre': clean_html(video_data.get('genre')),
  3137. 'channel': clean_html(dict_get(video_data, ('category', 'channel'))),
  3138. 'season_number': int_or_none(video_data.get('season')),
  3139. 'episode_number': int_or_none(video_data.get('episode')),
  3140. 'release_year': int_or_none(video_data.get('releasedate')),
  3141. 'age_limit': int_or_none(video_data.get('age_restriction')),
  3142. }
  3143. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  3144. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  3145. entry.update({
  3146. '_type': 'url_transparent',
  3147. 'url': formats[0]['url'],
  3148. })
  3149. else:
  3150. entry['formats'] = formats
  3151. entries.append(entry)
  3152. if len(entries) == 1:
  3153. return entries[0]
  3154. else:
  3155. return self.playlist_result(entries)
  3156. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  3157. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3158. urls = set()
  3159. formats = []
  3160. for source in jwplayer_sources_data:
  3161. if not isinstance(source, dict):
  3162. continue
  3163. source_url = urljoin(
  3164. base_url, self._proto_relative_url(source.get('file')))
  3165. if not source_url or source_url in urls:
  3166. continue
  3167. urls.add(source_url)
  3168. source_type = source.get('type') or ''
  3169. ext = determine_ext(source_url, default_ext=mimetype2ext(source_type))
  3170. if source_type == 'hls' or ext == 'm3u8' or 'format=m3u8-aapl' in source_url:
  3171. formats.extend(self._extract_m3u8_formats(
  3172. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  3173. m3u8_id=m3u8_id, fatal=False))
  3174. elif source_type == 'dash' or ext == 'mpd' or 'format=mpd-time-csf' in source_url:
  3175. formats.extend(self._extract_mpd_formats(
  3176. source_url, video_id, mpd_id=mpd_id, fatal=False))
  3177. elif ext == 'smil':
  3178. formats.extend(self._extract_smil_formats(
  3179. source_url, video_id, fatal=False))
  3180. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  3181. elif source_type.startswith('audio') or ext in (
  3182. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  3183. formats.append({
  3184. 'url': source_url,
  3185. 'vcodec': 'none',
  3186. 'ext': ext,
  3187. })
  3188. else:
  3189. format_id = str_or_none(source.get('label'))
  3190. height = int_or_none(source.get('height'))
  3191. if height is None and format_id:
  3192. # Often no height is provided but there is a label in
  3193. # format like "1080p", "720p SD", or 1080.
  3194. height = parse_resolution(format_id).get('height')
  3195. a_format = {
  3196. 'url': source_url,
  3197. 'width': int_or_none(source.get('width')),
  3198. 'height': height,
  3199. 'tbr': int_or_none(source.get('bitrate'), scale=1000),
  3200. 'filesize': int_or_none(source.get('filesize')),
  3201. 'ext': ext,
  3202. 'format_id': format_id,
  3203. }
  3204. if source_url.startswith('rtmp'):
  3205. a_format['ext'] = 'flv'
  3206. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  3207. # of jwplayer.flash.swf
  3208. rtmp_url_parts = re.split(
  3209. r'((?:mp4|mp3|flv):)', source_url, maxsplit=1)
  3210. if len(rtmp_url_parts) == 3:
  3211. rtmp_url, prefix, play_path = rtmp_url_parts
  3212. a_format.update({
  3213. 'url': rtmp_url,
  3214. 'play_path': prefix + play_path,
  3215. })
  3216. if rtmp_params:
  3217. a_format.update(rtmp_params)
  3218. formats.append(a_format)
  3219. return formats
  3220. def _live_title(self, name):
  3221. self._downloader.deprecation_warning('yt_dlp.InfoExtractor._live_title is deprecated and does not work as expected')
  3222. return name
  3223. def _int(self, v, name, fatal=False, **kwargs):
  3224. res = int_or_none(v, **kwargs)
  3225. if res is None:
  3226. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3227. if fatal:
  3228. raise ExtractorError(msg)
  3229. else:
  3230. self.report_warning(msg)
  3231. return res
  3232. def _float(self, v, name, fatal=False, **kwargs):
  3233. res = float_or_none(v, **kwargs)
  3234. if res is None:
  3235. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3236. if fatal:
  3237. raise ExtractorError(msg)
  3238. else:
  3239. self.report_warning(msg)
  3240. return res
  3241. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  3242. path='/', secure=False, discard=False, rest={}, **kwargs):
  3243. cookie = http.cookiejar.Cookie(
  3244. 0, name, value, port, port is not None, domain, True,
  3245. domain.startswith('.'), path, True, secure, expire_time,
  3246. discard, None, None, rest)
  3247. self.cookiejar.set_cookie(cookie)
  3248. def _get_cookies(self, url):
  3249. """ Return a http.cookies.SimpleCookie with the cookies for the url """
  3250. return LenientSimpleCookie(self._downloader.cookiejar.get_cookie_header(url))
  3251. def _apply_first_set_cookie_header(self, url_handle, cookie):
  3252. """
  3253. Apply first Set-Cookie header instead of the last. Experimental.
  3254. Some sites (e.g. [1-3]) may serve two cookies under the same name
  3255. in Set-Cookie header and expect the first (old) one to be set rather
  3256. than second (new). However, as of RFC6265 the newer one cookie
  3257. should be set into cookie store what actually happens.
  3258. We will workaround this issue by resetting the cookie to
  3259. the first one manually.
  3260. 1. https://new.vk.com/
  3261. 2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
  3262. 3. https://learning.oreilly.com/
  3263. """
  3264. for header, cookies in url_handle.headers.items():
  3265. if header.lower() != 'set-cookie':
  3266. continue
  3267. cookies = cookies.encode('iso-8859-1').decode('utf-8')
  3268. cookie_value = re.search(
  3269. rf'{cookie}=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)', cookies)
  3270. if cookie_value:
  3271. value, domain = cookie_value.groups()
  3272. self._set_cookie(domain, cookie, value)
  3273. break
  3274. @classmethod
  3275. def get_testcases(cls, include_onlymatching=False):
  3276. # Do not look in super classes
  3277. t = vars(cls).get('_TEST')
  3278. if t:
  3279. assert not hasattr(cls, '_TESTS'), f'{cls.ie_key()}IE has _TEST and _TESTS'
  3280. tests = [t]
  3281. else:
  3282. tests = vars(cls).get('_TESTS', [])
  3283. for t in tests:
  3284. if not include_onlymatching and t.get('only_matching', False):
  3285. continue
  3286. t['name'] = cls.ie_key()
  3287. yield t
  3288. if getattr(cls, '__wrapped__', None):
  3289. yield from cls.__wrapped__.get_testcases(include_onlymatching)
  3290. @classmethod
  3291. def get_webpage_testcases(cls):
  3292. tests = vars(cls).get('_WEBPAGE_TESTS', [])
  3293. for t in tests:
  3294. t['name'] = cls.ie_key()
  3295. yield t
  3296. if getattr(cls, '__wrapped__', None):
  3297. yield from cls.__wrapped__.get_webpage_testcases()
  3298. @classproperty(cache=True)
  3299. def age_limit(cls):
  3300. """Get age limit from the testcases"""
  3301. return max(traverse_obj(
  3302. (*cls.get_testcases(include_onlymatching=False), *cls.get_webpage_testcases()),
  3303. (..., (('playlist', 0), None), 'info_dict', 'age_limit')) or [0])
  3304. @classproperty(cache=True)
  3305. def _RETURN_TYPE(cls):
  3306. """What the extractor returns: "video", "playlist", "any", or None (Unknown)"""
  3307. tests = tuple(cls.get_testcases(include_onlymatching=False))
  3308. if not tests:
  3309. return None
  3310. elif not any(k.startswith('playlist') for test in tests for k in test):
  3311. return 'video'
  3312. elif all(any(k.startswith('playlist') for k in test) for test in tests):
  3313. return 'playlist'
  3314. return 'any'
  3315. @classmethod
  3316. def is_single_video(cls, url):
  3317. """Returns whether the URL is of a single video, None if unknown"""
  3318. if cls.suitable(url):
  3319. return {'video': True, 'playlist': False}.get(cls._RETURN_TYPE)
  3320. @classmethod
  3321. def is_suitable(cls, age_limit):
  3322. """Test whether the extractor is generally suitable for the given age limit"""
  3323. return not age_restricted(cls.age_limit, age_limit)
  3324. @classmethod
  3325. def description(cls, *, markdown=True, search_examples=None):
  3326. """Description of the extractor"""
  3327. desc = ''
  3328. if cls._NETRC_MACHINE:
  3329. if markdown:
  3330. desc += f' [*{cls._NETRC_MACHINE}*](## "netrc machine")'
  3331. else:
  3332. desc += f' [{cls._NETRC_MACHINE}]'
  3333. if cls.IE_DESC is False:
  3334. desc += ' [HIDDEN]'
  3335. elif cls.IE_DESC:
  3336. desc += f' {cls.IE_DESC}'
  3337. if cls.SEARCH_KEY:
  3338. desc += f'{";" if cls.IE_DESC else ""} "{cls.SEARCH_KEY}:" prefix'
  3339. if search_examples:
  3340. _COUNTS = ('', '5', '10', 'all')
  3341. desc += f' (e.g. "{cls.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(search_examples)}")'
  3342. if not cls.working():
  3343. desc += ' (**Currently broken**)' if markdown else ' (Currently broken)'
  3344. # Escape emojis. Ref: https://github.com/github/markup/issues/1153
  3345. name = (' - **{}**'.format(re.sub(r':(\w+:)', ':\u200B\\g<1>', cls.IE_NAME))) if markdown else cls.IE_NAME
  3346. return f'{name}:{desc}' if desc else name
  3347. def extract_subtitles(self, *args, **kwargs):
  3348. if (self.get_param('writesubtitles', False)
  3349. or self.get_param('listsubtitles')):
  3350. return self._get_subtitles(*args, **kwargs)
  3351. return {}
  3352. def _get_subtitles(self, *args, **kwargs):
  3353. raise NotImplementedError('This method must be implemented by subclasses')
  3354. class CommentsDisabled(Exception):
  3355. """Raise in _get_comments if comments are disabled for the video"""
  3356. def extract_comments(self, *args, **kwargs):
  3357. if not self.get_param('getcomments'):
  3358. return None
  3359. generator = self._get_comments(*args, **kwargs)
  3360. def extractor():
  3361. comments = []
  3362. interrupted = True
  3363. try:
  3364. while True:
  3365. comments.append(next(generator))
  3366. except StopIteration:
  3367. interrupted = False
  3368. except KeyboardInterrupt:
  3369. self.to_screen('Interrupted by user')
  3370. except self.CommentsDisabled:
  3371. return {'comments': None, 'comment_count': None}
  3372. except Exception as e:
  3373. if self.get_param('ignoreerrors') is not True:
  3374. raise
  3375. self._downloader.report_error(e)
  3376. comment_count = len(comments)
  3377. self.to_screen(f'Extracted {comment_count} comments')
  3378. return {
  3379. 'comments': comments,
  3380. 'comment_count': None if interrupted else comment_count,
  3381. }
  3382. return extractor
  3383. def _get_comments(self, *args, **kwargs):
  3384. raise NotImplementedError('This method must be implemented by subclasses')
  3385. @staticmethod
  3386. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  3387. """ Merge subtitle items for one language. Items with duplicated URLs/data
  3388. will be dropped. """
  3389. list1_data = {(item.get('url'), item.get('data')) for item in subtitle_list1}
  3390. ret = list(subtitle_list1)
  3391. ret.extend(item for item in subtitle_list2 if (item.get('url'), item.get('data')) not in list1_data)
  3392. return ret
  3393. @classmethod
  3394. def _merge_subtitles(cls, *dicts, target=None):
  3395. """ Merge subtitle dictionaries, language by language. """
  3396. if target is None:
  3397. target = {}
  3398. for d in filter(None, dicts):
  3399. for lang, subs in d.items():
  3400. target[lang] = cls._merge_subtitle_items(target.get(lang, []), subs)
  3401. return target
  3402. def extract_automatic_captions(self, *args, **kwargs):
  3403. if (self.get_param('writeautomaticsub', False)
  3404. or self.get_param('listsubtitles')):
  3405. return self._get_automatic_captions(*args, **kwargs)
  3406. return {}
  3407. def _get_automatic_captions(self, *args, **kwargs):
  3408. raise NotImplementedError('This method must be implemented by subclasses')
  3409. @functools.cached_property
  3410. def _cookies_passed(self):
  3411. """Whether cookies have been passed to YoutubeDL"""
  3412. return self.get_param('cookiefile') is not None or self.get_param('cookiesfrombrowser') is not None
  3413. def mark_watched(self, *args, **kwargs):
  3414. if not self.get_param('mark_watched', False):
  3415. return
  3416. if (self.supports_login() and self._get_login_info()[0] is not None) or self._cookies_passed:
  3417. self._mark_watched(*args, **kwargs)
  3418. def _mark_watched(self, *args, **kwargs):
  3419. raise NotImplementedError('This method must be implemented by subclasses')
  3420. def geo_verification_headers(self):
  3421. headers = {}
  3422. geo_verification_proxy = self.get_param('geo_verification_proxy')
  3423. if geo_verification_proxy:
  3424. headers['Ytdl-request-proxy'] = geo_verification_proxy
  3425. return headers
  3426. @staticmethod
  3427. def _generic_id(url):
  3428. return urllib.parse.unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  3429. def _generic_title(self, url='', webpage='', *, default=None):
  3430. return (self._og_search_title(webpage, default=None)
  3431. or self._html_extract_title(webpage, default=None)
  3432. or urllib.parse.unquote(os.path.splitext(url_basename(url))[0])
  3433. or default)
  3434. def _extract_chapters_helper(self, chapter_list, start_function, title_function, duration, strict=True):
  3435. if not duration:
  3436. return
  3437. chapter_list = [{
  3438. 'start_time': start_function(chapter),
  3439. 'title': title_function(chapter),
  3440. } for chapter in chapter_list or []]
  3441. if strict:
  3442. warn = self.report_warning
  3443. else:
  3444. warn = self.write_debug
  3445. chapter_list.sort(key=lambda c: c['start_time'] or 0)
  3446. chapters = [{'start_time': 0}]
  3447. for idx, chapter in enumerate(chapter_list):
  3448. if chapter['start_time'] is None:
  3449. warn(f'Incomplete chapter {idx}')
  3450. elif chapters[-1]['start_time'] <= chapter['start_time'] <= duration:
  3451. chapters.append(chapter)
  3452. elif chapter not in chapters:
  3453. issue = (f'{chapter["start_time"]} > {duration}' if chapter['start_time'] > duration
  3454. else f'{chapter["start_time"]} < {chapters[-1]["start_time"]}')
  3455. warn(f'Invalid start time ({issue}) for chapter "{chapter["title"]}"')
  3456. return chapters[1:]
  3457. def _extract_chapters_from_description(self, description, duration):
  3458. duration_re = r'(?:\d+:)?\d{1,2}:\d{2}'
  3459. sep_re = r'(?m)^\s*(%s)\b\W*\s(%s)\s*$'
  3460. return self._extract_chapters_helper(
  3461. re.findall(sep_re % (duration_re, r'.+?'), description or ''),
  3462. start_function=lambda x: parse_duration(x[0]), title_function=lambda x: x[1],
  3463. duration=duration, strict=False) or self._extract_chapters_helper(
  3464. re.findall(sep_re % (r'.+?', duration_re), description or ''),
  3465. start_function=lambda x: parse_duration(x[1]), title_function=lambda x: x[0],
  3466. duration=duration, strict=False)
  3467. @staticmethod
  3468. def _availability(is_private=None, needs_premium=None, needs_subscription=None, needs_auth=None, is_unlisted=None):
  3469. all_known = all(
  3470. x is not None for x in
  3471. (is_private, needs_premium, needs_subscription, needs_auth, is_unlisted))
  3472. return (
  3473. 'private' if is_private
  3474. else 'premium_only' if needs_premium
  3475. else 'subscriber_only' if needs_subscription
  3476. else 'needs_auth' if needs_auth
  3477. else 'unlisted' if is_unlisted
  3478. else 'public' if all_known
  3479. else None)
  3480. def _configuration_arg(self, key, default=NO_DEFAULT, *, ie_key=None, casesense=False):
  3481. '''
  3482. @returns A list of values for the extractor argument given by "key"
  3483. or "default" if no such key is present
  3484. @param default The default value to return when the key is not present (default: [])
  3485. @param casesense When false, the values are converted to lower case
  3486. '''
  3487. ie_key = ie_key if isinstance(ie_key, str) else (ie_key or self).ie_key()
  3488. val = traverse_obj(self._downloader.params, ('extractor_args', ie_key.lower(), key))
  3489. if val is None:
  3490. return [] if default is NO_DEFAULT else default
  3491. return list(val) if casesense else [x.lower() for x in val]
  3492. def _yes_playlist(self, playlist_id, video_id, smuggled_data=None, *, playlist_label='playlist', video_label='video'):
  3493. if not playlist_id or not video_id:
  3494. return not video_id
  3495. no_playlist = (smuggled_data or {}).get('force_noplaylist')
  3496. if no_playlist is not None:
  3497. return not no_playlist
  3498. video_id = '' if video_id is True else f' {video_id}'
  3499. playlist_id = '' if playlist_id is True else f' {playlist_id}'
  3500. if self.get_param('noplaylist'):
  3501. self.to_screen(f'Downloading just the {video_label}{video_id} because of --no-playlist')
  3502. return False
  3503. self.to_screen(f'Downloading {playlist_label}{playlist_id} - add --no-playlist to download just the {video_label}{video_id}')
  3504. return True
  3505. def _error_or_warning(self, err, _count=None, _retries=0, *, fatal=True):
  3506. RetryManager.report_retry(
  3507. err, _count or int(fatal), _retries,
  3508. info=self.to_screen, warn=self.report_warning, error=None if fatal else self.report_warning,
  3509. sleep_func=self.get_param('retry_sleep_functions', {}).get('extractor'))
  3510. def RetryManager(self, **kwargs):
  3511. return RetryManager(self.get_param('extractor_retries', 3), self._error_or_warning, **kwargs)
  3512. def _extract_generic_embeds(self, url, *args, info_dict={}, note='Extracting generic embeds', **kwargs):
  3513. display_id = traverse_obj(info_dict, 'display_id', 'id')
  3514. self.to_screen(f'{format_field(display_id, None, "%s: ")}{note}')
  3515. return self._downloader.get_info_extractor('Generic')._extract_embeds(
  3516. smuggle_url(url, {'block_ies': [self.ie_key()]}), *args, **kwargs)
  3517. @classmethod
  3518. def extract_from_webpage(cls, ydl, url, webpage):
  3519. ie = (cls if isinstance(cls._extract_from_webpage, types.MethodType)
  3520. else ydl.get_info_extractor(cls.ie_key()))
  3521. for info in ie._extract_from_webpage(url, webpage) or []:
  3522. # url = None since we do not want to set (webpage/original)_url
  3523. ydl.add_default_extra_info(info, ie, None)
  3524. yield info
  3525. @classmethod
  3526. def _extract_from_webpage(cls, url, webpage):
  3527. for embed_url in orderedSet(
  3528. cls._extract_embed_urls(url, webpage) or [], lazy=True):
  3529. yield cls.url_result(embed_url, None if cls._VALID_URL is False else cls)
  3530. @classmethod
  3531. def _extract_embed_urls(cls, url, webpage):
  3532. """@returns all the embed urls on the webpage"""
  3533. if '_EMBED_URL_RE' not in cls.__dict__:
  3534. assert isinstance(cls._EMBED_REGEX, (list, tuple))
  3535. for idx, regex in enumerate(cls._EMBED_REGEX):
  3536. assert regex.count('(?P<url>') == 1, \
  3537. f'{cls.__name__}._EMBED_REGEX[{idx}] must have exactly 1 url group\n\t{regex}'
  3538. cls._EMBED_URL_RE = tuple(map(re.compile, cls._EMBED_REGEX))
  3539. for regex in cls._EMBED_URL_RE:
  3540. for mobj in regex.finditer(webpage):
  3541. embed_url = urllib.parse.urljoin(url, unescapeHTML(mobj.group('url')))
  3542. if cls._VALID_URL is False or cls.suitable(embed_url):
  3543. yield embed_url
  3544. class StopExtraction(Exception):
  3545. pass
  3546. @classmethod
  3547. def _extract_url(cls, webpage): # TODO: Remove
  3548. """Only for compatibility with some older extractors"""
  3549. return next(iter(cls._extract_embed_urls(None, webpage) or []), None)
  3550. @classmethod
  3551. def __init_subclass__(cls, *, plugin_name=None, **kwargs):
  3552. if plugin_name:
  3553. mro = inspect.getmro(cls)
  3554. super_class = cls.__wrapped__ = mro[mro.index(cls) + 1]
  3555. cls.PLUGIN_NAME, cls.ie_key = plugin_name, super_class.ie_key
  3556. cls.IE_NAME = f'{super_class.IE_NAME}+{plugin_name}'
  3557. while getattr(super_class, '__wrapped__', None):
  3558. super_class = super_class.__wrapped__
  3559. setattr(sys.modules[super_class.__module__], super_class.__name__, cls)
  3560. _PLUGIN_OVERRIDES[super_class].append(cls)
  3561. return super().__init_subclass__(**kwargs)
  3562. class SearchInfoExtractor(InfoExtractor):
  3563. """
  3564. Base class for paged search queries extractors.
  3565. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  3566. Instances should define _SEARCH_KEY and optionally _MAX_RESULTS
  3567. """
  3568. _MAX_RESULTS = float('inf')
  3569. _RETURN_TYPE = 'playlist'
  3570. @classproperty
  3571. def _VALID_URL(cls):
  3572. return rf'{cls._SEARCH_KEY}(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)'
  3573. def _real_extract(self, query):
  3574. prefix, query = self._match_valid_url(query).group('prefix', 'query')
  3575. if prefix == '':
  3576. return self._get_n_results(query, 1)
  3577. elif prefix == 'all':
  3578. return self._get_n_results(query, self._MAX_RESULTS)
  3579. else:
  3580. n = int(prefix)
  3581. if n <= 0:
  3582. raise ExtractorError(f'invalid download number {n} for query "{query}"')
  3583. elif n > self._MAX_RESULTS:
  3584. self.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  3585. n = self._MAX_RESULTS
  3586. return self._get_n_results(query, n)
  3587. def _get_n_results(self, query, n):
  3588. """Get a specified number of results for a query.
  3589. Either this function or _search_results must be overridden by subclasses """
  3590. return self.playlist_result(
  3591. itertools.islice(self._search_results(query), 0, None if n == float('inf') else n),
  3592. query, query)
  3593. def _search_results(self, query):
  3594. """Returns an iterator of search results"""
  3595. raise NotImplementedError('This method must be implemented by subclasses')
  3596. @classproperty
  3597. def SEARCH_KEY(cls):
  3598. return cls._SEARCH_KEY
  3599. class UnsupportedURLIE(InfoExtractor):
  3600. _VALID_URL = '.*'
  3601. _ENABLED = False
  3602. IE_DESC = False
  3603. def _real_extract(self, url):
  3604. raise UnsupportedError(url)
  3605. _PLUGIN_OVERRIDES = collections.defaultdict(list)