PL
apps/winzik / src / Mobile / YouTubePages.php · commit 6576d6f
<?phpnamespace App\Mobile;use App\Media\YouTube;use JumPHP\Native\Clipboard;use JumPHP\Native\Shell;/** * The pages of MobileView that get songs from the net: YouTube (search, a pasted link, MP3 or MP4, the queue of the * downloads with their progress, retry / remove) and Spotify (the user's own account: their playlists and liked songs, * each song found on YouTube and downloaded). They call WinZik's own YouTube and SpotifyAccount, as the dialogs of the * computer do (YouTubeForm, SpotifyForm): whatever downloads behind them (yt-dlp, or the phone's own way), the pages are * the same, and what it says when it can not is shown as it is. */trait YouTubePages{    /** what the YouTube page says (the search, an error, what was queued) */    public string $ytStatus = '';    /** a link of Spotify / Deezer being read */    private bool $ytResolving = false;    /** @var list<array{id: string, name: string, count: int}> the user's Spotify playlists */    public array $spLists = [];    private bool $spAsked = false;    public bool $spLoading = false;    public string $spMessage = '';    private function enterYouTube(): void    {        $this->fields['ytQuery'] ??= '';        $yt = $this->wz?->youtube;        if ($yt !== null && $this->ytStatus === '' && $yt->results === []) {            $this->ytStatus = 'Tapez un artiste, un titre, ou collez un lien (YouTube, Spotify, Deezer...).';        }    }    private function ytFormat(): string    {        return ($this->wz?->options['ytFormat'] ?? 'mp3') === 'mp4' ? 'mp4' : 'mp3';    }    /** The search typed (or the link pasted): YouTubeForm::onFindClick. */    public function ytSearch(): void    {        $wz = $this->wz;        $yt = $wz?->youtube;        $typed = trim($this->fields['ytQuery'] ?? '');        $this->field = '';        if ($wz === null || $yt === null) {            return;        }        if ($typed === '') {            $this->ytStatus = 'Tapez un artiste, un titre ou un lien, puis Chercher.';            return;        }        if (preg_match('#^https?://.*(spotify\.com|deezer\.com|deezer\.page\.link)#i', $typed)) {            // Spotify / Deezer (DRM): the same songs, taken from YouTube            $this->ytStatus = 'Lecture du lien...';            $this->ytResolving = true;            $format = $this->ytFormat();            $yt->resolveLink($typed)->then(function (mixed $songs) use ($format): void {                $this->ytResolving = false;                if (!is_array($songs) || $songs === []) {                    $this->ytStatus = "Impossible de savoir quels morceaux sont derrière ce lien : vérifiez qu'il est complet et public, puis réessayez.";                    return;                }                [$added, $here] = $this->queueSongs($songs, $format);                $this->ytStatus = $added . ' morceau(x) ajouté(s) aux téléchargements (pris sur YouTube)' . ($here > 0 ? ' ; ' . $here . ' déjà là' : '') . '.';            }, function (): void {                $this->ytResolving = false;                $this->ytStatus = 'Lien illisible : vérifiez la connexion, puis réessayez.';            });            return;        }        if (preg_match('#^https?://#i', $typed)) {            // any address the downloader knows: downloaded as it is            $this->ytDownload(['id' => $typed, 'title' => $typed, 'url' => $typed, 'duration' => 0, 'channel' => '']);            return;        }        $yt->spotifyId = (string)($wz->options['spotifyId'] ?? '');        $yt->spotifySecret = (string)($wz->options['spotifySecret'] ?? '');        if ($yt->search($typed, 1, $yt->source)) {            $this->ytStatus = '';            $this->scroll['page:youtube'] = 0.0;        } else {            $this->ytStatus = $yt->error !== '' ? $yt->error : ($wz->tools?->describe() ?: 'La recherche ne peut pas démarrer pour l\'instant : réessayez dans un instant.');        }    }    /**     * Songs of a link or of a Spotify playlist into the queue, except those already here (no double).     * @param list<array{title: string, url: string}> $songs     * @return array{0: int, 1: int} queued, already here     */    private function queueSongs(array $songs, string $format): array    {        $wz = $this->wz;        $yt = $wz?->youtube;        if ($wz === null || $yt === null) {            return [0, 0];        }        $yt->forgetFiles();        $playlist = array_map(fn (string $f) => $wz->path($f), $wz->playlist->items);        $added = $here = 0;        foreach ($songs as $s) {            if ($yt->alreadyHave($s['title'], $s['url'], $playlist) !== null) {                $here++;                continue;            }            $yt->download(['id' => $s['url'], 'title' => $s['title'], 'url' => $s['url']], $format, $s['title']);            $added++;        }        $wz->saveQueue();        return [$added, $here];    }    /** A result (or a link) downloaded in the format chosen: YouTubeForm::onGetClick. @param array<string, mixed> $entry */    private function ytDownload(array $entry): void    {        $wz = $this->wz;        $yt = $wz?->youtube;        if ($wz === null || $yt === null) {            return;        }        // what the downloader says when it can not (no ffmpeg on this phone, yt-dlp not there yet), as it says it        $cannot = $this->cannotDownload();        if ($cannot !== '') {            $this->ytStatus = $cannot;            return;        }        $format = $this->ytFormat();        $yt->download(['id' => (string)$entry['url'], 'title' => (string)$entry['title'], 'url' => (string)$entry['url']], $format);        $wz->saveQueue();        $this->ytStatus = '« ' . $entry['title'] . ' » (' . strtoupper($format) . ') ajouté aux téléchargements.';        $wz->notice('Téléchargement : ' . $entry['title'], 3);    }    /** Why nothing can be downloaded now (the backend's own French words), '' when it can. */    private function cannotDownload(): string    {        $yt = $this->wz?->youtube;        if ($yt === null) {            return 'Les téléchargements ne marchent pas sur cet appareil.';        }        return $yt->cannotDownload();    }    /** @return string|null the state of a result already asked ('done', 'error', 'queued'...), null: never */    private function ytJobOf(string $url): ?string    {        foreach (array_reverse($this->wz?->youtube->jobs ?? []) as $job) {            if (($job['url'] ?? '') === $url) {                return (string)$job['state'];            }        }        return null;    }    private function renderYouTube(): void    {        $wz = $this->wz;        $yt = $wz->youtube;        $rows = [];        if ($yt === null) {            $this->renderPage('YouTube', 'Chercher et télécharger', [                ['section', 'Pas disponible ici'],                ['note', "Les téléchargements de YouTube ne marchent pas sur cet appareil pour l'instant : WinZik installé sur l'ordinateur (Linux, Windows) les fait, et la playlist du téléphone lit les fichiers que vous y copiez."],            ]);            return;        }        $rows[] = ['input', 'Rechercher', 'ytQuery', 'Artiste, titre, ou lien collé'];        $rows[] = ['pills', [['Coller un lien', 'ytPaste', null, false, 'paste'], ['Chercher', 'ytFind', null, true, 'search']]];        $rows[] = ['row2', 'search', 'Chercher sur ' . (YouTube::SOURCES[$yt->source] ?? 'YouTube'), 'Toucher pour changer de site', 'more', 'ytSource', 'chevron'];        $format = $this->ytFormat();        $rows[] = ['chipset', [['MP3 · musique', 'ytFormat', 'mp3', $format === 'mp3'], ['MP4 · vidéo', 'ytFormat', 'mp4', $format === 'mp4']]];        if ($yt->searching !== '' || $this->ytResolving) {            $rows[] = ['busy', $this->ytResolving ? 'Lecture du lien...' : 'Recherche de « ' . $yt->searching . ' »...'];        } elseif ($yt->error !== '') {            $rows[] = ['note', $yt->error, $this->col('danger')];        } elseif ($this->ytStatus !== '') {            $rows[] = ['note', $this->ytStatus];        }        if ($yt->jobs !== []) {            // the queue: what downloads now, what waits, what is done (into the play list) or failed (retry)            [$finished, $all, $fraction] = $yt->total();            $rows[] = ['section', 'Téléchargements', $finished . ' / ' . $all . ' · ' . (int)round($fraction * 100) . ' %'];            foreach ($yt->jobs as $i => $job) {                $state = match ($job['state']) {                    'queued' => 'En attente',                    'download' => 'Téléchargement · ' . (int)round($job['progress'] * 100) . ' %',                    'convert' => 'Conversion...',                    'done' => 'Ajouté à la playlist',                    default => 'Erreur : ' . ($job['error'] !== '' ? $job['error'] : 'échec'),                };                $progress = in_array($job['state'], ['done', 'convert'], true) ? 1.0 : (float)$job['progress'];                $rows[] = ['job', $job['title'], strtoupper($job['format']) . ' · ' . $state, $job['state'] === 'error' ? 1.0 : $progress, $i, $job['state']];            }            $over = array_filter($yt->jobs, fn (array $j) => $j['state'] === 'done' || $j['state'] === 'error');            $rows[] = ['pills', [...($over !== [] ? [['Effacer les terminés', 'ytClearDone', null, false]] : []), ['Tout arrêter', 'ytClearAll', null, false]]];        }        if ($yt->results !== [] && $yt->searching === '') {            $rows[] = ['section', 'Résultats', 'Page ' . $yt->page];            foreach ($yt->results as $k => $r) {                $asked = $this->ytJobOf((string)$r['url']);                $sub = YouTube::clock((int)$r['duration']) . ((string)$r['channel'] !== '' ? ' · ' . $r['channel'] : '');                $icon = $asked === 'done' ? 'check' : ($asked !== null && $asked !== 'error' ? 'queue' : 'download');                $rows[] = ['result', $r['title'], $sub, 'ytGet', $k, $icon, 'ytGet', $format === 'mp4' ? 'film' : 'youtube'];            }            $pager = [];            if ($yt->page > 1) {                $pager[] = ['Page précédente', 'ytPage', -1, false];            }            if (count($yt->results) >= YouTube::RESULTS) {                $pager[] = ['Page suivante', 'ytPage', 1, false];            }            if ($pager !== []) {                $rows[] = ['pills', $pager];            }        }        if (($cannot = $this->cannotDownload()) !== '') {            $rows[] = ['note', $cannot, $this->col('danger')];        }        $rows[] = ['note', 'MP3 : ' . $yt->musicDir . ' · MP4 : ' . $yt->videoDir];        $this->renderPage('YouTube', 'Chercher, télécharger en MP3 ou en vidéo', $rows);    }    private function enterSpotify(): void    {        $this->fields['spotifyId'] = (string)($this->wz?->options['spotifyId'] ?? '');        $this->spMessage = '';    }    /** Spotify's playlists of the user (the liked songs first). */    private function spLoad(): void    {        $account = $this->wz?->spotify();        if ($account === null) {            return;        }        $this->spAsked = true;        $this->spLoading = true;        $account->playlists()->then(function (mixed $lists): void {            $this->spLoading = false;            $this->spLists = is_array($lists) ? array_values($lists) : [];        }, function (): void {            $this->spLoading = false;        });    }    /** A playlist: its songs taken from YouTube (those already here are not). SpotifyForm::onImportClick. */    public function spImport(int $index): void    {        $wz = $this->wz;        $account = $wz?->spotify();        $list = $this->spLists[$index] ?? null;        if ($wz === null || $account === null || $list === null) {            return;        }        if ($wz->youtube === null) {            $this->spMessage = "Les téléchargements ne marchent pas sur cet appareil : la playlist ne peut pas être prise sur YouTube ici.";            return;        }        $format = $this->ytFormat();        $this->spLoading = true;        $this->spMessage = 'Lecture de « ' . $list['name'] . ' »...';        $account->songs($list['id'])->then(function (mixed $songs) use ($format, $list): void {            $this->spLoading = false;            $songs = is_array($songs) ? $songs : [];            [$added, $here] = $this->queueSongs($songs, $format);            $this->wz?->notice($added . ' morceau(x) de « ' . $list['name'] . ' » en téléchargement' . ($here > 0 ? ', ' . $here . ' déjà là' : ''), 6);            $this->spMessage = $songs === [] ? 'Cette playlist est vide, ou Spotify ne l\'a pas donnée : réessayez avec « Actualiser ».'                : $added . ' morceau(x) ajouté(s) aux téléchargements' . ($here > 0 ? ' ; ' . $here . ' déjà là (pas de doublon)' : '') . ' : suivez-les dans la page YouTube.';        }, function (): void {            $this->spLoading = false;            $this->spMessage = 'Spotify ne répond pas : vérifiez la connexion, puis réessayez.';        });    }    private function renderSpotify(): void    {        $wz = $this->wz;        $account = $wz->spotify();        $rows = [];        if ($account === null) {            // no Client ID yet: where to get one, typed here            $rows[] = ['section', 'Votre application Spotify'];            $rows[] = ['note', 'WinZik lit vos playlists avec votre propre « Client ID » Spotify (gratuit) : créez une app sur le site des développeurs de Spotify, Redirect URI ' . self::SPOTIFY_REDIRECT . ', cochez « Web API », puis copiez son Client ID ici.'];            $rows[] = ['pills', [['Ouvrir le site', 'spDashboard', null, false], ['Copier l\'adresse', 'spCopy', null, false]]];            $rows[] = ['input', 'Client ID', 'spotifyId', 'Collez votre Client ID'];            $rows[] = ['pills', [['Enregistrer', 'spSaveId', null, true]]];            $this->renderPage('Spotify', 'Mes playlists, prises sur YouTube', $rows);            return;        }        if ($account->connected() && !$this->spAsked) {            $this->spLoad();        }        $state = match ($account->state) {            'waiting' => 'Acceptez dans le navigateur (page de Spotify), puis revenez ici.' . ($account->error !== '' ? '  ' . $account->error : ''),            'connected' => 'Connecté à votre compte Spotify : touchez une playlist pour la télécharger.',            'error' => 'Spotify refuse la connexion (' . $account->error . ') : vérifiez votre Client ID dans les Options, puis « Se connecter ».',            default => 'Reliez WinZik à votre compte Spotify : le navigateur s\'ouvre sur la page de Spotify.',        };        $rows[] = ['note', $state, $account->state === 'error' ? $this->col('danger') : null];        if (!$account->connected()) {            $rows[] = ['pills', [['Se connecter à Spotify', 'spConnect', null, true, 'spotify']]];        } else {            $format = $this->ytFormat();            $rows[] = ['chipset', [['MP3 · musique', 'ytFormat', 'mp3', $format === 'mp3'], ['MP4 · vidéo', 'ytFormat', 'mp4', $format === 'mp4']]];            if ($this->spLoading) {                $rows[] = ['busy', $this->spMessage !== '' ? $this->spMessage : 'Lecture de vos playlists...'];            } elseif ($this->spMessage !== '') {                $rows[] = ['note', $this->spMessage];            }            $rows[] = ['section', 'Mes playlists', count($this->spLists) > 0 ? (string)count($this->spLists) : ''];            foreach ($this->spLists as $k => $p) {                $rows[] = ['row2', $p['id'] === 'liked' ? 'star' : 'list', $p['name'], $p['count'] > 0 ? $p['count'] . ' morceau(x)' : 'Toucher pour la télécharger', 'spImport', $k, 'download'];            }            $rows[] = ['pills', [['Actualiser', 'spReload', null, false], ['Se déconnecter', 'spLogout', null, false]]];        }        if ($wz->youtube !== null && $wz->youtube->jobs !== []) {            [$finished, $all, $fraction] = $wz->youtube->total();            $rows[] = ['progress', 'Téléchargements : ' . $finished . ' / ' . $all, $fraction];            $rows[] = ['row', 'download', 'Voir les téléchargements', 'goto', 'youtube', 'text', 'chevron'];        }        $this->renderPage('Spotify', 'Mes playlists, prises sur YouTube', $rows);    }    /** What a tap does on these pages. */    private function tapYouTube(string $id, mixed $data): bool    {        $wz = $this->wz;        $yt = $wz?->youtube;        switch ($id) {            case 'ytFind':                $this->ytSearch();                return true;            case 'ytPaste':                Clipboard::paste()->then(function (mixed $text): void {                    $text = trim((string)$text);                    if ($text === '') {                        $this->ytStatus = 'Le presse-papiers est vide : copiez d\'abord un lien (Partager > Copier le lien).';                        return;                    }                    $this->fields['ytQuery'] = $text;                    $this->ytSearch();                }, function (): void {                    $this->ytStatus = 'Impossible de lire le presse-papiers : collez le lien dans la case (appui long > Coller).';                });                return true;            case 'ytFormat':                if ($wz !== null) {                    $wz->options['ytFormat'] = $data === 'mp4' ? 'mp4' : 'mp3';                    $wz->touch();                }                return true;            case 'ytSourcePick':                if ($yt !== null && isset(YouTube::SOURCES[(string)$data])) {                    $yt->source = (string)$data;                    $this->closeSheet();                    if (trim($this->fields['ytQuery'] ?? '') !== '' && !preg_match('#^https?://#i', trim($this->fields['ytQuery']))) {                        $this->ytSearch();                    }                }                return true;            case 'ytGet':                $r = $yt?->results[(int)$data] ?? null;                if ($r !== null) {                    $this->ytDownload($r);                }                return true;            case 'ytPage':                if ($yt !== null && ((int)$data > 0 ? $yt->nextPage() : $yt->previousPage())) {                    $this->scroll['page:youtube'] = 0.0;                }                return true;            case 'ytRemove':                $yt?->remove((int)$data);                $wz?->saveQueue();                return true;            case 'ytRetry':                $job = $yt?->jobs[(int)$data] ?? null;                if ($yt !== null && $job !== null && ($job['url'] ?? '') !== '') {                    $yt->remove((int)$data);                    $yt->download(['id' => (string)$job['url'], 'title' => $job['title'], 'url' => (string)$job['url']], $job['format'], (string)($job['key'] ?? ''));                    $wz->saveQueue();                }                return true;            case 'ytClearDone':                $yt?->clearFinished();                return true;            case 'ytClearAll':                $yt?->clearQueue();                $wz?->saveQueue();                return true;            case 'spDashboard':                if (!Shell::openUrl(self::SPOTIFY_DASHBOARD)) {                    $wz?->notice('Ouvrez : ' . self::SPOTIFY_DASHBOARD, 6);                }                return true;            case 'spCopy':                $done = Clipboard::copy(self::SPOTIFY_REDIRECT);                $wz?->notice($done ? 'Copié : ' . self::SPOTIFY_REDIRECT : 'Adresse : ' . self::SPOTIFY_REDIRECT, 4);                return true;            case 'spSaveId':                $this->submitYouTube('spotifyId');                return true;            case 'spConnect':                $account = $wz?->spotify();                if ($account !== null && !$account->login()) {                    $this->spMessage = $account->error;                }                $this->spAsked = false;                return true;            case 'spLogout':                $wz?->spotify()?->logout();                $this->spLists = [];                $this->spAsked = false;                $this->spMessage = '';                return true;            case 'spReload':                $this->spMessage = '';                $this->spLoad();                return true;            case 'spImport':                $this->spImport((int)$data);                return true;        }        return false;    }    /** Entrée in a field of these pages. */    private function submitYouTube(string $id): bool    {        if ($id === 'ytQuery') {            $this->ytSearch();            return true;        }        if ($id === 'spotifyId' && $this->wz !== null && $this->screen === 'spotify') {            $this->wz->options['spotifyId'] = trim($this->fields['spotifyId'] ?? '');            $this->wz->save();            $this->field = '';            $this->spAsked = false;            return true;        }        return false;    }    /** the sheet of the sites to search on */    private function youTubeSheet(): ?array    {        if ($this->sheet !== 'ytSource') {            return null;        }        $current = $this->wz?->youtube->source ?? 'youtube';        $chips = [];        $yt = $this->wz?->youtube;        // without yt-dlp (the phone): the sites its own client knows        $native = $yt !== null && $yt->native();        foreach (YouTube::SOURCES as $key => $label) {            if ($native && !in_array($key, ['youtube', 'ytmusic', 'deezer', 'spotify'], true)) {                continue;            }            $chips[] = [$label, 'ytSourcePick', $key, $key === $current];        }        return [            ['title', 'Chercher sur', 'Spotify et Deezer : chaque morceau est pris sur YouTube'],            ['chipset', $chips],            ['space', 8],        ];    }}