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.

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