PT
apps/winzik / src / Media / Lrclib.php · commit 6576d6f
<?phpnamespace App\Media;use App\Model\Lyrics;use JumPHP\Async\Task;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;/** * Synchronised lyrics from LRCLIB (https://lrclib.net, a free database of lyrics with their times, open to everyone): * by artist, title and length first, else a search; its LRC ("[mm:ss.xx] line") becomes a .LYR of 2001. Through the * engine's Http: the same in the browser (LRCLIB answers to pages too). A generic client name, nothing about the user. */final class Lrclib{    public const URL = 'https://lrclib.net/api';    public function __construct(private Http $http)    {    }    /** @return Task Lyrics|null (null: nothing synchronised for this song) */    public function find(string $artist, string $title, float $duration): Task    {        $result = new Task();        $headers = ['Accept' => 'application/json', 'User-Agent' => 'WinZik (https://jumphp.net/winzik)'];        $done = function (?Lyrics $l) use ($result): void {            $result->settle($l);        };        $search = function () use ($artist, $title, $headers, $done): void {            $q = http_build_query(['q' => trim("$artist $title")]);            $this->http->request('GET', self::URL . "/search?$q", null, $headers, 20)->then(function (HttpResponse $r) use ($done): void {                foreach ($r->ok() && is_array($r->json()) ? (array)$r->json() : [] as $hit) {                    $lyrics = is_array($hit) ? self::fromLrc((string)($hit['syncedLyrics'] ?? '')) : null;                    if ($lyrics !== null) {                        $done($lyrics);                        return;                    }                }                $done(null);            }, fn () => $done(null));        };        if ($artist === '' || $title === '') {            $search();            return $result;        }        $q = http_build_query(['artist_name' => $artist, 'track_name' => $title] + ($duration > 0 ? ['duration' => (int)round($duration)] : []));        $this->http->request('GET', self::URL . "/get?$q", null, $headers, 20)->then(function (HttpResponse $r) use ($done, $search): void {            $data = $r->ok() ? $r->json() : null;            $lyrics = is_array($data) ? self::fromLrc((string)($data['syncedLyrics'] ?? '')) : null;            $lyrics !== null ? $done($lyrics) : $search();        }, fn () => $search());        return $result;    }    /** LRC ("[01:02.50] a line", several times on a line possible) as the lines of a .LYR; null without times. */    public static function fromLrc(string $lrc): ?Lyrics    {        $lines = [];        foreach (preg_split('/\r?\n/', $lrc) ?: [] as $row) {            if (!preg_match_all('/\[(\d+):(\d+(?:[.:]\d+)?)\]/', $row, $m, PREG_SET_ORDER)) {                continue;            }            $text = trim((string)preg_replace('/\[[^\]]*\]/', '', $row));            foreach ($m as $t) {                $lines[] = [(int)$t[1] * 60 + (float)str_replace(':', '.', $t[2]), $text === '' ? ' ' : $text];            }        }        if ($lines === []) {            return null;        }        usort($lines, fn (array $a, array $b) => $a[0] <=> $b[0]);        return new Lyrics($lines);    }}