-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
252 lines (209 loc) · 7.91 KB
/
main.ts
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
import Innertube, { Constants, UniversalCache } from 'youtubei.js';
import { type Context, YT } from 'youtubei.js';
import GoogleVideo, { base64ToU8, PART, Protos, QUALITY } from '../../dist/src/index.js';
import { decryptResponse, encryptRequest } from './utils.js';
type ClientConfig = {
clientKeyData: Uint8Array;
encryptedClientKey: Uint8Array;
onesieUstreamerConfig: Uint8Array;
baseUrl: string;
};
/**
* Fetches and parses the YouTube TV client configuration.
* Configurations from other clients can be used as well. I chose TVHTML5 for its simplicity.
*/
async function getYouTubeTVClientConfig(): Promise<ClientConfig> {
const tvConfigResponse = await fetch('https://www.youtube.com/tv_config?action_get_config=true&client=lb4&theme=cl', {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version'
}
});
const tvConfig = await tvConfigResponse.text();
if (!tvConfig.startsWith(')]}'))
throw new Error('Invalid response from YouTube TV config endpoint.');
const tvConfigJson = JSON.parse(tvConfig.slice(4));
const webPlayerContextConfig = tvConfigJson.webPlayerContextConfig.WEB_PLAYER_CONTEXT_CONFIG_ID_LIVING_ROOM_WATCH;
const onesieHotConfig = webPlayerContextConfig.onesieHotConfig;
const clientKeyData = base64ToU8(onesieHotConfig.clientKey);
const encryptedClientKey = base64ToU8(onesieHotConfig.encryptedClientKey);
const onesieUstreamerConfig = base64ToU8(onesieHotConfig.onesieUstreamerConfig);
const baseUrl = onesieHotConfig.baseUrl;
return {
clientKeyData,
encryptedClientKey,
onesieUstreamerConfig,
baseUrl
};
}
type OnesieRequestArgs = {
videoId: string;
poToken?: string;
clientConfig: ClientConfig;
innertube: Innertube;
};
type OnesieRequest = {
body: Uint8Array;
encodedVideoId: string;
}
/**
* Prepares a Onesie request.
*/
async function prepareOnesieRequest(args: OnesieRequestArgs): Promise<OnesieRequest> {
const { videoId, poToken, clientConfig, innertube } = args;
const { clientKeyData, encryptedClientKey, onesieUstreamerConfig } = clientConfig;
const clonedInnerTubeContext: Context = structuredClone(innertube.session.context);
// Change or remove these if you want to use a different client. I chose TVHTML5 purely for testing.
clonedInnerTubeContext.client.clientName = Constants.CLIENTS.TV.NAME;
clonedInnerTubeContext.client.clientVersion = Constants.CLIENTS.TV.VERSION;
const params: Record<string, any> = {
playbackContext: {
contentPlaybackContext: {
vis: 0,
splay: false,
lactMilliseconds: '-1',
signatureTimestamp: innertube.session.player?.sts
}
},
videoId
};
if (poToken) {
params.serviceIntegrityDimensions = {};
params.serviceIntegrityDimensions.poToken = poToken;
}
const playerRequestJson = {
context: clonedInnerTubeContext,
...params
};
const headers = [ {
name: 'Content-Type',
value: 'application/json'
},
{
name: 'User-Agent',
value: innertube.session.context.client.userAgent
},
{
name: 'X-Goog-Visitor-Id',
value: innertube.session.context.client.visitorData
} ];
const onesieRequest = Protos.OnesiePlayerRequest.encode({
url: 'https://youtubei.googleapis.com/youtubei/v1/player?key=AIzaSyDCU8hByM-4DrUqRUYnGn-3llEO78bcxq8',
headers,
body: JSON.stringify(playerRequestJson),
proxiedByTrustedBandaid: true,
field6: false
}).finish();
const { encrypted, hmac, iv } = await encryptRequest(clientKeyData, onesieRequest);
const body = Protos.OnesieRequest.encode({
urls: [],
playerRequest: {
encryptedClientKey,
encryptedOnesiePlayerRequest: encrypted,
enableCompression: false,
hmac: hmac,
iv: iv,
TQ: true,
YP: true
},
clientAbrState: {
timeSinceLastManualFormatSelectionMs: 0,
lastManualDirection: 0,
lastManualSelectedResolution: QUALITY.HD720,
stickyResolution: QUALITY.HD720,
playerTimeMs: 0,
visibility: 0
},
streamerContext: {
field5: [],
field6: [],
poToken: poToken ? base64ToU8(poToken) : undefined,
playbackCookie: undefined,
clientInfo: {
clientName: parseInt(Constants.CLIENTS.TV.NAME_ID),
clientVersion: clonedInnerTubeContext.client.clientVersion
}
},
bufferedRanges: [],
onesieUstreamerConfig
}).finish();
const videoIdBytes = base64ToU8(videoId);
const encodedVideoIdChars = [];
for (const byte of videoIdBytes) {
encodedVideoIdChars.push(byte.toString(16).padStart(2, '0'));
}
const encodedVideoId = encodedVideoIdChars.join('');
return { body, encodedVideoId };
}
/**
* Fetches basic video info (streaming data, video details, etc.) using a Onesie request (/initplayback).
*/
async function getBasicInfo(innertube: Innertube, videoId: string): Promise<YT.VideoInfo> {
const redirectorResponse = await fetch(`https://redirector.googlevideo.com/initplayback?source=youtube&itag=0&pvi=0&pai=0&owc=yes&cmo:sensitive_content=yes&alr=yes&id=${Math.round(Math.random() * 1E5)}`, { method: 'GET' });
const redirectorResponseUrl = await redirectorResponse.text();
if (!redirectorResponseUrl.startsWith('https://'))
throw new Error('Invalid redirector response');
const clientConfig = await getYouTubeTVClientConfig();
const onesieRequest = await prepareOnesieRequest({ videoId, /* If needed - poToken,*/ clientConfig, innertube });
let url = `${redirectorResponseUrl.split('/initplayback')[0]}${clientConfig.baseUrl}`;
const queryParams = [];
queryParams.push(`id=${onesieRequest.encodedVideoId}`);
queryParams.push('opr=1');
queryParams.push('por=1');
queryParams.push('rn=1');
queryParams.push('cmo:sensitive_content=yes');
url += `&${queryParams.join('&')}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'accept': '*/*',
'content-type': 'text/plain'
},
referrer: 'https://www.youtube.com/',
body: onesieRequest.body
});
const arrayBuffer = await response.arrayBuffer();
const googUmp = new GoogleVideo.UMP(new GoogleVideo.ChunkedDataBuffer([ new Uint8Array(arrayBuffer) ]));
const onesie: (Protos.OnesieHeader & { data?: Uint8Array })[] = [];
googUmp.parse((part) => {
const data = part.data.chunks[0];
switch (part.type) {
case PART.SABR_ERROR:
console.log('[SABR_ERROR]:', Protos.SabrError.decode(data));
break;
case PART.ONESIE_HEADER:
onesie.push(Protos.OnesieHeader.decode(data));
break;
case PART.ONESIE_DATA:
onesie[onesie.length - 1].data = data;
break;
default:
break;
}
});
const onesiePlayerResponse = onesie.find((header) => header.type === Protos.OnesieHeaderType.PLAYER_RESPONSE);
if (onesiePlayerResponse) {
if (!onesiePlayerResponse.cryptoParams)
throw new Error('Crypto params not found');
const iv = onesiePlayerResponse.cryptoParams.iv;
const hmac = onesiePlayerResponse.cryptoParams.hmac;
const encrypted = onesiePlayerResponse.data;
const decryptedData = await decryptResponse(iv, hmac, encrypted, clientConfig.clientKeyData);
const response = Protos.OnesiePlayerResponse.decode(decryptedData);
if (response.onesieProxyStatus !== 1)
throw new Error('Onesie proxy status not OK');
if (response.httpStatus !== 200)
throw new Error('Http status not OK');
const playerResponse = {
success: true,
status_code: 200,
data: JSON.parse(new TextDecoder().decode(response.body))
};
return new YT.VideoInfo([ playerResponse ], innertube.actions, '');
}
throw new Error('Player response not found');
}
const innertube = await Innertube.create({ cache: new UniversalCache(true) });
const videoInfo = await getBasicInfo(innertube, 'JAs6WyK-Kr0');
console.log('Basic info:', videoInfo);
console.log('Deciphered audio URL:', videoInfo.chooseFormat({ format: 'mp4', quality: 'best', type: 'audio' }).decipher(innertube.session.player));