远程遥控完成

This commit is contained in:
mtvpls
2026-05-30 22:34:07 +08:00
parent 30554fcd77
commit 3a030cce5a
13 changed files with 1036 additions and 88 deletions
+116 -36
View File
@@ -3,6 +3,14 @@ const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Server } = require('socket.io');
const {
attachTVRemoteIO,
cleanupTVRemoteDevices,
clearTVRemoteHub,
registerTVRemoteDevice,
removeTVRemoteSocket,
updateTVRemoteDevice,
} = require('./src/lib/tv-remote-hub.js');
function shouldInitSQLite() {
const isCloudflare = process.env.CF_PAGES === '1' || process.env.BUILD_TARGET === 'cloudflare';
@@ -705,6 +713,95 @@ class WatchRoomServer {
}
}
function parseCookieHeader(cookieHeader) {
if (!cookieHeader) return {};
return cookieHeader.split(';').reduce((acc, part) => {
const index = part.indexOf('=');
if (index <= 0) return acc;
const key = part.slice(0, index).trim();
const value = part.slice(index + 1).trim();
if (key) acc[key] = value;
return acc;
}, {});
}
function parseSocketAuth(socket) {
const cookies = parseCookieHeader(socket.handshake.headers.cookie || '');
const raw = cookies.auth || socket.handshake.auth?.token || '';
if (!raw) return null;
let decoded = raw;
try {
decoded = decodeURIComponent(decoded);
} catch {}
if (decoded.includes('%')) {
try {
decoded = decodeURIComponent(decoded);
} catch {}
}
try {
return JSON.parse(decoded);
} catch {
return null;
}
}
class TVRemoteServer {
constructor(io) {
this.io = io;
this.cleanupInterval = null;
attachTVRemoteIO(io);
this.setupEventHandlers();
this.startCleanupTimer();
}
setupEventHandlers() {
this.io.on('connection', (socket) => {
socket.on('tv-remote:register-tv', (data, callback) => {
const auth = parseSocketAuth(socket);
if (!auth?.username) {
callback?.({ success: false, error: '未登录' });
return;
}
const deviceId = String(data?.deviceId || '').slice(0, 128);
if (!deviceId) {
callback?.({ success: false, error: '缺少设备 ID' });
return;
}
callback?.(registerTVRemoteDevice(socket.id, auth.username, data));
});
socket.on('tv-remote:tv-state', (data) => {
const auth = parseSocketAuth(socket);
if (!auth?.username) return;
updateTVRemoteDevice(socket.id, auth.username, data);
});
socket.on('disconnect', () => {
removeTVRemoteSocket(socket.id);
});
});
}
startCleanupTimer() {
this.cleanupInterval = setInterval(() => {
cleanupTVRemoteDevices();
}, 30_000);
}
destroy() {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
clearTVRemoteHub();
}
}
app.prepare().then(async () => {
const httpServer = createServer(async (req, res) => {
try {
@@ -722,20 +819,20 @@ app.prepare().then(async () => {
console.log('[WatchRoom] Config:', watchRoomConfig);
let watchRoomServer = null;
let tvRemoteServer = null;
const io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
tvRemoteServer = new TVRemoteServer(io);
console.log('[TVRemote] Socket.IO remote server initialized');
// 只在启用观影室且使用内部服务器时初始化 Socket.IO
if (watchRoomConfig.enabled && watchRoomConfig.serverType === 'internal') {
console.log('[WatchRoom] Initializing Socket.IO server...');
// 初始化 Socket.IO
const io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
// 初始化观影室服务器
watchRoomServer = new WatchRoomServer(io);
console.log('[WatchRoom] Socket.IO server initialized');
@@ -754,31 +851,14 @@ app.prepare().then(async () => {
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
if (watchRoomConfig.enabled && watchRoomConfig.serverType === 'internal') {
console.log(`> Socket.IO ready on ws://${hostname}:${port}`);
}
console.log(`> Socket.IO ready on ws://${hostname}:${port}`);
});
// 优雅关闭
process.on('SIGINT', () => {
console.log('\n[Server] Shutting down...');
if (watchRoomServer) {
watchRoomServer.destroy();
}
httpServer.close(() => {
console.log('[Server] Server closed');
process.exit(0);
});
});
const forceExit = (signal) => {
console.log(`\n[Server] Received ${signal}, force exiting...`);
process.exit(0);
};
process.on('SIGTERM', () => {
console.log('\n[Server] Shutting down...');
if (watchRoomServer) {
watchRoomServer.destroy();
}
httpServer.close(() => {
console.log('[Server] Server closed');
process.exit(0);
});
});
process.on('SIGINT', () => forceExit('SIGINT'));
process.on('SIGTERM', () => forceExit('SIGTERM'));
});