const express = require('express'); const fs = require('fs').promises; const fsSync = require('fs'); const path = require('path'); const app = express(); const PORT = 3000; // 获取当前时间,格式:YYYY-MM-DD HH:mm:ss function getCurrentTime() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } function extractBetweenZUXOSandST(str) { // const regex = /_ZUXOS_(.+?)_ST_/; const regex = /_ZUXOS_(.+?)(_ST_|_DEV_)/; const match = str.match(regex); return match ? match[1] : null; } // 解析 JSON 和 URL-encoded 请求体 app.use(express.json()); app.use(express.urlencoded({ extended: true })); // 提供静态文件服务(可选) app.use(express.static(__dirname)); // POST /upgrade 接口:返回 ota.xml 内容 app.post('/upgrade', async (req, res) => { try { // 构建完整的请求 URL(host + path + query) const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; const version = extractBetweenZUXOSandST(req.originalUrl); // 记录日志:[时间] URL const logEntry = `[${getCurrentTime()}] 当前版本:${version} ${fullUrl}\n`; // 同步写入日志文件 fsSync.appendFileSync(path.join(__dirname, 'log.txt'), logEntry); // 返回 ota.xml 文件内容 const xmlFilePath = path.join(__dirname, version + '.xml'); const xmlContent = await fs.readFile(xmlFilePath, 'utf-8'); res.setHeader('Content-Type', 'application/xml'); res.status(200).send(xmlContent); } catch (error) { console.error('Error reading or sending OTA config:', error); if (error.code === 'ENOENT') { res.status(404).send('OTA configuration file not found'); } else { res.status(500).send('Failed to retrieve OTA configuration'); } } }); // GET / 页面:展示 log.txt 内容 app.get('/', async (req, res) => { const logPath = path.join(__dirname, 'log.txt'); try { let data = ''; try { data = await fs.readFile(logPath, 'utf8'); } catch (err) { if (err.code !== 'ENOENT') throw err; } res.send(`

Log Content:

${data}
`); } catch (err) { console.error('Error reading log file:', err); res.status(500).send('Error reading log file'); } }); // 启动服务器 app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Endpoints:'); console.log(` - POST /upgrade`); console.log(` - GET / (view logs)`); });