This repository was archived by the owner on Aug 9, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmessaging.ts
More file actions
544 lines (505 loc) · 18.6 KB
/
Copy pathmessaging.ts
File metadata and controls
544 lines (505 loc) · 18.6 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import type { Unsubscriber } from './queue';
import { ytcQueue } from './queue';
import { chatReportUserOptions, ChatUserActions, ChatReportUserOptions, ChatPollActions } from '../ts/chat-constants';
import type { Chat } from './typings/chat';
import sha1 from 'sha-1';
const currentDomain = location.protocol.includes('youtube') ? (location.protocol + '//' + location.host) : 'https://www.youtube.com';
let interceptor: Chat.Interceptor = { clients: [] };
const isYtcInterceptor = (i: Chat.Interceptors, showError = false, ...debug: any[]): i is Chat.YtcInterceptor => {
const check = i.source === 'ytc';
if (!check && showError) console.error('Interceptor source is not YTC.', debug);
return check;
};
interface YtCfg {
data_: {
INNERTUBE_API_KEY: string;
INNERTUBE_CONTEXT: any;
};
}
/** Register a client to the interceptor. */
const registerClient = (
port: Chat.Port,
getInitialData = false
): void => {
if (interceptor.clients.some((client) => client.name === port.name)) {
console.debug(
'Client already registered. Not registering',
{ interceptor, port }
);
port.postMessage(
{
type: 'registerClientResponse',
success: false,
failReason: 'Client already registered'
}
);
return;
}
// Assign pseudo-unique name
port.name = `${Date.now()}${Math.random()}`;
// Unregister client when port disconnects
port.onDisconnect.addListener(() => {
const i = interceptor.clients.findIndex(
(clientPort) => clientPort.name === port.name
);
if (i < 0) {
console.error('Failed to unregister client', { port, interceptor });
return;
}
interceptor.clients.splice(i, 1);
console.debug('Unregister client successful', { port, interceptor });
});
// Add client to array
interceptor.clients.push(port);
console.debug('Register client successful', { port, interceptor });
port.postMessage(
{
type: 'registerClientResponse',
success: true
}
);
if (getInitialData && isYtcInterceptor(interceptor)) {
const selfChannel = interceptor.queue.selfChannel.get();
const payload: Chat.InitialData = {
type: 'initialData',
initialData: interceptor.queue.getInitialData(),
selfChannel: selfChannel != null
? {
name: selfChannel.authorName?.simpleText ?? '',
channelId: selfChannel.authorExternalChannelId ?? ''
}
: null
};
port.postMessage(payload);
console.debug('Sent initial data', { port, interceptor, payload });
}
};
/**
* Parses the given YTC json response, and adds it to the queue of the
* interceptor that sent it.
*/
export const processMessageChunk = (json: string): void => {
if (!isYtcInterceptor(interceptor, true, 'processMessageChunk', json)) return;
if (interceptor.clients.length < 1) {
console.debug('No clients', { interceptor, json });
return;
}
interceptor.queue.addJsonToQueue(json, false, interceptor);
};
/** Parses a sent message and adds a fake message entry. */
export const processSentMessage = (json: string): void => {
if (!isYtcInterceptor(interceptor, true, 'processSentMessage', json)) return;
const fakeJson: Ytc.SentChatItemAction = JSON.parse(json);
const fakeChunk: Ytc.RawResponse = {
continuationContents: {
liveChatContinuation: {
continuations: [{
timedContinuationData: {
timeoutMs: 0
}
}],
actions: fakeJson.actions
}
}
};
interceptor.queue.addJsonToQueue(JSON.stringify(
fakeChunk
), false, interceptor, true);
};
/** Parses and sets initial message data and metadata. */
export const setInitialData = (json: string): void => {
if (!isYtcInterceptor(interceptor, true, 'setInitialData', json)) return;
interceptor.queue.addJsonToQueue(json, true, interceptor);
const parsedJson = JSON.parse(json);
const actionPanel = (parsedJson?.continuationContents?.liveChatContinuation ||
parsedJson?.contents?.liveChatRenderer)
?.actionPanel;
const user = actionPanel?.liveChatMessageInputRenderer
?.sendButton?.buttonRenderer?.serviceEndpoint
?.sendLiveChatMessageEndpoint?.actions[0]
?.addLiveChatTextMessageFromTemplateAction?.template
?.liveChatTextMessageRenderer ?? {
authorName: {
simpleText: parsedJson?.continuationContents?.liveChatContinuation?.viewerName
}
};
interceptor.queue.selfChannel.set(user);
};
/** Updates the player progress of the queue of the interceptor. */
export const updatePlayerProgress = (playerProgress: number): void => {
if (!isYtcInterceptor(interceptor, true, 'updatePlayerProgress', playerProgress)) return;
interceptor.queue.updatePlayerProgress(playerProgress, true);
};
/**
* Sets the theme of the interceptor, and sends the new theme to any currently
* registered clients.
*/
export const setTheme = (dark: boolean): void => {
if (!isYtcInterceptor(interceptor, true, 'setTheme', dark)) return;
interceptor.dark = dark;
interceptor.clients.forEach(
(port) => port.postMessage({ type: 'themeUpdate', dark })
);
console.debug(`Set dark theme to ${dark.toString()}`);
};
/** Returns a message with the theme of the interceptor. */
const getTheme = (port: Chat.Port): void => {
if (!isYtcInterceptor(interceptor, true, 'getTheme', port)) return;
port.postMessage({ type: 'themeUpdate', dark: interceptor.dark });
};
// TODO: Figure this out when doing MV3 for LTL
const sendLtlMessage = (message: Chat.LtlMessage): void => {
interceptor.clients.forEach(
(clientPort) => clientPort.postMessage({ type: 'ltlMessage', message })
);
};
function getCookie(name: string): string {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return (parts.pop() ?? '').split(';').shift() ?? '';
return '';
}
function parseServiceEndpoint(baseContext: any, serviceEndpoint: any, prop: string): { params: string, context: any } {
const { clickTrackingParams, [prop]: { params } } = serviceEndpoint;
const clonedContext = JSON.parse(JSON.stringify(baseContext));
clonedContext.clickTracking = {
clickTrackingParams
};
return {
params,
context: clonedContext
};
}
const fetcher = async (...args: any[]): Promise<any> => {
return await new Promise((resolve) => {
const encoded = JSON.stringify(args);
window.addEventListener('proxyFetchResponse', (e) => {
const response = JSON.parse((e as CustomEvent).detail);
resolve(response);
});
window.dispatchEvent(new CustomEvent('proxyFetchRequest', {
detail: encoded
}));
});
};
const executeChatAction = async (
message: Ytc.ParsedMessage,
ytcfg: YtCfg,
action: ChatUserActions,
reportOption?: ChatReportUserOptions
): Promise<void> => {
const fetcher = async (...args: any[]): Promise<any> => {
return await new Promise((resolve, reject) => {
const id = `${Date.now()}_${Math.random().toString(36).slice(2)}`;
const encoded = JSON.stringify({ id, args });
let timeout = 0;
const onFetchResponse = (e: Event): void => {
const response = JSON.parse((e as CustomEvent).detail) as {
id: string;
response?: any;
error?: string;
};
if (response.id !== id) return;
window.clearTimeout(timeout);
window.removeEventListener('proxyFetchResponse', onFetchResponse);
if (response.error != null) {
reject(new Error(response.error));
return;
}
resolve(response.response);
};
timeout = window.setTimeout(() => {
window.removeEventListener('proxyFetchResponse', onFetchResponse);
reject(new Error('proxy fetch timed out'));
}, 5000);
window.addEventListener('proxyFetchResponse', onFetchResponse);
window.dispatchEvent(new CustomEvent('proxyFetchRequest', {
detail: encoded
}));
});
};
let success = true;
if (message.params == null) {
success = false;
}
try {
if (message.params == null) {
throw new Error('Missing context menu params for message');
}
const apiKey = ytcfg.data_.INNERTUBE_API_KEY;
const contextMenuUrl = `${currentDomain}/youtubei/v1/live_chat/get_item_context_menu?params=` +
`${encodeURIComponent(message.params)}&pbj=1&key=${apiKey}&prettyPrint=false`;
const baseContext = ytcfg.data_.INNERTUBE_CONTEXT;
const time = Math.floor(Date.now() / 1000);
const sapisid = getCookie('__Secure-3PAPISID') || getCookie('SAPISID');
const auth = sapisid ? `SAPISIDHASH ${time}_${sha1(`${time} ${sapisid} ${currentDomain}`)}` : null;
const authuser = (ytcfg as any)?.data_?.SESSION_INDEX;
const visitorId = (ytcfg as any)?.data_?.VISITOR_DATA ?? baseContext?.client?.visitorData;
const clientName = (ytcfg as any)?.data_?.INNERTUBE_CLIENT_NAME;
const clientVersion = (ytcfg as any)?.data_?.INNERTUBE_CLIENT_VERSION;
const heads = {
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
...(authuser != null ? { 'X-Goog-AuthUser': String(authuser) } : {}),
...(visitorId != null ? { 'X-Goog-Visitor-Id': String(visitorId) } : {}),
...(clientName != null ? { 'X-Youtube-Client-Name': String(clientName) } : {}),
...(clientVersion != null ? { 'X-Youtube-Client-Version': String(clientVersion) } : {}),
'X-Origin': currentDomain,
...(auth != null ? { Authorization: auth } : {})
},
method: 'POST' as const,
mode: 'same-origin' as const
};
const contextMenuContext = JSON.parse(JSON.stringify(baseContext));
const res = await fetcher(contextMenuUrl, {
...heads,
body: JSON.stringify({ context: contextMenuContext })
});
function findServiceEndpoint(root: any, prop: string): any | null {
const queue = [root];
const visited = new Set<any>();
while (queue.length > 0) {
const current = queue.shift();
if (current == null || typeof current !== 'object' || visited.has(current)) continue;
visited.add(current);
if (typeof current?.[prop]?.params === 'string') {
return current;
}
for (const value of Object.values(current)) {
if (value != null && typeof value === 'object') {
queue.push(value);
}
}
}
return null;
}
function parseServiceEndpoint(serviceEndpoint: any, prop: string): { params: string, context: any } {
if (typeof serviceEndpoint?.[prop]?.params !== 'string') {
throw new Error(`Missing service endpoint params for ${prop}`);
}
const { clickTrackingParams, [prop]: { params } } = serviceEndpoint;
const clonedContext = JSON.parse(JSON.stringify(baseContext));
if (clickTrackingParams != null) {
clonedContext.clickTracking = {
clickTrackingParams
};
}
return {
params,
context: clonedContext
};
}
function findDeleteMessageEndpoint(root: any): any | null {
const queue = [root];
const visited = new Set<any>();
const candidates: Array<{ iconType?: string, label?: string, endpoint: any }> = [];
while (queue.length > 0) {
const current = queue.shift();
if (current == null || typeof current !== 'object' || visited.has(current)) continue;
visited.add(current);
const menu = current?.menuServiceItemRenderer;
const iconType = menu?.icon?.iconType;
const endpoint = menu?.serviceEndpoint;
const label = (
Array.isArray(menu?.text?.runs)
? menu.text.runs.map((r: any) => r?.text).filter(Boolean).join('')
: menu?.text?.simpleText
) as string | undefined;
// Prefer stable identifiers (DELETE icon + moderate endpoint) over localized label text.
if (typeof endpoint?.moderateLiveChatEndpoint?.params === 'string') {
candidates.push({ iconType, label, endpoint });
}
for (const value of Object.values(current)) {
if (value != null && typeof value === 'object') {
queue.push(value);
}
}
}
for (const c of candidates) {
if (c.iconType === 'DELETE') return c.endpoint;
}
for (const c of candidates) {
const l = (c.label ?? '').toLowerCase();
if (l.includes('remove') || l.includes('delete') || l.includes('retract') || l.includes('unsend')) {
return c.endpoint;
}
}
if (candidates.length === 1) return candidates[0].endpoint;
return null;
}
if (action === ChatUserActions.BLOCK) {
const serviceEndpoint = findServiceEndpoint(res, 'moderateLiveChatEndpoint');
if (serviceEndpoint == null) {
throw new Error('Could not find moderate endpoint in context menu');
}
const { params, context } = parseServiceEndpoint(serviceEndpoint, 'moderateLiveChatEndpoint');
const moderationResponse = await fetcher(`${currentDomain}/youtubei/v1/live_chat/moderate?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context
})
});
if (moderationResponse?.error != null || moderationResponse?.success === false) {
throw new Error('Moderation request failed');
}
} else if (action === ChatUserActions.DELETE_MESSAGE) {
const serviceEndpoint = findDeleteMessageEndpoint(res);
if (serviceEndpoint == null) {
throw new Error('Could not find delete endpoint in context menu');
}
const { params, context } = parseServiceEndpoint(serviceEndpoint, 'moderateLiveChatEndpoint');
const moderationResponse = await fetcher(`${currentDomain}/youtubei/v1/live_chat/moderate?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context
})
});
if (moderationResponse?.error != null || moderationResponse?.success === false) {
throw new Error('Moderation request failed');
}
} else if (action === ChatUserActions.REPORT_USER) {
const serviceEndpoint = findServiceEndpoint(res, 'getReportFormEndpoint');
if (serviceEndpoint == null) {
throw new Error('Could not find report endpoint in context menu');
}
const { params, context } = parseServiceEndpoint(serviceEndpoint, 'getReportFormEndpoint');
const modal = await fetcher(`${currentDomain}/youtubei/v1/flag/get_form?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context
})
});
const options = modal?.actions?.[0]
?.openPopupAction?.popup?.reportFormModalRenderer
?.optionsSupportedRenderers?.optionsRenderer?.items;
if (!Array.isArray(options) || options.length < 1) {
throw new Error('Report options are missing');
}
const reportIndex = chatReportUserOptions.findIndex(d => d.value === reportOption);
const index = reportIndex >= 0 && reportIndex < options.length ? reportIndex : 0;
const submitEndpoint = options[index]?.optionSelectableItemRenderer?.submitEndpoint;
const clickTrackingParams = submitEndpoint?.clickTrackingParams;
const flagAction = submitEndpoint?.flagEndpoint?.flagAction;
if (flagAction == null) {
throw new Error('Report submit endpoint is missing');
}
if (clickTrackingParams != null) {
context.clickTracking = {
clickTrackingParams
};
}
const flagResponse = await fetcher(`${currentDomain}/youtubei/v1/flag/flag?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
action: flagAction,
context
})
});
if (flagResponse?.error != null || flagResponse?.success === false) {
throw new Error('Report request failed');
}
}
} catch (e) {
console.debug('Error executing chat action', e);
success = false;
}
interceptor.clients.forEach(
(clientPort) => clientPort.postMessage({
type: 'chatUserActionResponse',
action: action,
message,
success
})
);
};
const executePollAction = async (
poll: Ytc.ParsedPoll,
ytcfg: YtCfg,
action: ChatPollActions,
): Promise<void> => {
try {
const apiKey = ytcfg.data_.INNERTUBE_API_KEY;
const baseContext = ytcfg.data_.INNERTUBE_CONTEXT;
const time = Math.floor(Date.now() / 1000);
const SAPISID = getCookie('__Secure-3PAPISID');
const sha = sha1(`${time} ${SAPISID} ${currentDomain}`);
const auth = `SAPISIDHASH ${time}_${sha}`;
const heads = {
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
Authorization: auth
},
method: 'POST'
};
if (action === ChatPollActions.END_POLL) {
const params = poll.item.action?.params || '';
const url = poll.item.action?.api || '/youtubei/v1/live_chat/live_chat_action';
// Call YouTube API to end the poll
await fetcher(`${currentDomain}${url}?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context: baseContext
})
});
}
} catch (e) {
console.debug('Error executing poll action', e);
}
}
export const initInterceptor = (
source: Chat.InterceptorSource,
ytcfg: YtCfg,
isReplay?: boolean
): void => {
if (source === 'ytc') {
const queue = ytcQueue(isReplay);
let queueUnsub: Unsubscriber | undefined;
const ytcInterceptor: Chat.YtcInterceptor = {
...interceptor,
source: 'ytc',
dark: false,
queue,
queueUnsub
};
ytcInterceptor.queueUnsub = queue.latestAction.subscribe((latestAction) => {
if (!latestAction) return;
interceptor.clients.forEach((port) => port.postMessage(latestAction));
});
interceptor = ytcInterceptor;
} else {
interceptor.source = source;
}
chrome.runtime.onConnect.addListener((port) => {
port.onMessage.addListener((message: Chat.BackgroundMessage) => {
switch (message.type) {
case 'registerClient':
registerClient(port, message.getInitialData);
break;
case 'getTheme':
getTheme(port);
break;
case 'sendLtlMessage':
sendLtlMessage(message.message);
break;
case 'executeChatAction':
executeChatAction(message.message, ytcfg, message.action, message.reportOption).catch(console.error);
break;
case 'executePollAction':
executePollAction(message.poll, ytcfg, message.action).catch(console.error);
break;
case 'ping':
port.postMessage({ type: 'ping' });
break;
default:
console.error('Unknown message type', port, message);
break;
}
});
});
};