import express from "express"; import expressWs from "express-ws"; import { MediaPlayer } from "./MediaPlayer"; interface PlaylistAppendRequest { url: string; } const app = express(); expressWs(app); app.use(express.json()); const apiRouter = express.Router(); const mediaPlayer = new MediaPlayer(); apiRouter.get("/playlist", async (req, res) => { const playlist = await mediaPlayer.getPlaylist(); res.send(playlist); }); apiRouter.post("/playlist", async (req, res) => { try { const { url } = req.body as PlaylistAppendRequest; await mediaPlayer.append(url); res.send(JSON.stringify({ success: true })); } catch (error: any) { res.status(500) .send(JSON.stringify({ success: false, error: error.message })); } }); apiRouter.delete("/playlist/:index", async (req, res) => { const { index } = req.params as { index: string }; await mediaPlayer.deletePlaylistItem(parseInt(index)); res.send(JSON.stringify({ success: true })); }); apiRouter.post("/play", async (req, res) => { try { await mediaPlayer.play(); res.send(JSON.stringify({ success: true })); } catch (error: any) { res.status(500) .send(JSON.stringify({ success: false, error: error.message })); } }); apiRouter.post("/pause", async (req, res) => { try { await mediaPlayer.pause(); res.send(JSON.stringify({ success: true })); } catch (error: any) { res.status(500) .send(JSON.stringify({ success: false, error: error.message })); } }); apiRouter.get("/nowplaying", async (req, res) => { const nowPlaying = await mediaPlayer.getNowPlaying(); const pauseState = await mediaPlayer.getPauseState(); const volume = await mediaPlayer.getVolume(); const idle = await mediaPlayer.getIdle(); res.send(JSON.stringify({ success: true, nowPlaying: nowPlaying, isPaused: pauseState, volume: volume, isIdle: idle })); }); apiRouter.post("/volume", async (req, res) => { const { volume } = req.body as { volume: number }; await mediaPlayer.setVolume(volume); res.send(JSON.stringify({ success: true })); }); apiRouter.ws("/events", (ws, req) => { console.log(req.query); mediaPlayer.subscribe(ws); ws.on("close", () => { mediaPlayer.unsubscribe(ws); }); }); // Serve static files for React app (after building) app.use(express.static("dist/frontend")); // Mount API routes under /api app.use("/api", apiRouter); // Serve React app for all other routes (client-side routing) app.get("*", (req, res) => { res.sendFile("dist/frontend/index.html", { root: "." }); }); app.listen(3000, () => { console.log("Server is running on port 3000"); });