]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/rokfin.py
[rokfin] Implement login (#2992)
[yt-dlp.git] / yt_dlp / extractor / rokfin.py
1 import itertools
2 import re
3 import urllib.parse
4 from datetime import datetime
5
6 from .common import InfoExtractor
7 from ..utils import (
8 ExtractorError,
9 determine_ext,
10 float_or_none,
11 format_field,
12 int_or_none,
13 str_or_none,
14 traverse_obj,
15 try_get,
16 unescapeHTML,
17 unified_timestamp,
18 url_or_none,
19 urlencode_postdata,
20 )
21
22 _API_BASE_URL = 'https://prod-api-v2.production.rokfin.com/api/v2/public/'
23
24
25 class RokfinIE(InfoExtractor):
26 _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?P<id>(?P<type>post|stream)/\d+)'
27 _NETRC_MACHINE = 'rokfin'
28 _AUTH_BASE = 'https://secure.rokfin.com/auth/realms/rokfin-web/protocol/openid-connect'
29 _access_mgmt_tokens = {} # OAuth 2.0: RFC 6749, Sec. 1.4-5
30 _TESTS = [{
31 'url': 'https://www.rokfin.com/post/57548/Mitt-Romneys-Crazy-Solution-To-Climate-Change',
32 'info_dict': {
33 'id': 'post/57548',
34 'ext': 'mp4',
35 'title': 'Mitt Romney\'s Crazy Solution To Climate Change',
36 'thumbnail': r're:https://img\.production\.rokfin\.com/.+',
37 'upload_date': '20211023',
38 'timestamp': 1634998029,
39 'channel': 'Jimmy Dore',
40 'channel_id': 65429,
41 'channel_url': 'https://rokfin.com/TheJimmyDoreShow',
42 'duration': 213.0,
43 'availability': 'public',
44 'live_status': 'not_live',
45 'dislike_count': int,
46 'like_count': int,
47 }
48 }, {
49 'url': 'https://rokfin.com/post/223/Julian-Assange-Arrested-Streaming-In-Real-Time',
50 'info_dict': {
51 'id': 'post/223',
52 'ext': 'mp4',
53 'title': 'Julian Assange Arrested: Streaming In Real Time',
54 'thumbnail': r're:https://img\.production\.rokfin\.com/.+',
55 'upload_date': '20190412',
56 'timestamp': 1555052644,
57 'channel': 'Ron Placone',
58 'channel_id': 10,
59 'channel_url': 'https://rokfin.com/RonPlacone',
60 'availability': 'public',
61 'live_status': 'not_live',
62 'dislike_count': int,
63 'like_count': int,
64 'tags': ['FreeThinkingMedia^', 'RealProgressives^'],
65 }
66 }, {
67 'url': 'https://www.rokfin.com/stream/10543/Its-A-Crazy-Mess-Regional-Director-Blows-Whistle-On-Pfizers-Vaccine-Trial-Data',
68 'info_dict': {
69 'id': 'stream/10543',
70 'ext': 'mp4',
71 'title': '"It\'s A Crazy Mess" Regional Director Blows Whistle On Pfizer\'s Vaccine Trial Data',
72 'thumbnail': r're:https://img\.production\.rokfin\.com/.+',
73 'description': 'md5:324ce2d3e3b62e659506409e458b9d8e',
74 'channel': 'Ryan Cristián',
75 'channel_id': 53856,
76 'channel_url': 'https://rokfin.com/TLAVagabond',
77 'availability': 'public',
78 'is_live': False,
79 'was_live': True,
80 'live_status': 'was_live',
81 'timestamp': 1635874720,
82 'release_timestamp': 1635874720,
83 'release_date': '20211102',
84 'upload_date': '20211102',
85 'dislike_count': int,
86 'like_count': int,
87 'tags': ['FreeThinkingMedia^'],
88 }
89 }]
90
91 def _real_extract(self, url):
92 video_id, video_type = self._match_valid_url(url).group('id', 'type')
93 metadata = self._download_json_using_access_token(f'{_API_BASE_URL}{video_id}', video_id)
94
95 scheduled = unified_timestamp(metadata.get('scheduledAt'))
96 live_status = ('was_live' if metadata.get('stoppedAt')
97 else 'is_upcoming' if scheduled
98 else 'is_live' if video_type == 'stream'
99 else 'not_live')
100
101 video_url = traverse_obj(metadata, 'url', ('content', 'contentUrl'), expected_type=url_or_none)
102 formats, subtitles = [{'url': video_url}] if video_url else [], {}
103 if determine_ext(video_url) == 'm3u8':
104 formats, subtitles = self._extract_m3u8_formats_and_subtitles(
105 video_url, video_id, fatal=False, live=live_status == 'is_live')
106
107 if not formats:
108 if traverse_obj(metadata, 'premiumPlan', 'premium'):
109 self.raise_login_required('This video is only available to premium users', True, method='cookies')
110 elif scheduled:
111 self.raise_no_formats(
112 f'Stream is offline; sheduled for {datetime.fromtimestamp(scheduled).strftime("%Y-%m-%d %H:%M:%S")}',
113 video_id=video_id, expected=True)
114 self._sort_formats(formats)
115
116 uploader = traverse_obj(metadata, ('createdBy', 'username'), ('creator', 'username'))
117 timestamp = (scheduled or float_or_none(metadata.get('postedAtMilli'), 1000)
118 or unified_timestamp(metadata.get('creationDateTime')))
119 return {
120 'id': video_id,
121 'formats': formats,
122 'subtitles': subtitles,
123 'title': str_or_none(traverse_obj(metadata, 'title', ('content', 'contentTitle'))),
124 'duration': float_or_none(traverse_obj(metadata, ('content', 'duration'))),
125 'thumbnail': url_or_none(traverse_obj(metadata, 'thumbnail', ('content', 'thumbnailUrl1'))),
126 'description': str_or_none(traverse_obj(metadata, 'description', ('content', 'contentDescription'))),
127 'like_count': int_or_none(metadata.get('likeCount')),
128 'dislike_count': int_or_none(metadata.get('dislikeCount')),
129 'channel': str_or_none(traverse_obj(metadata, ('createdBy', 'name'), ('creator', 'name'))),
130 'channel_id': traverse_obj(metadata, ('createdBy', 'id'), ('creator', 'id')),
131 'channel_url': url_or_none(f'https://rokfin.com/{uploader}') if uploader else None,
132 'timestamp': timestamp,
133 'release_timestamp': timestamp if live_status != 'not_live' else None,
134 'tags': traverse_obj(metadata, ('tags', ..., 'title'), expected_type=str_or_none),
135 'live_status': live_status,
136 'availability': self._availability(
137 needs_premium=bool(traverse_obj(metadata, 'premiumPlan', 'premium')),
138 is_private=False, needs_subscription=False, needs_auth=False, is_unlisted=False),
139 # 'comment_count': metadata.get('numComments'), # Data provided by website is wrong
140 '__post_extractor': self.extract_comments(video_id) if video_type == 'post' else None,
141 }
142
143 def _get_comments(self, video_id):
144 pages_total = None
145 for page_n in itertools.count():
146 raw_comments = self._download_json(
147 f'{_API_BASE_URL}comment?postId={video_id[5:]}&page={page_n}&size=50',
148 video_id, note=f'Downloading viewer comments page {page_n + 1}{format_field(pages_total, template=" of %s")}',
149 fatal=False) or {}
150
151 for comment in raw_comments.get('content') or []:
152 yield {
153 'text': str_or_none(comment.get('comment')),
154 'author': str_or_none(comment.get('name')),
155 'id': comment.get('commentId'),
156 'author_id': comment.get('userId'),
157 'parent': 'root',
158 'like_count': int_or_none(comment.get('numLikes')),
159 'dislike_count': int_or_none(comment.get('numDislikes')),
160 'timestamp': unified_timestamp(comment.get('postedAt'))
161 }
162
163 pages_total = int_or_none(raw_comments.get('totalPages')) or None
164 is_last = raw_comments.get('last')
165 if not raw_comments.get('content') or is_last or (page_n > pages_total if pages_total else is_last is not False):
166 return
167
168 def _perform_login(self, username, password):
169 # https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth (Sec. 3.1)
170 login_page = self._download_webpage(
171 f'{self._AUTH_BASE}/auth?client_id=web&redirect_uri=https%3A%2F%2Frokfin.com%2Ffeed&response_mode=fragment&response_type=code&scope=openid',
172 None, note='loading login page', errnote='error loading login page')
173 authentication_point_url = unescapeHTML(self._search_regex(
174 r'<form\s+[^>]+action\s*=\s*"(https://secure\.rokfin\.com/auth/realms/rokfin-web/login-actions/authenticate\?[^"]+)"',
175 login_page, name='Authentication URL'))
176
177 resp_body = self._download_webpage(
178 authentication_point_url, None, note='logging in', fatal=False, expected_status=404,
179 data=urlencode_postdata({'username': username, 'password': password, 'rememberMe': 'off', 'credentialId': ''}))
180 if not self._authentication_active():
181 if re.search(r'(?i)(invalid\s+username\s+or\s+password)', resp_body or ''):
182 raise ExtractorError('invalid username/password', expected=True)
183 raise ExtractorError('Login failed')
184
185 urlh = self._request_webpage(
186 f'{self._AUTH_BASE}/auth', None,
187 note='granting user authorization', errnote='user authorization rejected by Rokfin',
188 query={
189 'client_id': 'web',
190 'prompt': 'none',
191 'redirect_uri': 'https://rokfin.com/silent-check-sso.html',
192 'response_mode': 'fragment',
193 'response_type': 'code',
194 'scope': 'openid',
195 })
196 self._access_mgmt_tokens = self._download_json(
197 f'{self._AUTH_BASE}/token', None,
198 note='getting access credentials', errnote='error getting access credentials',
199 data=urlencode_postdata({
200 'code': urllib.parse.parse_qs(urllib.parse.urldefrag(urlh.geturl()).fragment).get('code')[0],
201 'client_id': 'web',
202 'grant_type': 'authorization_code',
203 'redirect_uri': 'https://rokfin.com/silent-check-sso.html'
204 }))
205
206 def _authentication_active(self):
207 return not (
208 {'KEYCLOAK_IDENTITY', 'KEYCLOAK_IDENTITY_LEGACY', 'KEYCLOAK_SESSION', 'KEYCLOAK_SESSION_LEGACY'}
209 - set(self._get_cookies(self._AUTH_BASE)))
210
211 def _get_auth_token(self):
212 return try_get(self._access_mgmt_tokens, lambda x: ' '.join([x['token_type'], x['access_token']]))
213
214 def _download_json_using_access_token(self, url_or_request, video_id, headers={}, query={}):
215 assert 'authorization' not in headers
216 headers = headers.copy()
217 auth_token = self._get_auth_token()
218 refresh_token = self._access_mgmt_tokens.get('refresh_token')
219 if auth_token:
220 headers['authorization'] = auth_token
221
222 json_string, urlh = self._download_webpage_handle(
223 url_or_request, video_id, headers=headers, query=query, expected_status=401)
224 if not auth_token or urlh.code != 401 or refresh_token is None:
225 return self._parse_json(json_string, video_id)
226
227 self._access_mgmt_tokens = self._download_json(
228 f'{self._AUTH_BASE}/token', video_id,
229 note='User authorization expired or canceled by Rokfin. Re-authorizing ...', errnote='Failed to re-authorize',
230 data=urlencode_postdata({
231 'grant_type': 'refresh_token',
232 'refresh_token': refresh_token,
233 'client_id': 'web'
234 }))
235 headers['authorization'] = self._get_auth_token()
236 if headers['authorization'] is None:
237 raise ExtractorError('User authorization lost', expected=True)
238
239 return self._download_json(url_or_request, video_id, headers=headers, query=query)
240
241
242 class RokfinPlaylistBaseIE(InfoExtractor):
243 _TYPES = {
244 'video': 'post',
245 'audio': 'post',
246 'stream': 'stream',
247 'dead_stream': 'stream',
248 'stack': 'stack',
249 }
250
251 def _get_video_data(self, metadata):
252 for content in metadata.get('content') or []:
253 media_type = self._TYPES.get(content.get('mediaType'))
254 video_id = content.get('id') if media_type == 'post' else content.get('mediaId')
255 if not media_type or not video_id:
256 continue
257
258 yield self.url_result(f'https://rokfin.com/{media_type}/{video_id}', video_id=f'{media_type}/{video_id}',
259 video_title=str_or_none(traverse_obj(content, ('content', 'contentTitle'))))
260
261
262 class RokfinStackIE(RokfinPlaylistBaseIE):
263 IE_NAME = 'rokfin:stack'
264 IE_DESC = 'Rokfin Stacks'
265 _VALID_URL = r'https?://(?:www\.)?rokfin\.com/stack/(?P<id>[^/]+)'
266 _TESTS = [{
267 'url': 'https://www.rokfin.com/stack/271/Tulsi-Gabbard-Portsmouth-Townhall-FULL--Feb-9-2020',
268 'playlist_count': 8,
269 'info_dict': {
270 'id': '271',
271 },
272 }]
273
274 def _real_extract(self, url):
275 list_id = self._match_id(url)
276 return self.playlist_result(self._get_video_data(
277 self._download_json(f'{_API_BASE_URL}stack/{list_id}', list_id)), list_id)
278
279
280 class RokfinChannelIE(RokfinPlaylistBaseIE):
281 IE_NAME = 'rokfin:channel'
282 IE_DESC = 'Rokfin Channels'
283 _VALID_URL = r'https?://(?:www\.)?rokfin\.com/(?!((feed/?)|(discover/?)|(channels/?))$)(?P<id>[^/]+)/?$'
284 _TESTS = [{
285 'url': 'https://rokfin.com/TheConvoCouch',
286 'playlist_mincount': 100,
287 'info_dict': {
288 'id': '12071-new',
289 'title': 'TheConvoCouch - New',
290 'description': 'md5:bb622b1bca100209b91cd685f7847f06',
291 },
292 }]
293
294 _TABS = {
295 'new': 'posts',
296 'top': 'top',
297 'videos': 'video',
298 'podcasts': 'audio',
299 'streams': 'stream',
300 'stacks': 'stack',
301 }
302
303 def _real_initialize(self):
304 self._validate_extractor_args()
305
306 def _validate_extractor_args(self):
307 requested_tabs = self._configuration_arg('tab', None)
308 if requested_tabs is not None and (len(requested_tabs) > 1 or requested_tabs[0] not in self._TABS):
309 raise ExtractorError(f'Invalid extractor-arg "tab". Must be one of {", ".join(self._TABS)}', expected=True)
310
311 def _entries(self, channel_id, channel_name, tab):
312 pages_total = None
313 for page_n in itertools.count(0):
314 if tab in ('posts', 'top'):
315 data_url = f'{_API_BASE_URL}user/{channel_name}/{tab}?page={page_n}&size=50'
316 else:
317 data_url = f'{_API_BASE_URL}post/search/{tab}?page={page_n}&size=50&creator={channel_id}'
318 metadata = self._download_json(
319 data_url, channel_name,
320 note=f'Downloading video metadata page {page_n + 1}{format_field(pages_total, template=" of %s")}')
321
322 yield from self._get_video_data(metadata)
323 pages_total = int_or_none(metadata.get('totalPages')) or None
324 is_last = metadata.get('last')
325 if is_last or (page_n > pages_total if pages_total else is_last is not False):
326 return
327
328 def _real_extract(self, url):
329 channel_name = self._match_id(url)
330 channel_info = self._download_json(f'{_API_BASE_URL}user/{channel_name}', channel_name)
331 channel_id = channel_info['id']
332 tab = self._configuration_arg('tab', default=['new'])[0]
333
334 return self.playlist_result(
335 self._entries(channel_id, channel_name, self._TABS[tab]),
336 f'{channel_id}-{tab}', f'{channel_name} - {tab.title()}', str_or_none(channel_info.get('description')))