-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
786 lines (665 loc) · 23.5 KB
/
content.js
File metadata and controls
786 lines (665 loc) · 23.5 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
/**
* Kick AutoSend - Content Script
* Copyright (c) 2025 Kick AutoSend
*
* This script provides chat automation features for Kick.com
* Including auto-reply, message repeater, and voice rotation
*/
// Content script ready flag
let contentScriptReady = false;
// Set content script as ready immediately
contentScriptReady = true;
// Current state cached in the page
let STATE = {
enabled: false,
whitelist: [],
blacklistedWords: [],
customMessage: '',
includeSubscribers: false,
voiceRotationEnabled: false,
voiceRotationRepeater: false,
voiceRotationResponder: false,
voiceMode: 'random',
selectedVoices: ['duke', 'trump', 'spongebob'],
customVoices: [],
channelRestriction: '',
responderInterval: 30, // Default responder interval
showStatusPill: true
};
// Simple message tracking (no complex storage)
let processedMessages = new Set();
const MAX_PROCESSED_MESSAGES = 500;
let observerStarted = false;
let currentObserver = null; // Store reference to current observer
let pageLoadTime = Date.now(); // Track when page was loaded
let lastResponseTime = 0; // Track last response time for cooldown
// Rate limiting
let lastMessageTime = 0;
let messageCount = 0;
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const MAX_MESSAGES_PER_WINDOW = 60;
// Available TTS voices
const VOICES = [
'anthony', 'trump', 'spongebob', 'drphil', 'tate', 'petergriffin', 'biden', 'arnold',
'train', 'joerogan', 'alexjones', 'samueljackson', 'kermit', 'eddie', 'goku', 'ice',
'herbert', 'unc', 'icespice', 'snoop', 'rock', 'morgan', 'sketch', 'kevinhart',
'50cent', 'kanye', 'mcgregor', 'willsmith', 'elon', 'kamala', 'jordan', 'shapiro',
'djkhaled', 'jayz', 'princeharry', 'robertdowneyjr', 'billgates', 'lex', 'duke',
'ebz', 'ariana', 'kim', 'cardi', 'rainbow', 'swift', 'watson', 'hillary', 'thrall', 'steve', 'rfk'
];
// Voice rotation functionality
let voiceIndex = 0;
function getRandomVoice() {
const allVoices = [...(STATE.selectedVoices || ['duke']), ...(STATE.customVoices || [])];
return allVoices[Math.floor(Math.random() * allVoices.length)];
}
function getSequentialVoice() {
const allVoices = [...(STATE.selectedVoices || ['duke']), ...(STATE.customVoices || [])];
const voice = allVoices[voiceIndex % allVoices.length];
voiceIndex++;
return voice;
}
function getNextVoice(context = 'responder') {
const isEnabled = context === 'repeater' ?
STATE.voiceRotationRepeater :
STATE.voiceRotationResponder;
if (!isEnabled) return null;
return STATE.voiceMode === 'random' ? getRandomVoice() : getSequentialVoice();
}
// Message processing with voice replacement
function processMessage(template, context = 'responder') {
const isEnabled = context === 'repeater' ?
STATE.voiceRotationRepeater :
STATE.voiceRotationResponder;
if (!isEnabled) return template;
const voicePattern = /![a-zA-Z0-9]+/g;
const matches = template.match(voicePattern);
if (!matches || matches.length === 0) return template;
const currentVoice = matches[0];
const nextVoice = getNextVoice(context);
if (nextVoice) {
const processedMessage = template.replace(currentVoice, `!${nextVoice}`);
return processedMessage;
}
return template;
}
// Blacklist check function
function containsBlacklistedWords(text) {
if (!STATE.blacklistedWords || STATE.blacklistedWords.length === 0) {
return false;
}
const lowerText = text.toLowerCase();
return STATE.blacklistedWords.some(word => {
if (word.trim()) {
return lowerText.includes(word.toLowerCase());
}
return false;
});
}
// Statistics tracking
function updateStats(stat, value = 1) {
try {
chrome.runtime.sendMessage({
type: 'UPDATE_STATS',
stat: stat,
value: value
});
} catch (error) {
// Silent error handling for production
}
}
// Helper functions to find chat elements
// Kick exposes stable IDs — prefer them. Avoid broad fallbacks like
// button[type="submit"] which could match buttons injected by other
// Kick-related browser extensions.
function getChatInput() {
return document.getElementById('chat-input') ||
document.querySelector('[data-testid="chat-input"]');
}
function getSendButton() {
return document.getElementById('send-message-button');
}
// Send message function
async function sendMessage(text) {
const input = getChatInput();
if (!input) {
return false;
}
input.focus();
// Clear content
document.execCommand('selectAll', false, null);
document.execCommand('delete', false, null);
// Insert text
const ev = new InputEvent('beforeinput', {
inputType: 'insertText',
data: text,
bubbles: true,
cancelable: true,
composed: true,
});
input.dispatchEvent(ev);
await new Promise(r => setTimeout(r, 100));
// Safety net if text did not appear
if (!input.textContent || input.textContent.trim() === '') {
document.execCommand('insertText', false, text);
}
await new Promise(r => setTimeout(r, 50));
const btn = getSendButton();
if (btn) {
btn.click();
return true;
}
// Fallback to Enter key
const kd = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true });
const ku = new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true });
input.dispatchEvent(kd);
input.dispatchEvent(ku);
return true;
}
// Check if user is timed out
function isUserTimedOut() {
const timeoutIndicator = document.querySelector('[data-testid="chat-input"]');
if (timeoutIndicator && timeoutIndicator.getAttribute('contenteditable') === 'false') {
const parentDiv = timeoutIndicator.closest('.relative');
if (parentDiv) {
const timeoutText = parentDiv.querySelector('div[class*="pointer-events-none"]');
if (timeoutText && timeoutText.textContent.includes('timed out')) {
return true;
}
}
}
return false;
}
// Check if user is banned
function isUserBanned() {
const chatInput = document.querySelector('[data-testid="chat-input"]');
if (chatInput && chatInput.getAttribute('contenteditable') === 'false') {
const parentContainer = chatInput.closest('.flex.grow.flex-col.gap-2');
if (parentContainer) {
const banText = parentContainer.querySelector('div[class*="pointer-events-none"]');
if (banText && banText.textContent.includes('banned from chat')) {
return true;
}
}
}
return false;
}
// Badge check - look for subscriber badge images
function hasSubscriberBadge(msgEl) {
const badgeImg = msgEl.querySelector('img[src*="channel_subscriber_badges"]');
return !!badgeImg;
}
// Parse message with emotes
function parseMessageWithEmotes(element) {
const clone = element.cloneNode(true);
const emoteSpans = clone.querySelectorAll('span[data-emote-name]');
emoteSpans.forEach(emoteSpan => {
const emoteName = emoteSpan.getAttribute('data-emote-name');
if (emoteName) {
const textNode = document.createTextNode(emoteName);
emoteSpan.parentNode.replaceChild(textNode, emoteSpan);
}
});
return clone.textContent || '';
}
// Get message ID for duplicate prevention
function getMessageId(node) {
const holder = node.closest('div[data-index]');
if (holder && holder.getAttribute('data-index')) {
return 'idx:' + String(holder.getAttribute('data-index'));
}
const userBtn = node.querySelector('button[title]');
const username = userBtn ? userBtn.textContent.trim() : 'unknown';
const contentSpan = node.querySelector('span.font-normal');
const text = contentSpan ? (contentSpan.textContent || '').trim() : '';
// Create a unique ID based on content and username
const content = `${username}:${text}`;
const hash = content.split('').reduce((a, b) => {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a;
}, 0);
return `msg:${username}:${Math.abs(hash)}`;
}
// Check if message is truly new (sent after observer started)
function isNewMessage(node) {
// Prefer explicit timestamps when available
const messageTime = node.getAttribute('data-timestamp') ||
node.getAttribute('data-time') ||
node.querySelector('[data-time]')?.getAttribute('data-time');
if (messageTime) {
const messageTimestamp = parseInt(messageTime);
if (!isNaN(messageTimestamp)) {
return messageTimestamp > pageLoadTime;
}
}
// Otherwise: the node is new if it wasn't pre-seeded during startObserver()
// (the observer only fires for newly-added DOM nodes after it starts)
return true;
}
// Check cooldown
function checkCooldown() {
const now = Date.now();
const cooldownMs = (STATE.responderInterval || 30) * 1000; // Convert seconds to milliseconds
if (now - lastResponseTime < cooldownMs) {
return false;
}
return true;
}
// Get current channel name from the page
function getCurrentChannel() {
const el = document.getElementById('channel-username');
const text = el?.textContent?.trim();
if (text) return text.toLowerCase();
// Fallback: extract from URL
const match = window.location.href.match(/kick\.com\/([^\/\?]+)/);
return match ? match[1].toLowerCase() : null;
}
// Check if current channel is allowed
function isChannelAllowed() {
if (!STATE.channelRestriction || STATE.channelRestriction.trim() === '') {
return true; // No restriction set
}
const currentChannel = getCurrentChannel();
if (!currentChannel) {
return true; // Allow if we can't determine channel
}
const restrictedChannel = STATE.channelRestriction.toLowerCase().trim();
return currentChannel === restrictedChannel;
}
// Main message processing function
function handleMessageNode(node) {
// 1. Extension enabled check
if (!STATE.enabled || !observerStarted) {
return;
}
// 2. Channel restriction check
if (!isChannelAllowed()) {
return;
}
// 3. Valid HTML element check
if (!(node instanceof HTMLElement)) {
return;
}
// 4. Find message wrapper
const wrapper = node.matches('.group.relative') ? node : node.querySelector('.group.relative');
if (!wrapper) {
return;
}
// 5. Parse username
const userBtn = wrapper.querySelector('button[title]');
const username = userBtn ? userBtn.textContent.trim() : null;
if (!username) {
return;
}
// 6. Whitelist check
const isWhitelisted = STATE.whitelist.includes(username.toLowerCase());
if (!isWhitelisted) {
return;
}
// 7. Check if already processed
const id = getMessageId(node);
if (processedMessages.has(id)) {
return;
}
// 8. Check if message is truly new (not from page load)
if (!isNewMessage(node)) {
return;
}
// 9. Check cooldown
if (!checkCooldown()) {
return;
}
// 10. Parse message text
let text = '';
const contentSpan = wrapper.querySelector('span.font-normal');
if (contentSpan) {
text = parseMessageWithEmotes(contentSpan);
} else {
text = parseMessageWithEmotes(wrapper);
}
text = text.trim();
// 11. Message starts with ! check
if (!text.startsWith('!')) {
return;
}
// 12. Blacklist check
if (containsBlacklistedWords(text)) {
return;
}
// 13. Subscriber badge check
if (!STATE.includeSubscribers && hasSubscriberBadge(wrapper)) {
return;
}
// 14. Additional safety check - prevent rapid processing
if (processedMessages.has(id)) {
return;
}
// Check for timeout/ban status
if (isUserTimedOut()) {
return;
}
if (isUserBanned()) {
return;
}
// Rate limiting check
const now = Date.now();
if (now - lastMessageTime > RATE_LIMIT_WINDOW) {
messageCount = 0;
lastMessageTime = now;
}
if (messageCount >= MAX_MESSAGES_PER_WINDOW) {
return;
}
messageCount++;
// All conditions met! Mark as processed immediately
processedMessages.add(id);
if (processedMessages.size > MAX_PROCESSED_MESSAGES) {
const iterator = processedMessages.values();
for (let i = 0; i < processedMessages.size - MAX_PROCESSED_MESSAGES; i++) {
processedMessages.delete(iterator.next().value);
}
}
updateStats('totalProcessed');
// Update last response time
lastResponseTime = Date.now();
// Determine what message to send
let messageToSend = text; // Default: echo original message
if (STATE.customMessage && STATE.customMessage.trim()) {
messageToSend = STATE.customMessage;
}
// Process message for voice rotation
messageToSend = processMessage(messageToSend, 'responder');
const delay = 200 + Math.floor(Math.random() * 400);
setTimeout(() => {
sendMessage(messageToSend).then(success => {
if (success) {
updateStats('totalReplies');
updateStats('successCount');
}
});
}, delay);
}
// Start observer
function startObserver() {
if (observerStarted) {
return;
}
// Prefer the chatroom-messages container — drastically reduces mutation
// noise vs watching the whole document.body. Retry if not yet mounted.
const root = document.getElementById('chatroom-messages') || document.body;
if (!root) {
setTimeout(() => { if (STATE.enabled && !observerStarted) startObserver(); }, 500);
return;
}
// Pre-seed processedMessages with all currently-visible messages so we
// don't respond to backlog on page load.
root.querySelectorAll('div[data-index]').forEach(el => {
try { processedMessages.add(getMessageId(el)); } catch (e) {}
});
pageLoadTime = Date.now();
const obs = new MutationObserver((mutations) => {
for (const m of mutations) {
for (const n of m.addedNodes) {
if (!(n instanceof HTMLElement)) continue;
// Add a small delay to ensure DOM is fully updated
setTimeout(() => {
// Double check extension is still enabled
if (!STATE.enabled || !observerStarted) return;
// Direct message nodes often carry data-index
if (n.hasAttribute && n.hasAttribute('data-index')) handleMessageNode(n);
// Scan children that look like messages
n.querySelectorAll('div[data-index]').forEach(el => handleMessageNode(el));
// Fallback selector
if (n.querySelector && n.querySelector('button[title]') && n.querySelector('span.font-normal')) {
handleMessageNode(n);
}
}, 50); // 50ms delay
}
}
});
obs.observe(root, { childList: true, subtree: true });
observerStarted = true;
currentObserver = obs;
}
// Stop observer
function stopObserver() {
if (currentObserver) {
currentObserver.disconnect();
currentObserver = null;
}
observerStarted = false;
processedMessages.clear();
}
// Listen for state updates from background or popup
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// Handle ping requests to test connection
if (msg && msg.type === "PING") {
sendResponse({
status: 'ready',
timestamp: Date.now(),
contentScriptReady: true,
enabled: STATE.enabled,
whitelist: STATE.whitelist
});
return true;
}
// Handle master state changes
if (msg && msg.type === "MASTER_STATE_CHANGE") {
if (!msg.enabled) {
stopObserver();
} else {
startObserver();
}
sendResponse({status: 'master_state_updated'});
return true;
}
if (msg && msg.type === "STATE" && msg.payload) {
STATE = {
...STATE,
...msg.payload,
enabled: msg.payload.enabled !== undefined ? msg.payload.enabled : STATE.enabled,
whitelist: (msg.payload.whitelist || []).map(s => String(s).toLowerCase().slice(0, 50)),
blacklistedWords: (msg.payload.blacklistedWords || []).map(s => String(s).toLowerCase().slice(0, 50)),
channelRestriction: String(msg.payload.channelRestriction || '').slice(0, 100),
responderInterval: parseInt(msg.payload.responderInterval) || STATE.responderInterval || 30,
};
// Start/stop observer based on enabled state
if (STATE.enabled && !observerStarted) {
startObserver();
} else if (!STATE.enabled && observerStarted) {
stopObserver();
}
}
if (msg && msg.type === "AUTOSEND_STATUS") {
if (msg.active === false) {
clearStatusPill(msg.mode);
}
return true;
}
if (msg && msg.type === "SEND_REPEATER_MESSAGE") {
// Track for status pill — next send scheduled roughly intervalMs from now
if (msg.mode && msg.intervalMs) {
setStatusPill(msg.mode, Date.now() + msg.intervalMs);
}
// Check channel restriction
if (!isChannelAllowed()) {
if (sendResponse) {
sendResponse({ success: false, error: 'Channel restriction: not allowed on this channel' });
}
return true;
}
let processedMessage = processMessage(msg.message, 'repeater');
sendMessage(processedMessage).then(success => {
if (success) {
updateStats('totalRepeater');
updateStats('successCount');
if (sendResponse) {
sendResponse({ success: true, message: 'Message sent successfully' });
}
} else {
if (sendResponse) {
sendResponse({ success: false, error: 'Message send failed' });
}
}
}).catch(error => {
if (sendResponse) {
sendResponse({ success: false, error: error.toString() });
}
});
return true;
}
});
// Load initial state and start observer
chrome.storage.local.get(["enabled", "whitelist", "blacklistedWords", "customMessage", "includeSubscribers", "voiceRotationRepeater", "voiceRotationResponder", "voiceMode", "selectedVoices", "customVoices", "channelRestriction", "responderInterval"], (cfg) => {
try {
STATE.enabled = Boolean(cfg.enabled);
STATE.whitelist = Array.isArray(cfg.whitelist)
? cfg.whitelist.map(s => String(s).toLowerCase())
: [];
STATE.blacklistedWords = Array.isArray(cfg.blacklistedWords)
? cfg.blacklistedWords.map(s => String(s).toLowerCase())
: [];
STATE.customMessage = String(cfg.customMessage || '');
STATE.includeSubscribers = Boolean(cfg.includeSubscribers);
STATE.voiceRotationRepeater = Boolean(cfg.voiceRotationRepeater);
STATE.voiceRotationResponder = Boolean(cfg.voiceRotationResponder);
STATE.voiceMode = String(cfg.voiceMode || 'random');
STATE.selectedVoices = Array.isArray(cfg.selectedVoices) ? cfg.selectedVoices : ['duke', 'trump', 'spongebob'];
STATE.customVoices = Array.isArray(cfg.customVoices) ? cfg.customVoices : [];
STATE.channelRestriction = String(cfg.channelRestriction || '');
STATE.responderInterval = parseInt(cfg.responderInterval) || 30;
// Start observer if enabled
if (STATE.enabled) {
startObserver();
}
} catch (error) {
STATE.enabled = false;
STATE.whitelist = [];
STATE.blacklistedWords = [];
}
});
// =========================
// Status pill above chat input
// =========================
const PILL_ID = 'kickautosend-status-pill';
let pillState = { mode: null, nextSendAt: 0 };
let pillTicker = null;
function ensurePillElement() {
let pill = document.getElementById(PILL_ID);
if (pill) return pill;
const input = getChatInput();
if (!input) return null;
// Anchor container — float the pill above it without affecting layout
const anchor = input.closest('.relative') || input.parentElement;
if (!anchor) return null;
// Ensure anchor is a positioning context
const computed = getComputedStyle(anchor);
if (computed.position === 'static') anchor.style.position = 'relative';
pill = document.createElement('div');
pill.id = PILL_ID;
pill.setAttribute('contenteditable', 'false');
pill.style.cssText = [
'position:absolute', 'top:50%', 'right:34px', 'transform:translateY(-50%)', 'z-index:9999',
'display:inline-flex', 'align-items:center', 'gap:4px',
'padding:1px 6px 1px 8px',
'font:500 10px/1.4 system-ui,-apple-system,sans-serif',
'color:#0a0a0a', 'background:#53fc18', 'border-radius:4px',
'user-select:none', 'pointer-events:auto',
'box-shadow:0 1px 2px rgba(0,0,0,.3)'
].join(';');
const label = document.createElement('span');
label.className = 'kas-pill-label';
label.textContent = '';
pill.appendChild(label);
const stopBtn = document.createElement('button');
stopBtn.type = 'button';
stopBtn.textContent = '×';
stopBtn.title = 'Stop';
stopBtn.style.cssText = [
'all:unset', 'cursor:pointer', 'padding:0 2px',
'font:700 12px/1 system-ui', 'color:#0a0a0a'
].join(';');
const stopHandler = (e) => {
e.preventDefault();
e.stopPropagation();
const type = pillState.mode === 'commaflage' ? 'STOP_COMMAFLAGE' : 'STOP_REPEATER';
chrome.runtime.sendMessage({ type }, () => { void chrome.runtime.lastError; });
clearStatusPill(pillState.mode);
};
stopBtn.addEventListener('mousedown', stopHandler);
stopBtn.addEventListener('click', stopHandler);
pill.appendChild(stopBtn);
anchor.appendChild(pill);
return pill;
}
function setStatusPill(mode, nextSendAt) {
if (STATE.showStatusPill === false) { clearStatusPill(); return; }
pillState.mode = mode;
pillState.nextSendAt = nextSendAt;
renderStatusPill();
if (!pillTicker) {
pillTicker = setInterval(renderStatusPill, 500);
}
}
function clearStatusPill(mode) {
if (mode && pillState.mode && mode !== pillState.mode) return; // different mode stopping — ignore
pillState = { mode: null, nextSendAt: 0 };
if (pillTicker) {
clearInterval(pillTicker);
pillTicker = null;
}
const pill = document.getElementById(PILL_ID);
if (pill) pill.remove();
}
function renderStatusPill() {
if (!pillState.mode) return;
if (STATE.showStatusPill === false) { clearStatusPill(); return; }
const pill = ensurePillElement();
if (!pill) return;
const label = pill.querySelector('.kas-pill-label');
if (!label) return;
const remaining = Math.max(0, Math.round((pillState.nextSendAt - Date.now()) / 1000));
const tag = pillState.mode === 'commaflage' ? 'CF' : 'REP';
label.textContent = remaining > 0 ? `${tag} ${remaining}s` : `${tag} …`;
// Auto-hide if we've gone 10s past expected send (SW probably died)
if (Date.now() - pillState.nextSendAt > 10_000) {
clearStatusPill(pillState.mode);
}
}
// =========================
// Toolbar button (next to Kick's Chat/gear buttons)
// =========================
const TOOLBAR_BTN_ID = 'kickautosend-toolbar-btn';
function ensureToolbarButton() {
if (document.getElementById(TOOLBAR_BTN_ID)) return;
const sendBtn = document.getElementById('send-message-button');
if (!sendBtn || !sendBtn.parentElement) return;
const btn = document.createElement('button');
btn.id = TOOLBAR_BTN_ID;
btn.type = 'button';
btn.title = 'Open KickAutoSend';
// Match Kick's icon-button sizing (size-8 = 32px)
btn.style.cssText = [
'all:unset', 'cursor:pointer', 'display:inline-flex',
'align-items:center', 'justify-content:center',
'width:32px', 'height:32px', 'border-radius:4px',
'color:#53fc18', 'transition:background .15s'
].join(';');
btn.addEventListener('mouseenter', () => btn.style.background = 'rgba(255,255,255,.08)');
btn.addEventListener('mouseleave', () => btn.style.background = 'transparent');
const img = document.createElement('img');
img.src = chrome.runtime.getURL('assets/logo.png');
img.alt = 'KickAutoSend';
img.style.cssText = 'width:20px;height:20px;object-fit:contain;pointer-events:none';
btn.appendChild(img);
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
chrome.runtime.sendMessage({ type: 'OPEN_POPUP' }, () => { void chrome.runtime.lastError; });
});
sendBtn.parentElement.insertBefore(btn, sendBtn);
}
// Keep the toolbar button alive across Kick's client-side route changes
const toolbarObserver = new MutationObserver(() => ensureToolbarButton());
toolbarObserver.observe(document.body, { childList: true, subtree: true });
ensureToolbarButton();