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.

2629 lines
121 KiB

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