webrtc/index.js

62 lines
2.6 KiB
JavaScript
Raw Normal View History

2023-09-27 14:26:12 +08:00
import express from 'express'
import expressWs from 'express-ws'
2023-09-28 16:06:38 +08:00
import { exec } from 'child_process'
2023-09-27 14:26:12 +08:00
const app = express()
const wsInstance = expressWs(app)
app.use(express.static('public'))
// Websocket 处理 webRTC 信令
app.ws('/webrtc/:channel', (ws, req) => {
ws.id = req.headers['sec-websocket-key']
ws.channel = req.params.channel
2023-09-30 22:45:01 +08:00
ws.name = req.query.name
2023-09-27 14:26:12 +08:00
// 设备离开频道时广播给所有在线设备
ws.on('close', () => {
console.log(ws.id, '设备离开频道:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
client.send(JSON.stringify({ type: 'pull', id: ws.id, channel: ws.channel }))
}
})
})
// 设备发生错误时广播给所有在线设备
ws.on('error', () => {
console.log(ws.id, '设备发生错误:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
client.send(JSON.stringify({ type: 'error', id: ws.id, channel: ws.channel }))
}
})
})
// 设备发送信令时转发给指定在线设备
ws.on('message', message => {
console.log(ws.id, '设备发送信令:', ws.channel, wsInstance.getWss().clients.size)
2023-09-28 23:49:26 +08:00
const data = JSON.parse(message)
2023-09-27 14:26:12 +08:00
wsInstance.getWss().clients.forEach(client => {
2023-09-28 23:49:26 +08:00
if (client !== ws && client.readyState === 1 && client.channel === ws.channel && client.id === data.id) {
client.send(JSON.stringify({ ...data, id: ws.id }))
2023-09-27 14:26:12 +08:00
}
})
})
// 设备加入频道时广播给所有在线设备(也获取所有在线设备)
console.log(ws.id, '设备加入频道:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
2023-09-30 22:45:01 +08:00
client.send(JSON.stringify({ type: 'push', id: ws.id, name: ws.name, channel: ws.channel }))
ws.send(JSON.stringify({ type: 'list', id: client.id, name: client.name, channel: client.channel }))
2023-09-27 14:26:12 +08:00
}
})
})
2023-09-28 16:06:38 +08:00
// WEBHOOK 处理 GitHub 事件
app.post('/webhook', (req, res) => {
console.log('WEBHOOK:', req.body)
return exec('git pull;npm i', (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: err })
return res.json({ stdout, stderr })
})
})
2023-09-28 16:03:19 +08:00
app.listen(4096, () => console.log('Server started on port 4096'))