NL
apps/winzik / src / Cloud / CloudAccount.php · commit 6576d6f
<?phpnamespace App\Cloud;use App\Core\WinZik;use JumPHP\Async\Task;use JumPHP\Http\HttpResponse;/** * The user's WinZik account on jumphp.net (docs: comptes-applications of the playground): a pseudo and a password, no * e-mail. An HTTP client like App\Core\Market: every call settles a Task (never blocks). The device's token is kept in * var/cloud.json ({login, deviceId, deviceName, token}) and sent as `Authorization: Bearer`; it is never logged nor shown. * * Base URL: project.yaml `cloud_url` (https://jumphp.net/api/apps/winzik) or env JUMPHP_CLOUD_URL; '' = no cloud (tests). * Requests go to <base>/account/... Errors settle with a CloudError (French message, server code, HTTP status); a 401 * (token revoked) forgets the token: the user signs in again. */final class CloudAccount{    public string $login = '';    public string $deviceId = '';    public string $deviceName = '';    private string $token = '';    /** @var \Closure(): void called once the token is gone (revoked, signed out elsewhere) */    public ?\Closure $onSignedOut = null;    /**     * @param \Closure(string, string, string|array|null, array<string, string>, float): Task $request an HTTP request     *        (method, url, body, headers, timeout) settling with a JumPHP\Http\HttpResponse ($engine->http()->request)     * @param string $kind desktop | phone | web     */    public function __construct(private \Closure $request, private string $url, private string $file, public readonly string $kind = 'desktop')    {        $this->url = rtrim($url, '/');        $saved = WinZik::readJsonFile($file);        if (is_array($saved)) {            $this->login = (string)($saved['login'] ?? '');            $this->deviceId = (string)($saved['deviceId'] ?? '');            $this->deviceName = (string)($saved['deviceName'] ?? '');            $this->token = (string)($saved['token'] ?? '');        }        if ($this->deviceName === '') {            $this->deviceName = self::defaultDeviceName($kind);        }    }    /** A name with nothing personal in it (the user can change it): never the computer's or the user's own name. */    public static function defaultDeviceName(string $kind): string    {        return match ($kind) {            'phone' => 'Téléphone',            'web' => 'Navigateur',            default => 'Ordinateur',        };    }    public function enabled(): bool    {        return $this->url !== '';    }    public function url(): string    {        return $this->url;    }    public function signedIn(): bool    {        return $this->enabled() && $this->token !== '';    }    // --- sign in ---------------------------------------------------------------------------------------------    /** Creates the account: settles with {login, recovery} (the recovery code: shown once, the only way back). */    public function signUp(string $login, string $password, ?string $deviceName = null): Task    {        return $this->enter('/signup', $login, $password, $deviceName);    }    /** Signs this device in: settles with {login}. */    public function signIn(string $login, string $password, ?string $deviceName = null): Task    {        return $this->enter('/login', $login, $password, $deviceName);    }    /** Without the password: settles with {login, recovery} (a NEW recovery code; every device signed out, this one in). */    public function recover(string $login, string $recovery, string $newPassword, ?string $deviceName = null): Task    {        $this->rename($deviceName);        $result = new Task();        $this->call('POST', '/recover', ['login' => trim($login), 'recovery' => trim($recovery), 'newPassword' => $newPassword,            'device' => ['name' => $this->deviceName, 'kind' => $this->kind]], false)->then(function (array $data) use ($result): void {                $this->keep($data);                $result->settle(['login' => $this->login, 'recovery' => (string)($data['recovery'] ?? '')]);            }, fn (\Throwable $e) => $result->settle(null, $e));        return $result;    }    private function enter(string $path, string $login, string $password, ?string $deviceName): Task    {        $this->rename($deviceName);        $result = new Task();        $this->call('POST', $path, ['login' => trim($login), 'password' => $password,            'device' => ['name' => $this->deviceName, 'kind' => $this->kind]], false)->then(function (array $data) use ($result): void {                $this->keep($data);                $out = ['login' => $this->login];                if (isset($data['recovery'])) {                    $out['recovery'] = (string)$data['recovery'];                }                $result->settle($out);            }, fn (\Throwable $e) => $result->settle(null, $e));        return $result;    }    private function rename(?string $deviceName): void    {        $name = trim((string)$deviceName);        if ($name !== '') {            $this->deviceName = mb_substr($name, 0, 40);        }    }    /** @param array<string, mixed> $data the answer of signup / login / recover */    private function keep(array $data): void    {        $this->login = (string)($data['login'] ?? $this->login);        $this->deviceId = (string)($data['device']['id'] ?? $this->deviceId);        $this->token = (string)($data['token'] ?? '');        $this->save();    }    /** Signs this device out (the token forgotten here even when the server cannot be reached). */    public function signOut(): Task    {        $task = $this->signedIn() ? $this->call('POST', '/logout', []) : self::done([]);        $this->forget();        return $task;    }    /** The token is no longer good (or the user signed out): forgotten; the login stays to fill the form. */    public function forget(): void    {        $had = $this->token !== '';        $this->token = '';        $this->deviceId = '';        $this->save();        if ($had && $this->onSignedOut !== null) {            ($this->onSignedOut)();        }    }    public function save(): void    {        @mkdir(dirname($this->file), 0777, true);        WinZik::writeJsonFile($this->file, ['login' => $this->login, 'deviceId' => $this->deviceId, 'deviceName' => $this->deviceName,            'token' => $this->token]);        @chmod($this->file, 0600);    }    // --- the account ---------------------------------------------------------------------------------------------    /** {login, createdAt, device, devices: [{id, name, kind, online, lastSeen, current}], usage, limits} */    public function me(): Task    {        return $this->call('GET', '/me');    }    /** Presence (every 60 s): {now, device, online: [devices], playlist: {version, entries}, lyrics, next} */    public function hello(): Task    {        return $this->call('POST', '/hello', []);    }    public function revoke(string $deviceId): Task    {        return $this->call('DELETE', '/devices/' . rawurlencode($deviceId));    }    public function changePassword(string $password, string $newPassword): Task    {        return $this->call('PUT', '/password', ['password' => $password, 'newPassword' => $newPassword]);    }    /** Deletes the account (its playlist, its lyrics, its devices): this device is signed out. */    public function deleteAccount(string $password): Task    {        $result = new Task();        $this->call('DELETE', '/me', ['password' => $password])->then(function (array $data) use ($result): void {            $this->login = '';            $this->forget();            $result->settle($data);        }, fn (\Throwable $e) => $result->settle(null, $e));        return $result;    }    // --- the cloud ---------------------------------------------------------------------------------------------    /** {version, entries} (version 0: no playlist yet) */    public function getPlaylist(): Task    {        return $this->call('GET', '/cloud/playlist');    }    /**     * Writes the playlist read at $version. Settles with {version, entries} or, when another device wrote in between,     * {conflict: true, version, entries} (the current one: replay the changes on it and write again).     * @param list<array<string, mixed>> $entries     */    public function putPlaylist(array $entries, int $version): Task    {        return $this->call('PUT', '/cloud/playlist', ['entries' => $entries], true, ['If-Match' => '"' . $version . '"'], [412]);    }    /** The .lyr of an entry: settles with its text, or null when it has none. */    public function getLyrics(string $entryId): Task    {        $result = new Task();        $this->raw('GET', '/cloud/lyrics/' . rawurlencode($entryId), null, [])->then(function (HttpResponse $r) use ($result): void {            if ($r->status === 404) {                $result->settle(null);            } elseif (!$r->ok()) {                $result->settle(null, $this->error($r));            } else {                $result->settle($r->body);            }        }, fn (\Throwable $e) => $result->settle(null, $e));        return $result;    }    /**     * The lyrics of an entry unless they are still the ones of $etag (the server's ETag of what this device has):     * settles with {text: ?string (null: none, or not changed), etag: string, changed: bool}.     */    public function getLyricsIf(string $entryId, string $etag = ''): Task    {        $result = new Task();        $this->raw('GET', '/cloud/lyrics/' . rawurlencode($entryId), null, $etag !== '' ? ['If-None-Match' => $etag] : [])->then(function (HttpResponse $r) use ($result, $etag): void {            if ($r->status === 304) {                $result->settle(['text' => null, 'etag' => $etag, 'changed' => false]);            } elseif ($r->status === 404) {                $result->settle(['text' => null, 'etag' => '', 'changed' => false]);            } elseif (!$r->ok()) {                $result->settle(null, $this->error($r));            } else {                $result->settle(['text' => $r->body, 'etag' => (string)$r->header('etag', self::lyricsEtag($r->body)), 'changed' => true]);            }        }, fn (\Throwable $e) => $result->settle(null, $e));        return $result;    }    /** The ETag the server gives a .lyr (the start of its SHA-256): known without asking after a send. */    public static function lyricsEtag(string $utf8): string    {        return '"' . substr(hash('sha256', $utf8), 0, 32) . '"';    }    /** @param string $text the .lyr (any encoding: sent as UTF-8) */    public function putLyrics(string $entryId, string $text): Task    {        if (!mb_check_encoding($text, 'UTF-8')) {            $text = mb_convert_encoding($text, 'UTF-8', 'Windows-1252');        }        return $this->call('PUT', '/cloud/lyrics/' . rawurlencode($entryId), $text, true, ['Content-Type' => 'text/plain; charset=utf-8']);    }    public function deleteLyrics(string $entryId): Task    {        return $this->call('DELETE', '/cloud/lyrics/' . rawurlencode($entryId));    }    /** The relay room and key of the week: {relay, room, key, alg, week, exp, expiresIn} */    public function link(): Task    {        return $this->call('GET', '/cloud/link');    }    // --- HTTP ----------------------------------------------------------------------------------------------------    /**     * @param string|array<string, mixed>|null $body     * @param array<string, string> $headers     * @param list<int> $accepted statuses settled as data (with conflict: true), not as an error     */    private function call(string $method, string $path, string|array|null $body = null, bool $auth = true, array $headers = [], array $accepted = []): Task    {        $result = new Task();        if (!$this->enabled()) {            $result->settle(null, new CloudError('Pas de cloud ici : pas de réseau.', 'disabled', 0));            return $result;        }        if ($auth && $this->token === '') {            $result->settle(null, new CloudError('Connectez-vous d\'abord à votre compte.', 'unauthorized', 401));            return $result;        }        $this->raw($method, $path, $body, $headers, $auth)->then(function (HttpResponse $r) use ($result, $accepted): void {            if (in_array($r->status, $accepted, true)) {                $data = $r->json();                $result->settle(['conflict' => true] + (is_array($data) ? $data : []));                return;            }            if (!$r->ok()) {                $result->settle(null, $this->error($r));                return;            }            $data = $r->body === '' ? [] : $r->json();            $result->settle(is_array($data) ? $data : []);        }, fn (\Throwable $e) => $result->settle(null, new CloudError('Serveur injoignable : vérifiez la connexion.', 'network', 0, $e)));        return $result;    }    /** @param array<string, string> $headers */    private function raw(string $method, string $path, string|array|null $body, array $headers, bool $auth = true): Task    {        $headers += ['Accept' => 'application/json'];        if ($auth && $this->token !== '') {            $headers['Authorization'] = 'Bearer ' . $this->token;        }        try {            return ($this->request)($method, $this->url . '/account' . $path, $body, $headers, 30.0);        } catch (\Throwable $e) {            return self::failed(new CloudError('Serveur injoignable : vérifiez la connexion.', 'network', 0, $e));        }    }    private function error(HttpResponse $r): CloudError    {        $data = null;        try {            $data = $r->json();        } catch (\Throwable) {        }        $code = is_array($data) ? (string)($data['code'] ?? '') : '';        if ($r->status === 401 && $code !== 'bad_credentials') {            $this->forget();        // revoked / unknown token: signed in again        }        $message = match (true) {            $code === 'bad_credentials' => 'Pseudo ou mot de passe incorrect.',            $code === 'login_taken' => 'Ce pseudo est déjà pris : choisissez-en un autre.',            $code === 'bad_login' => 'Pseudo refusé : 3 à 32 lettres, chiffres, « . », « - » ou « _ » (pas d\'adresse e-mail ni de numéro de téléphone).',            $code === 'bad_password' => 'Mot de passe trop court : 8 caractères au moins.',            $code === 'rate_limited' || $r->status === 429 => 'Trop d\'essais : réessayez dans ' . max(1, (int)ceil(((int)($data['retryAfter'] ?? 60)) / 60)) . ' minute(s).',            $code === 'revoked' => 'Cet appareil a été déconnecté du compte : reconnectez-vous.',            $r->status === 401 => 'Connectez-vous à nouveau à votre compte.',            $code === 'quota' || $code === 'too_big' => 'Limite du compte atteinte.',            $r->status === 403 => 'Mot de passe incorrect.',            $r->status === 404 => 'Introuvable sur le serveur.',            default => is_array($data) && is_string($data['error'] ?? null) ? (string)$data['error'] : 'Erreur du serveur (HTTP ' . $r->status . ').',        };        return new CloudError($message, $code !== '' ? $code : 'http', $r->status);    }    private static function done(mixed $value): Task    {        $task = new Task();        $task->settle($value);        return $task;    }    private static function failed(\Throwable $e): Task    {        $task = new Task();        $task->settle(null, $e);        return $task;    }}