): 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 = 'WinZik' . $page . ''; @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 $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): 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 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 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; } }