-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
2007 lines (1682 loc) · 67.8 KB
/
popup.js
File metadata and controls
2007 lines (1682 loc) · 67.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
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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);
};
// 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'
];
// Theme configurations with default voices
const THEMES = {
kick: {
name: 'Kick Theme',
image: 'assets/logo.png',
title: 'Kick AutoSend',
emoji: '⚡',
defaultVoices: ['morgan', 'watson', 'joerogan', 'rock', 'arnold', 'samueljackson', 'kevinhart', 'snoop', 'jordan', 'willsmith', 'elon', 'billgates', 'lex', 'eddie', 'sketch'],
defaultCommands: []
},
fnv: {
name: 'FNV Theme',
image: 'assets/fnv.jpg',
title: 'FNV Sender 🌋',
emoji: '🎮',
defaultVoices: ['drphil', 'spongebob', '50cent', 'steve', 'duke'],
defaultCommands: []
}
};
// DOM elements
const elements = {
// Tabs
tabs: document.querySelectorAll('.tab'),
tabContents: document.querySelectorAll('.tab-content'),
// Theme controls
themeToggle: document.getElementById('themeToggle'),
headerImage: document.getElementById('headerImage'),
headerText: document.getElementById('headerText'),
masterEnabled: document.getElementById('masterEnabled'),
// Basic tab
enabled: document.getElementById('enabled'),
whitelist: document.getElementById('whitelist'),
customMessage: document.getElementById('customMessage'),
includeSubscribers: document.getElementById('includeSubscribers'),
responderAllowCommands: document.getElementById('responderAllowCommands'),
whitelistCounter: document.getElementById('whitelist-counter'),
messageCounter: document.getElementById('message-counter'),
// Repeater tab
repeaterEnabled: document.getElementById('repeaterEnabled'),
repeaterMessage: document.getElementById('repeaterMessage'),
interval: document.getElementById('interval'),
maxCount: document.getElementById('maxCount'),
startRepeater: document.getElementById('startRepeater'),
stopRepeater: document.getElementById('stopRepeater'),
repeaterCounter: document.getElementById('repeater-counter'),
repeaterStats: document.getElementById('repeaterStats'),
nextMessage: document.getElementById('nextMessage'),
messagesLeft: document.getElementById('messagesLeft'),
// Preset controls
presetName: document.getElementById('presetName'),
savePreset: document.getElementById('savePreset'),
presetList: document.getElementById('presetList'),
// Voices tab
voiceRotationEnabled: document.getElementById('voiceRotationEnabled'), // Legacy
voiceRotationRepeater: document.getElementById('voiceRotationRepeater'),
voiceRotationResponder: document.getElementById('voiceRotationResponder'),
voiceMode: document.getElementById('voiceMode'),
voiceGrid: document.getElementById('voiceGrid'),
selectAllVoices: document.getElementById('selectAllVoices'),
clearAllVoices: document.getElementById('clearAllVoices'),
customVoiceName: document.getElementById('customVoiceName'),
addCustomVoice: document.getElementById('addCustomVoice'),
// Queue tab elements removed (queue tab replaced with commandflage)
// Advanced tab
maxCharLimit: document.getElementById('maxCharLimit'),
blacklistedWords: document.getElementById('blacklistedWords'),
blacklistCounter: document.getElementById('blacklist-counter'),
responderInterval: document.getElementById('responderInterval'),
// Stats tab
totalReplies: document.getElementById('totalReplies'),
totalProcessed: document.getElementById('totalProcessed'),
totalRepeater: document.getElementById('totalRepeater'),
totalTimeouts: document.getElementById('totalTimeouts'),
totalBans: document.getElementById('totalBans'),
successRate: document.getElementById('successRate'),
topPresets: document.getElementById('topPresets'),
resetStats: document.getElementById('resetStats'),
resetPresetStats: document.getElementById('resetPresetStats'),
exportSettings: document.getElementById('exportSettings'),
importSettings: document.getElementById('importSettings'),
importFile: document.getElementById('importFile'),
// Commandflage tab
commandflageEnabled: document.getElementById('commandflageEnabled'),
commandflageCommands: document.getElementById('commandflageCommands'),
commandsCounter: document.getElementById('commands-counter'),
commandInterval: document.getElementById('commandInterval'),
commandRounds: document.getElementById('commandRounds'),
commandCount: document.getElementById('commandCount'),
randomizeCommands: document.getElementById('randomizeCommands'),
startCommandflage: document.getElementById('startCommandflage'),
stopCommandflage: document.getElementById('stopCommandflage'),
commandflageStats: document.getElementById('commandflageStats'),
commandsSent: document.getElementById('commandsSent'),
currentRound: document.getElementById('currentRound'),
nextCommand: document.getElementById('nextCommand'),
// Advanced tab additions
channelRestriction: document.getElementById('channelRestriction'),
messagesLeft: document.getElementById('messagesLeft'),
// Save buttons
save: document.getElementById('save'),
saveResponder: document.getElementById('saveResponder'),
saveVoices: document.getElementById('saveVoices'),
// Status
status: document.getElementById('status'),
// Indicators
repeaterIndicator: document.getElementById('repeater-indicator'),
responderIndicator: document.getElementById('responder-indicator'),
voicesIndicator: document.getElementById('voices-indicator'),
commandflageIndicator: document.getElementById('commandflage-indicator'),
// Tooltips
tooltipsEnabled: document.getElementById('tooltipsEnabled'),
// Status pill
showStatusPill: document.getElementById('showStatusPill')
};
// Default settings
const DEFAULT_SETTINGS = {
masterEnabled: true,
enabled: false,
whitelist: [],
customMessage: '',
includeSubscribers: false,
responderAllowCommands: false,
repeaterEnabled: false,
repeaterMessage: '',
interval: 90,
maxCount: 0,
voiceRotationEnabled: false, // Legacy setting, will be migrated
voiceRotationRepeater: false,
voiceRotationResponder: false,
voiceMode: 'random',
selectedVoices: ['duke', 'trump', 'spongebob'],
responderInterval: 30,
maxCharLimit: 150,
blacklistedWords: [],
currentTheme: 'kick',
customVoices: [], // User-added custom voices
messagePresets: [], // New setting for saved presets
presetStats: {}, // Track usage count for each preset
channelRestriction: '', // Restrict to specific channel
commandflageEnabled: false,
commandflageCommands: [],
randomizeCommands: true,
commandInterval: 3,
commandRounds: 1,
commandCount: 0,
tooltipsEnabled: true,
showStatusPill: true,
stats: {
totalReplies: 0,
totalProcessed: 0,
totalRepeater: 0,
totalCommandflage: 0,
timeouts: 0,
bans: 0,
successCount: 0
}
};
let currentSettings = { ...DEFAULT_SETTINGS };
let repeaterInterval = null;
let pendingRepeaterTimeouts = new Set(); // Track all pending timeouts
let commandflageInterval = null;
let commandflageStats = { sent: 0, round: 1 };
let commandflageCountdown = null;
// Theme functionality
function initThemes() {
// Load saved theme
const savedTheme = currentSettings.currentTheme || 'kick';
applyTheme(savedTheme);
// Theme toggle event
elements.themeToggle.addEventListener('click', () => {
const currentTheme = document.body.getAttribute('data-theme') || 'kick';
const newTheme = currentTheme === 'kick' ? 'fnv' : 'kick';
applyTheme(newTheme);
currentSettings.currentTheme = newTheme;
saveSettings();
});
}
function applyTheme(themeName) {
const theme = THEMES[themeName];
if (!theme) return;
document.body.setAttribute('data-theme', themeName);
elements.headerImage.src = theme.image;
elements.headerText.textContent = theme.title;
// Update theme button to show the OTHER theme name
if (themeName === 'kick') {
elements.themeToggle.textContent = '🔄 FNV';
} else {
elements.themeToggle.textContent = '🔄 Standard';
}
// Update emoji fallback
const emoji = document.querySelector('.header-emoji');
if (emoji) {
emoji.textContent = theme.emoji;
}
// Handle image load error
elements.headerImage.onerror = function() {
this.style.display = 'none';
emoji.style.display = 'inline';
};
// Reset image display when theme changes
elements.headerImage.style.display = '';
emoji.style.display = 'none';
// Ensure logo state is properly applied after theme change
if (!elements.masterEnabled.checked) {
elements.headerImage.style.filter = 'brightness(30%)';
} else {
elements.headerImage.style.filter = '';
}
// Update default selected voices if user hasn't customized them
const hasCustomSelection = currentSettings.selectedVoices &&
currentSettings.selectedVoices.length > 0 &&
currentSettings.selectedVoices.some(voice => !theme.defaultVoices.includes(voice));
if (!hasCustomSelection) {
currentSettings.selectedVoices = [...theme.defaultVoices.slice(0, 5)]; // Use first 5 default voices
updateVoiceSelection();
}
// Only update commandflage commands when switching themes if they're empty
if (!currentSettings.commandflageCommands || currentSettings.commandflageCommands.length === 0) {
currentSettings.commandflageCommands = [...theme.defaultCommands];
}
// Always update placeholder to show theme-appropriate defaults
elements.commandflageCommands.placeholder = theme.defaultCommands.join(', ');
}
// Tab switching functionality
function initTabs() {
elements.tabs.forEach(tab => {
tab.addEventListener('click', () => {
const targetTab = tab.dataset.tab;
// Update tab appearance
elements.tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
// Show/hide content
elements.tabContents.forEach(content => {
content.classList.remove('active');
if (content.id === targetTab) {
content.classList.add('active');
}
});
// Hide global save button only on tabs that have their own save mechanisms
const saveContainer = document.getElementById('global-save-container');
if (saveContainer) {
const hideOnTabs = ['repeater', 'commandflage'];
saveContainer.style.display = hideOnTabs.includes(targetTab) ? 'none' : 'block';
}
// Remember last opened tab across popup sessions
chrome.storage.local.set({ lastActiveTab: targetTab });
});
});
// Restore previously active tab
chrome.storage.local.get(['lastActiveTab'], ({ lastActiveTab }) => {
if (!lastActiveTab) return;
const target = Array.from(elements.tabs).find(t => t.dataset.tab === lastActiveTab);
if (target && !target.classList.contains('active')) target.click();
});
}
// Character counter functionality
function updateCharCounter(input, counter, maxChars = 500) {
const length = input.value.length;
if (input === elements.whitelist) {
const users = input.value.split('\n').filter(line => line.trim()).length;
counter.textContent = `${users} users`;
} else if (input === elements.blacklistedWords) {
const words = input.value.split(',').filter(word => word.trim()).length;
counter.textContent = `${words} words`;
} else {
counter.textContent = `${length}/${maxChars} characters`;
counter.classList.remove('warning', 'error');
if (length > maxChars * 0.8) {
counter.classList.add('warning');
}
if (length > maxChars) {
counter.classList.add('error');
}
}
}
// Voice grid functionality
function initVoiceGrid() {
elements.voiceGrid.innerHTML = '';
// Combine default voices with custom voices
const allVoices = [...VOICES, ...currentSettings.customVoices];
allVoices.forEach(voice => {
const voiceItem = document.createElement('div');
voiceItem.className = 'voice-item';
const isCustom = currentSettings.customVoices.includes(voice);
voiceItem.innerHTML = `
<input type="checkbox" id="voice-${voice}" value="${voice}">
<label for="voice-${voice}">!${voice}${isCustom ? ' ✨' : ''}</label>
${isCustom ? `<button class="preset-btn delete voice-delete-btn" data-voice="${voice}" style="padding: 1px 3px; font-size: 8px; margin-left: 2px;">×</button>` : ''}
`;
elements.voiceGrid.appendChild(voiceItem);
});
// Add event listeners to delete buttons
document.querySelectorAll('.voice-delete-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const voiceName = btn.getAttribute('data-voice');
removeCustomVoice(voiceName);
});
});
// Add event listeners to voice checkboxes for indicator updates
document.querySelectorAll('#voiceGrid input[type="checkbox"]').forEach(checkbox => {
checkbox.addEventListener('change', () => {
setTimeout(updateAllTabIndicators, 50);
});
});
}
// Voice selection functionality
function updateVoiceSelection() {
const allVoices = [...VOICES, ...currentSettings.customVoices];
allVoices.forEach(voice => {
const checkbox = document.getElementById(`voice-${voice}`);
if (checkbox) {
checkbox.checked = currentSettings.selectedVoices.includes(voice);
}
});
}
function getSelectedVoices() {
const allVoices = [...VOICES, ...currentSettings.customVoices];
return allVoices.filter(voice => {
const checkbox = document.getElementById(`voice-${voice}`);
return checkbox && checkbox.checked;
});
}
// HTML escape for safe innerHTML insertion
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Input sanitization functions
function sanitizeInput(input, maxLength = 500) {
if (typeof input !== 'string') return '';
return input.trim().slice(0, maxLength);
}
function sanitizeVoiceName(input) {
if (typeof input !== 'string') return '';
return input.trim().toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 20);
}
function sanitizeUsername(input) {
if (typeof input !== 'string') return '';
return input.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 50);
}
// Custom voice management
function addCustomVoice() {
const rawInput = elements.customVoiceName.value;
const voiceName = sanitizeVoiceName(rawInput);
if (!voiceName) {
showStatus('Please enter a valid voice name (letters and numbers only)', 'error');
return;
}
if (voiceName.length < 2) {
showStatus('Voice name must be at least 2 characters', 'error');
return;
}
if (VOICES.includes(voiceName)) {
showStatus('This voice already exists in the default list', 'error');
return;
}
if (currentSettings.customVoices.includes(voiceName)) {
showStatus('This custom voice already exists', 'error');
return;
}
if (currentSettings.customVoices.length >= 20) {
showStatus('Maximum 20 custom voices allowed', 'error');
return;
}
currentSettings.customVoices.push(voiceName);
elements.customVoiceName.value = '';
initVoiceGrid();
updateVoiceSelection();
saveSettings();
showStatus(`Custom voice "${voiceName}" added!`, 'success');
}
function removeCustomVoice(voiceName) {
if (confirm(`Remove custom voice "${voiceName}"?`)) {
currentSettings.customVoices = currentSettings.customVoices.filter(v => v !== voiceName);
currentSettings.selectedVoices = currentSettings.selectedVoices.filter(v => v !== voiceName);
initVoiceGrid();
updateVoiceSelection();
saveSettings();
showStatus(`Custom voice "${voiceName}" removed`, 'success');
}
}
// removeCustomVoice is now handled by event listeners, no need for global access
// Voice rotation functionality
function getRandomVoice() {
const voices = currentSettings.selectedVoices;
if (voices.length === 0) return 'duke';
return voices[Math.floor(Math.random() * voices.length)];
}
let voiceIndex = 0;
function getSequentialVoice() {
const voices = currentSettings.selectedVoices;
if (voices.length === 0) return 'duke';
const voice = voices[voiceIndex % voices.length];
voiceIndex++;
return voice;
}
function getNextVoice(context = 'responder') {
const isEnabled = context === 'repeater' ?
currentSettings.voiceRotationRepeater :
currentSettings.voiceRotationResponder;
if (!isEnabled) return null;
return currentSettings.voiceMode === 'random' ? getRandomVoice() : getSequentialVoice();
}
// Message processing with voice replacement
function processMessage(template, context = 'responder') {
const isEnabled = context === 'repeater' ?
currentSettings.voiceRotationRepeater :
currentSettings.voiceRotationResponder;
if (!isEnabled) return template;
// Special handling for responder: if message contains only !command (no additional text),
// check if user wants to allow command responding
if (context === 'responder') {
const trimmedMessage = template.trim();
// Check if message is only a command (starts with ! and has no spaces or additional text)
if (/^!\w+$/.test(trimmedMessage)) {
// If user disabled command responding, return unchanged
if (!currentSettings.responderAllowCommands) {
return template; // Return unchanged - it's a command, not a TTS message
}
// If commands are allowed, continue with normal processing
}
}
// Replace !voice commands with selected voice, but only if followed by text
return template.replace(/!\w+(?=\s)/g, (match) => {
// Only replace if it's a known TTS voice and followed by a space (indicating more text)
if (VOICES.some(voice => match === `!${voice}`) ||
currentSettings.customVoices.some(voice => match === `!${voice}`)) {
const nextVoice = getNextVoice(context);
return `!${nextVoice}`;
}
return match;
});
}
// Statistics functionality
function updateStats(key, increment = 1) {
currentSettings.stats[key] += increment;
loadStats();
saveSettings();
}
function loadStats() {
elements.totalReplies.textContent = currentSettings.stats.totalReplies;
elements.totalProcessed.textContent = currentSettings.stats.totalProcessed;
elements.totalRepeater.textContent = currentSettings.stats.totalRepeater;
const totalAttempts = currentSettings.stats.totalReplies + currentSettings.stats.totalRepeater;
const successfulSends = currentSettings.stats.successCount;
let successRate = 100; // Default to 100% if no attempts
if (totalAttempts > 0) {
successRate = Math.round((successfulSends / totalAttempts) * 100);
}
elements.successRate.textContent = `${successRate}% (${successfulSends}/${totalAttempts})`;
}
function resetStats() {
if (confirm('Are you sure you want to reset all statistics?')) {
currentSettings.stats = {
totalReplies: 0,
totalProcessed: 0,
totalRepeater: 0,
totalCommandflage: 0,
timeouts: 0,
bans: 0,
successCount: 0
};
loadStats();
saveSettings();
showStatus('Statistics reset', 'success');
}
}
function resetPresetStats() {
if (confirm('Are you sure you want to reset preset usage statistics?')) {
currentSettings.presetStats = {};
updateStatsDisplay();
saveSettings();
showStatus('Preset usage statistics reset', 'success');
}
}
// Settings management
function loadSettings() {
chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS), (result) => {
currentSettings = { ...DEFAULT_SETTINGS, ...result };
// Ensure stats object exists
if (!currentSettings.stats) {
currentSettings.stats = DEFAULT_SETTINGS.stats;
}
// Ensure blacklistedWords exists
if (!currentSettings.blacklistedWords) {
currentSettings.blacklistedWords = [];
}
// Ensure customVoices exists
if (!currentSettings.customVoices) {
currentSettings.customVoices = [];
}
// Ensure presetStats exists
if (!currentSettings.presetStats) {
currentSettings.presetStats = {};
}
// Set initial commandflage commands based on current theme if empty
if (!currentSettings.commandflageCommands || currentSettings.commandflageCommands.length === 0) {
const currentTheme = THEMES[currentSettings.currentTheme || 'kick'];
if (currentTheme && currentTheme.defaultCommands) {
currentSettings.commandflageCommands = [...currentTheme.defaultCommands];
}
}
// Handle commandflage commands - they can be stored as string or array
if (typeof currentSettings.commandflageCommands === 'string') {
// Convert string to array for consistency
currentSettings.commandflageCommands = currentSettings.commandflageCommands
.split(',')
.map(s => s.trim())
.filter(Boolean);
}
// Update UI
elements.masterEnabled.checked = currentSettings.masterEnabled !== false; // Default to true
elements.enabled.checked = currentSettings.enabled;
elements.whitelist.value = Array.isArray(currentSettings.whitelist)
? currentSettings.whitelist.join('\n') : '';
elements.customMessage.value = currentSettings.customMessage || '';
elements.includeSubscribers.checked = currentSettings.includeSubscribers;
elements.responderAllowCommands.checked = currentSettings.responderAllowCommands || false;
elements.repeaterEnabled.checked = currentSettings.repeaterEnabled;
elements.repeaterMessage.value = currentSettings.repeaterMessage;
elements.interval.value = currentSettings.interval;
elements.maxCount.value = currentSettings.maxCount;
// Handle voice rotation migration
if (currentSettings.voiceRotationEnabled &&
currentSettings.voiceRotationRepeater === undefined &&
currentSettings.voiceRotationResponder === undefined) {
// Migrate legacy setting - apply to responder by default
currentSettings.voiceRotationResponder = true;
currentSettings.voiceRotationRepeater = false;
currentSettings.voiceRotationEnabled = false; // Clear legacy setting
}
elements.voiceRotationRepeater.checked = currentSettings.voiceRotationRepeater || false;
elements.voiceRotationResponder.checked = currentSettings.voiceRotationResponder || false;
elements.voiceMode.value = currentSettings.voiceMode;
elements.responderInterval.value = currentSettings.responderInterval || 30;
elements.maxCharLimit.value = currentSettings.maxCharLimit;
elements.blacklistedWords.value = Array.isArray(currentSettings.blacklistedWords)
? currentSettings.blacklistedWords.join(', ') : '';
elements.channelRestriction.value = currentSettings.channelRestriction || '';
elements.commandflageEnabled.checked = currentSettings.commandflageEnabled;
elements.commandflageCommands.value = Array.isArray(currentSettings.commandflageCommands) && currentSettings.commandflageCommands.length > 0
? currentSettings.commandflageCommands.join(', ') : '';
elements.randomizeCommands.checked = currentSettings.randomizeCommands;
elements.commandInterval.value = currentSettings.commandInterval || 3;
elements.commandRounds.value = currentSettings.commandRounds || 1;
elements.commandCount.value = currentSettings.commandCount || 0;
elements.tooltipsEnabled.checked = currentSettings.tooltipsEnabled !== false; // Default to true if not set
elements.showStatusPill.checked = currentSettings.showStatusPill !== false; // Default to true if not set
updateVoiceSelection();
loadStats();
updateAdvancedDisplay();
updateAllCounters();
// Ensure repeater message counter is updated with correct max limit
const maxChars = parseInt(elements.maxCharLimit?.value) || 150;
updateCharCounter(elements.repeaterMessage, elements.repeaterCounter, maxChars);
updatePresetDisplay(); // Load presets
updateStatsDisplay();
applyTheme(currentSettings.currentTheme || 'kick');
updateMasterState(); // Update master toggle state
updateAllTabIndicators(); // Update tab status indicators
updateTooltipVisibility(); // Update tooltip visibility based on setting
// Check for commaflage completion
checkCommaflageCompletion();
// Set up periodic checking for commaflage completion
setInterval(checkCommaflageCompletion, 2000); // Check every 2 seconds
// Initialize repeater UI state
if (elements.stopRepeater) elements.stopRepeater.disabled = true;
if (elements.startRepeater) elements.startRepeater.textContent = 'Save and Start';
if (elements.nextMessage) elements.nextMessage.textContent = '--';
if (elements.messagesLeft) elements.messagesLeft.textContent = '--';
// If the service worker repeater is already running, reflect that in the UI
chrome.runtime.sendMessage({ type: 'GET_REPEATER_STATUS' }, (status) => {
void chrome.runtime.lastError;
if (status && status.active) {
if (elements.stopRepeater) elements.stopRepeater.disabled = false;
if (elements.startRepeater) {
elements.startRepeater.disabled = true;
elements.startRepeater.textContent = 'Running…';
}
messagesSent = status.messagesSent || 0;
if (typeof startCountdown === 'function' && status.interval) {
startCountdown(status.interval);
}
}
});
});
}
function saveSettings() {
// Show loading state
const saveButton = elements.save;
const originalText = saveButton.textContent;
saveButton.textContent = 'Saving...';
saveButton.disabled = true;
// Collect and sanitize current values
currentSettings.enabled = Boolean(elements.enabled.checked);
// Sanitize whitelist
currentSettings.whitelist = elements.whitelist.value
.split('\n')
.map(s => sanitizeUsername(s))
.filter(Boolean)
.slice(0, 100); // Max 100 users
// Master toggle
currentSettings.masterEnabled = elements.masterEnabled.checked;
// Sanitize messages
currentSettings.customMessage = sanitizeInput(elements.customMessage.value, 500);
currentSettings.includeSubscribers = elements.includeSubscribers.checked;
currentSettings.responderAllowCommands = elements.responderAllowCommands.checked;
currentSettings.repeaterEnabled = elements.repeaterEnabled.checked;
currentSettings.repeaterMessage = sanitizeInput(elements.repeaterMessage.value, 500);
// Validate numeric inputs
const interval = parseInt(elements.interval.value);
currentSettings.interval = (interval >= 10 && interval <= 3600) ? interval : 90;
const maxCount = parseInt(elements.maxCount.value);
currentSettings.maxCount = (maxCount >= 0 && maxCount <= 1000) ? maxCount : 0;
currentSettings.voiceRotationRepeater = elements.voiceRotationRepeater.checked;
currentSettings.voiceRotationResponder = elements.voiceRotationResponder.checked;
currentSettings.voiceMode = ['random', 'sequential'].includes(elements.voiceMode.value) ? elements.voiceMode.value : 'random';
currentSettings.selectedVoices = getSelectedVoices();
const responderInterval = parseInt(elements.responderInterval.value);
currentSettings.responderInterval = (responderInterval >= 10 && responderInterval <= 300) ? responderInterval : 30;
const maxCharLimit = parseInt(elements.maxCharLimit.value);
currentSettings.maxCharLimit = (maxCharLimit >= 50 && maxCharLimit <= 500) ? maxCharLimit : 150;
// Sanitize blacklisted words
currentSettings.blacklistedWords = elements.blacklistedWords.value
.split(',')
.map(s => sanitizeInput(s, 50))
.filter(Boolean)
.slice(0, 50); // Max 50 blacklisted words
// Channel restriction
currentSettings.channelRestriction = sanitizeInput(elements.channelRestriction.value, 100);
// Commandflage settings
currentSettings.commandflageEnabled = elements.commandflageEnabled.checked;
currentSettings.commandflageCommands = elements.commandflageCommands.value
.split(',')
.map(s => sanitizeInput(s, 50))
.filter(Boolean)
.slice(0, 20); // Max 20 commands
currentSettings.randomizeCommands = elements.randomizeCommands.checked;
const commandInterval = parseInt(elements.commandInterval.value);
currentSettings.commandInterval = (commandInterval >= 1 && commandInterval <= 60) ? commandInterval : 3;
const commandRounds = parseInt(elements.commandRounds.value);
currentSettings.commandRounds = (commandRounds >= 0 && commandRounds <= 100) ? commandRounds : 1;
const commandCount = parseInt(elements.commandCount.value);
currentSettings.commandCount = (commandCount >= 0 && commandCount <= 1000) ? commandCount : 0;
// Tooltip setting
currentSettings.tooltipsEnabled = elements.tooltipsEnabled.checked;
currentSettings.showStatusPill = elements.showStatusPill.checked;
// Save to storage
chrome.storage.local.set(currentSettings, () => {
if (chrome.runtime.lastError) {
console.error('Error saving settings:', chrome.runtime.lastError);
showStatus('Error saving settings', 'error');
} else {
showStatus('Settings saved!', 'success');
updateAllTabIndicators(); // Update indicators after saving
// Notify content scripts
chrome.tabs.query({ url: ["https://kick.com/*", "https://*.kick.com/*"] }, (tabs) => {
tabs.forEach(tab => {
if (tab.id) {
chrome.tabs.sendMessage(tab.id, {
type: "STATE",
payload: currentSettings
}, () => {
void chrome.runtime.lastError;
});
}
});
});
}
// Reset button state
saveButton.textContent = originalText;
saveButton.disabled = false;
});
}
function exportSettings() {
const exportData = {
...currentSettings,
exportDate: new Date().toISOString(),
version: '2.0'
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `kick-auto-sender-settings-${new Date().toISOString().split('T')[0]}.json`;
a.click();
URL.revokeObjectURL(url);
showStatus('Settings exported!', 'success');
}
function importSettings() {
elements.importFile.click();
}
function handleImportFile(event) {
const file = event.target.files[0];
if (!file) return;
if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
showStatus('Please select a valid JSON file', 'error');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const importData = JSON.parse(e.target.result);
// Validate the import data
if (!importData || typeof importData !== 'object') {
throw new Error('Invalid settings file format');
}
// Check version compatibility (optional warning)
if (importData.version && importData.version !== '2.0') {
console.warn('Importing settings from different version:', importData.version);
}
// Merge imported settings with defaults to ensure all fields exist
const validatedSettings = { ...DEFAULT_SETTINGS };
// Copy over valid settings
Object.keys(DEFAULT_SETTINGS).forEach(key => {
if (key in importData && key !== 'stats') { // Don't import stats
// Type validation
if (typeof importData[key] === typeof DEFAULT_SETTINGS[key]) {
validatedSettings[key] = importData[key];
}
}
});
// Special handling for arrays
if (Array.isArray(importData.whitelist)) validatedSettings.whitelist = importData.whitelist;
if (Array.isArray(importData.blacklistedWords)) validatedSettings.blacklistedWords = importData.blacklistedWords;
if (Array.isArray(importData.selectedVoices)) validatedSettings.selectedVoices = importData.selectedVoices;
if (Array.isArray(importData.customVoices)) validatedSettings.customVoices = importData.customVoices;
if (Array.isArray(importData.messagePresets)) validatedSettings.messagePresets = importData.messagePresets;
if (Array.isArray(importData.commandflageCommands)) validatedSettings.commandflageCommands = importData.commandflageCommands;
// Special handling for objects
if (importData.presetStats && typeof importData.presetStats === 'object') {
validatedSettings.presetStats = importData.presetStats;
}
// Update current settings and save
currentSettings = validatedSettings;
chrome.storage.local.set(currentSettings);
// Reload the UI
loadSettings();
showStatus('Settings imported successfully!', 'success');
} catch (error) {
console.error('Import error:', error);
showStatus('Error importing settings: ' + error.message, 'error');
}
};
reader.onerror = function() {
showStatus('Error reading file', 'error');
};
reader.readAsText(file);
// Clear the input so the same file can be imported again
event.target.value = '';
}
// UI helpers
function showStatus(message, type = '') {
elements.status.textContent = message;
elements.status.className = `status ${type}`;
setTimeout(() => {
elements.status.textContent = '';
elements.status.className = 'status';
}, 3000);
}
// Tab indicator management
function updateTabIndicator(indicatorElement, status) {
if (!indicatorElement) return;
// Remove all status classes
indicatorElement.classList.remove('inactive', 'active', 'partial', 'error');
// Add the new status class
indicatorElement.classList.add(status);
// Set tooltip based on status
const tooltips = {
'inactive': 'Disabled',
'partial': 'Needs config',
'active': 'Running',
'error': 'Error'
};
indicatorElement.setAttribute('data-tooltip', tooltips[status] || 'Unknown');
}
function updateExtensionBadge(isEnabled) {
try {
if (isEnabled) {
// Active state - default icon, no badge
chrome.action.setIcon({
path: {
"16": "assets/logo.png",
"32": "assets/logo.png",
"48": "assets/logo.png",
"128": "assets/logo.png"
}
});
chrome.action.setBadgeText({text: ''});
chrome.action.setTitle({title: 'Kick AutoSend - Active'});
} else {
// Disabled state - use greyed-out icon with small red circle indicator
chrome.action.setIcon({
path: {
"16": "assets/logo-disabled.png",
"32": "assets/logo-disabled.png",
"48": "assets/logo-disabled.png",
"128": "assets/logo-disabled.png"
}
});
chrome.action.setBadgeText({text: ''}); // No badge - greyed icon is enough
chrome.action.setTitle({title: 'Kick AutoSend - Disabled'});
}
} catch (error) {
// Silent error handling for production
}
}
function updateMasterState() {
const isEnabled = elements.masterEnabled.checked;
// Update header logo to match state - use brightness filter for both themes
if (isEnabled) {
elements.headerImage.style.filter = '';
} else {
// Use brightness filter for both themes (consistent behavior)
elements.headerImage.style.filter = 'brightness(30%)';
}
// Update main container to show disabled state
const popup = document.querySelector('.container') || document.body;
if (isEnabled) {
popup.classList.remove('extension-disabled');
} else {
popup.classList.add('extension-disabled');