-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathchat-interceptor.ts
More file actions
307 lines (287 loc) · 10.8 KB
/
chat-interceptor.ts
File metadata and controls
307 lines (287 loc) · 10.8 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
import { fixLeaks } from '../ts/ytc-fix-memleaks';
import { frameIsReplay as isReplay, checkInjected } from '../ts/chat-utils';
import sha1 from 'sha-1';
import { chatReportUserOptions, ChatUserActions, ChatPollActions, isLiveTL } from '../ts/chat-constants';
function injectedFunction(): void {
const currentDomain = (location.protocol + '//' + location.host);
for (const eventName of ['visibilitychange', 'webkitvisibilitychange', 'blur']) {
window.addEventListener(eventName, event => {
event.stopImmediatePropagation();
}, true);
}
const fetchFallback = window.fetch;
(window as any).fetchFallback = fetchFallback;
window.fetch = async (...args) => {
const request = args[0] as Request;
const url = request.url;
const result = await fetchFallback(...args);
const ytApi = (end: string): string => `${currentDomain}/youtubei/v1/live_chat${end}`;
const isReceiving = url.startsWith(ytApi('/get_live_chat'));
const isSending = url.startsWith(ytApi('/send_message'));
const action = isReceiving ? 'messageReceive' : 'messageSent';
if (isReceiving || isSending) {
const response = JSON.stringify(await (result.clone()).json());
window.dispatchEvent(new CustomEvent(action, { detail: response }));
}
return result;
};
window.dispatchEvent(new CustomEvent('chatLoaded', {
detail: JSON.stringify(window.ytcfg)
}));
// eslint-disable-next-line @typescript-eslint/no-misused-promises
window.addEventListener('proxyFetchRequest', async (event) => {
const args = JSON.parse((event as any).detail as string) as [string, any];
const request = await fetchFallback(...args);
const response = await request.json();
window.dispatchEvent(new CustomEvent('proxyFetchResponse', {
detail: JSON.stringify(response)
}));
});
}
const chatLoaded = async (): Promise<void> => {
const warning = 'HC button detected, not injecting interceptor.';
if (!isLiveTL && checkInjected(warning)) return;
// Register interceptor
const port: Chat.Port = chrome.runtime.connect();
port.postMessage({ type: 'registerInterceptor', source: 'ytc', isReplay: isReplay() });
// Send JSON response to clients
window.addEventListener('messageReceive', (d) => {
port.postMessage({
type: 'processMessageChunk',
json: (d as CustomEvent).detail
});
});
window.addEventListener('messageSent', (d) => {
port.postMessage({
type: 'processSentMessage',
json: (d as CustomEvent).detail
});
});
window.addEventListener('chatLoaded', (d) => {
const ytcfg = (JSON.parse((d as CustomEvent).detail) as {
data_: {
INNERTUBE_API_KEY: string;
INNERTUBE_CONTEXT: any;
};
});
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
}));
});
};
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
};
}
/**
* Executes a poll action (e.g., ending a poll)
*/
async function handlePollAction(msg: any, fetcher: (...args: any[]) => Promise<any>): Promise<void> {
try {
const currentDomain = (location.protocol + '//' + location.host);
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} SAPISID1PHASH ${time}_${sha} SAPISID3PHASH ${time}_${sha}`;
const heads = {
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
Authorization: auth
},
method: 'POST'
};
if (msg.action === ChatPollActions.END_POLL) {
const poll = msg.poll;
const params = poll.item.action?.params || '';
const url = poll.item.action?.url || '/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);
}
}
/**
* Executes a chat action (e.g., blocking or reporting a user)
*/
async function handleChatAction(msg: any, fetcher: (...args: any[]) => Promise<any>): Promise<void> {
const message = msg.message;
if (message.params == null) return;
let success = true;
try {
const currentDomain = (location.protocol + '//' + location.host);
// const action = msg.action;
const apiKey = ytcfg.data_.INNERTUBE_API_KEY;
const contextMenuUrl = `${currentDomain}/youtubei/v1/live_chat/get_item_context_menu?params=` +
`${encodeURIComponent(message.params)}&pbj=1&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} SAPISID1PHASH ${time}_${sha} SAPISID3PHASH ${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 (msg.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 (msg.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 === msg.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;
}
port.postMessage({
type: 'chatUserActionResponse',
action: msg.action,
message,
success
});
}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
port.onMessage.addListener(async (msg: any) => {
if (msg.type === 'executePollAction') {
return handlePollAction(msg, fetcher);
}
if (msg.type === 'executeChatAction') {
return handleChatAction(msg, fetcher);
}
return;
});
});
// Inject interceptor script
const script = document.createElement('script');
script.innerHTML = `(${injectedFunction.toString()})();`;
document.body.appendChild(script);
// Handle initial data
const scripts = document.querySelector('body')?.querySelectorAll('script');
if (!scripts) {
console.error('Unable to get script elements.');
return;
}
for (const script of Array.from(scripts)) {
const start = 'window["ytInitialData"] = ';
const text = script.text;
if (!text || !text.startsWith(start)) {
continue;
}
const json = text.replace(start, '').slice(0, -1);
port.postMessage({
type: 'setInitialData',
json
});
break;
}
// Catch YT messages
window.addEventListener('message', (d) => {
if (d.data['yt-player-video-progress'] != null) {
port.postMessage({
type: 'updatePlayerProgress',
playerProgress: d.data['yt-player-video-progress'],
isFromYt: true
});
}
});
// Update dark theme whenever it changes
let wasDark: boolean | undefined;
const html = document.documentElement;
const sendTheme = (): void => {
const isDark = html.hasAttribute('dark');
if (isDark === wasDark) return;
port.postMessage({
type: 'setTheme',
dark: isDark
});
wasDark = isDark;
};
new MutationObserver(sendTheme).observe(html, {
attributes: true
});
sendTheme();
// Inject mem leak fix script
const fixLeakScript = document.createElement('script');
fixLeakScript.innerHTML = `(${fixLeaks.toString()})();`;
document.body.appendChild(fixLeakScript);
};
if (isLiveTL) {
chatLoaded().catch(console.error);
} else {
setTimeout(() => {
chatLoaded().catch(console.error);
}, 500);
}