-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
314 lines (287 loc) · 10.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { QUIBI_USERNAME, QUIBI_PASSWORD } from './credentials';
import { GetPlaybackInfoRequest, GetPlaybackInfoResponse, UserProfile, GetShowRequest, GetShowResponse, SearchRequest, SearchResponse } from './protos/compiled-protos.js';
let authInfo;
async function makeQuibiApiRequest(endpoint, encodedRequest, responseProto) {
const quibiApiUrl = 'https://qlient-api.quibi.com/';
const url = quibiApiUrl + endpoint;
const token = await getAuthToken();
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/protobuf',
'Authorization': 'Bearer ' + token
},
body: encodedRequest
});
const encoded = new Uint8Array(await response.arrayBuffer());
return responseProto.decode(encoded);
}
async function getUserProfile() {
const profile = await makeQuibiApiRequest(
'quibi.qlient.api.user.User/GetUserProfile', null, UserProfile);
console.log(profile);
}
function parsePlaybackInfoResponse(playbackInfo) {
console.log(playbackInfo.manifests);
// TODO: properly parse this
const licenseUrl = playbackInfo.licenseUrl;
// Use "horizontal-video" manifest which is hopefully the last manifest
let manifest = playbackInfo.manifests[playbackInfo.manifests.length - 1];
const manifestUrl = manifest.url;
// Manifests also contain authParams (URL params) which have identical
// values to authCookies. However, the Android client uses cookies
// and we already need a web extension to bypass same origin policy so
// let's authenticate via cookies.
let cookiePromises = manifest.authCookies.map(authCookie =>
browser.cookies.set({
url: manifest.url,
name: authCookie.name,
value: authCookie.value,
domain: authCookie.domain,
path: authCookie.path
})
);
Promise.all(cookiePromises).then(cookies => {
cookies.forEach(console.log);
initPlayer(manifestUrl, licenseUrl, playbackInfo.subtitles);
});
}
async function getPlaybackInfo(episodeId) {
const getPlaybackInfoRequest = GetPlaybackInfoRequest.create({
episodeId: episodeId,
deviceOs: 2,
connectivity: 1,
securityLevel: 2,
});
const encodedRequest = GetPlaybackInfoRequest.encode(getPlaybackInfoRequest).finish();
const playbackInfo = await makeQuibiApiRequest(
'quibi.service.playback.Playback/GetPlaybackInfo', encodedRequest, GetPlaybackInfoResponse);
console.log(playbackInfo);
parsePlaybackInfoResponse(playbackInfo);
}
async function getShow(showId) {
const getShowRequest = GetShowRequest.create({ id: showId });
const showResponse = await makeQuibiApiRequest(
'quibi.qlient.api.content.Content/GetShow',
GetShowRequest.encode(getShowRequest).finish(),
GetShowResponse);
parseGetShowResponse(showResponse);
}
function parseGetShowResponse(showResponse) {
const show = showResponse.show;
let videoLinks = document.getElementById("video-links");
videoLinks.innerHTML = "";
let header = videoLinks.appendChild(document.createElement("h2"));
header.innerText = `${show.title} Episodes`;
showResponse.seasons.forEach((season) => {
season.episodes.forEach((episode) => {
const displayName =
`${show.title} S${episode.seasonNum}E${episode.episodeNum} - ${episode.title}`;
let link = document.createElement("button");
link.onclick = function (_) { getPlaybackInfo(episode.id); };
link.innerText = displayName;
videoLinks.appendChild(link);
videoLinks.appendChild(document.createElement("br"));
});
});
}
async function search(query) {
const searchRequest = SearchRequest.create({
query: query,
});
const searchResponse = await makeQuibiApiRequest(
'quibi.qlient.api.search.Search/SearchShows',
SearchRequest.encode(searchRequest).finish(),
SearchResponse);
console.log(searchResponse);
parseSearchResults(searchResponse);
}
function initPlayer(manifestUrl, licenseUrl, subtitles) {
console.log('shaka-player loaded');
// When using the UI, the player is made automatically by the UI object.
const video = document.getElementById('video');
const ui = video['ui'];
const controls = ui.getControls();
const player = controls.getPlayer();
player.configure({
drm: {
servers: {
'com.widevine.alpha': licenseUrl,
}
}
});
// Listen for error events.
player.addEventListener('error', onPlayerErrorEvent);
controls.addEventListener('error', onUIErrorEvent);
player.load(manifestUrl).then(function () {
console.log('The video has now been loaded!');
for (const subtitle of subtitles) {
// Use a different language string SUBTITLE_KIND_CC
// so it shows as a different text track
// TODO: this should be possible via the 'kind' argument
// TODO: how to use enums?
const language =
subtitle.iso_639_2Code + (subtitle.kind === 2 ? '-cc' : '');
player.addTextTrack(subtitle.url, language, '', 'text/vtt');
}
}).catch(onPlayerError);
}
function onPlayerErrorEvent(errorEvent) {
// Extract the shaka.util.Error object from the event.
onPlayerError(event.detail);
}
function onPlayerError(error) {
// Handle player error
console.error('Error code', error.code, 'object', error);
}
function onUIErrorEvent(errorEvent) {
// Extract the shaka.util.Error object from the event.
onPlayerError(event.detail);
}
function initFailed() {
// Handle the failure to load
console.error('Unable to load the UI library!');
}
function onErrorEvent(event) {
onError(event.detail);
}
function onError(error) {
console.error('Error code', error.code, 'object', error);
}
async function makeQuibiAuthRequest(data) {
const authUrl = 'https://login.quibi.com/oauth/token';
const response = await fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
return await response.json();
}
function updateAuthInfo(authResponse, now) {
if ("refresh_token" in authResponse) {
authInfo.refreshToken = authResponse["refresh_token"]
}
authInfo.accessToken = authResponse["access_token"];
authInfo.expiryUnix = now + authResponse["expires_in"]
window.localStorage.setItem('quibiAuthInfo', JSON.stringify(authInfo));
return authInfo;
}
async function getAuthToken() {
// TODO: tons of error handling
// TODO: refactor
// load authInfo from local storage
if (authInfo == null) {
console.log("loading authInfo from local storage");
authInfo = JSON.parse(window.localStorage.getItem('quibiAuthInfo')) || {};
}
// OAuth client id for android app
const oAuthClientId = "dd1r0IBYVwi8CJeVS57mSN7HXIojPr5j"
const now = Math.floor(Date.now() / 1000);
// if there's no auth info, make the initial request
if (!("refreshToken" in authInfo)) {
console.log("making initial auth request");
const response = await makeQuibiAuthRequest({
"password": QUIBI_PASSWORD,
"scope": "openid profile email offline_access",
"client_id": oAuthClientId,
"username": QUIBI_USERNAME,
"realm": "Username-Password-Authentication",
"audience": "https://qlient-api.quibi.com",
"grant_type": "http://auth0.com/oauth/grant-type/password-realm"
});
return updateAuthInfo(response, now).accessToken;
} else {
if (now > authInfo.expiryUnix) {
console.log("refreshing auth token");
const response = await makeQuibiAuthRequest({
"client_id": oAuthClientId,
"refresh_token": authInfo.refreshToken,
"grant_type": "refresh_token"
});
return updateAuthInfo(response, now).accessToken;
} else {
console.log("already have valid token");
return authInfo.accessToken;
}
}
}
async function doAuth() {
const request = {
"password": QUIBI_PASSWORD,
"scope": "openid profile email offline_access",
"client_id": QUIBI_AUTH0_CLIENT_ID_ANDROID,
"username": QUIBI_USERNAME,
"realm": "Username-Password-Authentication",
"audience": "https://qlient-api.quibi.com",
"grant_type": "http://auth0.com/oauth/grant-type/password-realm"
};
console.log(await makeQuibiAuthRequest(request));
// TODO: token refreshes
httpRequest.send(JSON.stringify({
"client_id": QUIBI_AUTH0_CLIENT_ID_ANDROID,
"refresh_token": "",
"grant_type": "refresh_token"
}));
}
function parseSearchResults(searchResults) {
let resultsDiv = document.getElementById("search-results");
resultsDiv.innerHTML = "";
if (searchResults.episodes.results.length > 0) {
let episodesHeader = resultsDiv.appendChild(document.createElement('h2'));
episodesHeader.innerText = "Episodes";
console.log(searchResults.episodes.results);
for (const result of searchResults.episodes.results) {
const show = result.episodeResult.show;
const episode = result.episodeResult.episode;
const displayName =
`${show.title} S${episode.seasonNum}E${episode.episodeNum} - ${episode.title}`
let button = resultsDiv.appendChild(document.createElement("button"));
resultsDiv.appendChild(document.createElement("br"));
button.onclick = function (_) { getPlaybackInfo(episode.id); };
button.innerText = displayName;
}
}
if (searchResults.shows.results.length > 0) {
let episodesHeader = resultsDiv.appendChild(document.createElement('h2'));
episodesHeader.innerText = "Shows";
for (const result of searchResults.shows.results) {
const show = result.showResult.show;
let button = resultsDiv.appendChild(document.createElement("button"));
resultsDiv.appendChild(document.createElement("br"));
button.onclick = function (_) { getShow(show.id); };
button.innerText = show.title;
}
}
}
function setupSearch() {
let searchButton = document.getElementById("search-button");
let searchInput = document.getElementById("search-input");
const searchFunction = function (_) {
search(searchInput.value);
}
searchButton.onclick = searchFunction;
searchInput.addEventListener('keyup', function (e) {
if (e.key === 'Enter') {
searchFunction();
}
});
}
function run() {
setupSearch();
// getUserProfile();
// getPlaybackInfo(episode_id);
// initPlayer();
// doAuth();
// getAuthToken().then(console.log);
search("reno");
}
window.onload = function () {
run();
}
// Listen to the custom shaka-ui-loaded event, to wait until the UI is loaded.
// document.addEventListener('shaka-ui-loaded', initPlayer());
// Listen to the custom shaka-ui-load-failed event, in case Shaka Player fails
// to load (e.g. due to lack of browser support).
document.addEventListener('shaka-ui-load-failed', initFailed);