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.

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