188 lines
6.0 KiB
Python
188 lines
6.0 KiB
Python
from __future__ import annotations
|
|
|
|
import io
|
|
import logging
|
|
import threading
|
|
from urllib.parse import parse_qs
|
|
from wsgiref.simple_server import (
|
|
WSGIRequestHandler,
|
|
WSGIServer,
|
|
make_server,
|
|
)
|
|
from socketserver import ThreadingMixIn
|
|
|
|
from .templates import CONNECTED, NOT_CONNECTED
|
|
|
|
logger = logging.getLogger("kronic.cast.dial")
|
|
|
|
DEVICE_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
|
|
<root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:r="urn:restful-tv-org:schemas:upnp-dd">
|
|
<specVersion>
|
|
<major>1</major>
|
|
<minor>0</minor>
|
|
</specVersion>
|
|
<URLBase>{base}</URLBase>
|
|
<device>
|
|
<deviceType>urn:schemas-upnp-org:device:dail:1</deviceType>
|
|
<friendlyName>{friendly_name}</friendlyName>
|
|
<manufacturer>Kronic</manufacturer>
|
|
<modelName>Kronic Media Server</modelName>
|
|
<UDN>uuid:{uuid}</UDN>
|
|
</device>
|
|
</root>"""
|
|
|
|
|
|
class SilentWSGIRequestHandler(WSGIRequestHandler):
|
|
def log_message(self, format, *args):
|
|
logger.debug("%s - - %s", self.address_string(), format % args)
|
|
|
|
def address_string(self):
|
|
return self.client_address[0]
|
|
|
|
|
|
class ThreadedWSGIServer(ThreadingMixIn, WSGIServer):
|
|
daemon_threads = True
|
|
allow_reuse_address = True
|
|
|
|
|
|
class DialApplication:
|
|
def __init__(self, identity, youtube):
|
|
self.identity = identity
|
|
self.youtube = youtube
|
|
|
|
@staticmethod
|
|
def _response(start_response, status, body=b"", headers=None):
|
|
if isinstance(body, str):
|
|
body = body.encode("utf-8")
|
|
headers = list(headers or [])
|
|
headers.append(("Content-Length", str(len(body))))
|
|
start_response(status, headers)
|
|
return [body]
|
|
|
|
def __call__(self, environ, start_response):
|
|
method = environ.get("REQUEST_METHOD", "GET").upper()
|
|
path = environ.get("PATH_INFO", "/")
|
|
|
|
if path == "/ssdp/device-desc.xml" and method == "GET":
|
|
host = environ.get("HTTP_HOST", "")
|
|
body = DEVICE_TEMPLATE.format(
|
|
base=f"http://{host}",
|
|
friendly_name=self.identity.friendly_name,
|
|
uuid=self.identity.uuid,
|
|
)
|
|
return self._response(
|
|
start_response,
|
|
"200 OK",
|
|
body,
|
|
[
|
|
("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS"),
|
|
("Access-Control-Expose-Headers", "Location"),
|
|
("Application-URL", f"http://{host}/apps"),
|
|
("Content-Type", "application/xml; charset=utf-8"),
|
|
],
|
|
)
|
|
|
|
if path == "/apps/YouTube" and method == "GET":
|
|
body = CONNECTED if self.youtube.state_xml_connected() else NOT_CONNECTED
|
|
return self._response(
|
|
start_response,
|
|
"200 OK",
|
|
body,
|
|
[
|
|
("Content-Type", "application/xml; charset=utf-8"),
|
|
("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS"),
|
|
("Access-Control-Expose-Headers", "Location"),
|
|
("Cache-Control", "no-cache, must-revalidate, no-store"),
|
|
],
|
|
)
|
|
|
|
if path == "/apps/YouTube" and method == "POST":
|
|
length = int(environ.get("CONTENT_LENGTH") or 0)
|
|
body = environ["wsgi.input"].read(length).decode("utf-8", "replace")
|
|
form = parse_qs(body)
|
|
pairing_code = (form.get("pairingCode") or [""])[0]
|
|
try:
|
|
self.youtube.dial_launch(pairing_code)
|
|
except Exception as error:
|
|
logger.exception("DIAL YouTube launch failed")
|
|
return self._response(
|
|
start_response,
|
|
"500 Internal Server Error",
|
|
f"Pairing failed: {error}",
|
|
[("Content-Type", "text/plain; charset=utf-8")],
|
|
)
|
|
|
|
return self._response(
|
|
start_response,
|
|
"201 Created",
|
|
b"",
|
|
[("Location", "/apps/YouTube/run")],
|
|
)
|
|
|
|
if path == "/apps/YouTube/run" and method == "DELETE":
|
|
self.youtube.dial_stop()
|
|
return self._response(start_response, "200 OK", b"")
|
|
|
|
if method == "OPTIONS":
|
|
return self._response(
|
|
start_response,
|
|
"200 OK",
|
|
b"",
|
|
[
|
|
("Access-Control-Allow-Origin", "*"),
|
|
("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"),
|
|
("Access-Control-Allow-Headers", "Content-Type"),
|
|
],
|
|
)
|
|
|
|
return self._response(
|
|
start_response,
|
|
"404 Not Found",
|
|
"Only YouTube is supported",
|
|
[("Content-Type", "text/plain; charset=utf-8")],
|
|
)
|
|
|
|
|
|
class DialServer:
|
|
def __init__(self, identity, youtube, host="0.0.0.0", port=0):
|
|
self.identity = identity
|
|
self.youtube = youtube
|
|
self.host = host
|
|
self.port = int(port)
|
|
self.server = None
|
|
self.thread = None
|
|
self.ready = threading.Event()
|
|
|
|
def _run(self):
|
|
app = DialApplication(self.identity, self.youtube)
|
|
self.server = make_server(
|
|
self.host,
|
|
self.port,
|
|
app,
|
|
server_class=ThreadedWSGIServer,
|
|
handler_class=SilentWSGIRequestHandler,
|
|
)
|
|
self.server.timeout = 0.25
|
|
self.ready.set()
|
|
while self.thread is not None:
|
|
self.server.handle_request()
|
|
self.server.server_close()
|
|
|
|
def start(self):
|
|
self.thread = threading.Thread(
|
|
target=self._run,
|
|
name="KronicDialServer",
|
|
daemon=True,
|
|
)
|
|
self.thread.start()
|
|
self.ready.wait(5)
|
|
if self.server is None:
|
|
raise RuntimeError("Kronic DIAL server failed to start")
|
|
return tuple(self.server.socket.getsockname()[:2])
|
|
|
|
def stop(self):
|
|
thread = self.thread
|
|
self.thread = None
|
|
if thread is not None:
|
|
thread.join(timeout=3)
|