PT
apps/winzik / tests / Cast / FakeRenderer.php · commit 6576d6f
<?phpnamespace Tests\Cast;use App\Cast\LanHttp;use JumPHP\Net\HttpRequest;use JumPHP\Net\HttpResponse;use JumPHP\Net\HttpServer;/** * A DLNA media renderer that does not exist (no TV here): an HTTP server on 127.0.0.1 with a device description * (MediaRenderer, AVTransport + RenderingControl), the SOAP actions of a TV (state, position, volume), and an SSDP * responder on UDP answering M-SEARCH with its LOCATION. Like a real TV it then reads the song it was given from the * address it got (a Range request: the first 64 KB), so the test proves the URL works. */final class FakeRenderer{    public HttpServer $http;    public int $port;    /** @var resource the SSDP responder */    public $udp;    public int $udpPort;    /** @var list<array{action: string, args: array<string, string>}> every SOAP action received */    public array $actions = [];    public string $uri = '';    public string $metadata = '';    /** STOPPED | PLAYING | PAUSED_PLAYBACK | NO_MEDIA_PRESENT */    public string $state = 'NO_MEDIA_PRESENT';    public float $position = 0.0;    private float $since = 0.0;    public int $volume = 20;    /** the next SetAVTransportURI is refused with this UPnP error (0 none) */    public int $refuse = 0;    /** @var array{status: int, headers: array<string, string>, length: int}|null what the song's URL answered the "TV" */    public ?array $fetched = null;    private LanHttp $client;    public function __construct(public string $name = 'Téléviseur du salon')    {        $this->client = new LanHttp();        $this->http = new HttpServer();        $this->http->handle('/desc.xml', fn () => HttpResponse::text($this->description(), 200, 'text/xml; charset="utf-8"'));        $this->http->handle('/ctrl/', fn (HttpRequest $r) => $this->soap($r));        $this->port = $this->http->listen(0, '127.0.0.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);    }    public function poll(): void    {        $this->http->poll();        $this->client->poll();        while (is_string($data = @stream_socket_recvfrom($this->udp, 2048, 0, $peer)) && $data !== '') {            if (str_starts_with($data, 'M-SEARCH') && str_contains($data, 'MediaRenderer')) {                $answer = "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=1800\r\nEXT:\r\nLOCATION: http://127.0.0.1:{$this->port}/desc.xml\r\n"                    . "SERVER: Linux/4.4 UPnP/1.0 FakeTV/1.0\r\nST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n"                    . "USN: uuid:fake-tv-0001::urn:schemas-upnp-org:device:MediaRenderer:1\r\n\r\n";                stream_socket_sendto($this->udp, $answer, 0, (string)$peer);            }        }        if ($this->state === 'PLAYING') {            $now = microtime(true);            $this->position += $now - $this->since;            $this->since = $now;        }    }    public function close(): void    {        $this->http->close();        @fclose($this->udp);        $this->client->close();    }    /** @return list<string> the actions in order */    public function names(): array    {        return array_map(fn (array $a) => $a['action'], $this->actions);    }    /** The TV's own remote: pause. */    public function pauseHere(): void    {        $this->poll();        $this->state = 'PAUSED_PLAYBACK';    }    /** The TV's own remote: play from there. */    public function playHere(float $at): void    {        $this->state = 'PLAYING';        $this->position = $at;        $this->since = microtime(true);    }    private function description(): string    {        return '<?xml version="1.0"?><root xmlns="urn:schemas-upnp-org:device-1-0"><specVersion><major>1</major><minor>0</minor></specVersion>'            . '<device><deviceType>urn:schemas-upnp-org:device:MediaRenderer:1</deviceType><friendlyName>' . htmlspecialchars($this->name) . '</friendlyName>'            . '<manufacturer>Fake</manufacturer><modelName>TV 2026</modelName><UDN>uuid:fake-tv-0001</UDN><serviceList>'            . '<service><serviceType>urn:schemas-upnp-org:service:RenderingControl:1</serviceType><serviceId>urn:upnp-org:serviceId:RenderingControl</serviceId>'            . '<SCPDURL>/rc.xml</SCPDURL><controlURL>ctrl/rc</controlURL><eventSubURL>/ev/rc</eventSubURL></service>'            . '<service><serviceType>urn:schemas-upnp-org:service:AVTransport:1</serviceType><serviceId>urn:upnp-org:serviceId:AVTransport</serviceId>'            . '<SCPDURL>/avt.xml</SCPDURL><controlURL>/ctrl/avt</controlURL><eventSubURL>/ev/avt</eventSubURL></service>'            . '</serviceList></device></root>';    }    private function soap(HttpRequest $r): HttpResponse    {        if ($r->method !== 'POST' || !preg_match('/#(\w+)"?$/', (string)$r->header('soapaction'), $m)) {            return HttpResponse::status(405);        }        $action = $m[1];        $args = [];        if (preg_match('#<u:' . $action . '[^>]*>(.*)</u:' . $action . '>#s', $r->body, $b)) {            preg_match_all('#<(\w+)>(.*?)</\1>#s', $b[1], $all, PREG_SET_ORDER);            foreach ($all as $a) {                $args[$a[1]] = html_entity_decode($a[2], ENT_QUOTES | ENT_XML1, 'UTF-8');            }        }        $this->actions[] = ['action' => $action, 'args' => $args];        $out = [];        switch ($action) {            case 'SetAVTransportURI':                if ($this->refuse > 0) {                    $code = $this->refuse;                    $this->refuse = 0;                    return HttpResponse::text('<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault>'                        . '<faultcode>s:Client</faultcode><faultstring>UPnPError</faultstring><detail><UPnPError xmlns="urn:schemas-upnp-org:control-1-0">'                        . "<errorCode>$code</errorCode><errorDescription>Illegal MIME-Type</errorDescription></UPnPError></detail></s:Fault></s:Body></s:Envelope>",                        500, 'text/xml; charset="utf-8"');                }                $this->uri = $args['CurrentURI'] ?? '';                $this->metadata = $args['CurrentURIMetaData'] ?? '';                $this->state = 'STOPPED';                $this->position = 0.0;                // the TV reads the beginning of the song, as a real one does                $this->client->request('GET', $this->uri, '', ['Range' => 'bytes=0-65535'], 5.0, function (?array $res): void {                    $this->fetched = $res === null ? null : ['status' => $res['status'], 'headers' => $res['headers'], 'length' => strlen($res['body'])];                });                break;            case 'Play':                $this->state = 'PLAYING';                $this->since = microtime(true);                break;            case 'Pause':                $this->state = 'PAUSED_PLAYBACK';                break;            case 'Stop':                $this->state = $this->uri === '' ? 'NO_MEDIA_PRESENT' : 'STOPPED';                break;            case 'Seek':                $this->position = (float)\App\Cast\DlnaTarget::seconds($args['Target'] ?? '0:00:00');                $this->since = microtime(true);                break;            case 'GetTransportInfo':                $out = ['CurrentTransportState' => $this->state, 'CurrentTransportStatus' => 'OK', 'CurrentSpeed' => '1'];                break;            case 'GetPositionInfo':                $out = ['Track' => '1', 'TrackDuration' => '0:03:00', 'TrackURI' => $this->uri,                    'RelTime' => \App\Cast\DlnaTarget::clock($this->position), 'AbsTime' => 'NOT_IMPLEMENTED'];                break;            case 'SetVolume':                $this->volume = (int)($args['DesiredVolume'] ?? 0);                break;        }        $body = '';        foreach ($out as $k => $v) {            $body .= "<$k>" . htmlspecialchars($v, ENT_XML1) . "</$k>";        }        $urn = str_contains($r->path, '/rc') ? 'urn:schemas-upnp-org:service:RenderingControl:1' : 'urn:schemas-upnp-org:service:AVTransport:1';        return HttpResponse::text('<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'            . "<s:Body><u:{$action}Response xmlns:u=\"$urn\">$body</u:{$action}Response></s:Body></s:Envelope>", 200, 'text/xml; charset="utf-8"');    }}