IT
apps/winzik / src / Media / Covers.php · commit 6576d6f
<?phpnamespace App\Media;use App\Model\Id3Tag;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;/** * The picture of a song (its album's cover, or the artist) and what is known of its record, for the card of the play * list: the cover in the MP3 itself (ID3v2 APIC, yt-dlp puts the video's picture there), else Deezer's public search * (no account) by artist and title: the cover of the album, its title, its release date. Kept in the cache. */final class Covers{    /** @var array<string, bool> songs being looked for */    private array $asked = [];    public function __construct(private string $dir, private ?Http $http)    {    }    private function key(string $file): string    {        return $this->dir . '/' . md5($file);    }    /** The picture of a song, null while it is being looked for (or when there is none). */    public function picture(string $file, Id3Tag $tag): ?string    {        $key = $this->key($file);        foreach (['jpg', 'png'] as $ext) {            if (is_file("$key.$ext")) {                return "$key.$ext";            }        }        if ($tag->picture !== '') {            @mkdir($this->dir, 0777, true);            $ext = str_starts_with($tag->picture, "\\x89PNG") ? 'png' : 'jpg';            file_put_contents("$key.$ext", $tag->picture);            $tag->picture = '';     // in the cache now: not kept in memory            return "$key.$ext";        }        $this->lookUp($file, $tag);        return null;    }    /** @return array{album?: string, date?: string, artist?: string} what Deezer says of the record */    public function info(string $file): array    {        $json = @file_get_contents($this->key($file) . '.json');        $data = is_string($json) ? json_decode($json, true) : null;        return is_array($data) ? $data : [];    }    /** Letters and digits only, lower case, without accents: "Été (Remix)" -> "eteremix". */    private static function plain(string $s): string    {        return (string)preg_replace('/[^a-z0-9]/', '', \App\Model\Text::fold($s));    }    /** Is Deezer's answer the song: its title in ours (or ours in its), and the same artist when the tag gives one? */    public static function sameSong(Id3Tag $tag, string $fileName, string $title, string $artist): bool    {        $t = self::plain($title);        $ours = self::plain($tag->title !== '' ? $tag->title : $fileName);        if ($t === '' || $ours === '' || (!str_contains($ours, $t) && !str_contains($t, $ours))) {            return false;        }        if ($tag->artist === '') {            return true;        }        $a = self::plain($artist);        $mine = self::plain($tag->artist);        return $a !== '' && $mine !== '' && (str_contains($mine, $a) || str_contains($a, $mine));    }    private function lookUp(string $file, Id3Tag $tag): void    {        $key = $this->key($file);        // the songs WinZik brings (assets/music) are its own: no record of them anywhere, never asked        if ($this->http === null || isset($this->asked[$file]) || is_file("$key.json") || str_contains(strtr($file, '\\', '/'), '/assets/music/')) {            return;        }        $this->asked[$file] = true;        $name = pathinfo($file, PATHINFO_FILENAME);        $q = $tag->artist !== '' && $tag->title !== '' ? $tag->artist . ' ' . $tag->title : (string)preg_replace('/\\(.*?\\)|\\[.*?\\]|clip officiel|official( video)?|lyrics?/iu', ' ', $name);        $headers = ['Accept' => 'application/json', 'User-Agent' => 'WinZik'];        $this->http->request('GET', 'https://api.deezer.com/search?' . http_build_query(['q' => trim($q), 'limit' => 1]), null, $headers, 15)            ->then(function (HttpResponse $r) use ($key, $headers, $tag, $name): void {                $hit = $r->ok() ? ($r->json()['data'][0] ?? null) : null;                // Deezer always answers something: only a record of the same song (its title, and its artist when known)                if (is_array($hit) && !self::sameSong($tag, $name, (string)($hit['title'] ?? ''), (string)($hit['artist']['name'] ?? ''))) {                    $hit = null;                }                @mkdir($this->dir, 0777, true);                if (!is_array($hit)) {                    file_put_contents("$key.json", '{}');      // nothing found: not asked again                    return;                }                $info = ['album' => (string)($hit['album']['title'] ?? ''), 'artist' => (string)($hit['artist']['name'] ?? '')];                file_put_contents("$key.json", (string)json_encode($info));                $cover = (string)($hit['album']['cover_medium'] ?? '');                if ($cover !== '') {                    $this->http?->request('GET', $cover, null, ['User-Agent' => 'WinZik'], 15)->then(function (HttpResponse $img) use ($key): void {                        if ($img->ok() && $img->body !== '') {                            file_put_contents("$key.jpg", $img->body);                        }                    }, fn () => null);                }                $album = (int)($hit['album']['id'] ?? 0);                if ($album > 0) {                    // its release date (on the album)                    $this->http?->request('GET', "https://api.deezer.com/album/$album", null, $headers, 15)->then(function (HttpResponse $a) use ($key, $info): void {                        $date = $a->ok() ? (string)($a->json()['release_date'] ?? '') : '';                        if ($date !== '') {                            file_put_contents("$key.json", (string)json_encode($info + ['date' => $date]));                        }                    }, fn () => null);                }            }, fn () => null);    }}