ES
apps/winzik / src / Core / LyricsDownload.php · commit 6576d6f
<?phpnamespace App\Core;use App\Model\Lyrics;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;/** * The download of the lyrics of a song from the old WinZik site (Download() of winster5.bas, shown by Form20): * two tries, <ARTIST>/<ARTIST> - <TITLE>.LYR then <ARTIST>/<TITLE>.LYR, in upper case like findlyr_Click did. * winster.free.fr is gone: its files are read from the Internet Archive. Never blocks: Http answers in a later frame. */final class LyricsDownload{    /** the try (Form20.Label10 "Essai n°") */    public int $attempt = 0;    /** what is going on (Label7 "Action en cours") */    public string $action = 'Recherche du réseau...';    /** 0..1 (the yellow bar Label8) */    public float $progress = 0.0;    public ?bool $ok = null;    public bool $cancelled = false;    /** @var ?\Closure(bool): void */    public ?\Closure $onDone = null;    /** @var list<string> the addresses tried */    public array $urls = [];    public function __construct(private Http $http, public string $artist, public string $title, public string $target)    {    }    /** @return list<string> the two addresses of 2001 for this song */    public static function candidates(string $artist, string $title): array    {        $a = self::encode(strtoupper($artist));        $t = self::encode(strtoupper($title));        return [            WinZik::ARCHIVE . WinZik::LYRICS_ROOT . $a . '/' . $a . '%20-%20' . $t . '.LYR',            WinZik::ARCHIVE . WinZik::LYRICS_ROOT . $a . '/' . $t . '.LYR',        ];    }    private static function encode(string $text): string    {        return str_replace('%2B', '+', rawurlencode(\App\Model\Text::toCp1252($text)));    }    public function start(): void    {        if ($this->artist === '' || $this->title === '') {            $this->finish(false, "Il faut l'artiste et le titre (tag ID3)");            return;        }        $this->urls = self::candidates($this->artist, $this->title);        $this->attempt = 0;        $this->tryNext();    }    private function tryNext(): void    {        if ($this->cancelled) {            return;        }        if ($this->attempt >= count($this->urls)) {            $this->finish(false, 'Aucune parole disponible');            return;        }        $url = $this->urls[$this->attempt];        $this->attempt++;        $this->action = "Recherche de l'hote...";        $this->progress = max($this->progress, 0.15 + 0.35 * ($this->attempt - 1));        $this->http->get($url)->then(            fn (HttpResponse $r) => $this->answer($r),            function (\Throwable $e): void {                if (!$this->cancelled) {                    $this->finish(false, 'Probleme de connection...');                }            },        );    }    private function answer(HttpResponse $r): void    {        if ($this->cancelled) {            return;        }        $this->progress += 0.2;        $this->action = 'Hote trouver';        $body = $r->body;        // a page instead of the file ("<!DOCTYPE": Erreur !!!) or no [LYR]: the other address        if (!$r->ok() || str_starts_with(ltrim($body), '<') || Lyrics::parse($body) === null) {            $this->action = 'Erreur !!!';            $this->tryNext();            return;        }        $this->action = 'Télechargement des paroles';        @mkdir(dirname($this->target), 0777, true);        $saved = @file_put_contents($this->target, $body) !== false;        $this->finish($saved, $saved ? 'Telechargement terminer' : "Impossible d'écrire " . basename($this->target));    }    private function finish(bool $ok, string $action): void    {        $this->ok = $ok;        $this->action = $action;        $this->progress = 1.0;        if ($this->onDone !== null) {            ($this->onDone)($ok);        }    }    public function cancel(): void    {        $this->cancelled = true;        $this->ok = false;        $this->action = 'Annulé';    }    public function finished(): bool    {        return $this->ok !== null;    }    /** Each frame (nothing to do: Http's answers come by themselves; the bar moves a little while waiting). */    public function update(): void    {        if ($this->ok === null && $this->progress < 0.9) {            $this->progress += 0.002;        }    }}