diff --git a/src/main/modules/openApi/index.ts b/src/main/modules/openApi/index.ts index 95c2633c..f897bf0c 100644 --- a/src/main/modules/openApi/index.ts +++ b/src/main/modules/openApi/index.ts @@ -9,6 +9,7 @@ let status: LX.OpenAPI.Status = { let httpServer: http.Server let sockets = new Set() +let responses = new Set>() const handleStartServer = async(port = 9000, ip = '127.0.0.1') => new Promise((resolve, reject) => { httpServer = http.createServer((req, res) => { @@ -32,11 +33,72 @@ const handleStartServer = async(port = 9000, ip = '127.0.0.1') => new Promise + // + // + // + // + // + // Nodejs Server-Sent Events + // + // + //

Hello SSE!

+ + //

List of Server-sent events

+ //
    + + // + // + // ` + // break case '/lyric': code = 200 res.setHeader('Content-Type', 'text/plain; charset=utf-8') msg = global.lx.player_status.lyric break + case '/subscribe-player-status': + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + Connection: 'keep-alive', + 'Cache-Control': 'no-cache', + }) + req.socket.setTimeout(0) + req.on('close', () => { + res.end('OK') + responses.delete(res) + }) + for (const [k, v] of Object.entries(global.lx.player_status)) { + res.write(`event: ${k}\n`) + res.write(`data: ${JSON.stringify(v)}\n\n`) + } + responses.add(res) + return default: code = 401 msg = 'Forbidden' @@ -81,10 +143,21 @@ const handleStopServer = async() => new Promise((resolve, reject) => { }) for (const socket of sockets) socket.destroy() sockets.clear() + responses.clear() }) +const sendStatus = (status: Partial) => { + if (!responses.size) return + for (const [k, v] of Object.entries(status)) { + for (const resp of responses) { + resp.write(`event: ${k}\n`) + resp.write(`data: ${JSON.stringify(v)}\n\n`) + } + } +} export const stopServer = async() => { + global.lx.event_app.off('player_status', sendStatus) if (!status.status) { status.status = false status.message = '' @@ -113,6 +186,7 @@ export const startServer = async(port: number) => { status.message = err.message status.address = '' }) + global.lx.event_app.on('player_status', sendStatus) return status }