76 lines
2.1 KiB
JavaScript
76 lines
2.1 KiB
JavaScript
import WebSocket from 'ws'
|
|
|
|
const wss = new WebSocket.Server({ noServer: true })
|
|
|
|
function getClientByDevice (dev) {
|
|
for (let i in wss.clients) {
|
|
let client = wss.clients[i]
|
|
if (client.device === dev) return client
|
|
}
|
|
return null
|
|
}
|
|
|
|
wss.on('connection', function (ws) {
|
|
ws.on('device', function (devid) {
|
|
ws.device = devid
|
|
})
|
|
|
|
ws.on('connect', function (devid) {
|
|
let target = getClientByDevice(devid)
|
|
if (!target) return ws.emit('errno', { code: 100, error: 'Target device is not available.' })
|
|
target.emit('request', ws.device)
|
|
})
|
|
|
|
ws.on('detach', function () {
|
|
if (!ws.controlled) return
|
|
ws.controlled = null
|
|
let target = getClientByDevice(devid)
|
|
if (!target) return
|
|
target.controller = null
|
|
target.emit('detach')
|
|
})
|
|
|
|
ws.on('accept', function (devid) {
|
|
ws.controller = devid
|
|
let target = getClientByDevice(devid)
|
|
if (!target) return ws.emit('errno', { code: 100, error: 'Target device is not available.' })
|
|
target.controlled = devid
|
|
target.emit('accepted', devid)
|
|
})
|
|
|
|
ws.on('play', function (id) {
|
|
if (!ws.controlled) return
|
|
let target = getClientByDevice(ws.controlled)
|
|
if (!target) return ws.emit('errno', { code: 100, error: 'Target device is not available.' })
|
|
target.emit('play', id)
|
|
})
|
|
|
|
ws.on('seekto', function (num) {
|
|
if (!ws.controlled) return
|
|
let target = getClientByDevice(ws.controlled)
|
|
if (!target) return ws.emit('errno', { code: 100, error: 'Target device is not available.' })
|
|
target.emit('seekto', num)
|
|
})
|
|
|
|
ws.on('volumeto', function (num) {
|
|
if (!ws.controlled) return
|
|
let target = getClientByDevice(ws.controlled)
|
|
if (!target) return ws.emit('errno', { code: 100, error: 'Target device is not available.' })
|
|
target.emit('volumeto', num)
|
|
})
|
|
})
|
|
|
|
module.exports = function (server) {
|
|
server.on('upgrade', function (request, socket, head) {
|
|
const pathname = url.parse(request.url).pathname
|
|
|
|
if (pathname === '/remote') {
|
|
wss.handleUpgrade(request, socket, head, function (ws) {
|
|
wss.emit('connection', ws, request)
|
|
})
|
|
} else {
|
|
socket.destroy()
|
|
}
|
|
})
|
|
}
|