import { pool } from '../database.js'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import { authenticate } from '../middleware/auth.js'; const SECRET = process.env.JWT_SECRET || 'yx-nav-secret-2026'; const router = (app) => { // ---- 前端公开接口(首页数据) ---- app.get('/api/site', async (req, res) => { try { const [cats] = await pool.query('SELECT * FROM categories ORDER BY sort, id'); const [links] = await pool.query( 'SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id WHERE l.is_show = 1 ORDER BY c.sort, l.sort, l.id' ); const [sets] = await pool.query('SELECT * FROM settings'); const settings = {}; sets.forEach(s => { settings[s.key] = s.value; }); const linksMapped = links.map(r => ({ ...r, categoryId: r.category_id })); res.json({ status: 200, message: '加载成功', result: { categories: cats, links: linksMapped, settings } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); // ---- 公开接口 ---- app.post('/api/auth/login', async (req, res) => { try { const { username, password } = req.body; const [users] = await pool.query('SELECT * FROM users WHERE username = ?', [username]); if (!users.length || !bcrypt.compareSync(password, users[0].password)) { return res.json({ status: 401, message: '用户名或密码错误' }); } const user = users[0]; const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '7d' }); res.json({ status: 200, message: '登录成功', result: { token, user: { id: user.id, nickname: user.nickname } } }); } catch { res.json({ status: 401, message: '登录失败' }); } }); app.get('/api/site/stats', async (req, res) => { try { const [cats] = await pool.query('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id'); const [sets] = await pool.query('SELECT * FROM settings'); const settings = {}; sets.forEach(s => { settings[s.key] = s.value; }); const totalViews = (await pool.query('SELECT COALESCE(SUM(views),0) as total FROM links'))[0][0].total; res.json({ status: 200, result: { categories: cats, settings, totalViews } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); app.post('/api/links/:id/view', async (req, res) => { try { await pool.query('UPDATE links SET views = views + 1 WHERE id = ?', [Number(req.params.id)]); res.json({ status: 200, result: { data: {} } }); } catch { res.json({ status: 500, message: '更新失败' }); } }); // ---- 后台管理接口 ---- app.get('/api/admin/profile', authenticate, async (req, res) => { try { const [users] = await pool.query('SELECT id, username, nickname, role FROM users WHERE id = ?', [req.user.id]); res.json({ status: 200, result: { data: users[0] } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); app.put('/api/admin/profile', authenticate, async (req, res) => { try { await pool.query('UPDATE users SET nickname = ? WHERE id = ?', [req.body.nickname, req.user.id]); res.json({ status: 200, message: '更新成功' }); } catch { res.json({ status: 500, message: '更新失败' }); } }); // 修改密码 app.put('/api/admin/password', authenticate, async (req, res) => { try { const { oldPassword, newPassword } = req.body; const [users] = await pool.query('SELECT password FROM users WHERE id = ?', [req.user.id]); if (!users.length || !bcrypt.compareSync(oldPassword, users[0].password)) { return res.json({ status: 401, message: '当前密码错误' }); } const hash = bcrypt.hashSync(newPassword, 10); await pool.query('UPDATE users SET password = ? WHERE id = ?', [hash, req.user.id]); res.json({ status: 200, message: '密码修改成功' }); } catch { res.json({ status: 500, message: '修改失败' }); } }); app.get('/api/admin/categories', authenticate, async (req, res) => { try { const [rows] = await pool.query('SELECT * FROM categories ORDER BY sort, id'); res.json({ status: 200, result: { data: rows } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); app.post('/api/admin/categories', authenticate, async (req, res) => { try { const { name, icon, sort, parentId } = req.body; const [result] = await pool.query('INSERT INTO categories (name, icon, sort, parent_id) VALUES (?, ?, ?, ?)', [name, icon || '🔗', sort || 0, parentId || null]); res.json({ status: 200, message: '创建成功', result: { data: { id: Number(result.insertId) } } }); } catch { res.json({ status: 500, message: '创建失败' }); } }); app.put('/api/admin/categories/:id', authenticate, async (req, res) => { try { const { name, icon, sort, parentId } = req.body; await pool.query('UPDATE categories SET name = ?, icon = ?, sort = ?, parent_id = ? WHERE id = ?', [name, icon || '🔗', sort ?? 0, parentId || null, Number(req.params.id)]); res.json({ status: 200, message: '更新成功' }); } catch { res.json({ status: 500, message: '更新失败' }); } }); app.delete('/api/admin/categories/:id', authenticate, async (req, res) => { try { await pool.query('DELETE FROM categories WHERE id = ?', [Number(req.params.id)]); res.json({ status: 200, message: '删除成功' }); } catch { res.json({ status: 500, message: '删除失败' }); } }); app.get('/api/admin/links', authenticate, async (req, res) => { try { const { keyword, categoryId, page = '1', pageSize = '20' } = req.query; const p = Math.max(1, Number(page)); const ps = Math.min(100, Math.max(1, Number(pageSize))); const offset = (p - 1) * ps; let where = ''; const params = []; if (keyword) { where += ' WHERE (l.title LIKE ? OR l.description LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); } if (categoryId) { where += (where ? ' AND' : ' WHERE') + ' l.category_id = ?'; params.push(Number(categoryId)); } const [countRows] = await pool.query(`SELECT COUNT(*) as total FROM links l${where}`, params); const total = Number(countRows[0].total); const [rows] = await pool.query(`SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id${where} ORDER BY l.sort, l.id LIMIT ? OFFSET ?`, [...params, ps, offset]); res.json({ status: 200, result: { data: { list: rows, total, page: p, pageSize: ps } } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); app.post('/api/admin/links', authenticate, async (req, res) => { try { const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body; const [result] = await pool.query('INSERT INTO links (title, url, category_id, description, icon_url, sort, is_show) VALUES (?, ?, ?, ?, ?, ?, ?)', [title, url, Number(categoryId), description || '', iconUrl || '', sort || 0, isShow !== false ? 1 : 0]); res.json({ status: 200, message: '创建成功', result: { data: { id: Number(result.insertId) } } }); } catch { res.json({ status: 500, message: '创建失败' }); } }); app.put('/api/admin/links/:id', authenticate, async (req, res) => { try { const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body; await pool.query('UPDATE links SET title=?, url=?, category_id=?, description=?, icon_url=?, sort=?, is_show=? WHERE id=?', [title, url, Number(categoryId), description, iconUrl, sort, isShow !== false ? 1 : 0, Number(req.params.id)]); res.json({ status: 200, message: '更新成功' }); } catch { res.json({ status: 500, message: '更新失败' }); } }); app.delete('/api/admin/links/:id', authenticate, async (req, res) => { try { await pool.query('DELETE FROM links WHERE id = ?', [Number(req.params.id)]); res.json({ status: 200, message: '删除成功' }); } catch { res.json({ status: 500, message: '删除失败' }); } }); app.put('/api/admin/links/sort', authenticate, async (req, res) => { try { for (const { id, sort } of (req.body.sorts || [])) { await pool.query('UPDATE links SET sort = ? WHERE id = ?', [sort, Number(id)]); } res.json({ status: 200, message: '排序成功' }); } catch { res.json({ status: 500, message: '排序失败' }); } }); // 批量删除链接 app.post('/api/admin/links/batch-delete', authenticate, async (req, res) => { try { const ids = (req.body.ids || []).map(Number).filter(Boolean); if (ids.length === 0) return res.json({ status: 400, message: '请选择链接' }); await pool.query(`DELETE FROM links WHERE id IN (${ids.map(() => '?').join(',')})`, ids); res.json({ status: 200, message: `已删除 ${ids.length} 条链接` }); } catch { res.json({ status: 500, message: '删除失败' }); } }); // 批量移动分类 app.post('/api/admin/links/batch-move', authenticate, async (req, res) => { try { const ids = (req.body.ids || []).map(Number).filter(Boolean); const categoryId = Number(req.body.categoryId); if (ids.length === 0 || !categoryId) return res.json({ status: 400, message: '参数不完整' }); await pool.query(`UPDATE links SET category_id = ? WHERE id IN (${ids.map(() => '?').join(',')})`, [categoryId, ...ids]); res.json({ status: 200, message: `已移动 ${ids.length} 条链接` }); } catch { res.json({ status: 500, message: '移动失败' }); } }); app.get('/api/admin/settings', authenticate, async (req, res) => { try { const [sets] = await pool.query('SELECT * FROM settings'); const settings = {}; sets.forEach(s => { settings[s.key] = s.value; }); res.json({ status: 200, result: { data: settings } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); // 后台统计 app.get('/api/admin/stats', authenticate, async (req, res) => { try { const [cats] = await pool.query('SELECT c.*, IFNULL(COUNT(l.id),0) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id GROUP BY c.id ORDER BY c.sort, c.id'); const [linkRows] = await pool.query('SELECT COUNT(*) as total, COALESCE(SUM(views),0) as views FROM links'); res.json({ status: 200, result: { data: { categories: cats, linkCount: Number(linkRows[0].total), totalViews: Number(linkRows[0].views) } } }); } catch { res.json({ status: 500, message: '加载失败' }); } }); app.put('/api/admin/settings', authenticate, async (req, res) => { try { for (const [key, value] of Object.entries(req.body)) { await pool.query('INSERT INTO settings (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)', [key, value]); } res.json({ status: 200, message: '保存成功' }); } catch { res.json({ status: 500, message: '保存失败' }); } }); // ---- 商汤科技额度查询(代理) ---- let sensenovaCache = { data: null, time: 0 }; app.get('/api/proxy/sensenova/status', async (req, res) => { try { // 5分钟缓存 if (Date.now() - sensenovaCache.time < 5 * 60 * 1000 && sensenovaCache.data) { return res.json({ status: 200, result: sensenovaCache.data }); } const [sets] = await pool.query("SELECT value FROM settings WHERE `key` = 'sensenova_api_key'"); const apiKey = sets.length > 0 ? sets[0].value : ''; if (!apiKey) { sensenovaCache = { data: { valid: false, message: '未配置 API Key' }, time: Date.now() }; return res.json({ status: 200, result: sensenovaCache.data }); } // 调用模型列表 API 验证 Key 有效性 const modelResp = await fetch('https://token.sensenova.cn/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` }, signal: AbortSignal.timeout(10000), }); if (modelResp.status === 200) { const models = await modelResp.json(); // 尝试轻量调用检查配额 let quotaInfo = { available: true, models: [] }; for (const m of ['sensenova-6.7-flash-lite', 'deepseek-v4-flash', 'sensenova-u1-fast']) { if (models.data?.some((md) => md.id === m)) { quotaInfo.models.push(m); } } sensenovaCache = { data: { valid: true, models: quotaInfo.models, message: 'API Key 有效' }, time: Date.now() }; } else if (modelResp.status === 401) { sensenovaCache = { data: { valid: false, message: 'API Key 无效或已过期' }, time: Date.now() }; } else { sensenovaCache = { data: { valid: false, message: `API 返回 ${modelResp.status}` }, time: Date.now() }; } res.json({ status: 200, result: sensenovaCache.data }); } catch (err) { res.json({ status: 200, result: { valid: false, message: `查询失败: ${err?.message || '未知错误'}` } }); } }); }; export default router;