TR
apps/winzik / src / Cast / TvServer.php · commit 6576d6f
<?phpnamespace App\Cast;use JumPHP\Net\HttpRequest;use JumPHP\Net\HttpResponse;use JumPHP\Net\HttpServer;/** * WinZik's server for the TV, on the home network only (JumPHP\Net\HttpServer: non-blocking, Range, HEAD; only * private client addresses), open while something is cast. Nothing is reachable without the session's secret: * *   /c/<token>/m/<id>.<ext>   the song (Range: the TV seeks; DLNA headers; CORS for Cast) *   /c/<token>/i/<id>         its cover *   /c/<token>/v/<id>.vtt     its lyrics as WebVTT subtitles (the Default Media Receiver) *   /c/<token>/l/<id>.json    its lyrics for the TV page (lines, syllables and their moments, translations) *   /c/<token>/s              the state the TV page follows (GET, the page's own report in the query: pos, st, song) *   /c/<token>/k?do=…         a key of the TV's remote (next, prev, toggle, seek&t=) *   /tv/<code>                the TV page (a short code of 8 letters, typed on a TV: it holds the token) * * <token>: 128 random bits; <code>: 40 random bits (typed on a remote), both new for each cast session. */final class TvServer{    public const FIRST_PORT = 47620;    private const CODE_LETTERS = 'abcdefghjkmnpqrstuvwxyz23456789';    private ?HttpServer $server = null;    public string $token = '';    public string $code = '';    /** @var array<int, array{path: string, mime: string, cover: string, vtt: string, lyrics: string}> */    private array $songs = [];    /** @var \Closure(array<string, mixed>, string): array<string, mixed> the state for the TV page: fn ($report, $clientIp) */    public ?\Closure $onState = null;    /** @var \Closure(string, array<string, mixed>): void a key of the TV's remote: fn ($do, $query) */    public ?\Closure $onCommand = null;    /** @var list<string>|null tests: the addresses advertised (null: the computer's own) */    public ?array $addresses = null;    /** the address the TV reaches us at ('' unknown: the first one of this computer) */    public string $host = '';    /** @var array<string, float> the clients of the TV page (ip => when it last asked) */    public array $viewers = [];    /** the TV page's HTML (null: assets/cast/tv.html next to the sources) */    public ?string $page = null;    public function __construct(private ?\Closure $factory = null)    {    }    public static function supported(): bool    {        return HttpServer::isSupported();    }    /** Opens (a new secret each time). */    public function open(): bool    {        if ($this->isOpen()) {            return true;        }        if (!self::supported()) {            return false;        }        try {            $this->server = $this->factory !== null ? ($this->factory)() : new HttpServer();            $this->server->allow(fn (string $ip): bool => HttpServer::isPrivateAddress($ip));            $this->server->handle('/c/', fn (HttpRequest $r): ?HttpResponse => $this->serve($r));            $this->server->handle('/tv/', fn (HttpRequest $r): ?HttpResponse => $this->tvPage($r));            $this->server->listen(self::FIRST_PORT);        } catch (\Throwable) {            $this->server = null;            return false;        }        $this->token = bin2hex(random_bytes(16));        $this->code = '';        $bytes = random_bytes(8);        for ($i = 0; $i < 8; $i++) {            $this->code .= self::CODE_LETTERS[ord($bytes[$i]) % strlen(self::CODE_LETTERS)];        }        return true;    }    public function isOpen(): bool    {        return $this->server !== null && $this->server->isListening();    }    public function port(): int    {        return (int)$this->server?->port();    }    /** The address of this computer the device at $deviceIp reaches (the way out towards it). */    public function useHostFor(string $deviceIp): void    {        $this->host = self::addressTowards($deviceIp) ?? '';    }    public function base(): string    {        $host = $this->host !== '' ? $this->host : (($this->addresses ?? \App\Cloud\LanShare::localAddresses())[0] ?? '127.0.0.1');        return 'http://' . (str_contains($host, ':') ? "[$host]" : $host) . ':' . $this->port();    }    /** The address to type on the TV. */    public function tvUrl(): string    {        return $this->base() . '/tv/' . $this->code;    }    /** @param array{path: string, mime: string, cover: string, vtt: string, lyrics: string} $song */    public function addSong(int $id, array $song): void    {        $this->songs[$id] = $song;        // the songs before the last few are no longer served        foreach (array_keys($this->songs) as $old) {            if ($old < $id - 3) {                unset($this->songs[$old]);            }        }    }    /** @return array{url: string, cover: string, vtt: string, lyrics: string} the addresses of a song */    public function urls(int $id): array    {        $s = $this->songs[$id] ?? null;        $c = $this->base() . '/c/' . $this->token;        if ($s === null) {            return ['url' => '', 'cover' => '', 'vtt' => '', 'lyrics' => ''];        }        $ext = strtolower(pathinfo($s['path'], PATHINFO_EXTENSION)) ?: 'mp3';        return [            'url' => "$c/m/$id.$ext",            'cover' => $s['cover'] !== '' ? "$c/i/$id" : '',            'vtt' => $s['vtt'] !== '' ? "$c/v/$id.vtt" : '',            'lyrics' => $s['lyrics'] !== '' ? "$c/l/$id.json" : '',        ];    }    public function poll(): void    {        $this->server?->poll();    }    public function close(): void    {        $this->server?->close();        $this->server = null;        $this->songs = [];        $this->viewers = [];        $this->token = $this->code = '';    }    private function serve(HttpRequest $r): ?HttpResponse    {        if (!preg_match('#^/c/([0-9a-f]{32})/(.*)$#', $r->path, $m) || !hash_equals($this->token, $m[1])) {            return null;        }        $cors = ['Access-Control-Allow-Origin' => '*', 'Cache-Control' => 'no-store'];        if ($r->method === 'OPTIONS') {            return HttpResponse::text('', 204, 'text/plain', $cors + ['Access-Control-Allow-Methods' => 'GET, HEAD',                'Access-Control-Allow-Headers' => 'Range, Content-Type']);        }        $rest = $m[2];        if ($rest === 's') {            $this->viewers[$r->remoteAddress] = microtime(true);            $state = $this->onState !== null ? ($this->onState)($r->query, $r->remoteAddress) : [];            return HttpResponse::json($state, 200, $cors);        }        if ($rest === 'k') {            if ($this->onCommand !== null) {                ($this->onCommand)((string)($r->query['do'] ?? ''), $r->query);            }            return HttpResponse::json(['ok' => true], 200, $cors);        }        if (!preg_match('#^([mivl])/(\d+)(?:\.\w+)?$#', $rest, $p) || !isset($this->songs[(int)$p[2]])) {            return null;        }        $s = $this->songs[(int)$p[2]];        return match ($p[1]) {            'm' => HttpResponse::file($s['path'], $s['mime'], $cors + [                'transferMode.dlna.org' => 'Streaming',                'contentFeatures.dlna.org' => ($s['mime'] === 'audio/mpeg' ? 'DLNA.ORG_PN=MP3;' : '') . 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000',            ]),            'i' => $s['cover'] !== '' && is_file($s['cover'])                ? HttpResponse::file($s['cover'], str_ends_with($s['cover'], '.png') ? 'image/png' : 'image/jpeg', $cors) : null,            'v' => $s['vtt'] !== '' ? HttpResponse::text($s['vtt'], 200, 'text/vtt; charset=utf-8', $cors) : null,            default => $s['lyrics'] !== '' ? HttpResponse::text($s['lyrics'], 200, 'application/json', $cors) : null,        };    }    private function tvPage(HttpRequest $r): ?HttpResponse    {        $code = trim(substr($r->path, 4), '/');        if ($this->code === '' || !hash_equals($this->code, strtolower($code))) {            return null;        }        $html = $this->page ?? TvPage::html('http');        $html = str_replace('{{BASE}}', '/c/' . $this->token, $html);        return HttpResponse::text($html, 200, 'text/html; charset=utf-8', ['Cache-Control' => 'no-store']);    }    /** This computer's address on the way to $ip (a UDP socket "connected", nothing sent); null when none. */    public static function addressTowards(string $ip): ?string    {        if (!filter_var($ip, FILTER_VALIDATE_IP)) {            return null;        }        $s = @stream_socket_client('udp://' . (str_contains($ip, ':') ? "[$ip]" : $ip) . ':9', $no, $err, 0.2);        if ($s === false) {            return null;        }        $name = (string)@stream_socket_get_name($s, false);        fclose($s);        $local = preg_match('/^\[(.*)\]:\d+$/', $name, $m) ? $m[1] : (string)preg_replace('/:\d+$/', '', $name);        return $local !== '' && $local !== '0.0.0.0' ? $local : null;    }}