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.

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