|
| 1 | +"""Sendspin server application.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +import signal |
| 6 | +import socket |
| 7 | +import uuid |
| 8 | +from contextlib import suppress |
| 9 | +from dataclasses import dataclass |
| 10 | + |
| 11 | +import qrcode |
| 12 | +from aiosendspin.server import ( |
| 13 | + ClientAddedEvent, |
| 14 | + ClientRemovedEvent, |
| 15 | + SendspinEvent, |
| 16 | + SendspinServer, |
| 17 | + SendspinGroup, |
| 18 | +) |
| 19 | +from aiosendspin.server.stream import MediaStream |
| 20 | + |
| 21 | +from .server import SendspinPlayerServer |
| 22 | +from .source import decode_audio |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def print_qr_code(url: str) -> None: |
| 28 | + """Print a QR code to the console.""" |
| 29 | + qr = qrcode.QRCode( |
| 30 | + error_correction=qrcode.ERROR_CORRECT_L, |
| 31 | + box_size=1, |
| 32 | + border=1, |
| 33 | + ) |
| 34 | + qr.add_data(url) |
| 35 | + qr.make(fit=True) |
| 36 | + qr.print_ascii(invert=True) |
| 37 | + |
| 38 | + |
| 39 | +def get_local_ip() -> str: |
| 40 | + """Get the local IP address of this machine on the LAN.""" |
| 41 | + try: |
| 42 | + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: |
| 43 | + s.connect(("8.8.8.8", 80)) |
| 44 | + return s.getsockname()[0] |
| 45 | + except Exception: |
| 46 | + return "localhost" |
| 47 | + |
| 48 | + |
| 49 | +@dataclass |
| 50 | +class ServeConfig: |
| 51 | + """Configuration for the serve command.""" |
| 52 | + |
| 53 | + source: str |
| 54 | + port: int = 8927 |
| 55 | + name: str = "Sendspin Server" |
| 56 | + loop: bool = False |
| 57 | + |
| 58 | + |
| 59 | +async def run_server(config: ServeConfig) -> int: |
| 60 | + """Run the Sendspin server with the given audio source.""" |
| 61 | + event_loop = asyncio.get_event_loop() |
| 62 | + server_id = f"sendspin-cli-{uuid.uuid4().hex[:8]}" |
| 63 | + |
| 64 | + server = SendspinPlayerServer( |
| 65 | + loop=event_loop, |
| 66 | + server_id=server_id, |
| 67 | + server_name=config.name, |
| 68 | + ) |
| 69 | + |
| 70 | + client_connected = asyncio.Event() |
| 71 | + active_group: SendspinGroup | None = None |
| 72 | + shutdown_requested = False |
| 73 | + |
| 74 | + def handle_sigint() -> None: |
| 75 | + nonlocal shutdown_requested |
| 76 | + shutdown_requested = True |
| 77 | + print("\nShutting down...") |
| 78 | + # Cancel any active playback to trigger shutdown |
| 79 | + for task in asyncio.all_tasks(): |
| 80 | + if task is not asyncio.current_task(): |
| 81 | + task.cancel() |
| 82 | + |
| 83 | + event_loop.add_signal_handler(signal.SIGINT, handle_sigint) |
| 84 | + |
| 85 | + async def on_server_event(server: SendspinServer, event: SendspinEvent) -> None: |
| 86 | + nonlocal active_group |
| 87 | + |
| 88 | + if isinstance(event, ClientAddedEvent): |
| 89 | + client = server.get_client(event.client_id) |
| 90 | + assert client is not None |
| 91 | + |
| 92 | + print("Client connected", event.client_id) |
| 93 | + |
| 94 | + if active_group is None: |
| 95 | + active_group = client.group |
| 96 | + client_connected.set() |
| 97 | + return |
| 98 | + |
| 99 | + await active_group.add_client(client) |
| 100 | + |
| 101 | + if isinstance(event, ClientRemovedEvent): |
| 102 | + if active_group is None: |
| 103 | + return |
| 104 | + |
| 105 | + print("Client disconnected", event.client_id) |
| 106 | + |
| 107 | + if not active_group.clients: |
| 108 | + active_group = None |
| 109 | + |
| 110 | + server.add_event_listener(on_server_event) |
| 111 | + |
| 112 | + await server.start_server(port=config.port) |
| 113 | + local_ip = get_local_ip() |
| 114 | + url = f"http://{local_ip}:{config.port}/" |
| 115 | + print(f"\nServer running at {url}") |
| 116 | + if local_ip == "localhost": |
| 117 | + print("Unable to print QR code because no LAN IP available\n") |
| 118 | + print("Open in browser to use the web player") |
| 119 | + else: |
| 120 | + print() |
| 121 | + print_qr_code(url) |
| 122 | + print() |
| 123 | + print("Scan QR to open in browser to use the web player") |
| 124 | + print("Or connect with any Sendspin client") |
| 125 | + print("Press Ctrl+C to quit\n") |
| 126 | + |
| 127 | + try: |
| 128 | + while not shutdown_requested: |
| 129 | + # Wait for a client to connect |
| 130 | + if not active_group: |
| 131 | + client_connected.clear() |
| 132 | + await client_connected.wait() |
| 133 | + |
| 134 | + assert active_group is not None |
| 135 | + |
| 136 | + # Decode and stream audio |
| 137 | + try: |
| 138 | + audio_source = await decode_audio(config.source) |
| 139 | + media_stream = MediaStream( |
| 140 | + main_channel_source=audio_source.generator, |
| 141 | + main_channel_format=audio_source.format, |
| 142 | + ) |
| 143 | + await active_group.play_media(media_stream) |
| 144 | + except asyncio.CancelledError: |
| 145 | + if shutdown_requested: |
| 146 | + break |
| 147 | + # A client disconnected - only reset if no active clients remain |
| 148 | + if all(client.closing for client in active_group.clients): |
| 149 | + active_group = None |
| 150 | + except Exception as e: |
| 151 | + print(f"Playback error: {e}") |
| 152 | + logger.debug("Playback error", exc_info=True) |
| 153 | + |
| 154 | + finally: |
| 155 | + event_loop.remove_signal_handler(signal.SIGINT) |
| 156 | + with suppress(Exception): |
| 157 | + # Temp workaround until https://github.com/Sendspin/aiosendspin/pull/108 |
| 158 | + for client in server.clients: |
| 159 | + await client.disconnect(retry_connection=False) |
| 160 | + await server.close() |
| 161 | + |
| 162 | + return 0 |
0 commit comments