2026-02-10 09:54:38 +01:00
|
|
|
import { WebSocketServer } from 'ws'
|
2026-06-21 18:35:08 +02:00
|
|
|
import express from 'express'
|
|
|
|
|
import { fileURLToPath } from 'url'
|
|
|
|
|
import { dirname, join } from 'path'
|
2026-02-10 09:54:38 +01:00
|
|
|
import { setupWebSocketHandler } from './src/websocket-handler.js'
|
|
|
|
|
import { printServerInfo } from './src/server-utils.js'
|
2026-05-12 14:17:10 +02:00
|
|
|
import { loadState, saveState } from './src/persist.js'
|
2026-06-21 18:35:08 +02:00
|
|
|
import { listSpotVideos } from './src/spot-utils.js'
|
|
|
|
|
|
|
|
|
|
const SPOT_DIR = join(dirname(fileURLToPath(import.meta.url)), 'spot')
|
2026-02-10 09:54:38 +01:00
|
|
|
|
|
|
|
|
export default function websocketPlugin() {
|
|
|
|
|
return {
|
|
|
|
|
name: 'vite-plugin-websocket',
|
|
|
|
|
configureServer(server) {
|
|
|
|
|
const wss = new WebSocketServer({ noServer: true })
|
2026-05-12 14:17:10 +02:00
|
|
|
setupWebSocketHandler(wss, { initialState: loadState(), onStateChange: saveState })
|
2026-02-10 09:54:38 +01:00
|
|
|
|
2026-06-21 18:35:08 +02:00
|
|
|
// Video spot del time out: stesso comportamento di server.js (elenco + statici)
|
|
|
|
|
server.middlewares.use('/spot', (req, res, next) => {
|
|
|
|
|
if (req.url === '/list' || req.url === '/list/') {
|
|
|
|
|
res.setHeader('Content-Type', 'application/json')
|
|
|
|
|
return res.end(JSON.stringify(listSpotVideos(SPOT_DIR)))
|
|
|
|
|
}
|
|
|
|
|
next()
|
|
|
|
|
})
|
|
|
|
|
server.middlewares.use('/spot', express.static(SPOT_DIR))
|
|
|
|
|
|
2026-05-12 12:22:43 +02:00
|
|
|
// Rewrite /display → / (index.html) e /controller → /controller.html
|
|
|
|
|
server.middlewares.use((req, _res, next) => {
|
|
|
|
|
if (req.url === '/display' || req.url === '/display/') req.url = '/'
|
|
|
|
|
else if (req.url === '/controller' || req.url === '/controller/') req.url = '/controller.html'
|
|
|
|
|
next()
|
|
|
|
|
})
|
|
|
|
|
|
2026-02-10 09:54:38 +01:00
|
|
|
server.httpServer.on('upgrade', (request, socket, head) => {
|
|
|
|
|
const pathname = new URL(request.url, `http://${request.headers.host}`).pathname
|
2026-02-10 23:45:58 +01:00
|
|
|
if (pathname === '/ws') {
|
2026-02-10 09:54:38 +01:00
|
|
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
|
|
|
wss.emit('connection', ws, request)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
server.httpServer.once('listening', () => {
|
2026-05-12 12:22:43 +02:00
|
|
|
const { port } = server.httpServer.address()
|
|
|
|
|
setTimeout(() => printServerInfo(port), 100)
|
2026-02-10 09:54:38 +01:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|