938 lines
32 KiB
TypeScript
938 lines
32 KiB
TypeScript
import { Component, OnInit, OnDestroy, signal, computed, effect, inject, ElementRef, AfterViewInit } from '@angular/core';
|
|
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
|
|
import { ActivatedRoute, Router } from '@angular/router';
|
|
import { AlertController, ToastController, GestureController } from '@ionic/angular';
|
|
import { CantiService, Canto } from '../../services/canti.service';
|
|
import { LyricsParserService, ParsedSection } from '../../services/lyrics-parser.service';
|
|
import { ThemeService } from '../../services/theme.service';
|
|
import { SettingsService } from '../../services/settings.service';
|
|
import { ConnectivityService } from '../../services/connectivity.service';
|
|
import { PlaylistService } from '../../services/playlist.service';
|
|
import { YoutubePlayerService } from '../../services/youtube-player.service';
|
|
import { MyCantiService } from '../../services/my-canti.service';
|
|
import { ComunitaService } from '../../services/comunita.service';
|
|
import { StatsService } from '../../services/stats.service';
|
|
import { FaceDetectorService } from '../../services/face-detector.service';
|
|
|
|
@Component({
|
|
selector: 'app-player',
|
|
templateUrl: './player.page.html',
|
|
styleUrls: ['./player.page.scss'],
|
|
standalone: false
|
|
})
|
|
export class PlayerPage implements OnInit, AfterViewInit, OnDestroy {
|
|
public canto = signal<Canto | null>(null);
|
|
public activeSongId = signal<string | null>(null);
|
|
|
|
/** true = show chords (accordi mode), false = text only */
|
|
public showChords = signal<boolean>(false);
|
|
|
|
/** Autoscroll standard */
|
|
public isAutoscrolling = signal<boolean>(false);
|
|
public autoscrollSpeed = signal<number>(2);
|
|
private autoscrollTimer: any = null;
|
|
|
|
/** Font size scale factor (1.0 = default) */
|
|
public fontSize = signal<number>(1.0);
|
|
|
|
/** Parsed sections for the current view mode */
|
|
public parsedSections = computed<ParsedSection[]>(() => {
|
|
const c = this.canto();
|
|
if (!c) return [];
|
|
|
|
let sections: ParsedSection[];
|
|
// For local songs, if accordi is missing but testo has chords, use parseAccordi on testo
|
|
const hasChordsInText = !c.accordi && c.testo?.includes('[');
|
|
|
|
if ((this.showChords() && c.accordi) || (this.showChords() && hasChordsInText)) {
|
|
sections = this.lyricsParser.parseAccordi(c.accordi || c.testo);
|
|
} else {
|
|
sections = this.lyricsParser.parseText(c.testo);
|
|
}
|
|
|
|
// CRITICAL FIX: If sections are empty but we have text, force a manual section
|
|
if (sections.length === 0 && c.testo) {
|
|
const fallbackLines = c.testo.split('\n')
|
|
.filter(l => l.trim().length > 0)
|
|
.map(l => ({
|
|
text: l.trim(),
|
|
segments: [{ text: l.trim() }]
|
|
}));
|
|
|
|
if (fallbackLines.length > 0) {
|
|
sections = [{
|
|
type: 'verse',
|
|
lines: fallbackLines
|
|
}];
|
|
}
|
|
}
|
|
|
|
// Apply transposition if in chords mode
|
|
if (this.showChords()) {
|
|
return this.lyricsParser.transposeSections(sections, this.transposeAmount());
|
|
}
|
|
|
|
return sections;
|
|
});
|
|
|
|
public transposeAmount = signal<number>(0);
|
|
|
|
public currentLineIndex = signal<number>(0);
|
|
public math = Math;
|
|
public youtubePlayerService = inject(YoutubePlayerService);
|
|
private channel = new BroadcastChannel('karaoke_sync');
|
|
|
|
// Rimossi stati di freeze fragili per garantire fluidità e stabilità 100% dell'avanzamento
|
|
|
|
private readonly MIN_FONT = 0.6;
|
|
private readonly MAX_FONT = 5.0;
|
|
private readonly FONT_STEP = 0.15;
|
|
|
|
private initialPinchDistance: number | null = null;
|
|
private initialFontSize: number = 1.0;
|
|
|
|
private lastMatchedTranscript: string = '';
|
|
|
|
// --- Logic State ---
|
|
private lastAdvanceTimestamp: number = 0; // For safety cooldown
|
|
private readonly ADVANCE_COOLDOWN = 1500; // 1.5 seconds min
|
|
|
|
public lastScrollBlock = signal<'start' | 'center'>('start');
|
|
private lastProcessedTranscript: string = '';
|
|
private initialStartTime: number = 0;
|
|
|
|
private route = inject(ActivatedRoute);
|
|
public router = inject(Router);
|
|
public cantiService = inject(CantiService);
|
|
private lyricsParser = inject(LyricsParserService);
|
|
private alertCtrl = inject(AlertController);
|
|
private toastCtrl = inject(ToastController);
|
|
public themeService = inject(ThemeService);
|
|
public settingsService = inject(SettingsService);
|
|
public connectivityService = inject(ConnectivityService);
|
|
public playlistService = inject(PlaylistService);
|
|
public comunitaService = inject(ComunitaService);
|
|
private myCantiService = inject(MyCantiService);
|
|
private statsService = inject(StatsService);
|
|
private gestureCtrl = inject(GestureController);
|
|
private el = inject(ElementRef);
|
|
private sanitizer = inject(DomSanitizer);
|
|
public faceDetector = inject(FaceDetectorService);
|
|
|
|
public enableCameraNavigation = signal<boolean>(false);
|
|
|
|
private songStartTime: number = 0;
|
|
|
|
constructor() {
|
|
// Sync transposition automatically to display/projection page
|
|
effect(() => {
|
|
const amount = this.transposeAmount();
|
|
this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount });
|
|
});
|
|
|
|
// Sync mode from global settings
|
|
effect(() => {
|
|
this.showChords.set(this.settingsService.showChordsDefault());
|
|
}, { allowSignalWrites: true });
|
|
|
|
// Auto-scroll logic: keep active line in view
|
|
effect(() => {
|
|
const idx = this.currentLineIndex();
|
|
// Wait for DOM update
|
|
setTimeout(() => {
|
|
const activeElem = document.querySelector('.lyric-line.active');
|
|
if (activeElem) {
|
|
// Usa l'allineamento calcolato dinamico (start per manuale a pagine, center per automatico e standard)
|
|
// Usiamo behavior: 'auto' poiché il container CSS ha già 'scroll-behavior: smooth', evitando blocchi/conflitti nativi Chromium
|
|
const scrollBlock = this.lastScrollBlock();
|
|
activeElem.scrollIntoView({ behavior: 'auto', block: scrollBlock });
|
|
}
|
|
}, 100);
|
|
});
|
|
|
|
effect(() => {
|
|
const c = this.canto();
|
|
if (c) {
|
|
if (this.playlistService.autoPlayPlaylist()) {
|
|
setTimeout(() => this.initPlayer(c.id), 500);
|
|
}
|
|
}
|
|
});
|
|
|
|
// Reactive song loading based on activeSongId and available canti lists
|
|
effect(() => {
|
|
const id = this.activeSongId();
|
|
const allCanti = this.cantiService.canti();
|
|
const myCantiList = this.myCantiService.myCanti();
|
|
const comunitaCantiPers = this.comunitaService.comunitaCantiPersonali();
|
|
|
|
if (id) {
|
|
let found: any = null;
|
|
if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
|
|
found = comunitaCantiPers.find(c => c.id === id);
|
|
}
|
|
if (!found) {
|
|
found = allCanti.find(c => c.id === id);
|
|
}
|
|
if (!found) {
|
|
found = myCantiList.find(c => c.id === id);
|
|
}
|
|
if (!found) {
|
|
found = comunitaCantiPers.find(c => c.id === id);
|
|
}
|
|
|
|
if (found) {
|
|
const current = this.canto();
|
|
// Avoid duplicate triggers for the same song
|
|
if (!current || current.id !== found.id) {
|
|
this.logPreviousSongTime();
|
|
this.canto.set(found);
|
|
this.songStartTime = Date.now();
|
|
this.cantiService.getStorage()?.set('last_song_id', id);
|
|
this.channel.postMessage({ type: 'SYNC_CANTO', id: found.id });
|
|
}
|
|
}
|
|
}
|
|
}, { allowSignalWrites: true });
|
|
|
|
// Reactive transposition and speed determination based on canto, playlists, and community settings
|
|
effect(() => {
|
|
const c = this.canto();
|
|
if (!c) return;
|
|
|
|
const activePlaylistId = this.playlistService.activePlaylistId();
|
|
let playlistSongSetting: any = null;
|
|
if (activePlaylistId) {
|
|
const pl = this.playlistService.playlists().find(p => p.id === activePlaylistId);
|
|
if (pl && pl.songSettings && pl.songSettings[c.id]) {
|
|
playlistSongSetting = pl.songSettings[c.id];
|
|
}
|
|
}
|
|
|
|
if (playlistSongSetting) {
|
|
this.transposeAmount.set(playlistSongSetting.tonalita !== undefined ? playlistSongSetting.tonalita : 0);
|
|
this.autoscrollSpeed.set(playlistSongSetting.speed !== undefined ? playlistSongSetting.speed : 2);
|
|
} else if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
|
|
const settings = this.comunitaService.comunitaCantiSettings();
|
|
const songSetting = settings.find(s => s.id_canti === c.id_canti || s.id_canti === Number(c.id));
|
|
if (songSetting) {
|
|
if (songSetting.tonalita !== undefined) {
|
|
this.transposeAmount.set(songSetting.tonalita);
|
|
} else {
|
|
this.transposeAmount.set(0);
|
|
}
|
|
if (songSetting.speed !== undefined && songSetting.speed > 0) {
|
|
const mappedSpeed = Math.max(1, Math.min(10, Math.round(songSetting.speed / 100)));
|
|
this.autoscrollSpeed.set(mappedSpeed);
|
|
} else {
|
|
this.autoscrollSpeed.set(2);
|
|
}
|
|
} else {
|
|
this.transposeAmount.set(0);
|
|
this.autoscrollSpeed.set(2);
|
|
}
|
|
} else {
|
|
this.transposeAmount.set(0);
|
|
this.autoscrollSpeed.set(2);
|
|
}
|
|
}, { allowSignalWrites: true });
|
|
}
|
|
|
|
ngAfterViewInit() {
|
|
const gestureX = this.gestureCtrl.create({
|
|
el: this.el.nativeElement,
|
|
direction: 'x',
|
|
gestureName: 'swipe-song-x',
|
|
canStart: (ev) => {
|
|
const target = ev.event.target as HTMLElement;
|
|
return !target.closest('ion-footer') && !target.closest('ion-header');
|
|
},
|
|
onEnd: (ev) => {
|
|
if (Math.abs(ev.deltaX) > 60) {
|
|
if (ev.deltaX > 0) {
|
|
this.prev();
|
|
} else {
|
|
this.next();
|
|
}
|
|
}
|
|
}
|
|
});
|
|
gestureX.enable();
|
|
}
|
|
|
|
|
|
private getAllLines(): any[] {
|
|
const sections = this.parsedSections();
|
|
const allLines: any[] = [];
|
|
for (const s of sections) {
|
|
for (const l of s.lines) {
|
|
allLines.push(l);
|
|
}
|
|
}
|
|
return allLines;
|
|
}
|
|
|
|
ngOnInit() {
|
|
this.route.queryParams.subscribe(async params => {
|
|
let id = params['id'];
|
|
if (params['t']) {
|
|
this.initialStartTime = parseInt(params['t'], 10);
|
|
}
|
|
if (!id) {
|
|
const checkStorage = async () => {
|
|
let storage = this.cantiService.getStorage();
|
|
while (!storage) {
|
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
storage = this.cantiService.getStorage();
|
|
}
|
|
const storedId = await storage.get('last_song_id');
|
|
if (storedId && !this.activeSongId()) {
|
|
this.activeSongId.set(storedId);
|
|
}
|
|
};
|
|
checkStorage();
|
|
} else {
|
|
this.activeSongId.set(id);
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
|
|
onTouchStart(event: TouchEvent) {
|
|
if (event.touches.length === 2) {
|
|
this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
|
|
this.initialFontSize = this.fontSize();
|
|
}
|
|
}
|
|
|
|
onTouchMove(event: TouchEvent) {
|
|
if (event.touches.length === 2 && this.initialPinchDistance !== null) {
|
|
event.preventDefault();
|
|
const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
|
|
const ratio = currentDistance / this.initialPinchDistance;
|
|
let newSize = this.initialFontSize * ratio;
|
|
newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
|
|
if (Math.abs(newSize - this.fontSize()) > 0.01) {
|
|
this.fontSize.set(newSize);
|
|
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
|
|
}
|
|
}
|
|
}
|
|
|
|
onTouchEnd() {
|
|
this.initialPinchDistance = null;
|
|
}
|
|
|
|
private getDistance(t1: Touch, t2: Touch): number {
|
|
return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
|
|
}
|
|
|
|
toggleChords() {
|
|
this.showChords.update(v => !v);
|
|
this.channel.postMessage({ type: 'SYNC_CHORDS', showChords: this.showChords() });
|
|
this.transposeAmount.set(0);
|
|
}
|
|
|
|
transposeUp() {
|
|
this.transposeAmount.update(v => v + 1);
|
|
|
|
const c = this.canto();
|
|
if (c) {
|
|
const dbSpeed = this.autoscrollSpeed() * 100;
|
|
this.statsService.updateSongSettings(c.id_canti, this.transposeAmount(), dbSpeed);
|
|
|
|
const activePlaylistId = this.playlistService.activePlaylistId();
|
|
if (activePlaylistId) {
|
|
this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
|
|
}
|
|
}
|
|
}
|
|
|
|
transposeDown() {
|
|
this.transposeAmount.update(v => v - 1);
|
|
|
|
const c = this.canto();
|
|
if (c) {
|
|
const dbSpeed = this.autoscrollSpeed() * 100;
|
|
this.statsService.updateSongSettings(c.id_canti, this.transposeAmount(), dbSpeed);
|
|
|
|
const activePlaylistId = this.playlistService.activePlaylistId();
|
|
if (activePlaylistId) {
|
|
this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
|
|
}
|
|
}
|
|
}
|
|
|
|
zoomIn() {
|
|
if (this.fontSize() < this.MAX_FONT) {
|
|
this.fontSize.update(v => Math.min(v + this.FONT_STEP, this.MAX_FONT));
|
|
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
|
|
}
|
|
}
|
|
|
|
zoomOut() {
|
|
if (this.fontSize() > this.MIN_FONT) {
|
|
this.fontSize.update(v => Math.max(v - this.FONT_STEP, this.MIN_FONT));
|
|
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
|
|
}
|
|
}
|
|
|
|
toggleAudio() {
|
|
if (this.youtubePlayerService.currentCantoId() === this.canto()?.id) {
|
|
this.youtubePlayerService.togglePlayPause();
|
|
} else {
|
|
const c = this.canto();
|
|
if (c) {
|
|
this.playlistService.autoPlayPlaylist.set(true);
|
|
this.initPlayer(c.id);
|
|
}
|
|
}
|
|
}
|
|
|
|
stopVideo(event?: Event) {
|
|
if (event) event.stopPropagation();
|
|
this.youtubePlayerService.stop();
|
|
this.playlistService.autoPlayPlaylist.set(false);
|
|
}
|
|
|
|
onSeek(event: any) {
|
|
this.youtubePlayerService.seekTo(event.detail.value);
|
|
}
|
|
|
|
restart() {
|
|
this.currentLineIndex.set(0);
|
|
this.youtubePlayerService.seekTo(0);
|
|
this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });
|
|
this.lastScrollBlock.set('center');
|
|
}
|
|
|
|
public calculatePageStepSize(): number {
|
|
try {
|
|
const container = document.querySelector('.lyrics-container') as HTMLElement;
|
|
if (!container) return 3; // Ritorno generico se il contenitore non è pronto
|
|
|
|
const containerRect = container.getBoundingClientRect();
|
|
const visibleTop = Math.max(containerRect.top, 0);
|
|
let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);
|
|
|
|
const footer = document.querySelector('ion-footer') as HTMLElement;
|
|
if (footer) {
|
|
const footerRect = footer.getBoundingClientRect();
|
|
if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, footerRect.top);
|
|
}
|
|
}
|
|
|
|
const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
|
|
if (floatingBar) {
|
|
const barRect = floatingBar.getBoundingClientRect();
|
|
if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, barRect.top);
|
|
}
|
|
}
|
|
|
|
// Calcoliamo la reale altezza visibile
|
|
const visibleHeight = Math.max(0, visibleBottom - visibleTop);
|
|
|
|
const lineElems = document.querySelectorAll('.lyric-line');
|
|
|
|
if (lineElems.length === 0) return 3;
|
|
|
|
let totalHeight = 0;
|
|
lineElems.forEach((el: any) => {
|
|
totalHeight += el.clientHeight;
|
|
});
|
|
const avgLineHeight = totalHeight / lineElems.length;
|
|
|
|
if (avgLineHeight <= 0) return 3;
|
|
|
|
// Quante righe entrano effettivamente nella vista REALE non oscurata dello schermo
|
|
const linesPerPage = Math.floor(visibleHeight / avgLineHeight);
|
|
|
|
// Passo di scorrimento: una pagina intera pulita (zero sovrapposizione) per far sparire il testo precedente
|
|
const pageStep = Math.max(1, linesPerPage);
|
|
|
|
console.log('[PageScroll] Calcolo dinamico dello scorrimento a pagina (Area visibile depurata):', {
|
|
visibleHeight,
|
|
avgLineHeight,
|
|
linesPerPage,
|
|
pageStep
|
|
});
|
|
|
|
return pageStep;
|
|
} catch (e) {
|
|
console.warn('[PageScroll] Impossibile calcolare dinamicamente lo step di pagina:', e);
|
|
return 3; // Fallback di emergenza
|
|
}
|
|
}
|
|
|
|
public getVisibleLineIndices(): number[] {
|
|
try {
|
|
const container = document.querySelector('.lyrics-container') as HTMLElement;
|
|
if (!container) return [];
|
|
|
|
const containerRect = container.getBoundingClientRect();
|
|
const visibleTop = Math.max(containerRect.top, 0);
|
|
let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);
|
|
|
|
// Sottrai l'altezza dell'eventuale footer o barra sovrapposti ad alto z-index
|
|
const footer = document.querySelector('ion-footer') as HTMLElement;
|
|
if (footer) {
|
|
const footerRect = footer.getBoundingClientRect();
|
|
if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, footerRect.top);
|
|
}
|
|
}
|
|
|
|
const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
|
|
if (floatingBar) {
|
|
const barRect = floatingBar.getBoundingClientRect();
|
|
if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, barRect.top);
|
|
}
|
|
}
|
|
|
|
const lineElems = document.querySelectorAll('.lyric-line');
|
|
const visibleIndices: number[] = [];
|
|
|
|
for (let i = 0; i < lineElems.length; i++) {
|
|
const el = lineElems[i] as HTMLElement;
|
|
const rect = el.getBoundingClientRect();
|
|
|
|
// Consideriamo la riga visibile se la sua metà verticale è all'interno dei limiti visibili reali
|
|
const lineMiddle = (rect.top + rect.bottom) / 2;
|
|
if (lineMiddle >= visibleTop && lineMiddle <= visibleBottom) {
|
|
visibleIndices.push(i);
|
|
}
|
|
}
|
|
return visibleIndices;
|
|
} catch (e) {
|
|
console.warn('[PageScroll] Errore nel recupero degli indici delle righe visibili:', e);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
private calculateNextPageStartIndex(): number {
|
|
try {
|
|
const container = document.querySelector('.lyrics-container') as HTMLElement;
|
|
if (!container) return this.currentLineIndex() + 1;
|
|
|
|
const containerRect = container.getBoundingClientRect();
|
|
// Assicuriamoci che il limite inferiore non superi l'altezza reale della finestra
|
|
let visibleBottom = Math.min(containerRect.bottom, window.innerHeight || document.documentElement.clientHeight);
|
|
|
|
// Trova la posizione del footer o di qualunque elemento sovrapposto in fondo
|
|
const footer = document.querySelector('ion-footer') as HTMLElement;
|
|
if (footer) {
|
|
const footerRect = footer.getBoundingClientRect();
|
|
if (footerRect.height > 0 && window.getComputedStyle(footer).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, footerRect.top);
|
|
}
|
|
}
|
|
|
|
const floatingBar = document.querySelector('.floating-autoscroll-bar') as HTMLElement;
|
|
if (floatingBar) {
|
|
const barRect = floatingBar.getBoundingClientRect();
|
|
if (barRect.height > 0 && window.getComputedStyle(floatingBar).display !== 'none') {
|
|
visibleBottom = Math.min(visibleBottom, barRect.top);
|
|
}
|
|
}
|
|
|
|
// Aumentiamo il margine di tolleranza a 24px (o più) per essere sicuri
|
|
// di non perdere mai una riga parzialmente coperta. Meglio rileggere una riga
|
|
// in cima alla pagina successiva che perderla completamente a causa dello zoom.
|
|
const visibleLimitY = visibleBottom - 24;
|
|
const lineElems = document.querySelectorAll('.lyric-line');
|
|
|
|
const totalLines = this.getTotalLines();
|
|
const currentIdx = this.currentLineIndex();
|
|
|
|
// Scansiona le righe successive a quella attiva e trova la prima riga che non era COMPLETAMENTE visibile
|
|
let foundNextIdx = -1;
|
|
for (let i = currentIdx + 1; i < lineElems.length; i++) {
|
|
const el = lineElems[i] as HTMLElement;
|
|
const rect = el.getBoundingClientRect();
|
|
|
|
// Se la parte inferiore della riga ricade sotto l'area di visualizzazione utile (coperta da footer/log)
|
|
if (rect.bottom > visibleLimitY) {
|
|
foundNextIdx = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (foundNextIdx !== -1) {
|
|
console.log('[PageScroll] Riga coperta/tagliata in fondo rilevata. Diventerà la prima riga della nuova pagina:', foundNextIdx);
|
|
return foundNextIdx;
|
|
}
|
|
|
|
// Se tutto era perfettamente visibile, avanza dello step di pagina calcolato standard
|
|
const step = this.calculatePageStepSize();
|
|
return Math.min(totalLines - 1, currentIdx + step);
|
|
} catch (e) {
|
|
console.warn('[PageScroll] Errore nel calcolo dinamico dell\'indice della pagina successiva:', e);
|
|
return this.currentLineIndex() + 1;
|
|
}
|
|
}
|
|
|
|
next(isAutomatic: boolean = false, isVisual: boolean = false) {
|
|
this.lastAdvanceTimestamp = Date.now();
|
|
|
|
const totalLines = this.getTotalLines();
|
|
const prevIdx = this.currentLineIndex();
|
|
|
|
if (prevIdx < totalLines - 1) {
|
|
let nextIdx: number;
|
|
if (isAutomatic) {
|
|
if (prevIdx === 0) {
|
|
// Sulla prima pagina, avanziamo alla metà della pagina (inizio della seconda metà)
|
|
const visibleIndices = this.getVisibleLineIndices();
|
|
if (visibleIndices.length > 0) {
|
|
const halfLength = Math.max(1, Math.ceil(visibleIndices.length / 2));
|
|
nextIdx = Math.min(totalLines - 1, visibleIndices[halfLength] !== undefined ? visibleIndices[halfLength] : halfLength);
|
|
} else {
|
|
const pageSize = this.calculatePageStepSize();
|
|
const halfPageSize = Math.max(1, Math.ceil(pageSize / 2));
|
|
nextIdx = Math.min(totalLines - 1, prevIdx + halfPageSize);
|
|
}
|
|
} else {
|
|
// Avanzamento acustico automatico: avanza l'intera pagina lasciando centrale la riga di riferimento
|
|
nextIdx = this.calculateNextPageStartIndex();
|
|
}
|
|
this.lastScrollBlock.set('center');
|
|
} else if (this.settingsService.karaokePageScrollMode() || isVisual) {
|
|
// Modalità manuale a pagine (o trigger visuale): calcolo analitico preciso per non perdere righe coperte
|
|
nextIdx = this.calculateNextPageStartIndex();
|
|
this.lastScrollBlock.set('start');
|
|
} else {
|
|
// Avanzamento riga per riga standard manuale
|
|
nextIdx = prevIdx + 1;
|
|
this.lastScrollBlock.set('center');
|
|
}
|
|
|
|
this.currentLineIndex.set(nextIdx);
|
|
this.channel.postMessage({ type: 'SYNC_INDEX', index: nextIdx });
|
|
}
|
|
}
|
|
|
|
// Metodi di validazione e freeze rimossi per migliorare affidabilità e prevenire blocchi permanenti
|
|
|
|
prev(isVisual: boolean = false) {
|
|
this.lastAdvanceTimestamp = Date.now();
|
|
|
|
const prevIdx = this.currentLineIndex();
|
|
if (prevIdx > 0) {
|
|
const isPageMode = this.settingsService.karaokePageScrollMode() || isVisual;
|
|
const stepSize = isPageMode ? this.calculatePageStepSize() : 1;
|
|
const nextIdx = Math.max(0, prevIdx - stepSize);
|
|
|
|
if (nextIdx === 0) {
|
|
// Se torniamo all'inizio, allineiamo in alto
|
|
this.lastScrollBlock.set('start');
|
|
} else if (isPageMode) {
|
|
this.lastScrollBlock.set('start');
|
|
} else {
|
|
this.lastScrollBlock.set('center');
|
|
}
|
|
|
|
this.currentLineIndex.set(nextIdx);
|
|
this.channel.postMessage({ type: 'SYNC_INDEX', index: nextIdx });
|
|
}
|
|
}
|
|
|
|
nextSong() {
|
|
let list = this.playlistService.activeListIds();
|
|
if (list.length === 0) {
|
|
list = this.cantiService.canti().map(c => c.id);
|
|
}
|
|
|
|
const currentId = this.canto()?.id;
|
|
if (!currentId) return;
|
|
|
|
const index = list.indexOf(currentId);
|
|
if (index >= 0 && index < list.length - 1) {
|
|
const nextId = list[index + 1];
|
|
this.router.navigate(['/player'], { queryParams: { id: nextId } });
|
|
} else {
|
|
this.playlistService.autoPlayPlaylist.set(false);
|
|
}
|
|
}
|
|
|
|
prevSong() {
|
|
let list = this.playlistService.activeListIds();
|
|
if (list.length === 0) {
|
|
list = this.cantiService.canti().map(c => c.id);
|
|
}
|
|
|
|
const currentId = this.canto()?.id;
|
|
if (!currentId) return;
|
|
|
|
const index = list.indexOf(currentId);
|
|
if (index > 0) {
|
|
const prevId = list[index - 1];
|
|
this.router.navigate(['/player'], { queryParams: { id: prevId } });
|
|
}
|
|
}
|
|
|
|
private goToSong(id: string) {
|
|
this.router.navigate([], {
|
|
relativeTo: this.route,
|
|
queryParams: { id },
|
|
queryParamsHandling: 'merge'
|
|
});
|
|
this.restart();
|
|
}
|
|
|
|
getTotalLines(): number {
|
|
return this.parsedSections().reduce((acc, s) => acc + s.lines.length, 0);
|
|
}
|
|
|
|
isActiveLine(sectionIdx: number, lineIdx: number): boolean {
|
|
let flatIdx = 0;
|
|
for (let s = 0; s < this.parsedSections().length; s++) {
|
|
for (let l = 0; l < this.parsedSections()[s].lines.length; l++) {
|
|
if (s === sectionIdx && l === lineIdx) {
|
|
return flatIdx === this.currentLineIndex();
|
|
}
|
|
flatIdx++;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
async openDisplay() {
|
|
const url = this.router.serializeUrl(
|
|
this.router.createUrlTree(['/display'], { queryParams: { id: this.canto()?.id } })
|
|
);
|
|
const absoluteUrl = window.location.origin + window.location.pathname + url;
|
|
const win = window.open(absoluteUrl, '_blank', 'width=1024,height=768');
|
|
if (!win) {
|
|
const alert = await this.alertCtrl.create({
|
|
header: 'Proiezione TV',
|
|
message: 'Il browser ha bloccato l\'apertura della finestra. Vuoi copiare il link da inviare alla TV?',
|
|
buttons: [
|
|
{ text: 'Annulla', role: 'cancel' },
|
|
{ text: 'Copia Link', handler: () => { this.copyToClipboard(absoluteUrl); } }
|
|
]
|
|
});
|
|
await alert.present();
|
|
}
|
|
}
|
|
|
|
async copyToClipboard(text: string) {
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
const toast = await this.toastCtrl.create({
|
|
message: 'Link copiato negli appunti!',
|
|
duration: 2000,
|
|
position: 'top',
|
|
color: 'secondary'
|
|
});
|
|
await toast.present();
|
|
} catch (err) {}
|
|
}
|
|
|
|
openYoutube() {
|
|
const videoId = this.cantiService.getYoutubeId(this.canto()?.link_youtube);
|
|
if (videoId) {
|
|
window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
|
|
}
|
|
}
|
|
|
|
async editOrCloneCanto() {
|
|
const c = this.canto();
|
|
if (!c) return;
|
|
|
|
if (
|
|
this.settingsService.comunitaEnabled() &&
|
|
this.settingsService.showEditor() &&
|
|
this.comunitaService.comunitaCode() &&
|
|
!c.id.startsWith('my_')
|
|
) {
|
|
// Clone the song: Title: <original title>
|
|
const clonedTitle = c.titolo;
|
|
|
|
const clonedCanto = await this.myCantiService.saveCanto({
|
|
titolo: clonedTitle,
|
|
autore: c.autore,
|
|
link_youtube: c.link_youtube,
|
|
testo: c.testo || c.accordi || '',
|
|
accordi: c.accordi || c.testo || '',
|
|
id_momenti: c.id_momenti || []
|
|
});
|
|
|
|
// Redirect to the edit page for the newly cloned song
|
|
this.router.navigate(['/propose-canto'], { queryParams: { editId: clonedCanto.id } });
|
|
} else {
|
|
// Standard edit path
|
|
this.router.navigate(['/propose-canto'], { queryParams: { editId: c.id } });
|
|
}
|
|
}
|
|
|
|
private initPlayer(id: string) {
|
|
if (!this.youtubePlayerService.isPlayerSupported()) {
|
|
return;
|
|
}
|
|
const startT = this.initialStartTime;
|
|
this.initialStartTime = 0; // Reset
|
|
|
|
this.youtubePlayerService.setMediaSessionCallbacks(
|
|
() => this.nextSong(),
|
|
() => this.prevSong()
|
|
);
|
|
|
|
this.youtubePlayerService.initPlayer(
|
|
id,
|
|
startT,
|
|
() => {
|
|
if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
|
|
this.nextSong();
|
|
} else {
|
|
this.playlistService.autoPlayPlaylist.set(false);
|
|
}
|
|
},
|
|
() => {
|
|
if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
|
|
setTimeout(() => this.nextSong(), 1000);
|
|
} else {
|
|
this.playlistService.autoPlayPlaylist.set(false);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
togglePlaylistSelection() {
|
|
const c = this.canto();
|
|
if (c) {
|
|
this.playlistService.toggleSongSelection(c.id);
|
|
}
|
|
}
|
|
|
|
getCommunitySongNumber(canto: any): string | null {
|
|
if (!canto) return null;
|
|
if (!this.comunitaService.comunitaCode() || !this.comunitaService.isFilterActive()) return null;
|
|
const cantiInfo = this.comunitaService.comunitaCantiInfo();
|
|
const info = cantiInfo.find(x => x.id_canti === canto.id_canti || x.id_canti === Number(canto.id));
|
|
return info && info.num_canto ? info.num_canto.toString() : null;
|
|
}
|
|
|
|
getMySongNumber(canto: any): number {
|
|
if (!canto || !canto.id) return 0;
|
|
const index = this.myCantiService.myCanti().findIndex(c => c.id === canto.id);
|
|
return index !== -1 ? index + 1 : 0;
|
|
}
|
|
|
|
toggleAutoscroll() {
|
|
if (this.isAutoscrolling()) {
|
|
this.stopAutoscroll();
|
|
} else {
|
|
this.startAutoscroll();
|
|
}
|
|
}
|
|
|
|
startAutoscroll() {
|
|
this.isAutoscrolling.set(true);
|
|
if (this.autoscrollTimer) clearInterval(this.autoscrollTimer);
|
|
|
|
const scrollEl = this.el.nativeElement.querySelector('.lyrics-container');
|
|
if (!scrollEl) return;
|
|
|
|
this.autoscrollTimer = setInterval(() => {
|
|
if (!this.isAutoscrolling()) {
|
|
clearInterval(this.autoscrollTimer);
|
|
return;
|
|
}
|
|
const step = this.autoscrollSpeed() * 0.25;
|
|
scrollEl.scrollTop += step;
|
|
}, 40);
|
|
}
|
|
|
|
stopAutoscroll() {
|
|
this.isAutoscrolling.set(false);
|
|
if (this.autoscrollTimer) {
|
|
clearInterval(this.autoscrollTimer);
|
|
this.autoscrollTimer = null;
|
|
}
|
|
}
|
|
|
|
increaseAutoscrollSpeed() {
|
|
this.autoscrollSpeed.update(s => Math.min(10, s + 1));
|
|
const c = this.canto();
|
|
if (c) {
|
|
const dbSpeed = this.autoscrollSpeed() * 100;
|
|
this.statsService.updateSongSettings(c.id_canti, this.transposeAmount(), dbSpeed);
|
|
|
|
const activePlaylistId = this.playlistService.activePlaylistId();
|
|
if (activePlaylistId) {
|
|
this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
|
|
}
|
|
}
|
|
}
|
|
|
|
decreaseAutoscrollSpeed() {
|
|
this.autoscrollSpeed.update(s => Math.max(1, s - 1));
|
|
const c = this.canto();
|
|
if (c) {
|
|
const dbSpeed = this.autoscrollSpeed() * 100;
|
|
this.statsService.updateSongSettings(c.id_canti, this.transposeAmount(), dbSpeed);
|
|
|
|
const activePlaylistId = this.playlistService.activePlaylistId();
|
|
if (activePlaylistId) {
|
|
this.playlistService.updatePlaylistSongSettings(activePlaylistId, c.id, this.transposeAmount(), this.autoscrollSpeed());
|
|
}
|
|
}
|
|
}
|
|
|
|
private logPreviousSongTime() {
|
|
const c = this.canto();
|
|
if (c && this.songStartTime > 0) {
|
|
const timeSpent = (Date.now() - this.songStartTime) / 1000;
|
|
this.statsService.logSongView(c.id_canti, timeSpent);
|
|
this.songStartTime = 0;
|
|
}
|
|
}
|
|
|
|
toggleCameraNavigation() {
|
|
if (this.enableCameraNavigation()) {
|
|
this.stopCameraNavigation();
|
|
} else {
|
|
this.startCameraNavigation();
|
|
}
|
|
}
|
|
|
|
startCameraNavigation() {
|
|
this.enableCameraNavigation.set(true);
|
|
|
|
setTimeout(async () => {
|
|
const videoEl = document.querySelector('#face-preview-video') as HTMLVideoElement;
|
|
if (videoEl) {
|
|
try {
|
|
await this.faceDetector.start(videoEl, (direction) => {
|
|
console.log(`[PlayerPage] Head tilt trigger received: ${direction}`);
|
|
if (direction === 'next') {
|
|
this.next(false, true);
|
|
} else {
|
|
this.prev(true);
|
|
}
|
|
});
|
|
} catch (e) {
|
|
this.enableCameraNavigation.set(false);
|
|
alert('Impossibile accedere alla fotocamera. Assicurati di aver concesso i permessi e di usare HTTPS.');
|
|
}
|
|
}
|
|
}, 300);
|
|
}
|
|
|
|
stopCameraNavigation() {
|
|
this.enableCameraNavigation.set(false);
|
|
this.faceDetector.stop();
|
|
}
|
|
|
|
ngOnDestroy() {
|
|
this.stopAutoscroll();
|
|
this.logPreviousSongTime();
|
|
this.stopCameraNavigation();
|
|
this.channel.close();
|
|
}
|
|
}
|