RU
apps/winzik / src / Cast / Ssdp.php · commit 6576d6f
<?phpnamespace App\Cast;/** * SSDP / UPnP (DLNA) just enough to find the media renderers of the network (smart TVs, boxes, sound bars): an * M-SEARCH sent to 239.255.255.250:1900, the answers (unicast, to our port) give the address of each device's * description (LOCATION), whose XML names the device and the control addresses of its services (AVTransport: play a * URL; RenderingControl: the volume). No XML extension on the phone's PHP: read with patterns. */final class Ssdp{    public const ADDRESS = '239.255.255.250';    public const PORT = 1900;    public const RENDERER = 'urn:schemas-upnp-org:device:MediaRenderer:1';    public const AV_TRANSPORT = 'urn:schemas-upnp-org:service:AVTransport:1';    public const RENDERING = 'urn:schemas-upnp-org:service:RenderingControl:1';    public static function search(string $target = self::RENDERER, int $mx = 2): string    {        return "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: $mx\r\nST: $target\r\n"            . "USER-AGENT: WinZik/1.0 UPnP/1.1\r\n\r\n";    }    /**     * An answer to M-SEARCH (or a NOTIFY alive): its headers, lower-case; null when it is something else.     * @return array<string, string>|null with at least 'location'     */    public static function parse(string $packet): ?array    {        $lines = preg_split('/\r?\n/', $packet) ?: [];        $first = strtoupper(trim((string)array_shift($lines)));        if (!str_starts_with($first, 'HTTP/1.1 200') && !str_starts_with($first, 'HTTP/1.0 200') && !str_starts_with($first, 'NOTIFY ')) {            return null;        }        $headers = [];        foreach ($lines as $line) {            $colon = strpos($line, ':');            if ($colon !== false) {                $headers[strtolower(trim(substr($line, 0, $colon)))] = trim(substr($line, $colon + 1));            }        }        if (($headers['nts'] ?? '') === 'ssdp:byebye' || !isset($headers['location'])) {            return null;        }        $st = $headers['st'] ?? $headers['nt'] ?? '';        if ($st !== '' && stripos($st, 'MediaRenderer') === false && stripos($st, 'AVTransport') === false && $st !== 'upnp:rootdevice') {            return null;        }        return $headers;    }    /**     * The device description XML: its name and the absolute control URLs of AVTransport / RenderingControl.     * @return array{name: string, model: string, manufacturer: string, udn: string, avTransport: string, rendering: string}|null     *         null when it is not a media renderer (no AVTransport)     */    public static function description(string $xml, string $location): ?array    {        $tag = fn (string $name, string $in) => preg_match('#<(?:\w+:)?' . $name . '\b[^>]*>(.*?)</(?:\w+:)?' . $name . '>#s', $in, $m)            ? html_entity_decode(trim($m[1]), ENT_QUOTES | ENT_XML1, 'UTF-8') : '';        $base = $tag('URLBase', $xml) ?: $location;        $services = [];        preg_match_all('#<(?:\w+:)?service\b[^>]*>(.*?)</(?:\w+:)?service>#s', $xml, $all);        foreach ($all[1] as $service) {            $type = $tag('serviceType', $service);            $services[$type] = self::absolute($base, $tag('controlURL', $service));        }        $av = '';        $rc = '';        foreach ($services as $type => $url) {            if (stripos($type, ':service:AVTransport:') !== false && $av === '') {                $av = $url;            } elseif (stripos($type, ':service:RenderingControl:') !== false && $rc === '') {                $rc = $url;            }        }        if ($av === '') {            return null;        }        return [            'name' => $tag('friendlyName', $xml) ?: 'TV',            'model' => trim($tag('modelName', $xml)),            'manufacturer' => trim($tag('manufacturer', $xml)),            'udn' => $tag('UDN', $xml) ?: $location,            'avTransport' => $av,            'rendering' => $rc,        ];    }    /** A path of the description made absolute against its base address. */    public static function absolute(string $base, string $path): string    {        if ($path === '') {            return '';        }        if (preg_match('#^https?://#i', $path)) {            return $path;        }        $p = parse_url($base);        if ($p === false || !isset($p['host'])) {            return $path;        }        $root = ($p['scheme'] ?? 'http') . '://' . $p['host'] . (isset($p['port']) ? ':' . $p['port'] : '');        if (str_starts_with($path, '/')) {            return $root . $path;        }        $dir = isset($p['path']) ? rtrim(substr($p['path'], 0, (int)strrpos($p['path'], '/') + 1), '/') : '';        return $root . $dir . '/' . $path;    }}