You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3023 lines
138KB

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