feat: initial commit for TheFarmer project

This commit is contained in:
Karriis
2026-02-18 13:52:06 +08:00
commit 8ceb5fa9db
420 changed files with 61918 additions and 0 deletions

64
server/ws-gateway.js Normal file
View File

@@ -0,0 +1,64 @@
const http = require('http');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '.env') });
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
const { Server } = require('socket.io');
const { createClient } = require('redis');
const { log } = require('./src/utils');
const redisUrl = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
const gatewayPort = Number(process.env.WS_GATEWAY_PORT || 3001);
const corsOrigin = process.env.WS_GATEWAY_CORS_ORIGIN || '*';
const server = http.createServer();
const io = new Server(server, {
cors: {
origin: corsOrigin,
methods: ["GET", "POST"]
}
});
const subscriber = createClient({ url: redisUrl });
subscriber.on('error', (err) => {
log('Redis', `订阅异常: ${err.message}`);
});
function safeParseJson(input) {
try {
return JSON.parse(input);
} catch {
return {};
}
}
async function start() {
await subscriber.connect();
await Promise.all([
subscriber.pSubscribe('bot-log-*', (message, channel) => {
io.emit(channel, safeParseJson(message));
}),
subscriber.pSubscribe('bot-status-*', (message, channel) => {
io.emit(channel, safeParseJson(message));
}),
subscriber.pSubscribe('bot-error-*', (message, channel) => {
io.emit(channel, safeParseJson(message));
})
]);
io.on('connection', (socket) => {
log('Gateway', `Client connected: ${socket.id}`);
socket.on('disconnect', () => {
log('Gateway', `Client disconnected: ${socket.id}`);
});
});
server.listen(gatewayPort, () => {
log('Gateway', `WS Gateway running on http://localhost:${gatewayPort}`);
});
}
start().catch((err) => {
log('Gateway', `启动失败: ${err.message}`);
process.exit(1);
});