Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4003 lines (3478 loc) · 150 KB
/
Copy pathapp.js
File metadata and controls
4003 lines (3478 loc) · 150 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
/* ============================================================
CONFIG SUPABASE
============================================================ */
const SUPABASE_URL = "https://ostajdhuaxrjrwroayja.supabase.co";
const SUPABASE_ANON_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9zdGFqZGh1YXhyanJ3cm9heWphIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY1OTcyOTQsImV4cCI6MjA5MjE3MzI5NH0.YVzjs5VDHfGC8taGvlGxJiXb8Bh-NnZY1TjNeSTuGsY";
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const BUCKET_NAME = "Fioxisongs";
const APP_VERSION = "1.14.2";
const appVersionEl = document.getElementById("app-version");
if (appVersionEl) appVersionEl.textContent = `v${APP_VERSION}`;
const DEFAULT_COVER =
"data:image/svg+xml;utf8," +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240">' +
'<rect width="240" height="240" fill="#1c1f28"/>' +
'<text x="50%" y="55%" font-size="110" text-anchor="middle" dominant-baseline="middle" fill="#3b82f6">♪</text>' +
"</svg>"
);
/* ============================================================
ICONE DEL PLAYER
Quelle che cambiano con lo stato (play/pausa, modalità ripeti,
cuore) vanno sostituite da JS, quindi stanno qui; le fisse sono
direttamente in app.html. Stesso stile della navigazione: 24x24,
tratto arrotondato per le icone lineari, pieno per i comandi di
trasporto, che così si leggono meglio a colpo d'occhio.
============================================================ */
const ICONS = {
play: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.14v13.72a1 1 0 0 0 1.54.84l10.78-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14Z"/></svg>',
pause:
'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="7" y="4.5" width="3.6" height="15" rx="1.4"/><rect x="13.4" y="4.5" width="3.6" height="15" rx="1.4"/></svg>',
repeat:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 4h10a4 4 0 0 1 4 4v1"/><path d="M17 20H7a4 4 0 0 1-4-4v-1"/><path d="m18 6 3 3-3 3"/><path d="m6 18-3-3 3-3"/></svg>',
// stessa spirale, con l'"1" al centro: si legge come "ripeti questo brano"
repeatOne:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 4h10a4 4 0 0 1 4 4v1"/><path d="M17 20H7a4 4 0 0 1-4-4v-1"/><path d="m18 6 3 3-3 3"/><path d="m6 18-3-3 3-3"/><path d="m10.6 10.4 1.6-1.1v5.4"/></svg>',
heart:
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.29 1.51 4.04 3 5.5l7 7Z"/></svg>',
more: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="1.9"/><circle cx="12" cy="12" r="1.9"/><circle cx="19" cy="12" r="1.9"/></svg>',
};
/* ============================================================
TOAST (feedback errori / conferme, valido su tutte le pagine)
============================================================ */
function showToast(message, type = "error") {
const container = document.getElementById("toast-container");
if (!container) return;
const toast = document.createElement("div");
toast.className = `toast toast-${type}`;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("show"));
setTimeout(() => {
toast.classList.remove("show");
setTimeout(() => toast.remove(), 250);
}, 3500);
}
/* ============================================================
LOADER A TUTTA PAGINA
Viene nascosto solo quando si sa cosa mostrare: il form di login,
oppure la libreria già pronta. Se resta visibile fino al redirect,
il passaggio index.html -> app.html non si vede proprio.
============================================================ */
function hideAppLoader() {
document.getElementById("app-loader")?.classList.add("is-hidden");
}
// rete di sicurezza: se il controllo sessione si pianta (rete assente,
// Supabase irraggiungibile) meglio mostrare la pagina che lasciare
// l'utente bloccato davanti a un loader che gira all'infinito
setTimeout(hideAppLoader, 8000);
/* ============================================================
MODALE CONFERMA ELIMINAZIONE (richiede di scrivere "elimina")
============================================================ */
function confirmDelete({ title, message, onConfirm }) {
const overlay = document.getElementById("confirm-modal");
if (!overlay) return;
const titleEl = document.getElementById("confirm-modal-title");
const messageEl = document.getElementById("confirm-modal-message");
const input = document.getElementById("confirm-modal-input");
const cancelBtn = document.getElementById("confirm-modal-cancel");
const confirmBtn = document.getElementById("confirm-modal-confirm");
titleEl.textContent = title;
messageEl.textContent = message;
input.value = "";
confirmBtn.disabled = true;
overlay.hidden = false;
input.focus();
function onInput() {
confirmBtn.disabled = input.value.trim().toLowerCase() !== "elimina";
}
function onConfirmClick() {
if (confirmBtn.disabled) return;
close();
onConfirm();
}
function onOverlayClick(e) {
if (e.target === overlay) close();
}
function onKeydown(e) {
if (e.key === "Escape") close();
if (e.key === "Enter" && !confirmBtn.disabled) onConfirmClick();
}
function close() {
overlay.hidden = true;
input.removeEventListener("input", onInput);
confirmBtn.removeEventListener("click", onConfirmClick);
cancelBtn.removeEventListener("click", close);
overlay.removeEventListener("click", onOverlayClick);
document.removeEventListener("keydown", onKeydown);
}
input.addEventListener("input", onInput);
confirmBtn.addEventListener("click", onConfirmClick);
cancelBtn.addEventListener("click", close);
overlay.addEventListener("click", onOverlayClick);
document.addEventListener("keydown", onKeydown);
}
/* ============================================================
PWA: registrazione service worker (app installabile)
============================================================ */
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("sw.js").catch((err) => console.error("SW registration failed:", err));
});
}
/* ============================================================
PAGE DETECTION
============================================================ */
// pathname.endsWith("/") copre anche i root path con sottocartella,
// es. GitHub Pages "project site" (jacopofa92.github.io/Fioxify/),
// dove il pathname è "/Fioxify/" e non "/" o "*/index.html"
const isAuthPage =
window.location.pathname.endsWith("index.html") ||
window.location.pathname.endsWith("/");
const isAppPage = window.location.pathname.endsWith("app.html");
const isResetPasswordPage = window.location.pathname.endsWith("reset-password.html");
const REMEMBERED_EMAIL_KEY = "fioxify_remembered_email";
/* legge lo stato di approvazione del profilo dell'utente correntemente
autenticato; usato sia in fase di login sia nel controllo sessione
di app.html per bloccare gli account non ancora approvati */
async function fetchOwnProfileStatus(userId) {
const { data, error } = await supabase
.from("profiles")
.select("status, is_admin")
.eq("id", userId)
.single();
if (error) return { status: "pending", is_admin: false };
return data;
}
/* ============================================================
AUTH PAGE (se usi index.html)
============================================================ */
if (isAuthPage) {
const tabLogin = document.getElementById("tab-login");
const tabRegister = document.getElementById("tab-register");
const loginForm = document.getElementById("login-form");
const registerForm = document.getElementById("register-form");
const forgotForm = document.getElementById("forgot-form");
const loginEmail = document.getElementById("login-email");
const loginPassword = document.getElementById("login-password");
const loginRemember = document.getElementById("login-remember");
const loginBtn = document.getElementById("login-btn");
const loginError = document.getElementById("login-error");
const forgotPasswordLink = document.getElementById("forgot-password-link");
const registerEmail = document.getElementById("register-email");
const registerPassword = document.getElementById("register-password");
const registerPasswordConfirm = document.getElementById("register-password-confirm");
const registerBtn = document.getElementById("register-btn");
const registerError = document.getElementById("register-error");
const forgotEmail = document.getElementById("forgot-email");
const forgotBtn = document.getElementById("forgot-btn");
const forgotError = document.getElementById("forgot-error");
const backToLoginLink = document.getElementById("back-to-login-link");
function showView(name) {
tabLogin.classList.toggle("active", name === "login");
tabRegister.classList.toggle("active", name === "register");
loginForm.classList.toggle("active", name === "login");
registerForm.classList.toggle("active", name === "register");
forgotForm.classList.toggle("active", name === "forgot");
document.getElementById("auth-tabs").hidden = name === "forgot";
}
tabLogin?.addEventListener("click", () => showView("login"));
tabRegister?.addEventListener("click", () => showView("register"));
forgotPasswordLink?.addEventListener("click", () => showView("forgot"));
backToLoginLink?.addEventListener("click", () => showView("login"));
// precompila l'email se l'utente aveva scelto di ricordarla
const rememberedEmail = localStorage.getItem(REMEMBERED_EMAIL_KEY);
if (rememberedEmail) {
loginEmail.value = rememberedEmail;
loginRemember.checked = true;
}
// messaggio mostrato se si arriva qui perché l'account non è (più) approvato
const blockedReason = new URLSearchParams(window.location.search).get("blocked");
if (blockedReason === "pending") {
loginError.textContent = "Il tuo account è in attesa di approvazione da parte di un amministratore.";
} else if (blockedReason === "rejected") {
loginError.textContent = "La tua registrazione non è stata approvata.";
}
// disabilita il bottone e mostra uno spinner + testo di caricamento
// durante le chiamate async, così login/registrazione/recupero non
// sembrano "non aver fatto nulla" mentre aspettano Supabase
function setButtonLoading(btn, loading, loadingText) {
if (loading) {
btn.dataset.originalText = btn.textContent;
btn.disabled = true;
btn.innerHTML = `<span class="btn-spinner" aria-hidden="true"></span>${loadingText}`;
} else {
btn.disabled = false;
btn.textContent = btn.dataset.originalText || btn.textContent;
}
}
// <form>: il submit scatta sia col click sul bottone sia con Invio
// da dentro un input, senza bisogno di gestirlo a mano per ciascuno
loginForm?.addEventListener("submit", async (e) => {
e.preventDefault();
loginError.textContent = "";
const email = loginEmail.value.trim();
const password = loginPassword.value.trim();
if (!email || !password) {
loginError.textContent = "Inserisci email e password.";
return;
}
setButtonLoading(loginBtn, true, "Accesso in corso...");
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
setButtonLoading(loginBtn, false);
loginError.textContent = error.message || "Errore di login.";
return;
}
const profile = await fetchOwnProfileStatus(data.user.id);
if (!profile.is_admin && profile.status !== "approved") {
await supabase.auth.signOut();
setButtonLoading(loginBtn, false);
loginError.textContent =
profile.status === "rejected"
? "La tua registrazione non è stata approvata."
: "Il tuo account è in attesa di approvazione da parte di un amministratore.";
return;
}
if (loginRemember.checked) localStorage.setItem(REMEMBERED_EMAIL_KEY, email);
else localStorage.removeItem(REMEMBERED_EMAIL_KEY);
window.location.href = "app.html";
});
registerForm?.addEventListener("submit", async (e) => {
e.preventDefault();
registerError.textContent = "";
const email = registerEmail.value.trim();
const password = registerPassword.value.trim();
const passwordConfirm = registerPasswordConfirm.value.trim();
if (!email || !password || !passwordConfirm) {
registerError.textContent = "Compila tutti i campi.";
return;
}
if (password.length < 6) {
registerError.textContent = "La password deve avere almeno 6 caratteri.";
return;
}
if (password !== passwordConfirm) {
registerError.textContent = "Le password non coincidono.";
return;
}
setButtonLoading(registerBtn, true, "Verifica in corso...");
const { data: existingStatus } = await supabase.rpc("check_registration_email", {
check_email: email,
});
if (existingStatus) {
setButtonLoading(registerBtn, false);
registerError.textContent =
existingStatus === "pending"
? "Esiste già una registrazione in attesa di approvazione con questa email."
: existingStatus === "approved"
? "Esiste già un account con questa email. Prova ad accedere o usa \"Password dimenticata?\"."
: "La registrazione con questa email non è stata approvata. Contatta l'amministratore.";
return;
}
setButtonLoading(registerBtn, true, "Creazione account...");
const { error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: new URL("index.html", window.location.href).toString(),
},
});
if (error) {
setButtonLoading(registerBtn, false);
registerError.textContent = error.message || "Errore di registrazione.";
return;
}
// niente sessione "pending" in giro: la registrazione richiede
// l'approvazione di un admin prima di poter accedere
await supabase.auth.signOut();
setButtonLoading(registerBtn, false);
registerForm.querySelectorAll("input").forEach((input) => (input.value = ""));
registerError.style.color = "var(--success)";
registerError.textContent =
"Registrazione inviata! Il tuo account è in attesa di approvazione da parte di un amministratore.";
});
forgotForm?.addEventListener("submit", async (e) => {
e.preventDefault();
forgotError.textContent = "";
const email = forgotEmail.value.trim();
if (!email) {
forgotError.textContent = "Inserisci la tua email.";
return;
}
setButtonLoading(forgotBtn, true, "Invio in corso...");
const { error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: new URL("reset-password.html", window.location.href).toString(),
});
setButtonLoading(forgotBtn, false);
if (error) {
forgotError.textContent = error.message || "Errore durante l'invio dell'email.";
return;
}
forgotError.style.color = "var(--success)";
forgotError.textContent = "Se l'email è registrata, riceverai a breve un link per reimpostare la password.";
});
(async () => {
const { data } = await supabase.auth.getSession();
if (!data.session) {
hideAppLoader();
return;
}
const profile = await fetchOwnProfileStatus(data.session.user.id);
if (profile.is_admin || profile.status === "approved") {
// niente hideAppLoader: il loader deve restare finché la pagina
// non cambia, altrimenti si rivede il form di login per un istante
window.location.href = "app.html";
} else {
await supabase.auth.signOut();
hideAppLoader();
}
})();
}
/* ============================================================
RESET PASSWORD PAGE (reset-password.html, aperta dal link
ricevuto via email dopo "Password dimenticata?")
============================================================ */
if (isResetPasswordPage) {
const hint = document.getElementById("reset-password-hint");
const newPasswordInput = document.getElementById("reset-password-new");
const confirmPasswordInput = document.getElementById("reset-password-confirm");
const submitBtn = document.getElementById("reset-password-btn");
const errorEl = document.getElementById("reset-password-error");
const backLink = document.getElementById("reset-password-back-link");
backLink?.addEventListener("click", () => (window.location.href = "index.html"));
function unlockForm() {
hint.textContent = "Scegli una nuova password per il tuo account.";
newPasswordInput.disabled = false;
confirmPasswordInput.disabled = false;
submitBtn.disabled = false;
}
// il link di recupero autentica temporaneamente l'utente e Supabase
// emette l'evento PASSWORD_RECOVERY: solo a quel punto sblocchiamo il form
supabase.auth.onAuthStateChange((event) => {
if (event === "PASSWORD_RECOVERY") unlockForm();
});
// se il link ha già una sessione di recupero valida al caricamento
(async () => {
const { data } = await supabase.auth.getSession();
if (data.session) unlockForm();
else {
setTimeout(async () => {
const { data: retry } = await supabase.auth.getSession();
if (retry.session) unlockForm();
else hint.textContent = "Link di recupero non valido o scaduto. Richiedine uno nuovo dal login.";
}, 2000);
}
})();
submitBtn?.addEventListener("click", async () => {
errorEl.textContent = "";
const password = newPasswordInput.value.trim();
const passwordConfirm = confirmPasswordInput.value.trim();
if (password.length < 6) {
errorEl.textContent = "La password deve avere almeno 6 caratteri.";
return;
}
if (password !== passwordConfirm) {
errorEl.textContent = "Le password non coincidono.";
return;
}
const { error } = await supabase.auth.updateUser({ password });
if (error) {
errorEl.textContent = error.message || "Errore durante l'aggiornamento della password.";
return;
}
await supabase.auth.signOut();
hint.textContent = "Password aggiornata! Ora puoi accedere con la nuova password.";
newPasswordInput.hidden = true;
confirmPasswordInput.hidden = true;
submitBtn.hidden = true;
setTimeout(() => (window.location.href = "index.html"), 1800);
});
}
/* ============================================================
APP PAGE
============================================================ */
if (isAppPage) {
const userEmailSpan = document.getElementById("user-email");
const logoutBtn = document.getElementById("logout-btn");
const exitBtn = document.getElementById("exit-btn");
const changePasswordBtn = document.getElementById("change-password-btn");
const accountMenu = document.querySelector(".account-menu");
const accountMenuBtn = document.getElementById("account-menu-btn");
const accountMenuDropdown = document.getElementById("account-menu-dropdown");
const adminNavTab = document.getElementById("admin-nav-tab");
const adminNavTabMobile = document.getElementById("admin-nav-tab-mobile");
const adminPendingBadge = document.getElementById("admin-pending-badge");
const adminPendingList = document.getElementById("admin-pending-list");
const adminPendingEmpty = document.getElementById("admin-pending-empty");
const adminUsersList = document.getElementById("admin-users-list");
const statMyPlays = document.getElementById("stat-my-plays");
const statMyTracks = document.getElementById("stat-my-tracks");
const statMyUploads = document.getElementById("stat-my-uploads");
const statMyFavorites = document.getElementById("stat-my-favorites");
const statMyTopTracks = document.getElementById("stat-my-top-tracks");
const statPlaysChart = document.getElementById("stat-my-chart");
const fileInput = document.getElementById("file-input");
const uploadBtn = document.getElementById("upload-btn");
const uploadStatus = document.getElementById("upload-status");
const tracksList = document.getElementById("tracks-list");
const tracksSkeleton = document.getElementById("tracks-skeleton");
const emptyMessage = document.getElementById("empty-message");
const audioPlayer = document.getElementById("audio-player");
const currentTrackName = document.getElementById("current-track-name");
const currentTrackArtist = document.getElementById("current-track-artist");
const currentCover = document.getElementById("current-cover");
const searchInput = document.getElementById("search-input");
const sortSelect = document.getElementById("sort-select");
const newPlaylistName = document.getElementById("new-playlist-name");
const newPlaylistBtn = document.getElementById("new-playlist-btn");
const playlistsList = document.getElementById("playlists-list");
const playlistsSearchInput = document.getElementById("playlists-search-input");
const playlistsEmptyMessage = document.getElementById("playlists-empty-message");
const smartPlaylistsPanel = document.getElementById("smart-playlists-panel");
const smartPlaylistsList = document.getElementById("smart-playlists-list");
const newAlbumName = document.getElementById("new-album-name");
const newAlbumBtn = document.getElementById("new-album-btn");
const albumsList = document.getElementById("albums-list");
const albumsSearchInput = document.getElementById("albums-search-input");
const albumsEmptyMessage = document.getElementById("albums-empty-message");
const groupsPanel = document.getElementById("groups-panel");
const groupsList = document.getElementById("groups-list");
const uploadDropzone = document.getElementById("upload-dropzone");
const selectModeBtn = document.getElementById("select-mode-btn");
const groupArtistsBtn = document.getElementById("group-artists-btn");
const bulkBar = document.getElementById("bulk-bar");
const bulkCount = document.getElementById("bulk-count");
const bulkAddPlaylistBtn = document.getElementById("bulk-add-playlist-btn");
const bulkPlaylistMenu = document.getElementById("bulk-playlist-menu");
const bulkAddAlbumBtn = document.getElementById("bulk-add-album-btn");
const bulkAlbumMenu = document.getElementById("bulk-album-menu");
const bulkTagBtn = document.getElementById("bulk-tag-btn");
const bulkDeleteBtn = document.getElementById("bulk-delete-btn");
const bulkCancelBtn = document.getElementById("bulk-cancel-btn");
const bulkTagRow = document.getElementById("bulk-tag-row");
const bulkTagInput = document.getElementById("bulk-tag-input");
const bulkTagApplyBtn = document.getElementById("bulk-tag-apply-btn");
const shuffleBtn = document.getElementById("shuffle-btn");
const prevBtn = document.getElementById("prev-btn");
const nextBtn = document.getElementById("next-btn");
const repeatBtn = document.getElementById("repeat-btn");
const likeCurrentBtn = document.getElementById("like-current-btn");
const playPauseBtn = document.getElementById("play-pause-btn");
const seekBar = document.getElementById("seek-bar");
const currentTimeLabel = document.getElementById("current-time");
const durationLabel = document.getElementById("duration-time");
const waveformCanvas = document.getElementById("waveform-canvas");
const waveformCtx = waveformCanvas?.getContext("2d");
const audioVisualizerCanvas = document.getElementById("audio-visualizer");
const audioVisualizerCtx = audioVisualizerCanvas?.getContext("2d");
const miniPlayer = document.getElementById("mini-player");
const miniCover = document.getElementById("mini-cover");
const miniTrackName = document.getElementById("mini-track-name");
const miniTrackArtist = document.getElementById("mini-track-artist");
const miniPlayPauseBtn = document.getElementById("mini-play-pause-btn");
const miniProgressFill = document.getElementById("mini-progress-fill");
const fullPlayer = document.getElementById("full-player");
const fullPlayerBackdrop = document.getElementById("full-player-backdrop");
const collapsePlayerBtn = document.getElementById("collapse-player-btn");
const trackReactionsEl = document.getElementById("track-reactions");
const playerQueueEl = document.getElementById("player-queue");
const playerQueueList = document.getElementById("player-queue-list");
const playerQueueSource = document.getElementById("player-queue-source");
/* STATE */
let currentUser = null;
let isAdmin = false;
let allTracks = [];
let profilesById = {}; // userId -> { email }
let playlists = [];
let playlistTracksMap = {}; // playlistId -> [trackId, ...]
let albums = [];
let albumTracksMap = {}; // albumId -> [trackId, ...]
let favoriteTrackIds = new Set(); // preferiti PERSONALI dell'utente loggato
let userPlayStats = {}; // trackId -> { count, lastPlayedAt } PERSONALI dell'utente loggato
let userPlayRows = []; // righe grezze degli ascolti, servono al grafico per giorno
let reactionCountsByTrack = {}; // trackId -> { emoji: count } di TUTTI gli utenti
let myReactionsByTrack = {}; // trackId -> Set(emoji) SOLO dell'utente loggato
const REACTION_EMOJIS = ["🔥", "❤️", "😂", "👏", "🤯"];
let currentView = "library"; // "library" | "favorites" | "history" (sotto-viste della pagina Libreria)
let groupByArtist = false; // raggruppamento per artista, applicabile a qualunque vista
let searchTerm = "";
let albumSearchTerm = "";
let playlistSearchTerm = "";
let sortBy = "date"; // "date" | "title" | "artist" | "plays"
let currentQueue = [];
let currentIndex = -1;
let currentQueueLabel = null; // "Album X", "Playlist Y"... mostrato sopra la coda
let nowPlayingId = null;
/* Signed URL dei brani: createSignedUrl genera un token diverso ogni
volta. Il riuso qui serve solo a evitare chiamate inutili all'API di
Supabase entro la validità del link; la cache vera e propria
dell'audio (che evita di riscaricare i byte) è quella sotto,
indicizzata su storage_path invece che sull'URL firmato. */
const signedUrlCache = new Map(); // storage_path -> { url, expiresAt }
const SIGNED_URL_TTL_SECONDS = 3600;
const SIGNED_URL_REFRESH_MARGIN_SECONDS = 120;
async function getTrackAudioUrl(storagePath) {
const cached = signedUrlCache.get(storagePath);
if (cached && cached.expiresAt > Date.now()) return cached.url;
const { data, error } = await supabase.storage
.from(BUCKET_NAME)
.createSignedUrl(storagePath, SIGNED_URL_TTL_SECONDS);
if (error || !data?.signedUrl) {
console.error(error);
return null;
}
signedUrlCache.set(storagePath, {
url: data.signedUrl,
expiresAt: Date.now() + (SIGNED_URL_TTL_SECONDS - SIGNED_URL_REFRESH_MARGIN_SECONDS) * 1000,
});
return data.signedUrl;
}
/* Cache audio persistente lato pagina: le richieste che il tag <audio>
genera da solo (per src/seek) non passano in modo affidabile dal
Service Worker in tutti i browser (su Safari, in particolare,
saltano il fetch handler del SW). Scaricando qui con fetch() e
mettendo in Cache API teniamo il file per storage_path (stabile,
a differenza del signed URL che cambia token ogni volta) e lo
riproduciamo da un blob locale: niente nuova richiesta di rete
per un brano già ascoltato, indipendentemente dal browser. */
const AUDIO_CACHE_NAME = "fioxify-audio-v1";
let currentObjectUrl = null;
async function getTrackAudioBlob(storagePath, signedUrl) {
if (!("caches" in window)) {
const response = await fetch(signedUrl);
return response.blob();
}
const cache = await caches.open(AUDIO_CACHE_NAME);
const cached = await cache.match(storagePath);
if (cached) return cached.blob();
const response = await fetch(signedUrl);
if (response.ok) await cache.put(storagePath, response.clone());
return response.blob();
}
let shuffleOn = false;
// ordine di riproduzione casuale calcolato una volta sola: prima si
// sorteggiava un indice a ogni cambio brano, quindi la coda mostrata non
// corrispondeva a quello che sarebbe partito davvero (e un brano poteva
// ripetersi mentre altri non uscivano mai)
let shuffleOrder = [];
let shufflePos = -1;
let shuffleSignature = "";
let repeatMode = "none"; // "none" | "all" | "one"
let expandedPlaylistId = null;
let expandedAlbumId = null;
let expandedGroupKey = null;
let selectionMode = false;
let selectedTrackIds = new Set();
currentCover.src = DEFAULT_COVER;
/* TAG SYSTEM UPLOAD */
let currentTags = [];
const tagsContainer = document.getElementById("tags-container");
const tagInput = document.getElementById("tag-input");
function renderUploadTags() {
tagsContainer.innerHTML = "";
currentTags.forEach((tag, index) => {
tagsContainer.appendChild(buildEditableTagChip(tag, index));
});
}
function buildEditableTagChip(tag, index) {
const el = document.createElement("div");
el.className = "tag";
el.appendChild(document.createTextNode(tag));
const removeSpan = document.createElement("span");
removeSpan.className = "tag-remove";
removeSpan.dataset.index = index;
removeSpan.textContent = "×";
el.appendChild(removeSpan);
return el;
}
function renderTagChips(container, tags) {
container.innerHTML = "";
tags.forEach((t) => {
const span = document.createElement("span");
span.className = "tag";
span.textContent = t;
container.appendChild(span);
});
}
tagInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && tagInput.value.trim() !== "") {
e.preventDefault();
const newTag = tagInput.value.trim();
if (!currentTags.includes(newTag)) {
currentTags.push(newTag);
renderUploadTags();
}
tagInput.value = "";
}
});
tagsContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("tag-remove")) {
const index = e.target.dataset.index;
currentTags.splice(index, 1);
renderUploadTags();
}
});
/* SESSION CHECK */
(async () => {
const { data } = await supabase.auth.getSession();
if (!data.session) {
window.location.href = "index.html";
return;
}
currentUser = data.session.user;
const profile = await fetchOwnProfileStatus(currentUser.id);
if (!profile.is_admin && profile.status !== "approved") {
await supabase.auth.signOut();
window.location.href = `index.html?blocked=${profile.status === "rejected" ? "rejected" : "pending"}`;
return;
}
isAdmin = !!profile.is_admin;
userEmailSpan.textContent = currentUser.email || "Utente";
if (isAdmin) {
adminNavTab.hidden = false;
adminNavTabMobile.hidden = false;
await refreshAdminPendingBadge();
}
await loadData();
// solo ora la libreria è piena: nascondere prima farebbe vedere
// l'app montarsi a pezzi
hideAppLoader();
subscribeToRealtimeUpdates();
registerMediaSessionActions();
})();
/* ============================================================
CAMBIO PASSWORD (riusa il flusso nativo "recupero password":
invia all'utente loggato un'email con il link per impostarne
una nuova, senza bisogno di un provider email esterno)
============================================================ */
changePasswordBtn?.addEventListener("click", async () => {
const { error } = await supabase.auth.resetPasswordForEmail(currentUser.email, {
redirectTo: new URL("reset-password.html", window.location.href).toString(),
});
if (error) {
showToast(error.message || "Errore durante l'invio dell'email.", "error");
return;
}
showToast("Ti abbiamo inviato un'email per impostare la nuova password.", "success");
});
/* ============================================================
ADMIN: approvazione nuove registrazioni
============================================================ */
async function refreshAdminPendingBadge() {
const { count } = await supabase
.from("profiles")
.select("id", { count: "exact", head: true })
.eq("status", "pending");
const n = count || 0;
adminPendingBadge.hidden = n === 0;
adminPendingBadge.textContent = String(n);
}
async function setProfileStatus(userId, status) {
const { error } = await supabase.from("profiles").update({ status }).eq("id", userId);
if (error) {
showToast(error.message || "Operazione non riuscita.", "error");
return false;
}
return true;
}
function renderAdminUserRow(profile, { showActions }) {
const li = document.createElement("li");
li.className = "playlist-item";
const row = document.createElement("div");
row.className = "playlist-item-row";
const email = document.createElement("span");
email.className = "admin-user-email";
email.textContent = profile.email;
row.appendChild(email);
const pill = document.createElement("span");
pill.className = `admin-status-pill status-${profile.status}`;
pill.textContent = profile.status === "approved" ? "Approvato" : profile.status === "rejected" ? "Rifiutato" : "In attesa";
row.appendChild(pill);
if (showActions) {
const actions = document.createElement("div");
actions.className = "playlist-actions";
const approveBtn = document.createElement("button");
approveBtn.className = "icon-btn";
approveBtn.textContent = "✓ Approva";
approveBtn.addEventListener("click", async () => {
if (await setProfileStatus(profile.id, "approved")) {
showToast(`${profile.email} è stato approvato.`, "success");
await renderAdmin();
}
});
const rejectBtn = document.createElement("button");
rejectBtn.className = "icon-btn";
rejectBtn.textContent = "✕ Rifiuta";
rejectBtn.addEventListener("click", async () => {
if (await setProfileStatus(profile.id, "rejected")) {
showToast(`${profile.email} è stato rifiutato.`, "success");
await renderAdmin();
}
});
actions.appendChild(approveBtn);
actions.appendChild(rejectBtn);
row.appendChild(actions);
}
li.appendChild(row);
return li;
}
async function renderAdmin() {
if (!isAdmin) return;
const { data, error } = await supabase
.from("profiles")
.select("id, email, status, is_admin, created_at")
.order("created_at", { ascending: false });
if (error) {
showToast(error.message || "Impossibile caricare gli utenti.", "error");
return;
}
const pending = data.filter((p) => p.status === "pending");
const others = data.filter((p) => p.status !== "pending");
adminPendingList.innerHTML = "";
pending.forEach((p) => adminPendingList.appendChild(renderAdminUserRow(p, { showActions: true })));
adminPendingEmpty.textContent = pending.length === 0 ? "Nessuna richiesta in attesa." : "";
adminUsersList.innerHTML = "";
others.forEach((p) => adminUsersList.appendChild(renderAdminUserRow(p, { showActions: false })));
await refreshAdminPendingBadge();
}
/* ============================================================
STATISTICHE PERSONALI (visibili a tutti)
Si costruiscono con i dati che loadData() ha già in memoria:
gli ascolti sono per definizione solo i propri (track_plays ha
una RLS che limita la lettura alle proprie righe), quindi non
serve nessuna chiamata aggiuntiva.
============================================================ */
function renderStats() {
if (!statMyPlays) return;
const playedIds = Object.keys(userPlayStats);
const totalPlays = playedIds.reduce((sum, id) => sum + (userPlayStats[id]?.count || 0), 0);
statMyPlays.textContent = totalPlays;
statMyTracks.textContent = playedIds.length;
statMyUploads.textContent = allTracks.filter((t) => t.user_id === currentUser.id).length;
statMyFavorites.textContent = favoriteTrackIds.size;
const topTracks = allTracks
.filter((t) => (userPlayStats[t.id]?.count || 0) > 0)
.sort((a, b) => userPlayStats[b.id].count - userPlayStats[a.id].count)
.slice(0, 10);
renderStatList(statMyTopTracks, topTracks, (t) => ({
name: t.artist ? `${t.title} — ${t.artist}` : t.title,
value: `${userPlayStats[t.id].count} ascolti`,
}));
renderStatBarChart(buildLast30DaysPlays());
}
// un punto per giorno, anche quelli a zero: un grafico con i giorni
// vuoti saltati darebbe una lettura falsata dell'andamento
function buildLast30DaysPlays() {
const days = [];
const counts = {};
userPlayRows.forEach((row) => {
const day = (row.played_at || "").slice(0, 10);
if (day) counts[day] = (counts[day] || 0) + 1;
});
const today = new Date();
for (let i = 29; i >= 0; i--) {
const d = new Date(today);
d.setDate(today.getDate() - i);
const key = d.toISOString().slice(0, 10);
days.push({ day: key, plays: counts[key] || 0 });
}
return days;
}
function renderStatList(listEl, rows, mapRow) {
if (!listEl) return;
listEl.innerHTML = "";
if (!rows || !rows.length) {
const li = document.createElement("li");
li.className = "stat-empty";
li.textContent = "Ancora nessun dato.";
listEl.appendChild(li);
return;
}
rows.forEach((row) => {
const { name, value } = mapRow(row);
const li = document.createElement("li");
const nameSpan = document.createElement("span");
nameSpan.className = "stat-list-name";
nameSpan.textContent = name;
const valueSpan = document.createElement("span");
valueSpan.className = "stat-list-value";
valueSpan.textContent = value;
li.appendChild(nameSpan);
li.appendChild(valueSpan);
listEl.appendChild(li);
});
}
function renderStatBarChart(days) {
if (!statPlaysChart) return;
statPlaysChart.innerHTML = "";
// i giorni sono sempre 30, anche vuoti: il grafico è "senza dati" solo
// se in tutto il periodo non c'è un solo ascolto
if (!days.length || days.every((d) => !d.plays)) {
statPlaysChart.innerHTML = '<p class="stat-empty">Ancora nessun ascolto negli ultimi 30 giorni.</p>';
return;
}
const total = days.reduce((sum, d) => sum + d.plays, 0);
const maxPlays = Math.max(...days.map((d) => d.plays));
const peak = days.find((d) => d.plays === maxPlays);
const head = document.createElement("div");
head.className = "stat-chart-head";
const totalEl = document.createElement("span");
totalEl.className = "stat-chart-total";
totalEl.textContent = `${total} ${total === 1 ? "ascolto" : "ascolti"}`;
const peakEl = document.createElement("span");
peakEl.className = "stat-chart-peak";
peakEl.textContent = `record ${maxPlays} il ${formatDayLabel(peak.day)}`;
head.appendChild(totalEl);
head.appendChild(peakEl);
const bars = document.createElement("div");
bars.className = "stat-chart-bars";
days.forEach((d, i) => {
const bar = document.createElement("div");
const isToday = i === days.length - 1;
bar.className = "stat-bar" + (d.plays ? "" : " is-empty") + (isToday ? " is-today" : "");
// i giorni a zero restano come trattino sulla base: si vede che il
// giorno esiste ma non ci sono ascolti, invece di sparire
bar.style.height = d.plays ? `${Math.max((d.plays / maxPlays) * 100, 8)}%` : "2px";
// qui la cascata copre tutti i giorni: sono barre strette e
// affiancate, e l'effetto è proprio il riempirsi da sinistra
bar.style.setProperty("--row-index", String(i));
bar.title = `${formatDayLabel(d.day)}: ${d.plays} ${d.plays === 1 ? "ascolto" : "ascolti"}`;
bars.appendChild(bar);
});
const axis = document.createElement("div");
axis.className = "stat-chart-axis";
const from = document.createElement("span");
from.textContent = formatDayLabel(days[0].day);
const to = document.createElement("span");
to.textContent = "oggi";
axis.appendChild(from);
axis.appendChild(to);
statPlaysChart.appendChild(head);
statPlaysChart.appendChild(bars);
statPlaysChart.appendChild(axis);
}
function formatDayLabel(isoDay) {
const [, month, day] = isoDay.split("-");
return `${day}/${month}`;
}
/* ============================================================
AGGIORNAMENTO IN TEMPO REALE (libreria condivisa)
Quando un altro utente carica/modifica/elimina un brano, una
playlist o un album, la vista si aggiorna da sola senza dover
ricaricare la pagina.
============================================================ */
function notifyNewTrack(track) {
if (!track) return;
if (track.user_id === currentUser.id) return; // chi carica sa già di averlo fatto
if (track.is_private) return;
const who = profilesById[track.user_id]?.email || "Qualcuno";
showToast(`${who} ha aggiunto "${track.title}"`, "success");