-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
2101 lines (1769 loc) · 73.6 KB
/
Copy pathcontent.js
File metadata and controls
2101 lines (1769 loc) · 73.6 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
/**
* ═══════════════════════════════════════════════════════════════════════════
* UNLOOP - CONTENT SCRIPT (MAIN ENGINE)
* ═══════════════════════════════════════════════════════════════════════════
*
* This is the brain of the extension. It:
* 1) Detects when YouTube/YouTube Music/Spotify song changes
* 2) Extracts videoId + artist info
* 3) Checks whitelist → if yes → PLAY
* 4) Checks blacklist → if yes → SKIP
* 5) Checks history and applies mode rules:
* - Strict: Skip if ever played
* - Memory Fade: Skip if played within X days
* - Semi-Strict: Skip if not enough new songs since last play
* - Artist Smart: Skip if same artist played too recently
* 6) Shows toast notifications
* 7) Updates statistics
*
* DATA STRUCTURE:
* songHistory[trackId] = {
* platform: "Spotify" | "YouTube Music" | "YouTube",
* title: string,
* artist: string,
* totalPlays: number,
* totalSkips: number,
* totalListeningSeconds: number,
* firstPlayed: timestamp,
* lastPlayed: timestamp,
* plays: number, // For CSV export
* skips: number, // For CSV export
* avgListenDuration: number,
* quickSkipCount: number
* }
*
* All data stored in chrome.storage.local (private, offline, free)
* Session data in chrome.storage.session (resets on browser close)
* ═══════════════════════════════════════════════════════════════════════════
*/
(function() {
'use strict';
// ═══════════════════════════════════════════════════════════════
// EXTENSION CONTEXT GUARDS (Crash Protection)
// ═══════════════════════════════════════════════════════════════
/**
* Fast check if extension context is still valid
* Prevents "Extension context invalidated" errors
*/
function isExtensionAlive() {
return !!chrome?.runtime?.id;
}
/**
* Session management for SPA navigation safety
* Prevents stale async operations from completing after page changes
*/
let songProcessToken = 0;
let sessionKilled = false;
function killSession() {
sessionKilled = true;
songProcessToken++;
console.debug('[Unloop] Session refreshed - cancelling old operations');
}
// ═══════════════════════════════════════════════════════════════
// CONFIGURATION
// ═══════════════════════════════════════════════════════════════
const CONFIG = {
CHECK_INTERVAL: 1000, // How often to check for song changes (ms)
SKIP_DELAY: 400, // Delay before skipping (feels more natural)
TOAST_DURATION: 2500, // How long toast shows (ms)
DEBUG: true // Console logging
};
// ═══════════════════════════════════════════════════════════════
// STATE MANAGEMENT
// ═══════════════════════════════════════════════════════════════
const state = {
currentVideoId: null,
lastProcessedId: null,
isProcessing: false,
enabled: true,
currentStartTime: null,
currentTrackId: null,
settings: {
mode: 'strict',
memoryFadeHours: 72, // Use hours for precise control
songsBeforeRepeat: 5,
maxArtistPerSession: 3
},
whitelist: [],
blacklist: [],
sessionData: {
recentSongs: [], // Last N songs this session
artistPlayCount: {}, // Artist -> play count this session
newSongsSinceRepeat: 0, // Counter for semi-strict mode
recentArtists: [] // Last 20 artists for Smart Auto
},
// Smart Auto listening behavior tracking
listening: {
startTime: null,
currentVideoId: null,
duration: 0
}
};
// ═══════════════════════════════════════════════════════════════
// EXTENSION CONTEXT VALIDATION
// ═══════════════════════════════════════════════════════════════
/**
* Quick context check - faster than isExtensionValid()
* Use this in hot paths and before async completions
*/
function isContextAlive() {
return !!chrome?.runtime?.id;
}
function isExtensionValid() {
// Check if extension context is still alive
return !!(chrome && chrome.runtime && chrome.runtime.id);
}
function isContextInvalidatedError(error) {
return error && error.message &&
(error.message.includes('Extension context invalidated') ||
error.message.includes('Extension context'));
}
// Session cancellation tracking for navigation safety
// (Consolidated - single instance only)
// Token is already defined at top with isExtensionAlive guards
/**
* Safely call Chrome APIs with fallback on context invalidation
* This prevents crashes when YouTube Music navigation kills the extension context
*/
function safeChrome(fn, fallback = null) {
try {
if (!isExtensionValid()) {
console.warn('[Unloop] Extension context lost before API call');
return fallback;
}
return fn();
} catch (error) {
if (isContextInvalidatedError(error)) {
console.warn('[Unloop] Extension context invalidated during API call, returning fallback');
return fallback;
}
// Re-throw unexpected errors
throw error;
}
}
// ═══════════════════════════════════════════════════════════════
// LOGGING
// ═══════════════════════════════════════════════════════════════
function log(...args) {
if (CONFIG.DEBUG && isExtensionValid()) {
console.log('%c[Unloop]', 'color: #6366f1; font-weight: bold;', ...args);
}
}
function logSkip(reason) {
if (CONFIG.DEBUG && isExtensionValid()) {
console.log('%c[Unloop] ⏭️ SKIP:', 'color: #ef4444; font-weight: bold;', reason);
}
}
function logAllow(reason) {
if (CONFIG.DEBUG && isExtensionValid()) {
console.log('%c[Unloop] ✅ ALLOW:', 'color: #22c55e; font-weight: bold;', reason);
}
}
// Debug function to show current mode state
function logModeState() {
if (CONFIG.DEBUG && isExtensionValid()) {
console.log('%c[Unloop] 📊 MODE STATE:', 'color: #a855f7; font-weight: bold;', {
mode: state.settings.mode,
newSongsSinceRepeat: state.sessionData.newSongsSinceRepeat,
recentSongs: state.sessionData.recentSongs.length,
recentArtists: state.sessionData.recentArtists,
artistPlayCount: state.sessionData.artistPlayCount
});
}
}
// ═══════════════════════════════════════════════════════════════
// LISTENING TIME TRACKING
// ═══════════════════════════════════════════════════════════════
async function commitListeningTime(trackId) {
if (!trackId || !state.currentStartTime) return;
const seconds = Math.floor((Date.now() - state.currentStartTime) / 1000);
if (seconds < 3) return; // Ignore very short plays
try {
const result = await chrome.storage.local.get(['songHistory', 'stats']);
const history = result.songHistory || {};
const stats = result.stats || {};
if (history[trackId]) {
// Update song's listening time
history[trackId].totalListeningSeconds =
(history[trackId].totalListeningSeconds || 0) + seconds;
// Update global total
stats.totalListeningSeconds = (stats.totalListeningSeconds || 0) + seconds;
await chrome.storage.local.set({ songHistory: history, stats });
}
} catch (error) {
console.debug('[Unloop] Error committing listening time:', error);
}
}
// ═══════════════════════════════════════════════════════════════
// PLATFORM DETECTION
// ═══════════════════════════════════════════════════════════════
function detectPlatform() {
const hostname = window.location.hostname;
if (hostname.includes('open.spotify.com')) return 'Spotify';
if (hostname.includes('music.youtube.com')) return 'YouTube Music';
if (hostname.includes('youtube.com')) return 'YouTube';
return 'Unknown';
}
function logSkip(reason) {
console.log('%c[Unloop] ⏭️ SKIP:', 'color: #ef4444; font-weight: bold;', reason);
}
function logAllow(reason) {
console.log('%c[Unloop] ✅ ALLOW:', 'color: #22c55e; font-weight: bold;', reason);
}
// ═══════════════════════════════════════════════════════════════
// SPOTIFY-SPECIFIC DETECTION (2025 Working Selectors)
// ═══════════════════════════════════════════════════════════════
/**
* Extract Spotify track information
* Uses stable data-testid selectors that work in 2025
*/
function getSpotifyTrack() {
if (!isSpotify()) return null;
try {
const title = document.querySelector('[data-testid="context-item-info-title"]')?.innerText;
const artist = document.querySelector('[data-testid="context-item-info-artist"]')?.innerText;
const link = document.querySelector('[data-testid="context-item-info-title"] a');
const trackId = link?.href?.split("/")?.pop()?.split("?")[0];
if (!title || !artist || !trackId) return null;
return {
trackId: `spotify:${trackId}`,
title: title.trim(),
artist: artist.trim()
};
} catch (e) {
log('Spotify track detection error:', e);
return null;
}
}
/**
* Start Spotify song change watcher
* Uses MutationObserver on now-playing widget
*/
function startSpotifyWatcher() {
log('[Spotify] Starting watcher...');
const player = document.querySelector('[data-testid="now-playing-widget"]');
if (!player) {
log('[Spotify] Player not ready, retrying in 1s...');
setTimeout(startSpotifyWatcher, 1000);
return;
}
let lastTrack = null;
const observer = new MutationObserver(() => {
if (!isExtensionAlive() || sessionKilled) return;
const info = getSpotifyTrack();
if (!info) return;
if (lastTrack !== info.trackId) {
lastTrack = info.trackId;
log('[Spotify] Song changed:', info);
// Update state and trigger processing
state.currentVideoId = info.trackId;
processSong();
}
});
observer.observe(player, {
childList: true,
subtree: true,
attributes: true
});
log('[Spotify] Watcher attached successfully');
}
/**
* Skip current track on Spotify
*/
function spotifySkip() {
log('[Spotify] Skipping track...');
const skipBtn = document.querySelector('[data-testid="control-button-skip-forward"]');
if (skipBtn) {
skipBtn.click();
return true;
}
log('[Spotify] Skip button not found');
return false;
}
// ═══════════════════════════════════════════════════════════════
// SPOTIFY-SPECIFIC DETECTION (2025 Working Selectors)
// ═══════════════════════════════════════════════════════════════
/**
* Extract Spotify track information
* Uses stable data-testid selectors that work in 2025
*/
function getSpotifyTrack() {
if (!isSpotify()) return null;
try {
const title = document.querySelector('[data-testid="context-item-info-title"]')?.innerText;
const artist = document.querySelector('[data-testid="context-item-info-artist"]')?.innerText;
const link = document.querySelector('[data-testid="context-item-info-title"] a');
const trackId = link?.href?.split("/")?.pop()?.split("?")[0];
if (!title || !artist || !trackId) return null;
return {
trackId: `spotify:${trackId}`,
title: title.trim(),
artist: artist.trim()
};
} catch (e) {
log('Spotify track detection error:', e);
return null;
}
}
/**
* Start Spotify song change watcher
* Uses MutationObserver on now-playing widget
*/
function startSpotifyWatcher() {
log('[Spotify] Starting watcher...');
const player = document.querySelector('[data-testid="now-playing-widget"]');
if (!player) {
log('[Spotify] Player not ready, retrying in 1s...');
setTimeout(startSpotifyWatcher, 1000);
return;
}
let lastTrack = null;
const observer = new MutationObserver(() => {
if (!isExtensionAlive() || sessionKilled) return;
const info = getSpotifyTrack();
if (!info) return;
if (lastTrack !== info.trackId) {
lastTrack = info.trackId;
log('[Spotify] Song changed:', info);
// Update state and trigger processing
state.currentVideoId = info.trackId;
processSong();
}
});
observer.observe(player, {
childList: true,
subtree: true,
attributes: true
});
log('[Spotify] Watcher attached successfully ✓');
}
// ═══════════════════════════════════════════════════════════════
// PLATFORM DETECTION
// ═══════════════════════════════════════════════════════════════
function isYouTubeMusic() {
return window.location.hostname === 'music.youtube.com';
}
function isYouTube() {
return window.location.hostname === 'www.youtube.com';
}
function isSpotify() {
return window.location.hostname === 'open.spotify.com';
}
function getPlatform() {
if (isSpotify()) return 'Spotify Web';
return isYouTubeMusic() ? 'YouTube Music' : 'YouTube';
}
// ═══════════════════════════════════════════════════════════════
// VIDEO ID EXTRACTION
// ═══════════════════════════════════════════════════════════════
function getVideoId() {
// Spotify: Use dedicated track getter
if (isSpotify()) {
const track = getSpotifyTrack();
return track?.trackId || null;
}
// YouTube/YouTube Music: Extract video ID
// Method 1: URL parameter (works for both platforms)
const urlParams = new URLSearchParams(window.location.search);
const videoId = urlParams.get('v');
if (videoId) return videoId;
// Method 2: YouTube Music player data
if (isYouTubeMusic()) {
try {
const player = document.querySelector('ytmusic-player-bar');
if (player && player.__data?.playerResponse?.videoDetails?.videoId) {
return player.__data.playerResponse.videoDetails.videoId;
}
} catch (e) {}
}
return null;
}
// ═══════════════════════════════════════════════════════════════
// SONG METADATA EXTRACTION
// ═══════════════════════════════════════════════════════════════
function getSongInfo() {
let title = null;
let artist = null;
let channel = null;
if (isSpotify()) {
// Use dedicated Spotify track getter
const track = getSpotifyTrack();
if (track) {
title = track.title;
artist = track.artist;
}
} else if (isYouTubeMusic()) {
// YouTube Music selectors
const titleEl = document.querySelector('.title.ytmusic-player-bar');
const artistEl = document.querySelector('.byline.ytmusic-player-bar a') ||
document.querySelector('.subtitle.ytmusic-player-bar yt-formatted-string a');
title = titleEl?.textContent?.trim();
artist = artistEl?.textContent?.trim();
} else {
// Regular YouTube selectors
const titleEl = document.querySelector('h1.ytd-video-primary-info-renderer') ||
document.querySelector('h1.ytd-watch-metadata yt-formatted-string');
const channelEl = document.querySelector('#channel-name a') ||
document.querySelector('ytd-video-owner-renderer #channel-name yt-formatted-string a');
title = titleEl?.textContent?.trim();
channel = channelEl?.textContent?.trim();
artist = channel; // Use channel as artist for regular YouTube
}
return { title, artist, channel };
}
// ═══════════════════════════════════════════════════════════════
// TOAST NOTIFICATIONS
// ═══════════════════════════════════════════════════════════════
function showToast(message, type = 'info', icon = '🎵') {
// Remove existing toast
const existing = document.querySelector('.unloop-toast');
if (existing) existing.remove();
// Create toast element
const toast = document.createElement('div');
toast.className = `unloop-toast ${type}`;
toast.innerHTML = `
<span class="unloop-toast-icon">${icon}</span>
<span class="unloop-toast-message">${message}</span>
<span class="unloop-toast-badge">Unloop</span>
<div class="unloop-toast-progress">
<div class="unloop-toast-progress-bar"></div>
</div>
`;
document.body.appendChild(toast);
// Trigger animation
requestAnimationFrame(() => {
toast.classList.add('show');
});
// Auto remove
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 400);
}, CONFIG.TOAST_DURATION);
}
// ═══════════════════════════════════════════════════════════════
// SKIP FUNCTIONALITY
// ═══════════════════════════════════════════════════════════════
function skipToNext() {
log('Attempting to skip to next track...');
let nextButton = null;
if (isSpotify()) {
// Spotify Web skip button
nextButton = document.querySelector('[data-testid="control-button-skip-forward"]') ||
document.querySelector('button[aria-label*="Next"]');
if (nextButton) {
nextButton.click();
log('✅ Clicked Spotify next button');
return true;
}
// Fallback: MediaSession API
if ('mediaSession' in navigator && navigator.mediaSession.setActionHandler) {
try {
navigator.mediaSession.setActionHandler('nexttrack', () => {});
log('✅ Triggered MediaSession next');
return true;
} catch (e) {}
}
} else if (isYouTubeMusic()) {
// YouTube Music next button selectors
nextButton = document.querySelector('.next-button') ||
document.querySelector('tp-yt-paper-icon-button.next-button') ||
document.querySelector('[aria-label="Next"]') ||
document.querySelector('.ytmusic-player-bar .next-button');
} else {
// Regular YouTube next button
nextButton = document.querySelector('.ytp-next-button') ||
document.querySelector('a.ytp-next-button');
}
if (nextButton) {
nextButton.click();
log('✅ Clicked next button');
return true;
}
// Fallback: keyboard shortcut (Shift+N)
log('⚠️ No button found, trying keyboard shortcut...');
document.dispatchEvent(new KeyboardEvent('keydown', {
key: 'N',
code: 'KeyN',
shiftKey: true,
bubbles: true
}));
return true;
}
// ═══════════════════════════════════════════════════════════════
// STORAGE OPERATIONS
// ═══════════════════════════════════════════════════════════════
async function loadSettings() {
if (!isExtensionValid()) return;
try {
return new Promise((resolve) => {
safeChrome(
() => chrome.storage.local.get(['enabled', 'settings', 'whitelist', 'blacklist'], (result) => {
if (chrome.runtime.lastError) {
log('Storage error:', chrome.runtime.lastError);
resolve();
return;
}
state.enabled = result.enabled !== false;
state.settings = { ...state.settings, ...result.settings };
state.whitelist = result.whitelist || [];
state.blacklist = result.blacklist || [];
resolve();
}),
null
);
// If safeChrome returns null (context invalidated), resolve anyway
setTimeout(() => resolve(), 100);
});
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] Settings load error:', error);
}
}
}
async function getHistory() {
if (!isExtensionValid()) return {};
try {
return new Promise((resolve) => {
const result = safeChrome(
() => chrome.storage.local.get(['songHistory'], (result) => {
if (chrome.runtime.lastError) {
resolve({});
return;
}
resolve(result.songHistory || {});
}),
{}
);
if (result === null) resolve({});
});
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] History fetch error:', error);
}
return {};
}
}
async function saveSong(videoId, songInfo, listenDuration = 0) {
if (!isExtensionValid()) return;
try {
const history = await getHistory();
const existing = history[videoId];
// Calculate Smart Auto learning metrics
const totalPlays = (existing?.totalPlays || 0) + 1;
const totalSkips = existing?.totalSkips || 0;
const prevAvgDuration = existing?.avgListenDuration || 0;
// Weighted moving average for listen duration
const newAvgDuration = prevAvgDuration > 0
? (prevAvgDuration * 0.7 + listenDuration * 0.3)
: listenDuration;
history[videoId] = {
timestamp: Date.now(),
lastPlayed: Date.now(),
firstPlayed: existing?.firstPlayed || Date.now(),
title: songInfo.title || 'Unknown',
artist: songInfo.artist || 'Unknown',
platform: songInfo.platform || detectPlatform(),
playCount: (existing?.playCount || 0) + 1,
plays: totalPlays, // For CSV export
skips: totalSkips, // For CSV export
totalListeningSeconds: existing?.totalListeningSeconds || 0, // For listening time tracking
// Smart Auto learning data
totalPlays: totalPlays,
totalSkips: totalSkips,
avgListenDuration: newAvgDuration,
quickSkipCount: existing?.quickSkipCount || 0, // Skips within 20 seconds
lastListenDuration: listenDuration
};
// Update stats
return new Promise((resolve) => {
if (!isExtensionValid()) {
resolve();
return;
}
safeChrome(
() => chrome.storage.local.get(['stats'], (result) => {
if (chrome.runtime.lastError || !isExtensionValid()) {
resolve();
return;
}
const stats = result.stats || { listened: 0, skipped: 0 };
stats.listened = (stats.listened || 0) + 1;
safeChrome(
() => chrome.storage.local.set({
songHistory: history,
stats: stats
}, () => {
if (chrome.runtime.lastError) {
log('Save error:', chrome.runtime.lastError);
}
resolve();
}),
null
);
}),
null
);
});
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] Save song error:', error);
}
}
}
/**
* Update song's lastPlayed timestamp for allowed repeats
* Used by memory-fade, semi-strict, artist-smart when they allow a repeat
*/
async function updateSongPlayed(videoId, songInfo) {
if (!isExtensionValid()) return;
try {
const history = await getHistory();
const existing = history[videoId];
if (!existing) {
// Song doesn't exist, treat as new
return saveSong(videoId, songInfo);
}
// Update lastPlayed and increment play count
history[videoId] = {
...existing,
lastPlayed: Date.now(),
playCount: (existing.playCount || 0) + 1,
plays: (existing.plays || 0) + 1,
totalPlays: (existing.totalPlays || 0) + 1
};
return new Promise((resolve) => {
if (!isExtensionValid()) {
resolve();
return;
}
safeChrome(
() => chrome.storage.local.set({ songHistory: history }, () => {
if (chrome.runtime.lastError) {
log('Update song error:', chrome.runtime.lastError);
}
log(`📊 Updated "${songInfo.title}" - plays: ${history[videoId].totalPlays}`);
resolve();
}),
null
);
});
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] Update song error:', error);
}
}
}
async function incrementSkipCount() {
if (!isExtensionValid()) return;
try {
return new Promise((resolve) => {
safeChrome(
() => chrome.storage.local.get(['stats'], (result) => {
if (chrome.runtime.lastError || !isExtensionValid()) {
resolve();
return;
}
const stats = result.stats || { listened: 0, skipped: 0 };
stats.skipped = (stats.skipped || 0) + 1;
safeChrome(
() => chrome.storage.local.set({ stats }, () => {
if (chrome.runtime.lastError) {
log('Skip count error:', chrome.runtime.lastError);
}
resolve();
}),
null
);
}),
null
);
});
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] Skip count error:', error);
}
}
}
// ═══════════════════════════════════════════════════════════════
// CORE DATA ENGINE - FIXES ALL STORAGE ISSUES
// ═══════════════════════════════════════════════════════════════
/**
* ✅ CORE FIX: Update song state consistently
* This function is called EVERY time a song is detected
* Fixes: Artist Discovery, Stats, Smart Learning, Everything
*/
async function updateSongState(platform, trackId, title, artist) {
if (!isContextAlive() || sessionKilled) return;
try {
const result = await chrome.storage.local.get(['history', 'stats']);
const history = result.history || {};
const stats = result.stats || {
totalUniqueSongs: 0,
totalArtists: 0,
totalListeningSeconds: 0,
loopsPrevented: 0,
smartScore: 50
};
// Initialize or update song record
if (!history[trackId]) {
history[trackId] = {
platform: platform,
title: title,
artist: artist,
plays: 0,
skips: 0,
listeningSeconds: 0,
firstPlayed: Date.now(),
lastPlayed: Date.now()
};
}
// Increment play count
history[trackId].plays++;
history[trackId].lastPlayed = Date.now();
// Update stats
stats.totalUniqueSongs = Object.keys(history).length;
// Calculate unique artists (with normalization)
const normalizeArtist = (name) => {
if (!name || name === 'Unknown') return null;
return name.toLowerCase().replace(/,/g, '').replace(/&/g, 'and').replace(/\s+/g, ' ').trim();
};
const artistSet = new Set();
Object.values(history).forEach(song => {
const normalized = normalizeArtist(song.artist);
if (normalized) artistSet.add(normalized);
});
stats.totalArtists = artistSet.size;
// Save to storage
await chrome.storage.local.set({ history, stats });
log(`✅ Data updated: ${stats.totalUniqueSongs} songs, ${stats.totalArtists} artists`);
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] updateSongState error:', error);
}
}
}
/**
* ✅ Add win to recent wins log
* Called when: loop prevented, smart decision, unique unlock
*/
async function addWin(text) {
if (!isContextAlive() || sessionKilled) return;
try {
const result = await chrome.storage.local.get(['recentWins']);
const recentWins = result.recentWins || [];
recentWins.unshift({
text: text,
time: Date.now()
});
// Keep only last 10 wins
await chrome.storage.local.set({
recentWins: recentWins.slice(0, 10)
});
log(`🏆 Win logged: ${text}`);
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] addWin error:', error);
}
}
}
/**
* ✅ Adjust smart learning score
* good = true: user liked our decision
* good = false: user didn't like our decision
*/
async function adjustSmartScore(good) {
if (!isContextAlive() || sessionKilled) return;
try {
const result = await chrome.storage.local.get(['stats']);
const stats = result.stats || { smartScore: 50 };
stats.smartScore = stats.smartScore || 50;
if (good) {
stats.smartScore += 2;
log('📈 Smart score +2');
} else {
stats.smartScore -= 1;
log('📉 Smart score -1');
}
// Clamp between 10-100
stats.smartScore = Math.max(10, Math.min(100, stats.smartScore));
await chrome.storage.local.set({ stats });
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] adjustSmartScore error:', error);
}
}
}
// ═══════════════════════════════════════════════════════════════
// BLOCK & FAVORITE FUNCTIONS (PRODUCTION-GRADE)
// ═══════════════════════════════════════════════════════════════
/**
* 🔒 Safe storage toggle - NEVER overwrites, always merges
* This is the key to reliable persistent storage
*/
async function toggleStore(key, id) {
if (!isContextAlive()) return false;
try {
const data = await chrome.storage.local.get([key]);
const map = data[key] || {};
// Toggle state
if (map[id]) {
delete map[id]; // Remove if exists
} else {
map[id] = true; // Add if doesn't exist
}
await chrome.storage.local.set({ [key]: map });
return map[id] === true; // Return new state
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error(`[Unloop] toggleStore error for ${key}:`, error);
}
return false;
}
}
/**
* 🚫 Toggle block for current song
* - If not blocked → block + skip immediately
* - If blocked → unblock
*/
async function toggleBlockCurrentSong() {
if (!isContextAlive() || sessionKilled) return;
const trackId = state.currentVideoId || getVideoId();
if (!trackId) {
showToast('No song detected', 'error', '❌');
return;
}
try {
const isNowBlocked = await toggleStore('blockedSongs', trackId);
if (isNowBlocked) {
showToast('🚫 Blocked & Skipping', 'skip', '🚫');
log(`🚫 Blocked song: ${trackId}`);
// Immediately skip
setTimeout(() => {
if (isContextAlive()) {
skipToNext();
}
}, 300);
} else {
showToast('✅ Unblocked', 'saved', '✅');
log(`✅ Unblocked song: ${trackId}`);
}
} catch (error) {
if (!isContextInvalidatedError(error)) {
console.error('[Unloop] toggleBlock error:', error);