IT
apps/winzik / tests / Cast / FakeCastDevice.php · commit 6576d6f
<?phpnamespace Tests\Cast;use App\Cast\CastV2;use App\Cast\Mdns;/** * A Google Cast device that does not exist (no Chromecast here): TLS on 127.0.0.1 with a self-signed certificate made * by the test, CastMessage frames, the platform receiver (CONNECT, PING / PONG, LAUNCH -> RECEIVER_STATUS with the * application's transportId, LAUNCH_ERROR for an unknown App ID, STOP, SET_VOLUME), the Default Media Receiver (LOAD -> * MEDIA_STATUS, PLAY, PAUSE, SEEK, STOP, GET_STATUS) and WinZik's receiver (STATE in, REPORT out). Plus an mDNS * responder on UDP answering the _googlecast._tcp question. */final class FakeCastDevice{    public const TRANSPORT = 'web-7';    /** @var resource */    private $server;    public int $port;    /** @var resource|null */    private $client = null;    private bool $secure = false;    private string $in = '';    /** @var list<array{namespace: string, source: string, destination: string, data: array}> every message received */    public array $messages = [];    /** @var list<string> the App IDs it knows */    public array $apps = [CastV2::DEFAULT_RECEIVER, 'A1B2C3D4'];    public string $running = '';    public string $playerState = 'IDLE';    public float $currentTime = 0.0;    public string $contentId = '';    public float $level = 0.5;    /** @var resource the mDNS responder */    public $udp;    public int $udpPort;    public function __construct(string $certFile)    {        $context = stream_context_create(['ssl' => ['local_cert' => $certFile, 'allow_self_signed' => true, 'verify_peer' => false]]);        $server = stream_socket_server('tcp://127.0.0.1:0', $no, $err, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);        assert($server !== false, $err);        stream_set_blocking($server, false);        $this->server = $server;        $this->port = (int)substr((string)strrchr((string)stream_socket_get_name($server, false), ':'), 1);        $udp = stream_socket_server('udp://127.0.0.1:0', $no, $err, STREAM_SERVER_BIND);        assert($udp !== false);        stream_set_blocking($udp, false);        $this->udp = $udp;        $this->udpPort = (int)substr((string)strrchr((string)stream_socket_get_name($udp, false), ':'), 1);    }    /** A self-signed certificate (as a Cast device has its own). */    public static function certificate(string $file): void    {        // its own openssl.cnf: a PHP without one finds none        $cnf = $file . '.cnf';        file_put_contents($cnf, "[ req ]\ndistinguished_name = dn\n[ dn ]\n");        $options = ['config' => $cnf, 'digest_alg' => 'sha256', 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA];        $key = openssl_pkey_new($options);        assert($key !== false, (string)openssl_error_string());        $csr = openssl_csr_new(['commonName' => 'fake-cast-device'], $key, $options);        assert($csr !== false && $csr !== true);        $cert = openssl_csr_sign($csr, null, $key, 1, $options);        assert($cert !== false);        openssl_x509_export($cert, $pem);        openssl_pkey_export($key, $keyPem, null, $options);        file_put_contents($file, $pem . $keyPem);    }    public function poll(): void    {        while (is_string($data = @stream_socket_recvfrom($this->udp, 2048, 0, $peer)) && $data !== '') {            if (str_contains($data, '_googlecast')) {                stream_socket_sendto($this->udp, Mdns::answer('Chromecast-Salon-fake01', 'Salon', 'Chromecast', 'fake01', '127.0.0.1', $this->port), 0, (string)$peer);            }        }        if ($this->client === null) {            $c = @stream_socket_accept($this->server, 0);            if ($c === false) {                return;            }            stream_set_blocking($c, false);            $this->client = $c;        }        if (!$this->secure) {            $ok = @stream_socket_enable_crypto($this->client, true, STREAM_CRYPTO_METHOD_TLS_SERVER);            if ($ok === false) {                @fclose($this->client);                $this->client = null;                return;            }            if ($ok === 0) {                return;            }            $this->secure = true;        }        while (is_string($chunk = @fread($this->client, 65536)) && $chunk !== '') {            $this->in .= $chunk;        }        if (feof($this->client) && $this->in === '') {            // the sender went away: the next one connects anew            @fclose($this->client);            $this->client = null;            $this->secure = false;            return;        }        foreach (CastV2::unframe($this->in) as $m) {            $data = (array)json_decode($m['payload'], true);            $this->messages[] = ['namespace' => $m['namespace'], 'source' => $m['source'], 'destination' => $m['destination'], 'data' => $data];            $this->answer($m['namespace'], $m['source'], $data);        }    }    /** @return list<string> the types received on a namespace */    public function types(string $namespace): array    {        return array_values(array_map(fn (array $m) => (string)($m['data']['type'] ?? ''), array_filter($this->messages, fn (array $m) => $m['namespace'] === $namespace)));    }    /** @return array<string, mixed>|null the last message of a type */    public function last(string $type): ?array    {        foreach (array_reverse($this->messages) as $m) {            if (($m['data']['type'] ?? '') === $type) {                return $m['data'];            }        }        return null;    }    /** Something said by the device itself (the TV's remote paused, the application stopped...). */    public function say(string $namespace, array $data, string $source = 'receiver-0'): void    {        if ($this->client !== null) {            @fwrite($this->client, CastV2::json($namespace, $data, 'sender-0', $source));        }    }    public function close(): void    {        if ($this->client !== null) {            @fclose($this->client);        }        @fclose($this->server);        @fclose($this->udp);    }    /** @param array<string, mixed> $d */    private function answer(string $ns, string $source, array $d): void    {        $type = (string)($d['type'] ?? '');        $id = (int)($d['requestId'] ?? 0);        if ($ns === CastV2::HEARTBEAT && $type === 'PING') {            $this->say(CastV2::HEARTBEAT, ['type' => 'PONG']);        } elseif ($ns === CastV2::RECEIVER && $type === 'LAUNCH') {            if (!in_array($d['appId'] ?? '', $this->apps, true)) {                $this->say(CastV2::RECEIVER, ['type' => 'LAUNCH_ERROR', 'requestId' => $id, 'reason' => 'NOT_FOUND']);                return;            }            $this->running = (string)$d['appId'];            $this->say(CastV2::RECEIVER, ['type' => 'RECEIVER_STATUS', 'requestId' => $id, 'status' => $this->receiverStatus()]);        } elseif ($ns === CastV2::RECEIVER && $type === 'STOP') {            $this->running = '';            $this->say(CastV2::RECEIVER, ['type' => 'RECEIVER_STATUS', 'requestId' => $id, 'status' => $this->receiverStatus()]);        } elseif ($ns === CastV2::RECEIVER && $type === 'SET_VOLUME') {            $this->level = (float)($d['volume']['level'] ?? $this->level);        } elseif ($ns === CastV2::MEDIA) {            match ($type) {                'LOAD' => [$this->contentId, $this->currentTime, $this->playerState] = [(string)$d['media']['contentId'], (float)($d['currentTime'] ?? 0),                    !empty($d['autoplay']) ? 'PLAYING' : 'PAUSED'],                'PLAY' => $this->playerState = 'PLAYING',                'PAUSE' => $this->playerState = 'PAUSED',                'SEEK' => $this->currentTime = (float)$d['currentTime'],                'STOP' => $this->playerState = 'IDLE',                default => null,            };            $this->mediaStatus($id);        } elseif ($ns === CastV2::WINZIK && $type === 'STATE') {            $s = $d['state'] ?? [];            $this->say(CastV2::WINZIK, ['type' => 'REPORT', 'song' => (int)($s['song']['id'] ?? -1), 'pos' => (float)($s['position'] ?? 0),                'st' => !empty($s['playing']) ? 'playing' : 'paused'], self::TRANSPORT);        }    }    public function mediaStatus(int $requestId = 0): void    {        $this->say(CastV2::MEDIA, ['type' => 'MEDIA_STATUS', 'requestId' => $requestId, 'status' => [[            'mediaSessionId' => 1, 'playerState' => $this->playerState, 'currentTime' => $this->currentTime,            'media' => ['contentId' => $this->contentId],        ]]], self::TRANSPORT);    }    /** @return array<string, mixed> */    private function receiverStatus(): array    {        return ['applications' => $this->running === '' ? [] : [['appId' => $this->running, 'displayName' => 'Lecteur', 'sessionId' => 'sess-1',            'transportId' => self::TRANSPORT, 'namespaces' => []]], 'volume' => ['level' => $this->level, 'muted' => false]];    }}