UK
apps/winzik / src / Media / SpotifyAccount.php · commit 6576d6f
<?phpnamespace App\Media;use JumPHP\Async\Task;/** * The user's own Spotify account, with the user's own app (Options: Client ID / secret): their playlists and liked * songs, to import into WinZik (each song then taken from YouTube, as for a Spotify link: Spotify never gives its sound). * * The official way (Authorization Code + PKCE): the browser opens Spotify's page, the user says yes, Spotify sends the * browser back to http://127.0.0.1:8888/callback (the redirect declared in the user's app), where WinZik listens for a * moment (a socket of PHP, never waiting), then the code becomes a token, renewed by itself (its refresh token is kept * in the settings). Nothing goes elsewhere than to Spotify. */final class SpotifyAccount{    public const REDIRECT = 'http://127.0.0.1:8888/callback';    public const PORT = 8888;    private const SCOPES = 'playlist-read-private playlist-read-collaborative user-library-read';    /** '' (nothing), 'waiting' (the browser is on Spotify's page), 'connected', 'error' */    public string $state = '';    public string $error = '';    /** @var resource|null the local listener while waiting for the browser */    private $server = null;    private string $verifier = '';    private string $expected = '';    private string $token = '';    private float $until = 0.0;    private float $waitingSince = 0.0;    /**     * @param \Closure(string, string, string|null, array<string, string>): Task $request HTTP (method, url, body, headers) -> Task of     *        an object with ->status, ->body, ok(), json()     * @param \Closure(string): bool $openBrowser     * @param \Closure(string): void $keepRefresh where the refresh token is kept (the settings)     */    public function __construct(private string $clientId, private \Closure $request, private \Closure $openBrowser,        public string $refresh = '', private ?\Closure $keepRefresh = null)    {        if ($refresh !== '') {            $this->state = 'connected';        }    }    public function connected(): bool    {        return $this->state === 'connected';    }    /** Opens Spotify's page in the browser and listens for its answer. */    public function login(): bool    {        if ($this->clientId === '') {            return $this->fail('mettez votre Client ID Spotify dans les Options');        }        $this->stopListening();        $server = @stream_socket_server('tcp://127.0.0.1:' . self::PORT, $no, $why);        if ($server === false) {            return $this->fail("le port " . self::PORT . " est pris ($why)");        }        stream_set_blocking($server, false);        $this->server = $server;        $this->verifier = rtrim(strtr(base64_encode(random_bytes(48)), '+/', '-_'), '=');        $challenge = rtrim(strtr(base64_encode(hash('sha256', $this->verifier, true)), '+/', '-_'), '=');        $this->expected = bin2hex(random_bytes(12));        $url = 'https://accounts.spotify.com/authorize?' . http_build_query([            'client_id' => $this->clientId, 'response_type' => 'code', 'redirect_uri' => self::REDIRECT, 'scope' => self::SCOPES,            'state' => $this->expected, 'code_challenge_method' => 'S256', 'code_challenge' => $challenge, 'show_dialog' => 'false',        ]);        $this->state = 'waiting';        $this->error = '';        $this->waitingSince = microtime(true);        if (!($this->openBrowser)($url)) {            $this->error = 'ouvrez cette adresse : ' . $url;        }        return true;    }    public function logout(): void    {        $this->stopListening();        $this->refresh = $this->token = '';        $this->state = '';        ($this->keepRefresh)?->__invoke('');    }    /** Each frame: the browser coming back to WinZik with its code. */    public function poll(): void    {        if ($this->server === null) {            return;        }        if (microtime(true) - $this->waitingSince > 300) {            $this->stopListening();            $this->fail('pas de réponse de Spotify en 5 minutes');            return;        }        $client = @stream_socket_accept($this->server, 0);        if ($client === false) {            return;        }        stream_set_timeout($client, 2);        $request = (string)fread($client, 8192);        $line = strtok($request, "\r\n") ?: '';        parse_str((string)parse_url((string)(explode(' ', $line)[1] ?? ''), PHP_URL_QUERY), $q);        $text = fn (string $key): string => isset($q[$key]) && is_string($q[$key]) ? $q[$key] : '';        $code = $text('code');        $error = $text('error');        // only the answer to OUR request counts (its state): any web page open meanwhile can call this address, it must        // neither connect a code of someone else nor stop the login        $ours = $this->expected !== '' && hash_equals($this->expected, $text('state'));        $ok = $ours && $code !== '';        $page = $ok ? 'WinZik est relié à votre compte Spotify : vous pouvez fermer cet onglet.' : 'WinZik : connexion refusée ou incomplète (' . htmlspecialchars($error !== '' ? $error : 'réponse inattendue') . ').';        $html = '<!doctype html><meta charset="utf-8"><title>WinZik</title><body style="font:16px sans-serif;background:#111;color:#eee;padding:40px">' . $page . '</body>';        @fwrite($client, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: " . strlen($html) . "\r\nConnection: close\r\n\r\n" . $html);        @fclose($client);        if (!$ours || ($code === '' && $error === '')) {            return;     // another request (a favicon, another page, a forged state...): keep listening        }        $this->stopListening();        if (!$ok) {            $this->fail('Spotify : ' . $error);            return;        }        $this->tokenRequest(['grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => self::REDIRECT,            'code_verifier' => $this->verifier]);    }    /** @param array<string, string> $form */    private function tokenRequest(array $form, ?Task $then = null): Task    {        $done = $then ?? new Task();        // PKCE: the app's id in the form, no secret (the code_verifier proves it is the WinZik that asked)        ($this->request)('POST', 'https://accounts.spotify.com/api/token', http_build_query($form + ['client_id' => $this->clientId]), [            'Content-Type' => 'application/x-www-form-urlencoded'])->then(function ($r) use ($done, $form): void {            $answer = self::json($r);            $data = $r->ok() ? $answer : null;            $token = is_array($data) ? (string)($data['access_token'] ?? '') : '';            if ($token === '') {                $said = is_array($answer) ? $answer['error_description'] ?? $answer['error'] ?? '' : '';                if (($form['grant_type'] ?? '') === 'refresh_token' && is_array($answer) && ($answer['error'] ?? '') === 'invalid_grant') {                    // the user took the access back (or it expired): log in again, not a "connected" that never works                    $this->refresh = $this->token = '';                    $this->state = '';                    ($this->keepRefresh)?->__invoke('');                }                $this->fail('Spotify refuse (HTTP ' . $r->status . ') : ' . (is_string($said) ? $said : ''));                $done->settle(false);                return;            }            $this->token = $token;            $this->until = microtime(true) + (int)($data['expires_in'] ?? 3600) - 60;            if (!empty($data['refresh_token'])) {                $this->refresh = (string)$data['refresh_token'];                ($this->keepRefresh)?->__invoke($this->refresh);            }            $this->state = 'connected';            $this->error = '';            $done->settle(true);        }, function (\Throwable $e) use ($done): void {            $this->fail('Spotify injoignable : ' . $e->getMessage());            $done->settle(false);        });        return $done;    }    /** A token that works (renewed with the refresh token when it is old). @return Task of bool */    private function ready(): Task    {        if ($this->token !== '' && microtime(true) < $this->until) {            $t = new Task();            $t->settle(true);            return $t;        }        if ($this->refresh === '') {            $this->fail('connectez-vous à Spotify');            $t = new Task();            $t->settle(false);            return $t;        }        return $this->tokenRequest(['grant_type' => 'refresh_token', 'refresh_token' => $this->refresh]);    }    /**     * Every page of a list of Spotify's API, one after the other. @param \Closure(array<string, mixed>): void $each per item     * @return Task settled with true when all came (false: an error)     */    private function pages(string $url, \Closure $each, ?Task $done = null, ?string $instead = null): Task    {        $done ??= new Task();        $this->ready()->then(function ($ok) use ($url, $each, $done, $instead): void {            if ($ok !== true) {                $done->settle(false);                return;            }            ($this->request)('GET', $url, null, ['Authorization' => 'Bearer ' . $this->token, 'Accept' => 'application/json'])->then(function ($r) use ($each, $done, $instead): void {                $answer = self::json($r);                $data = $r->ok() ? $answer : null;                if (!is_array($data) && $instead !== null && in_array($r->status, [403, 404, 410], true)) {                    $this->pages($instead, $each, $done);       // the address of before: the newer one                    return;                }                if (!is_array($data)) {                    $said = is_array($answer) && is_array($answer['error'] ?? null) ? (string)($answer['error']['message'] ?? '') : '';                    $this->fail('Spotify : HTTP ' . $r->status . ($said !== '' ? ' (' . $said . ')' : ''));                    $done->settle(false);                    return;                }                foreach ((array)($data['items'] ?? []) as $item) {                    if (is_array($item)) {                        $each($item);                    }                }                $next = (string)($data['next'] ?? '');                $next !== '' ? $this->pages($next, $each, $done) : $done->settle(true);            }, function (\Throwable $e) use ($done): void {                $this->fail('Spotify injoignable : ' . $e->getMessage());                $done->settle(false);            });        });        return $done;    }    /** @return Task of list<array{id: string, name: string, count: int}> the user's playlists, the liked songs first */    public function playlists(): Task    {        $out = [['id' => 'liked', 'name' => 'Titres likés', 'count' => 0]];        $result = new Task();        $this->pages('https://api.spotify.com/v1/me/playlists?limit=50', function (array $p) use (&$out): void {            $out[] = ['id' => (string)($p['id'] ?? ''), 'name' => (string)($p['name'] ?? ''), 'count' => (int)($p['tracks']['total'] ?? $p['items']['total'] ?? 0)];        })->then(function ($ok) use (&$out, $result): void {            $result->settle($ok === true ? $out : []);        });        return $result;    }    /** @return Task of list<array{title: string, url: string}> the songs of a playlist ('liked': the liked songs), as YouTube searches */    public function songs(string $playlist): Task    {        $url = $playlist === 'liked' ? 'https://api.spotify.com/v1/me/tracks?limit=50'            : 'https://api.spotify.com/v1/playlists/' . rawurlencode($playlist) . '/tracks?limit=50';        $out = [];        $result = new Task();        $instead = $playlist === 'liked' ? null : 'https://api.spotify.com/v1/playlists/' . rawurlencode($playlist) . '/items?limit=50';        $this->pages($url, function (array $item) use (&$out): void {            $t = $item['track'] ?? $item['item'] ?? null;            if (!is_array($t) || !isset($t['name']) || ($t['type'] ?? 'track') !== 'track') {                return;     // a podcast episode, a song gone from Spotify            }            $artists = implode(', ', array_map(fn ($a) => is_array($a) ? (string)($a['name'] ?? '') : '', (array)($t['artists'] ?? [])));            $name = (string)$t['name'];            $out[] = ['title' => trim($artists . ' - ' . $name, ' -'), 'url' => 'ytsearch1:' . str_replace(',', '', $artists) . ' ' . $name];        }, null, $instead)->then(function ($ok) use (&$out, $result): void {            $result->settle($ok === true ? $out : []);        });        return $result;    }    /** The answer as JSON, null when it is not (an HTML page of a proxy, a cut answer). @return mixed */    private static function json(object $r): mixed    {        try {            return $r->json();        } catch (\Throwable) {            return null;        }    }    private function stopListening(): void    {        if ($this->server !== null) {            @fclose($this->server);            $this->server = null;        }    }    private function fail(string $why): bool    {        $this->state = $this->refresh !== '' && $this->state === 'connected' ? 'connected' : 'error';        $this->error = $why;        return false;    }}