logo

youtube-dl

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

common.py (159011B)


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