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.

2622 lines
120 KiB

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