const express = require('express'); const http = require('http'); const { WebSocketServer } = require('ws'); const path = require('path'); const fs = require('fs'); const cors = require('cors'); const PORT = process.env.PORT || 3000; const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'dev_mock_teacher_pwd'; const DATA_DIR = path.join(__dirname, 'data'); const DB_FILE = path.join(DATA_DIR, 'db.json'); if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } // Simple JSON Database Helper function loadDb() { if (!fs.existsSync(DB_FILE)) { const initialData = { classes: [ { id: "801", name: "八年级(1)班", token: "device_secret_token_801", students: ["张三", "李四", "王浩", "赵晨", "陈欣", "刘洋", "周杰", "孙静"] }, { id: "802", name: "八年级(2)班", token: "device_secret_token_802", students: ["林平", "黄磊", "郑强", "韩梅梅", "李雷"] } ], messages: [], self_checks: {} }; fs.writeFileSync(DB_FILE, JSON.stringify(initialData, null, 2), 'utf8'); return initialData; } try { return JSON.parse(fs.readFileSync(DB_FILE, 'utf8')); } catch (err) { console.error('Failed to load DB:', err); return { classes: [], messages: [], self_checks: {} }; } } function saveDb(data) { try { fs.writeFileSync(DB_FILE, JSON.stringify(data, null, 2), 'utf8'); } catch (err) { console.error('Failed to save DB:', err); } } const db = loadDb(); const app = express(); app.use(cors()); app.use(express.json()); app.use(express.static(path.join(__dirname, '../Web'))); const server = http.createServer(app); // WebSocket Servers const wssDevice = new WebSocketServer({ noServer: true }); const wssAdmin = new WebSocketServer({ noServer: true }); // Device Sockets: class_id -> { ws, class_id, token, info, lastHeartbeat } const deviceSockets = new Map(); // Admin Sockets: Set of ws const adminSockets = new Set(); function broadcastToAdmins(payload) { const json = JSON.stringify(payload); for (const adminWs of adminSockets) { if (adminWs.readyState === 1) { // OPEN adminWs.send(json); } } } // Route HTTP Upgrade to corresponding WebSocket server server.on('upgrade', (request, socket, head) => { const url = new URL(request.url, `http://${request.headers.host}`); const pathname = url.pathname; if (pathname === '/ws/device') { wssDevice.handleUpgrade(request, socket, head, (ws) => { wssDevice.emit('connection', ws, request); }); } else if (pathname === '/ws/admin') { wssAdmin.handleUpgrade(request, socket, head, (ws) => { wssAdmin.emit('connection', ws, request); }); } else { socket.destroy(); } }); // Device WebSocket Handler wssDevice.on('connection', (ws) => { let boundClassId = null; ws.on('message', (data) => { try { const msg = JSON.parse(data.toString()); if (msg.type === 'register') { const cls = db.classes.find(c => c.id === msg.class_id); if (!cls || cls.token !== msg.device_token) { console.warn(`[Device Auth Failed] class_id: ${msg.class_id}`); ws.send(JSON.stringify({ type: 'auth_error', message: 'Invalid device token or class ID' })); ws.close(); return; } boundClassId = msg.class_id; deviceSockets.set(boundClassId, { ws, class_id: boundClassId, name: msg.class_name || cls.name, hostname: msg.hostname, version: msg.version, lastHeartbeat: Date.now() }); console.log(`[Device Online] ${cls.name} (${boundClassId}) from ${msg.hostname}`); broadcastToAdmins({ type: 'device_status', class_id: boundClassId, online: true, lastHeartbeat: Date.now(), hostname: msg.hostname }); } else if (msg.type === 'heartbeat') { if (boundClassId) { const dev = deviceSockets.get(boundClassId); if (dev) { dev.lastHeartbeat = Date.now(); broadcastToAdmins({ type: 'heartbeat', class_id: boundClassId, timestamp: Date.now() }); } } } else if (msg.type === 'status') { // Receipt from classroom (delivered, acknowledged, timeout) console.log(`[Receipt] msg_id: ${msg.msg_id}, status: ${msg.status}`); const m = db.messages.find(item => item.id === msg.msg_id); if (m) { m.status = msg.status; m.status_time = msg.timestamp || new Date().toISOString(); saveDb(db); } broadcastToAdmins({ type: 'message_status', msg_id: msg.msg_id, class_id: msg.class_id || boundClassId, status: msg.status, timestamp: new Date().toISOString() }); } else if (msg.type === 'self_check_result') { console.log(`[Self-Check Result] class: ${msg.class_id}`, msg.result); db.self_checks[msg.class_id] = { ...msg.result, updated_at: new Date().toISOString() }; saveDb(db); broadcastToAdmins({ type: 'self_check_result', class_id: msg.class_id, result: db.self_checks[msg.class_id] }); } else if (msg.type === 'logs_result') { broadcastToAdmins({ type: 'logs_result', class_id: msg.class_id, logs: msg.logs }); } } catch (err) { console.error('[Device WS Error]', err); } }); ws.on('close', () => { if (boundClassId && deviceSockets.get(boundClassId)?.ws === ws) { console.log(`[Device Offline] class_id: ${boundClassId}`); deviceSockets.delete(boundClassId); broadcastToAdmins({ type: 'device_status', class_id: boundClassId, online: false }); } }); }); // Admin WebSocket Handler wssAdmin.on('connection', (ws) => { adminSockets.add(ws); console.log('[Admin Connected] Total admins:', adminSockets.size); ws.on('close', () => { adminSockets.delete(ws); }); }); // Periodic Heartbeat Check (Mark offline if no heartbeat > 45s) setInterval(() => { const now = Date.now(); for (const [classId, dev] of deviceSockets.entries()) { if (now - dev.lastHeartbeat > 45000) { console.warn(`[Device Heartbeat Timeout] class_id: ${classId}`); try { dev.ws.close(); } catch {} deviceSockets.delete(classId); broadcastToAdmins({ type: 'device_status', class_id: classId, online: false }); } } }, 15000); // =================== REST API =================== // Login API app.post('/api/auth/login', (req, res) => { const { password } = req.body; if (password === ADMIN_PASSWORD) { return res.json({ success: true, token: 'classnotify-teacher-token-' + Date.now() }); } return res.status(401).json({ success: false, message: '密码错误' }); }); // Get Classes with Live Status app.get('/api/classes', (req, res) => { const list = db.classes.map(cls => { const dev = deviceSockets.get(cls.id); const isOnline = !!(dev && dev.ws.readyState === 1); const selfCheck = db.self_checks[cls.id] || null; return { id: cls.id, name: cls.name, students: cls.students || [], online: isOnline, hostname: dev ? dev.hostname : null, lastHeartbeat: dev ? dev.lastHeartbeat : null, selfCheck }; }); res.json({ success: true, classes: list }); }); // Send Notification to Classroom app.post('/api/notify/send', (req, res) => { const { class_id, student_name, text, msg_type, voice, shake, duration, title } = req.body; if (!class_id || !text) { return res.status(400).json({ success: false, message: '缺少班级或通知内容' }); } const dev = deviceSockets.get(class_id); if (!dev || dev.ws.readyState !== 1) { return res.status(404).json({ success: false, message: '目标教室设备当前不在线,无法即时送达' }); } const msgId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5); const payload = { type: msg_type === 'call' ? 'call' : 'notify', msg_id: msgId, title: title || (msg_type === 'call' ? '🔔 老师呼叫' : (msg_type === 'urgent' ? '⚠️ 紧急提醒' : '📢 班级通知')), text: text, msg_type: msg_type || 'call', voice: voice !== false, shake: shake !== false, duration: duration || 15 }; // Record in DB const record = { id: msgId, class_id, student_name: student_name || null, text, msg_type: payload.msg_type, created_at: new Date().toISOString(), status: 'sent' // sent -> delivered -> acknowledged / timeout }; db.messages.unshift(record); if (db.messages.length > 200) db.messages.pop(); saveDb(db); // Send to classroom device dev.ws.send(JSON.stringify(payload)); console.log(`[Notification Sent] To ${class_id}: ${text}`); // Broadcast to all admins broadcastToAdmins({ type: 'message_new', message: record }); res.json({ success: true, msg_id: msgId, message: '通知已发送到教室' }); }); // Send Remote Management Command app.post('/api/device/command', (req, res) => { const { class_id, command } = req.body; if (!class_id || !command) { return res.status(400).json({ success: false, message: '缺少参数' }); } const dev = deviceSockets.get(class_id); if (!dev || dev.ws.readyState !== 1) { return res.status(404).json({ success: false, message: '设备不在线' }); } dev.ws.send(JSON.stringify({ type: 'command', command: command })); console.log(`[Command Sent] To ${class_id}: ${command}`); res.json({ success: true, message: `指令 ${command} 已下发` }); }); // Get Notification History app.get('/api/notify/history', (req, res) => { res.json({ success: true, messages: db.messages.slice(0, 50) }); }); // Start Server server.listen(PORT, () => { console.log(`=================================================`); console.log(` ClassNotify Server is running on port ${PORT}`); console.log(` Teacher Web: http://localhost:${PORT}`); console.log(` Device WSS: ws://localhost:${PORT}/ws/device`); console.log(`=================================================`); });