-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmessaging.ts
More file actions
394 lines (354 loc) · 12.2 KB
/
messaging.ts
File metadata and controls
394 lines (354 loc) · 12.2 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
import type { Unsubscriber } from './queue';
import { ytcQueue } from './queue';
import sha1 from 'sha-1';
import { chatReportUserOptions, ChatUserActions, ChatReportUserOptions, ChatPollActions } from '../ts/chat-constants';
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> => {
if (message.params == null) return;
let success = true;
try {
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');
const sha = sha1(`${time} ${SAPISID} ${currentDomain}`);
const auth = `SAPISIDHASH ${time}_${sha}`;
const heads = {
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
Authorization: auth
},
method: 'POST'
};
const res = await fetcher(contextMenuUrl, {
...heads,
body: JSON.stringify({ context: baseContext })
});
if (action === ChatUserActions.BLOCK) {
const { params, context } = parseServiceEndpoint(baseContext,
res.liveChatItemContextMenuSupportedRenderers.menuRenderer.items[1]
.menuNavigationItemRenderer.navigationEndpoint.confirmDialogEndpoint
.content.confirmDialogRenderer.confirmButton.buttonRenderer.serviceEndpoint,
'moderateLiveChatEndpoint'
);
await fetcher(`${currentDomain}/youtubei/v1/live_chat/moderate?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context
})
});
} else if (action === ChatUserActions.REPORT_USER) {
const { params, context } = parseServiceEndpoint(baseContext,
res.liveChatItemContextMenuSupportedRenderers.menuRenderer.items[0].menuServiceItemRenderer.serviceEndpoint,
'getReportFormEndpoint'
);
const modal = await fetcher(`${currentDomain}/youtubei/v1/flag/get_form?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
params,
context
})
});
const index = chatReportUserOptions.findIndex(d => d.value === reportOption);
const options = modal.actions[0].openPopupAction.popup.reportFormModalRenderer.optionsSupportedRenderers.optionsRenderer.items;
const submitEndpoint = options[index].optionSelectableItemRenderer.submitEndpoint;
const clickTrackingParams = submitEndpoint.clickTrackingParams;
const flagAction = submitEndpoint.flagEndpoint.flagAction;
context.clickTracking = {
clickTrackingParams
};
await fetcher(`${currentDomain}/youtubei/v1/flag/flag?key=${apiKey}&prettyPrint=false`, {
...heads,
body: JSON.stringify({
action: flagAction,
context
})
});
}
} 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;
}
});
});
};