1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
| #!/usr/bin/env python3
""" DLNA MediaRenderer 接收服务端 (Pythonista / iPadOS 终极兼容版) """
import socket import struct import threading import time import uuid import re import html import webbrowser import xml.etree.ElementTree as ET from http.server import HTTPServer, BaseHTTPRequestHandler
HTTP_PORT = 8080 SSDP_PORT = 1900 MULTICAST_ADDR = "239.255.255.250" DEVICE_NAME = "MyDLNA-iPad-Pro" DEVICE_UUID = str(uuid.uuid5(uuid.NAMESPACE_DNS, "ipad-dlna.local"))
LOCAL_IP = None
def get_local_ip(): global LOCAL_IP if LOCAL_IP: return LOCAL_IP try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) LOCAL_IP = s.getsockname()[0] s.close() except Exception: LOCAL_IP = "127.0.0.1" return LOCAL_IP
BASE_URL = f"http://{get_local_ip()}:{HTTP_PORT}" DEVICE_DESC_URL = f"{BASE_URL}/description.xml"
class SafariPlayer: def __init__(self): self.current_url = None
def play(self, url): url = html.unescape(url) self.current_url = url webbrowser.open(url) print(f"[播放器] Safari 已打开: {url}")
def stop(self): self.current_url = None print("[播放器] 已停止")
player = SafariPlayer()
def get_device_description(): """用 ElementTree 生成设备描述 XML,避免手写格式错误""" root = ET.Element("root", { "xmlns": "urn:schemas-upnp-org:device-1-0" }) specVersion = ET.SubElement(root, "specVersion") ET.SubElement(specVersion, "major").text = "1" ET.SubElement(specVersion, "minor").text = "0" device = ET.SubElement(root, "device") ET.SubElement(device, "deviceType").text = "urn:schemas-upnp-org:device:MediaRenderer:1" ET.SubElement(device, "friendlyName").text = DEVICE_NAME ET.SubElement(device, "manufacturer").text = "MyDLNA" ET.SubElement(device, "manufacturerURL").text = "https://github.com" ET.SubElement(device, "modelDescription").text = "Pythonista DLNA MediaRenderer" ET.SubElement(device, "modelName").text = "MyDLNA Receiver" ET.SubElement(device, "modelNumber").text = "1.0" ET.SubElement(device, "modelURL").text = "https://github.com" ET.SubElement(device, "serialNumber").text = "001" ET.SubElement(device, "UDN").text = f"uuid:{DEVICE_UUID}" serviceList = ET.SubElement(device, "serviceList") services = [ ("urn:schemas-upnp-org:service:AVTransport:1", "urn:upnp-org:serviceId:AVTransport", "/service/AVTransport"), ("urn:schemas-upnp-org:service:ConnectionManager:1", "urn:upnp-org:serviceId:ConnectionManager", "/service/ConnectionManager"), ("urn:schemas-upnp-org:service:RenderingControl:1", "urn:upnp-org:serviceId:RenderingControl", "/service/RenderingControl"), ] for st, sid, base in services: svc = ET.SubElement(serviceList, "service") ET.SubElement(svc, "serviceType").text = st ET.SubElement(svc, "serviceId").text = sid ET.SubElement(svc, "SCPDURL").text = f"{base}/scpd" ET.SubElement(svc, "controlURL").text = f"{base}/control" ET.SubElement(svc, "eventSubURL").text = f"{base}/event" return '<?xml version="1.0"?>\n' + ET.tostring(root, encoding="unicode")
def get_avtransport_scpd(): root = ET.Element("scpd", {"xmlns": "urn:schemas-upnp-org:service-1-0"}) spec = ET.SubElement(root, "specVersion") ET.SubElement(spec, "major").text = "1" ET.SubElement(spec, "minor").text = "0" actions = ET.SubElement(root, "actionList") for name, args in [ ("SetAVTransportURI", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("CurrentURI","in","AVTransportURI"), ("CurrentURIMetaData","in","AVTransportURIMetaData")]), ("GetMediaInfo", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("NrTracks","out","NumberOfTracks"), ("MediaDuration","out","CurrentMediaDuration"), ("CurrentURI","out","AVTransportURI"), ("CurrentURIMetaData","out","AVTransportURIMetaData"), ("NextURI","out","NextAVTransportURI"), ("NextURIMetaData","out","NextAVTransportURIMetaData"), ("PlayMedium","out","PlaybackStorageMedium"), ("RecordMedium","out","RecordStorageMedium"), ("WriteStatus","out","RecordMediumWriteStatus")]), ("GetTransportInfo", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("CurrentTransportState","out","TransportState"), ("CurrentTransportStatus","out","TransportStatus"), ("CurrentSpeed","out","TransportPlaySpeed")]), ("GetPositionInfo", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Track","out","CurrentTrack"), ("TrackDuration","out","CurrentTrackDuration"), ("TrackMetaData","out","CurrentTrackMetaData"), ("TrackURI","out","CurrentTrackURI"), ("RelTime","out","RelativeTimePosition"), ("AbsTime","out","AbsoluteTimePosition"), ("RelCount","out","RelativeCounterPosition"), ("AbsCount","out","AbsoluteCounterPosition")]), ("Play", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Speed","in","TransportPlaySpeed")]), ("Stop", [("InstanceID","in","A_ARG_TYPE_InstanceID")]), ("Pause", [("InstanceID","in","A_ARG_TYPE_InstanceID")]), ]: act = ET.SubElement(actions, "action") ET.SubElement(act, "name").text = name argList = ET.SubElement(act, "argumentList") for n, d, r in args: a = ET.SubElement(argList, "argument") ET.SubElement(a, "name").text = n ET.SubElement(a, "direction").text = d ET.SubElement(a, "relatedStateVariable").text = r stateTable = ET.SubElement(root, "serviceStateTable") for name, dtype, default, allowed in [ ("TransportState", "string", None, ["STOPPED","PLAYING","PAUSED_PLAYBACK"]), ("TransportStatus", "string", None, ["OK","ERROR_OCCURRED"]), ("TransportPlaySpeed", "string", "1", None), ("AVTransportURI", "string", None, None), ("AVTransportURIMetaData", "string", None, None), ("NextAVTransportURI", "string", None, None), ("NextAVTransportURIMetaData", "string", None, None), ("NumberOfTracks", "ui4", "0", None), ("CurrentMediaDuration", "string", None, None), ("CurrentTrack", "ui4", "0", None), ("CurrentTrackDuration", "string", None, None), ("CurrentTrackMetaData", "string", None, None), ("CurrentTrackURI", "string", None, None), ("RelativeTimePosition", "string", None, None), ("AbsoluteTimePosition", "string", None, None), ("RelativeCounterPosition", "i4", None, None), ("AbsoluteCounterPosition", "i4", None, None), ("PlaybackStorageMedium", "string", None, ["NONE","NETWORK"]), ("RecordStorageMedium", "string", None, ["NOT_IMPLEMENTED"]), ("RecordMediumWriteStatus", "string", None, ["NOT_IMPLEMENTED"]), ("A_ARG_TYPE_InstanceID", "ui4", None, None), ]: sv = ET.SubElement(stateTable, "stateVariable", {"sendEvents": "no"}) ET.SubElement(sv, "name").text = name ET.SubElement(sv, "dataType").text = dtype if default: ET.SubElement(sv, "defaultValue").text = default if allowed: avl = ET.SubElement(sv, "allowedValueList") for v in allowed: ET.SubElement(avl, "allowedValue").text = v return '<?xml version="1.0"?>\n' + ET.tostring(root, encoding="unicode")
def get_connection_manager_scpd(): root = ET.Element("scpd", {"xmlns": "urn:schemas-upnp-org:service-1-0"}) spec = ET.SubElement(root, "specVersion") ET.SubElement(spec, "major").text = "1" ET.SubElement(spec, "minor").text = "0" actions = ET.SubElement(root, "actionList") act = ET.SubElement(actions, "action") ET.SubElement(act, "name").text = "GetProtocolInfo" argList = ET.SubElement(act, "argumentList") for n, d, r in [("Source","out","SourceProtocolInfo"), ("Sink","out","SinkProtocolInfo")]: a = ET.SubElement(argList, "argument") ET.SubElement(a, "name").text = n ET.SubElement(a, "direction").text = d ET.SubElement(a, "relatedStateVariable").text = r stateTable = ET.SubElement(root, "serviceStateTable") for name, dtype, default in [ ("SourceProtocolInfo", "string", None), ("SinkProtocolInfo", "string", "http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:video/x-msvideo:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp4:*"), ]: sv = ET.SubElement(stateTable, "stateVariable", {"sendEvents": "no"}) ET.SubElement(sv, "name").text = name ET.SubElement(sv, "dataType").text = dtype if default: ET.SubElement(sv, "defaultValue").text = default return '<?xml version="1.0"?>\n' + ET.tostring(root, encoding="unicode")
def get_rendering_control_scpd(): root = ET.Element("scpd", {"xmlns": "urn:schemas-upnp-org:service-1-0"}) spec = ET.SubElement(root, "specVersion") ET.SubElement(spec, "major").text = "1" ET.SubElement(spec, "minor").text = "0" actions = ET.SubElement(root, "actionList") for name, args in [ ("GetVolume", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Channel","in","A_ARG_TYPE_Channel"), ("CurrentVolume","out","Volume")]), ("SetVolume", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Channel","in","A_ARG_TYPE_Channel"), ("DesiredVolume","in","Volume")]), ("GetMute", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Channel","in","A_ARG_TYPE_Channel"), ("CurrentMute","out","Mute")]), ("SetMute", [("InstanceID","in","A_ARG_TYPE_InstanceID"), ("Channel","in","A_ARG_TYPE_Channel"), ("DesiredMute","in","Mute")]), ]: act = ET.SubElement(actions, "action") ET.SubElement(act, "name").text = name argList = ET.SubElement(act, "argumentList") for n, d, r in args: a = ET.SubElement(argList, "argument") ET.SubElement(a, "name").text = n ET.SubElement(a, "direction").text = d ET.SubElement(a, "relatedStateVariable").text = r stateTable = ET.SubElement(root, "serviceStateTable") for name, dtype, default, allowed in [ ("Volume", "ui2", None, None), ("Mute", "boolean", None, None), ("A_ARG_TYPE_InstanceID", "ui4", None, None), ("A_ARG_TYPE_Channel", "string", None, ["Master"]), ]: sv = ET.SubElement(stateTable, "stateVariable", {"sendEvents": "no"}) ET.SubElement(sv, "name").text = name ET.SubElement(sv, "dataType").text = dtype if default: ET.SubElement(sv, "defaultValue").text = default if allowed: avl = ET.SubElement(sv, "allowedValueList") for v in allowed: ET.SubElement(avl, "allowedValue").text = v return '<?xml version="1.0"?>\n' + ET.tostring(root, encoding="unicode")
DEVICE_DESCRIPTION = get_device_description() AVTRANSPORT_SCPD = get_avtransport_scpd() CONNECTION_MANAGER_SCPD = get_connection_manager_scpd() RENDERING_CONTROL_SCPD = get_rendering_control_scpd()
class SSDPServer(threading.Thread): def __init__(self): super().__init__(daemon=True) self.running = True self.sock = None
def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(("0.0.0.0", SSDP_PORT)) mreq = struct.pack("4sl", socket.inet_aton(MULTICAST_ADDR), socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) print(f"[SSDP] 服务已启动,监听 {MULTICAST_ADDR}:{SSDP_PORT}")
notify_thread = threading.Thread(target=self._send_notify_loop, daemon=True) notify_thread.start()
while self.running: try: self.sock.settimeout(1.0) data, addr = self.sock.recvfrom(2048) self._handle_request(data.decode("utf-8", errors="ignore"), addr) except socket.timeout: continue except Exception as e: if self.running: print(f"[SSDP] 错误: {e}")
def _handle_request(self, data, addr): if "M-SEARCH" not in data: return
st_match = re.search(r"ST:\s*(.+?)(?:\r|\n|$)", data, re.IGNORECASE) if not st_match: return
st = st_match.group(1).strip() print(f"[SSDP] TVBox 搜索: {st} (来自 {addr[0]}:{addr[1]})")
valid_keywords = [ "ssdp:all", "upnp:rootdevice", "MediaRenderer", "MediaRenderer:1", "MediaRenderer:2", "MediaRenderer:3", "AVTransport", "ConnectionManager", "RenderingControl" ] if not any(kw in st for kw in valid_keywords): print(f"[SSDP] ST 不匹配,忽略") return
self._send_response(addr, st)
def _send_response(self, addr, st): """发送 SSDP 响应 - 包含 EXT 头,兼容 cling 库""" response = ( "HTTP/1.1 200 OK\r\n" "CACHE-CONTROL: max-age=1800\r\n" f"DATE: {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())}\r\n" "EXT:\r\n" f"LOCATION: {DEVICE_DESC_URL}\r\n" "SERVER: UPnP/1.0 Python/3.x iPadDLNA/1.0\r\n" f"ST: {st}\r\n" f"USN: uuid:{DEVICE_UUID}::{st}\r\n" "\r\n" )
try: self.sock.sendto(response.encode(), addr) print(f"[SSDP] ✅ 已响应 -> {addr[0]}:{addr[1]}") except Exception as e: print(f"[SSDP] 发送失败: {e}")
def _send_notify_loop(self): while self.running: self._send_notify() time.sleep(15)
def _send_notify(self): notifies = [ "upnp:rootdevice", "urn:schemas-upnp-org:device:MediaRenderer:1", "urn:schemas-upnp-org:device:MediaRenderer:2", "urn:schemas-upnp-org:device:MediaRenderer:3", "urn:schemas-upnp-org:service:AVTransport:1", ]
for nt in notifies: msg = ( "NOTIFY * HTTP/1.1\r\n" f"HOST: {MULTICAST_ADDR}:{SSDP_PORT}\r\n" "CACHE-CONTROL: max-age=1800\r\n" f"LOCATION: {DEVICE_DESC_URL}\r\n" "NTS: ssdp:alive\r\n" "EXT:\r\n" "SERVER: UPnP/1.0 Python/3.x iPadDLNA/1.0\r\n" f"NT: {nt}\r\n" f"USN: uuid:{DEVICE_UUID}::{nt}\r\n" "\r\n" ) try: self.sock.sendto(msg.encode(), (MULTICAST_ADDR, SSDP_PORT)) except Exception: pass
def stop(self): self.running = False if self.sock: self.sock.close()
class HTTPServerV4(HTTPServer): address_family = socket.AF_INET
class DLNAHandler(BaseHTTPRequestHandler): current_uri = None transport_state = "STOPPED"
def log_message(self, format, *args): print(f"[HTTP] {self.address_string()} - {format % args}")
def do_GET(self): path = self.path print(f"[HTTP] GET {path}") if path == "/": self._send_diagnostic() elif path == "/description.xml": self._send_xml(DEVICE_DESCRIPTION) elif path == "/service/AVTransport/scpd": self._send_xml(AVTRANSPORT_SCPD) elif path == "/service/ConnectionManager/scpd": self._send_xml(CONNECTION_MANAGER_SCPD) elif path == "/service/RenderingControl/scpd": self._send_xml(RENDERING_CONTROL_SCPD) else: self.send_error(404, "Not Found")
def _send_diagnostic(self): """返回诊断页面,方便测试 HTTP 是否可达""" html = f"""<html><body> <h1>iPad DLNA 诊断页面</h1> <p>设备名: {DEVICE_NAME}</p> <p>IP: {LOCAL_IP}</p> <p>HTTP 服务正常</p> <p><a href="/description.xml">查看设备描述 XML</a></p> </body></html>""" self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", len(html.encode())) self.end_headers() self.wfile.write(html.encode())
def _send_xml(self, content): data = content.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/xml; charset=utf-8") self.send_header("Content-Length", len(data)) self.end_headers() self.wfile.write(data)
def do_POST(self): path = self.path if "/control" in path: content_length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(content_length).decode("utf-8") action = self._parse_soap_action(body) service_type = self._get_service_type(path)
if "SetAVTransportURI" in action: self._handle_set_av_transport_uri(body, service_type) elif "Play" in action: self._handle_play(service_type) elif "Stop" in action: self._handle_stop(service_type) elif "Pause" in action: self._handle_pause(service_type) elif "GetTransportInfo" in action: self._handle_get_transport_info(service_type) elif "GetMediaInfo" in action: self._handle_get_media_info(service_type) elif "GetPositionInfo" in action: self._handle_get_position_info(service_type) elif "GetProtocolInfo" in action: self._handle_get_protocol_info(service_type) elif "GetVolume" in action: self._handle_get_volume(service_type) elif "SetVolume" in action: self._send_soap_response(action, "", service_type) elif "GetMute" in action: self._handle_get_mute(service_type) elif "SetMute" in action: self._send_soap_response(action, "", service_type) else: self._send_soap_response(action, "", service_type) else: self.send_error(404, "Not Found")
def do_SUBSCRIBE(self): sid = f"uuid:{uuid.uuid4()}" self.send_response(200) self.send_header("SID", sid) self.send_header("TIMEOUT", "Second-1800") self.end_headers() print(f"[事件] TVBox 接收成功 -> SID: {sid}")
def do_UNSUBSCRIBE(self): self.send_response(200) self.end_headers() print("[事件] TVBox 等待下一个视频")
def _parse_soap_action(self, body): soap_action = self.headers.get("SOAPAction", "") if soap_action: return soap_action.strip('"').split("#")[-1] match = re.search(r"<u:([A-Za-z]+)", body) if match: return match.group(1) return ""
def _get_service_type(self, path): if "AVTransport" in path: return "urn:schemas-upnp-org:service:AVTransport:1" elif "ConnectionManager" in path: return "urn:schemas-upnp-org:service:ConnectionManager:1" elif "RenderingControl" in path: return "urn:schemas-upnp-org:service:RenderingControl:1" return "urn:schemas-upnp-org:service:AVTransport:1"
def _extract_tag_value(self, body, tag_name): patterns = [ f"<{tag_name}>([^<]+)</{tag_name}>", f"<[^>]*:{tag_name}>([^<]+)</[^>]*:{tag_name}>", ] for pattern in patterns: match = re.search(pattern, body) if match: return match.group(1) return ""
def _send_soap_response(self, action, body_content, service_type): response = f"""<?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="{service_type}"> {body_content} </u:{action}Response> </s:Body> </s:Envelope>""" data = response.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/xml; charset=utf-8") self.send_header("Content-Length", len(data)) self.end_headers() self.wfile.write(data)
def _handle_set_av_transport_uri(self, body, service_type): uri = self._extract_tag_value(body, "CurrentURI") if uri: DLNAHandler.current_uri = uri DLNAHandler.transport_state = "STOPPED" print(f"[投屏] 接收到视频 URL: {uri}") self._send_soap_response("SetAVTransportURI", "", service_type)
def _handle_play(self, service_type): if DLNAHandler.current_uri: DLNAHandler.transport_state = "PLAYING" player.play(DLNAHandler.current_uri) self._send_soap_response("Play", "", service_type)
def _handle_stop(self, service_type): DLNAHandler.transport_state = "STOPPED" player.stop() self._send_soap_response("Stop", "", service_type)
def _handle_pause(self, service_type): DLNAHandler.transport_state = "PAUSED_PLAYBACK" self._send_soap_response("Pause", "", service_type)
def _handle_get_transport_info(self, service_type): body = f"""<CurrentTransportState>{DLNAHandler.transport_state}</CurrentTransportState> <CurrentTransportStatus>OK</CurrentTransportStatus> <CurrentSpeed>1</CurrentSpeed>""" self._send_soap_response("GetTransportInfo", body, service_type)
def _handle_get_media_info(self, service_type): body = f"""<NrTracks>1</NrTracks> <MediaDuration>00:00:00</MediaDuration> <CurrentURI>{DLNAHandler.current_uri or ""}</CurrentURI> <CurrentURIMetaData></CurrentURIMetaData> <NextURI></NextURI> <NextURIMetaData></NextURIMetaData> <PlayMedium>NETWORK</PlayMedium> <RecordMedium>NOT_IMPLEMENTED</RecordMedium> <WriteStatus>NOT_IMPLEMENTED</WriteStatus>""" self._send_soap_response("GetMediaInfo", body, service_type)
def _handle_get_position_info(self, service_type): body = f"""<Track>1</Track> <TrackDuration>00:00:00</TrackDuration> <TrackMetaData></TrackMetaData> <TrackURI>{DLNAHandler.current_uri or ""}</TrackURI> <RelTime>00:00:00</RelTime> <AbsTime>00:00:00</AbsTime> <RelCount>0</RelCount> <AbsCount>0</AbsCount>""" self._send_soap_response("GetPositionInfo", body, service_type)
def _handle_get_protocol_info(self, service_type): body = """<Source></Source> <Sink>http-get:*:video/mp4:*,http-get:*:video/x-matroska:*,http-get:*:video/x-msvideo:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp4:*</Sink>""" self._send_soap_response("GetProtocolInfo", body, service_type)
def _handle_get_volume(self, service_type): body = "<CurrentVolume>50</CurrentVolume>" self._send_soap_response("GetVolume", body, service_type)
def _handle_get_mute(self, service_type): body = "<CurrentMute>0</CurrentMute>" self._send_soap_response("GetMute", body, service_type)
def main(): print("=" * 60) print(" DLNA MediaRenderer 接收服务端 (Pythonista / iPadOS)") print("=" * 60) print(f"设备名称: {DEVICE_NAME}") print(f"设备UUID: {DEVICE_UUID}") print(f"本机IP: {get_local_ip()}") print(f"HTTP端口: {HTTP_PORT}") print(f"设备描述: {DEVICE_DESC_URL}") print("=" * 60) print("\n⚠️ 请保持 Pythonista 在前台运行") print("⚠️ 请检查: 设置 -> 隐私 -> 本地网络 -> Pythonista (必须开启)") print("=" * 60) print(f"\n诊断页面: http://{LOCAL_IP}:{HTTP_PORT}/") print("先在同一 Wi-Fi 的 Safari 中打开诊断页面,确认 HTTP 可达")
ssdp = SSDPServer() ssdp.start()
httpd = HTTPServerV4(("0.0.0.0", HTTP_PORT), DLNAHandler) print(f"\n[HTTP] 服务已启动,监听 0.0.0.0:{HTTP_PORT}") print("\n等待投屏... (按 Ctrl+C 停止)\n")
try: httpd.serve_forever() except KeyboardInterrupt: print("\n\n正在停止服务...") ssdp.stop() httpd.shutdown() print("服务已停止")
if __name__ == "__main__": main()
|