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.

2623 lines
120 KiB

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