backend: better socket handling

This commit is contained in:
2025-02-15 02:19:14 -08:00
parent a3e0758205
commit b7ad824eb5
2 changed files with 13 additions and 8 deletions

View File

@@ -17,20 +17,24 @@ export class MediaPlayer {
private dataBuffer: string = ''; private dataBuffer: string = '';
constructor() { constructor() {
// Create a random string of length 5
const socketFilename = Math.random().toString(36).substring(2, 10);
const socketPath = `/tmp/mpv-${socketFilename}`;
console.log("Starting player process"); console.log("Starting player process");
this.playerProcess = spawn("mpv", [ this.playerProcess = spawn("mpv", [
"--no-video", "--no-video",
"--no-terminal", "--no-terminal",
"--idle=yes", "--idle=yes",
"--input-ipc-server=/tmp/mpv-socket" "--input-ipc-server=" + socketPath
]); ]);
this.socket = new Socket(); this.socket = new Socket();
this.playerProcess.on("spawn", () => { this.playerProcess.on("spawn", () => {
console.log("Player process spawned, opening socket"); console.log(`Player process spawned, opening socket @ ${socketPath}`);
setTimeout(() => { setTimeout(() => {
this.connectToSocket(); this.connectToSocket(socketPath);
}, 200); }, 200);
}); });
} }
@@ -123,13 +127,13 @@ export class MediaPlayer {
}); });
} }
private connectToSocket() { private connectToSocket(path: string) {
this.socket.connect("/tmp/mpv-socket"); this.socket.connect(path);
this.socket.on("data", data => this.receiveData(data.toString())); this.socket.on("data", data => this.receiveData(data.toString()));
} }
private handleEvent(event: string, data: any) { private handleEvent(event: string, data: any) {
console.log("Event [" + event + "]: " + JSON.stringify(data, null, 2)); console.log("MPV Event [" + event + "]: " + JSON.stringify(data, null, 2));
// Notify all subscribers // Notify all subscribers
this.eventSubscribers.forEach(subscriber => { this.eventSubscribers.forEach(subscriber => {
@@ -156,7 +160,7 @@ export class MediaPlayer {
this.pendingCommands.delete(response.request_id); this.pendingCommands.delete(response.request_id);
} }
} else if (response.event) { } else if (response.event) {
this.handleEvent(response.event, response.data); this.handleEvent(response.event, response);
} else { } else {
console.log(response); console.log(response);
} }

View File

@@ -78,10 +78,11 @@ apiRouter.post("/volume", async (req, res) => {
}); });
apiRouter.ws("/events", (ws, req) => { apiRouter.ws("/events", (ws, req) => {
console.log(req.query); console.log("Events client connected");
mediaPlayer.subscribe(ws); mediaPlayer.subscribe(ws);
ws.on("close", () => { ws.on("close", () => {
console.log("Events client disconnected");
mediaPlayer.unsubscribe(ws); mediaPlayer.unsubscribe(ws);
}); });
}); });