PageRenderTime 3233ms CodeModel.GetById 28ms RepoModel.GetById 7ms app.codeStats 0ms

/yt_dlp/extractor/nebula.py

https://gitlab.com/vitalii.dr/yt-dlp
Python | 288 lines | 279 code | 7 blank | 2 comment | 12 complexity | 55a8586c024566bee43027dd9d06f1aa MD5 | raw file
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import time
  6. import urllib
  7. from ..utils import (
  8. ExtractorError,
  9. parse_iso8601,
  10. try_get,
  11. )
  12. from .common import InfoExtractor
  13. class NebulaBaseIE(InfoExtractor):
  14. _NETRC_MACHINE = 'watchnebula'
  15. _nebula_api_token = None
  16. _nebula_bearer_token = None
  17. _zype_access_token = None
  18. def _perform_nebula_auth(self):
  19. username, password = self._get_login_info()
  20. if not (username and password):
  21. self.raise_login_required()
  22. data = json.dumps({'email': username, 'password': password}).encode('utf8')
  23. response = self._download_json(
  24. 'https://api.watchnebula.com/api/v1/auth/login/',
  25. data=data, fatal=False, video_id=None,
  26. headers={
  27. 'content-type': 'application/json',
  28. # Submitting the 'sessionid' cookie always causes a 403 on auth endpoint
  29. 'cookie': ''
  30. },
  31. note='Logging in to Nebula with supplied credentials',
  32. errnote='Authentication failed or rejected')
  33. if not response or not response.get('key'):
  34. self.raise_login_required()
  35. # save nebula token as cookie
  36. self._set_cookie(
  37. 'nebula.app', 'nebula-auth',
  38. urllib.parse.quote(
  39. json.dumps({
  40. "apiToken": response["key"],
  41. "isLoggingIn": False,
  42. "isLoggingOut": False,
  43. }, separators=(",", ":"))),
  44. expire_time=int(time.time()) + 86400 * 365,
  45. )
  46. return response['key']
  47. def _retrieve_nebula_api_token(self):
  48. """
  49. Check cookie jar for valid token. Try to authenticate using credentials if no valid token
  50. can be found in the cookie jar.
  51. """
  52. nebula_cookies = self._get_cookies('https://nebula.app')
  53. nebula_cookie = nebula_cookies.get('nebula-auth')
  54. if nebula_cookie:
  55. self.to_screen('Authenticating to Nebula with token from cookie jar')
  56. nebula_cookie_value = urllib.parse.unquote(nebula_cookie.value)
  57. nebula_api_token = self._parse_json(nebula_cookie_value, None).get('apiToken')
  58. if nebula_api_token:
  59. return nebula_api_token
  60. return self._perform_nebula_auth()
  61. def _call_nebula_api(self, url, video_id=None, method='GET', auth_type='api', note=''):
  62. assert method in ('GET', 'POST',)
  63. assert auth_type in ('api', 'bearer',)
  64. def inner_call():
  65. authorization = f'Token {self._nebula_api_token}' if auth_type == 'api' else f'Bearer {self._nebula_bearer_token}'
  66. return self._download_json(
  67. url, video_id, note=note, headers={'Authorization': authorization},
  68. data=b'' if method == 'POST' else None)
  69. try:
  70. return inner_call()
  71. except ExtractorError as exc:
  72. # if 401 or 403, attempt credential re-auth and retry
  73. if exc.cause and isinstance(exc.cause, urllib.error.HTTPError) and exc.cause.code in (401, 403):
  74. self.to_screen(f'Reauthenticating to Nebula and retrying, because last {auth_type} call resulted in error {exc.cause.code}')
  75. self._login()
  76. return inner_call()
  77. else:
  78. raise
  79. def _fetch_nebula_bearer_token(self):
  80. """
  81. Get a Bearer token for the Nebula API. This will be required to fetch video meta data.
  82. """
  83. response = self._call_nebula_api('https://api.watchnebula.com/api/v1/authorization/',
  84. method='POST',
  85. note='Authorizing to Nebula')
  86. return response['token']
  87. def _fetch_zype_access_token(self):
  88. """
  89. Get a Zype access token, which is required to access video streams -- in our case: to
  90. generate video URLs.
  91. """
  92. user_object = self._call_nebula_api('https://api.watchnebula.com/api/v1/auth/user/', note='Retrieving Zype access token')
  93. access_token = try_get(user_object, lambda x: x['zype_auth_info']['access_token'], str)
  94. if not access_token:
  95. if try_get(user_object, lambda x: x['is_subscribed'], bool):
  96. # TODO: Reimplement the same Zype token polling the Nebula frontend implements
  97. # see https://github.com/ytdl-org/youtube-dl/pull/24805#issuecomment-749231532
  98. raise ExtractorError(
  99. 'Unable to extract Zype access token from Nebula API authentication endpoint. '
  100. 'Open an arbitrary video in a browser with this account to generate a token',
  101. expected=True)
  102. raise ExtractorError('Unable to extract Zype access token from Nebula API authentication endpoint')
  103. return access_token
  104. def _build_video_info(self, episode):
  105. zype_id = episode['zype_id']
  106. zype_video_url = f'https://player.zype.com/embed/{zype_id}.html?access_token={self._zype_access_token}'
  107. channel_slug = episode['channel_slug']
  108. return {
  109. 'id': episode['zype_id'],
  110. 'display_id': episode['slug'],
  111. '_type': 'url_transparent',
  112. 'ie_key': 'Zype',
  113. 'url': zype_video_url,
  114. 'title': episode['title'],
  115. 'description': episode['description'],
  116. 'timestamp': parse_iso8601(episode['published_at']),
  117. 'thumbnails': [{
  118. # 'id': tn.get('name'), # this appears to be null
  119. 'url': tn['original'],
  120. 'height': key,
  121. } for key, tn in episode['assets']['thumbnail'].items()],
  122. 'duration': episode['duration'],
  123. 'channel': episode['channel_title'],
  124. 'channel_id': channel_slug,
  125. 'channel_url': f'https://nebula.app/{channel_slug}',
  126. 'uploader': episode['channel_title'],
  127. 'uploader_id': channel_slug,
  128. 'uploader_url': f'https://nebula.app/{channel_slug}',
  129. 'series': episode['channel_title'],
  130. 'creator': episode['channel_title'],
  131. }
  132. def _perform_login(self, username=None, password=None):
  133. # FIXME: username should be passed from here to inner functions
  134. self._nebula_api_token = self._retrieve_nebula_api_token()
  135. self._nebula_bearer_token = self._fetch_nebula_bearer_token()
  136. self._zype_access_token = self._fetch_zype_access_token()
  137. class NebulaIE(NebulaBaseIE):
  138. _VALID_URL = r'https?://(?:www\.)?(?:watchnebula\.com|nebula\.app)/videos/(?P<id>[-\w]+)'
  139. _TESTS = [
  140. {
  141. 'url': 'https://nebula.app/videos/that-time-disney-remade-beauty-and-the-beast',
  142. 'md5': 'fe79c4df8b3aa2fea98a93d027465c7e',
  143. 'info_dict': {
  144. 'id': '5c271b40b13fd613090034fd',
  145. 'ext': 'mp4',
  146. 'title': 'That Time Disney Remade Beauty and the Beast',
  147. 'description': 'Note: this video was originally posted on YouTube with the sponsor read included. We weren’t able to remove it without reducing video quality, so it’s presented here in its original context.',
  148. 'upload_date': '20180731',
  149. 'timestamp': 1533009600,
  150. 'channel': 'Lindsay Ellis',
  151. 'channel_id': 'lindsayellis',
  152. 'uploader': 'Lindsay Ellis',
  153. 'uploader_id': 'lindsayellis',
  154. },
  155. 'params': {
  156. 'usenetrc': True,
  157. },
  158. },
  159. {
  160. 'url': 'https://nebula.app/videos/the-logistics-of-d-day-landing-craft-how-the-allies-got-ashore',
  161. 'md5': '6d4edd14ce65720fa63aba5c583fb328',
  162. 'info_dict': {
  163. 'id': '5e7e78171aaf320001fbd6be',
  164. 'ext': 'mp4',
  165. 'title': 'Landing Craft - How The Allies Got Ashore',
  166. 'description': r're:^In this episode we explore the unsung heroes of D-Day, the landing craft.',
  167. 'upload_date': '20200327',
  168. 'timestamp': 1585348140,
  169. 'channel': 'Real Engineering',
  170. 'channel_id': 'realengineering',
  171. 'uploader': 'Real Engineering',
  172. 'uploader_id': 'realengineering',
  173. },
  174. 'params': {
  175. 'usenetrc': True,
  176. },
  177. },
  178. {
  179. 'url': 'https://nebula.app/videos/money-episode-1-the-draw',
  180. 'md5': '8c7d272910eea320f6f8e6d3084eecf5',
  181. 'info_dict': {
  182. 'id': '5e779ebdd157bc0001d1c75a',
  183. 'ext': 'mp4',
  184. 'title': 'Episode 1: The Draw',
  185. 'description': r'contains:There’s free money on offer… if the players can all work together.',
  186. 'upload_date': '20200323',
  187. 'timestamp': 1584980400,
  188. 'channel': 'Tom Scott Presents: Money',
  189. 'channel_id': 'tom-scott-presents-money',
  190. 'uploader': 'Tom Scott Presents: Money',
  191. 'uploader_id': 'tom-scott-presents-money',
  192. },
  193. 'params': {
  194. 'usenetrc': True,
  195. },
  196. },
  197. {
  198. 'url': 'https://watchnebula.com/videos/money-episode-1-the-draw',
  199. 'only_matching': True,
  200. },
  201. ]
  202. def _fetch_video_metadata(self, slug):
  203. return self._call_nebula_api(f'https://content.watchnebula.com/video/{slug}/',
  204. video_id=slug,
  205. auth_type='bearer',
  206. note='Fetching video meta data')
  207. def _real_extract(self, url):
  208. slug = self._match_id(url)
  209. video = self._fetch_video_metadata(slug)
  210. return self._build_video_info(video)
  211. class NebulaCollectionIE(NebulaBaseIE):
  212. IE_NAME = 'nebula:collection'
  213. _VALID_URL = r'https?://(?:www\.)?(?:watchnebula\.com|nebula\.app)/(?!videos/)(?P<id>[-\w]+)'
  214. _TESTS = [
  215. {
  216. 'url': 'https://nebula.app/tom-scott-presents-money',
  217. 'info_dict': {
  218. 'id': 'tom-scott-presents-money',
  219. 'title': 'Tom Scott Presents: Money',
  220. 'description': 'Tom Scott hosts a series all about trust, negotiation and money.',
  221. },
  222. 'playlist_count': 5,
  223. 'params': {
  224. 'usenetrc': True,
  225. },
  226. }, {
  227. 'url': 'https://nebula.app/lindsayellis',
  228. 'info_dict': {
  229. 'id': 'lindsayellis',
  230. 'title': 'Lindsay Ellis',
  231. 'description': 'Enjoy these hottest of takes on Disney, Transformers, and Musicals.',
  232. },
  233. 'playlist_mincount': 100,
  234. 'params': {
  235. 'usenetrc': True,
  236. },
  237. },
  238. ]
  239. def _generate_playlist_entries(self, collection_id, channel):
  240. episodes = channel['episodes']['results']
  241. for page_num in itertools.count(2):
  242. for episode in episodes:
  243. yield self._build_video_info(episode)
  244. next_url = channel['episodes']['next']
  245. if not next_url:
  246. break
  247. channel = self._call_nebula_api(next_url, collection_id, auth_type='bearer',
  248. note=f'Retrieving channel page {page_num}')
  249. episodes = channel['episodes']['results']
  250. def _real_extract(self, url):
  251. collection_id = self._match_id(url)
  252. channel_url = f'https://content.watchnebula.com/video/channels/{collection_id}/'
  253. channel = self._call_nebula_api(channel_url, collection_id, auth_type='bearer', note='Retrieving channel')
  254. channel_details = channel['details']
  255. return self.playlist_result(
  256. entries=self._generate_playlist_entries(collection_id, channel),
  257. playlist_id=collection_id,
  258. playlist_title=channel_details['title'],
  259. playlist_description=channel_details['description']
  260. )