-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_worker.js
More file actions
476 lines (412 loc) · 15.7 KB
/
service_worker.js
File metadata and controls
476 lines (412 loc) · 15.7 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
// Suppress "Receiving end does not exist" errors in console
const originalConsoleError = console.error;
console.error = function(...args) {
// Filter out the specific connection error
if (args[0] && typeof args[0] === 'string' && args[0].includes('Could not establish connection. Receiving end does not exist.')) {
return; // Don't log this error
}
// Log all other errors normally
originalConsoleError.apply(console, args);
};
// Sets defaults on install
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.get(null, (res) => {
const init = {};
if (typeof res.masterEnabled !== "boolean") init.masterEnabled = true;
if (typeof res.enabled !== "boolean") init.enabled = false;
if (!Array.isArray(res.whitelist)) init.whitelist = [];
if (typeof res.customMessage !== "string") init.customMessage = '';
if (typeof res.includeSubscribers !== "boolean") init.includeSubscribers = false;
if (typeof res.repeaterEnabled !== "boolean") init.repeaterEnabled = false;
if (typeof res.repeaterMessage !== "string") init.repeaterMessage = '!duke hello everyone!';
if (typeof res.interval !== "number") init.interval = 90;
if (typeof res.maxCount !== "number") init.maxCount = 0;
if (typeof res.voiceRotationRepeater !== "boolean") init.voiceRotationRepeater = false;
if (typeof res.voiceMode !== "string") init.voiceMode = 'random';
if (!Array.isArray(res.selectedVoices)) init.selectedVoices = ['duke', 'trump', 'spongebob'];
if (typeof res.minDelay !== "number") init.minDelay = 90;
if (typeof res.maxCharLimit !== "number") init.maxCharLimit = 150;
if (!Array.isArray(res.blacklistedWords)) init.blacklistedWords = [];
if (typeof res.useAdvancedLimits !== "boolean") init.useAdvancedLimits = false;
if (typeof res.currentTheme !== "string") init.currentTheme = 'kick';
if (!Array.isArray(res.customVoices)) init.customVoices = [];
if (!Array.isArray(res.messagePresets)) init.messagePresets = [];
if (typeof res.presetStats !== "object") init.presetStats = {};
if (typeof res.channelRestriction !== "string") init.channelRestriction = '';
if (typeof res.commandflageEnabled !== "boolean") init.commandflageEnabled = false;
if (!Array.isArray(res.commandflageCommands)) init.commandflageCommands = [];
if (typeof res.randomizeCommands !== "boolean") init.randomizeCommands = true;
if (typeof res.commandRounds !== "number") init.commandRounds = 1;
if (typeof res.commandCount !== "number") init.commandCount = 0;
if (typeof res.stats !== "object") init.stats = {
totalReplies: 0,
totalProcessed: 0,
totalRepeater: 0,
totalCommandflage: 0,
timeouts: 0,
bans: 0,
successCount: 0
};
if (Object.keys(init).length) chrome.storage.local.set(init);
});
});
// Broadcast state updates to all kick.com tabs
function notifyAllKickTabs() {
chrome.tabs.query({ url: ["https://kick.com/*", "https://*.kick.com/*"] }, (tabs) => {
chrome.storage.local.get(null, (cfg) => {
tabs.forEach(tab => {
if (tab.id) {
chrome.tabs.sendMessage(tab.id, { type: "STATE", payload: cfg }, () => {
// Ignore connection errors for tabs that might not be ready
if (chrome.runtime.lastError && chrome.runtime.lastError.message.includes('Receiving end does not exist')) {
// This is normal when content script is not ready or tab is being refreshed
return;
}
// For other errors, we can ignore them as well
void chrome.runtime.lastError;
});
}
});
});
});
}
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
notifyAllKickTabs();
});
// Repeater functionality in service worker
let repeaterInterval = null;
let repeaterState = {
active: false,
message: '',
interval: 90,
maxCount: 0,
messagesSent: 0,
tabId: null
};
// Commaflage functionality in service worker
let commaflageInterval = null;
let commaflageState = {
active: false,
commands: [],
randomize: true,
rounds: 1,
maxCommands: 0,
currentRound: 1,
commandsSent: 0,
tabId: null,
commandQueue: [],
currentCommandIndex: 0
};
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg && msg.type === "OPEN_POPUP") {
// chrome.action.openPopup requires a recent Chrome (Chrome 127+) and a user gesture.
// The click in the content script counts as a gesture; we relay it here.
if (chrome.action && chrome.action.openPopup) {
chrome.action.openPopup().catch(() => { /* unsupported or denied */ });
}
sendResponse({ ok: true });
return true;
}
if (msg && msg.type === "PING") {
// Send current state to the requesting tab
chrome.storage.local.get(null, (cfg) => {
if (sender.tab && sender.tab.id) {
chrome.tabs.sendMessage(sender.tab.id, { type: "STATE", payload: cfg }, () => {
// Ignore connection errors for tabs that might not be ready
if (chrome.runtime.lastError && chrome.runtime.lastError.message.includes('Receiving end does not exist')) {
// This is normal when content script is not ready or tab is being refreshed
return;
}
// For other errors, we can ignore them as well
void chrome.runtime.lastError;
});
}
});
sendResponse({ ok: true });
return true;
}
if (msg && msg.type === "UPDATE_STATS") {
// Forward stats updates to popup
chrome.runtime.sendMessage(msg, () => {
void chrome.runtime.lastError;
});
return true;
}
if (msg && msg.type === "START_REPEATER") {
startServiceWorkerRepeater(msg.config, msg.tabId);
sendResponse({ success: true });
return true;
}
if (msg && msg.type === "STOP_REPEATER") {
stopServiceWorkerRepeater();
sendResponse({ success: true });
return true;
}
if (msg && msg.type === "GET_REPEATER_STATUS") {
sendResponse(repeaterState);
return true;
}
if (msg && msg.type === "START_COMMAFLAGE") {
startServiceWorkerCommaflage(msg.config, msg.tabId);
sendResponse({ success: true });
return true;
}
if (msg && msg.type === "STOP_COMMAFLAGE") {
stopServiceWorkerCommaflage('manually stopped');
sendResponse({ success: true });
return true;
}
if (msg && msg.type === "GET_COMMAFLAGE_STATUS") {
sendResponse(commaflageState);
return true;
}
if (msg && msg.type === "CLEAR_COMMAFLAGE_COMPLETION") {
// Clear completion state
delete commaflageState.completionReason;
delete commaflageState.completionCommandsSent;
delete commaflageState.completionRoundsCompleted;
delete commaflageState.completionTime;
sendResponse({ success: true });
return true;
}
});
function startServiceWorkerRepeater(config, tabId) {
// Check if extension is globally enabled
chrome.storage.local.get(['masterEnabled'], (settings) => {
if (!settings.masterEnabled) {
return;
}
});
// Check channel restriction
chrome.storage.local.get(['channelRestriction'], (settings) => {
if (settings.channelRestriction && settings.channelRestriction.trim() !== '') {
// We'll check this in the content script when sending messages
}
});
// Stop any existing repeater
stopServiceWorkerRepeater();
repeaterState = {
active: true,
message: config.message,
interval: config.interval,
maxCount: config.maxCount,
messagesSent: 0,
tabId: tabId
};
// Send first message immediately
sendRepeaterMessageFromServiceWorker();
// Set up interval for subsequent messages
repeaterInterval = setInterval(() => {
// Check if we've reached max count
if (repeaterState.maxCount > 0 && repeaterState.messagesSent >= repeaterState.maxCount) {
stopServiceWorkerRepeater();
// Notify popup that max count was reached
chrome.runtime.sendMessage({
type: 'REPEATER_MAX_COUNT_REACHED',
messagesSent: repeaterState.messagesSent,
maxCount: repeaterState.maxCount
}, () => { void chrome.runtime.lastError; });
return;
}
// Check if tab still exists before sending
chrome.tabs.get(repeaterState.tabId, (tab) => {
if (chrome.runtime.lastError || !tab) {
stopServiceWorkerRepeater();
return;
}
// Send the message
sendRepeaterMessageFromServiceWorker();
});
}, repeaterState.interval * 1000);
}
function stopServiceWorkerRepeater() {
if (repeaterInterval) {
clearInterval(repeaterInterval);
repeaterInterval = null;
}
repeaterState.active = false;
notifyContentStatus(repeaterState.tabId, 'repeater');
}
function notifyContentStatus(tabId, mode) {
if (!tabId) return;
chrome.tabs.sendMessage(tabId, { type: 'AUTOSEND_STATUS', active: false, mode }, () => {
void chrome.runtime.lastError;
});
}
function sendRepeaterMessageFromServiceWorker() {
if (!repeaterState.tabId) return;
// Get current settings to apply voice rotation
chrome.storage.local.get(['voiceRotationRepeater', 'selectedVoices', 'customVoices', 'voiceMode'], (settings) => {
let processedMessage = repeaterState.message;
// Apply voice rotation if enabled
if (settings.voiceRotationRepeater && settings.selectedVoices && settings.selectedVoices.length > 0) {
processedMessage = applyVoiceRotation(processedMessage, settings);
}
chrome.tabs.sendMessage(repeaterState.tabId, {
type: 'SEND_REPEATER_MESSAGE',
message: processedMessage,
mode: 'repeater',
intervalMs: (repeaterState.interval || 90) * 1000
}, (response) => {
if (chrome.runtime.lastError) {
// Check if it's a connection error
if (chrome.runtime.lastError.message.includes('Receiving end does not exist')) {
// Don't stop the repeater, just skip this message and try again next time
// This is normal when content script is reloading or tab is being refreshed
return;
}
// For other errors, stop repeater
stopServiceWorkerRepeater();
} else {
repeaterState.messagesSent++;
// Send message count update to popup
chrome.runtime.sendMessage({
type: 'REPEATER_MESSAGE_SENT',
messagesSent: repeaterState.messagesSent,
maxCount: repeaterState.maxCount
}, () => { void chrome.runtime.lastError; });
// Check if max count reached
if (repeaterState.maxCount > 0 && repeaterState.messagesSent >= repeaterState.maxCount) {
// Send completion message to popup
chrome.runtime.sendMessage({
type: 'REPEATER_MAX_COUNT_REACHED',
messagesSent: repeaterState.messagesSent,
maxCount: repeaterState.maxCount
}, () => { void chrome.runtime.lastError; });
// Stop the repeater
stopServiceWorkerRepeater();
}
}
});
});
}
// Voice rotation functionality
let voiceIndex = 0;
function applyVoiceRotation(message, settings) {
// Get all available voices (selected + custom)
const allVoices = [...(settings.selectedVoices || ['duke']), ...(settings.customVoices || [])];
if (allVoices.length === 0) return message;
// Find voice commands in the message (e.g., !duke, !trump)
const voicePattern = /![a-zA-Z0-9]+/g;
const matches = message.match(voicePattern);
if (!matches || matches.length === 0) return message;
// Replace the first voice command found
const currentVoice = matches[0];
// Get next voice based on mode
let nextVoice;
if (settings.voiceMode === 'sequential') {
nextVoice = allVoices[voiceIndex % allVoices.length];
voiceIndex++;
} else {
// Random mode
nextVoice = allVoices[Math.floor(Math.random() * allVoices.length)];
}
// Replace the voice command
const processedMessage = message.replace(currentVoice, `!${nextVoice}`);
return processedMessage;
}
// Commaflage functions
function startServiceWorkerCommaflage(config, tabId) {
// Stop any existing commaflage
stopServiceWorkerCommaflage();
// Parse messages from comma-separated string (can be commands or regular text)
const commands = config.commands
.split(',')
.map(cmd => cmd.trim())
.filter(cmd => cmd.length > 0);
if (commands.length === 0) {
console.error('No valid messages provided for commaflage');
return;
}
commaflageState = {
active: true,
commands: commands,
randomize: config.randomize,
rounds: config.rounds,
maxCommands: config.maxCommands,
interval: config.interval || 3, // Default to 3 seconds
currentRound: 1,
commandsSent: 0,
tabId: tabId,
commandQueue: [],
currentCommandIndex: 0
};
// Prepare command queue for first round
prepareCommandQueue();
// Send first command immediately
sendNextCommaflageCommand();
// Set up interval for subsequent commands (configurable)
const intervalMs = (commaflageState.interval || 3) * 1000;
commaflageInterval = setInterval(() => {
sendNextCommaflageCommand();
}, intervalMs);
}
function stopServiceWorkerCommaflage(reason = 'stopped') {
if (commaflageInterval) {
clearInterval(commaflageInterval);
commaflageInterval = null;
}
// Store completion state for popup to check
commaflageState.completionReason = reason;
commaflageState.completionCommandsSent = commaflageState.commandsSent;
commaflageState.completionRoundsCompleted = commaflageState.currentRound - 1;
commaflageState.completionTime = Date.now();
commaflageState.active = false;
notifyContentStatus(commaflageState.tabId, 'commaflage');
}
function prepareCommandQueue() {
// Create a copy of commands for this round
let roundCommands = [...commaflageState.commands];
// Randomize if enabled
if (commaflageState.randomize) {
for (let i = roundCommands.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[roundCommands[i], roundCommands[j]] = [roundCommands[j], roundCommands[i]];
}
}
commaflageState.commandQueue = roundCommands;
commaflageState.currentCommandIndex = 0;
}
function sendNextCommaflageCommand() {
if (!commaflageState.tabId || !commaflageState.active) return;
// Check if we've exceeded max commands
if (commaflageState.maxCommands > 0 && commaflageState.commandsSent >= commaflageState.maxCommands) {
stopServiceWorkerCommaflage('max commands reached');
return;
}
// Check if current round is complete
if (commaflageState.currentCommandIndex >= commaflageState.commandQueue.length) {
// Round complete
if (commaflageState.rounds > 0 && commaflageState.currentRound >= commaflageState.rounds) {
stopServiceWorkerCommaflage('all rounds completed');
return;
}
// Start next round
commaflageState.currentRound++;
prepareCommandQueue();
}
// Get next message
const message = commaflageState.commandQueue[commaflageState.currentCommandIndex];
commaflageState.currentCommandIndex++;
// Send message
chrome.tabs.sendMessage(commaflageState.tabId, {
type: 'SEND_REPEATER_MESSAGE', // Reuse the same message sending system
message: message,
mode: 'commaflage',
intervalMs: (commaflageState.interval || 3) * 1000
}, (response) => {
if (chrome.runtime.lastError) {
// Check if it's a connection error
if (chrome.runtime.lastError.message.includes('Receiving end does not exist')) {
// Don't stop commaflage immediately, just skip this command and try again next time
// This is normal when content script is reloading or tab is being refreshed
return;
}
// For other errors, stop commaflage
stopServiceWorkerCommaflage('connection error');
} else {
commaflageState.commandsSent++;
}
});
}