diff --git a/.gitignore b/.gitignore index 1c1662d..31c019c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ -# 密钥:绝不入库(容器用 -e OMNI_KEY 注入) +# 密钥:绝不入库(容器用 -e 注入,如 HUB_API_KEY) .apikey .env -# 生成物 +# 生成物 / 本机状态 gallery/ gallery.json +hub.json node_modules/ *.log diff --git a/README.md b/README.md index 48d28b2..3ee19c7 100644 --- a/README.md +++ b/README.md @@ -59,15 +59,51 @@ docker run -d --name cover-ai --restart always --memory 384m -p 8128:3000 \ -e AI_BASE=https://ai.88531.cn/v1 \ -e AI_MODEL=mimo-v2.6-flash \ -e REGISTER_URL=https://ai.88531.cn/register \ + -e VERSION=1.0.0 \ + -e HUB_PROJECT_ID=<授权中心项目id> \ + -e HUB_API_KEY=<项目 api_key> \ cover-ai:1.0 ``` - **没有 `OMNI_KEY` 这类服务端密钥了**——Key 由每个使用者在页面里自己填(存浏览器 localStorage) - `AI_BASE` / `AI_MODEL` / `REGISTER_URL` 只是「表单默认值 + 引导链接」,可改 +- `HUB_*` 是授权中心(版本推送 / 公告 / 安装与在线统计),不配也能跑,只是没有更新提示和公告;`HUB_DISABLED=1` 可彻底关掉上报 - `server.js` / `ui.html` 是 COPY 进镜像的,改完要重新 `docker build` - 生成图落在 `/data/gallery/`(宿主目录),容器删了图还在 -## 五、为什么这么写(几个刻意的选择) +## 五、授权中心(版本号 / 新版本提示 / 公告 / 安装与在线统计) + +复用自建 CardAuth 的「免费工具遥测」三接口,右上角常驻当前版本,有新版本自动提示。 + +| 能力 | 表现 | +|---|---| +| 当前版本 | 右上角徽章 `v1.0.0`,点击弹出版本信息(当前 / 最新) | +| 版本推送 | 有新版本 → 徽章变黄 + 顶部黄色横幅「发现新版本 vX」(说明 + 下载链接 + 知道了,按版本记忆) | +| 公告 | 右上角 🔔,有公告亮橙点;点开面板看全部;`popup` 公告只弹一次(按 id 记忆);后台删公告 → 面板自动关、铃铛回「暂无公告」 | +| 安装数 | 首次启动登记 + 版本检查写 `ca_installations` | +| 在线数 | 开机一次 + 每 30 分钟心跳写 `ca_online_logs`(按天去重) | + +- 节流:更新检查 6 小时(失败 30 分钟重试)、心跳 30 分钟、公告 60 秒;**授权中心不可达不影响任何功能**(版本照常显示、公告保留上次结果、更新提示消失) +- 机器码 13 位数字只存服务端 `/data/hub.json`,**不下发浏览器、不在 UI 展示**;`hub.json` 已进 `.gitignore` +- 管理接口:`POST /api/hub/refresh` 绕过节流强刷一次;`GET /api/health` 看 `version` 与 `hub` 状态(`on` / `unconfigured` / `off`) + +### 看统计(安装数 / 今日在线 / 近 7 天在线) + +统计落在 CardAuth 库里,只读 SQL(进 `cardauth-db` 容器执行): + +```sql +SELECT COUNT(*) FROM ca_installations WHERE project_id=<本项目id> AND status='active'; -- 累计安装 +SELECT COUNT(DISTINCT machine_id) FROM ca_online_logs WHERE project_id= AND online_date=CURDATE(); -- 今日在线 +SELECT COUNT(DISTINCT machine_id) FROM ca_online_logs WHERE project_id= AND online_date >= CURDATE()-INTERVAL 7 DAY; -- 近 7 天 +``` + +### 发新版 / 发公告的顺序 + +1. 先把新镜像/新包推出去(用户点下载链接要能拉到东西) +2. 再在 CardAuth 里写 `ca_project_versions`(新版本 `is_latest=1`、旧版置 0)→ 客户端 6 小时内(或重启后)看到提示 +3. 公告写 `ca_announcements`,**`status` 必须 = 1**(默认 0 = 静默隐身,接口返回空且不报错) + +## 六、为什么这么写(几个刻意的选择) - **零依赖**:只用 Node 内置 `http`/`fetch`,不装 express、不带 `node_modules`,镜像几十 MB,构建 3 秒 - **不做用户体系**:内网单用户工具,加登录只会让"笨用户"用不了 diff --git a/server.js b/server.js index 7a40fac..280991a 100644 --- a/server.js +++ b/server.js @@ -8,6 +8,9 @@ * AI_BASE 默认接口地址(https://ai.88531.cn/v1) * AI_MODEL 默认模型(mimo-v2.6-flash) * REGISTER_URL 引导用户去免费注册拿 Key 的地址 + * VERSION 当前版本号(右上角显示) + * HUB_HOST / HUB_PROJECT_ID / HUB_API_KEY 授权中心(CardAuth):安装统计/在线/公告/版本推送 + * HUB_DISABLED=1 关闭上报 */ const http = require('http'); const fs = require('fs'); @@ -191,6 +194,117 @@ async function describe(cfg, dataUrl) { return { ok: true, text: String(txt).trim() }; } +/* ---------------- 授权中心(CardAuth:安装统计 / 在线数 / 公告 / 版本推送) ---------------- + * 只上报与拉取,不阻塞任何功能:授权中心挂了 → 版本照常显示、公告保留上次结果、更新提示消失。 + * 机器码只存服务端 DATA/hub.json,不下发浏览器、不在 UI 展示;关上报:HUB_DISABLED=1。 + * 节流:更新检查 6 小时(失败 30 分钟后重试)、心跳 30 分钟、公告 60 秒。 + */ +const VERSION = process.env.VERSION || '1.0.0'; +const HUB_HOST = (process.env.HUB_HOST || 'https://auth.88531.cn').replace(/\/+$/, ''); +const HUB_PROJECT_ID = (process.env.HUB_PROJECT_ID || '').trim(); +const HUB_API_KEY = (process.env.HUB_API_KEY || '').trim(); +const HUB_DISABLED = process.env.HUB_DISABLED === '1'; +const HUB_STATE = path.join(DATA, 'hub.json'); + +function hubState() { + try { return JSON.parse(fs.readFileSync(HUB_STATE, 'utf8')) || {}; } catch { return {}; } +} +function saveHubState(patch) { + const s = Object.assign(hubState(), patch); + try { fs.writeFileSync(HUB_STATE, JSON.stringify(s)); } catch {} + return s; +} +function machineId() { + const s = hubState(); + if (!/^\d{10,16}$/.test(String(s.machine_id || ''))) { + const id = String(Math.floor(1e12 + Math.random() * 8e12)).slice(0, 13); + saveHubState({ machine_id: id }); + return id; + } + return String(s.machine_id); +} +function hubReady() { return !HUB_DISABLED && !!HUB_PROJECT_ID && !!HUB_API_KEY; } + +/* 通用 8s 超时请求,永不抛异常(失败开放) */ +function hubReq(url, { method = 'GET', headers = {}, body } = {}) { + return new Promise((resolve) => { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), 8000); + fetch(url, { method, headers, body, signal: ctrl.signal }) + .then(async (r) => { + clearTimeout(t); + let d = null; + try { d = await r.json(); } catch {} + resolve({ status: r.status, data: d }); + }) + .catch((e) => { clearTimeout(t); resolve({ status: 0, error: String(e.message || e) }); }); + }); +} + +/* 安装登记 + 更新检查(成败看 data.code,HTTP 恒 200) */ +async function hubCheckUpdate(force = false) { + if (!hubReady()) return null; + const s = hubState(); + const now = Date.now(); + const gap = s.check_failed ? 30 * 60e3 : 6 * 3600e3; + if (!force && s.checked_at && now - s.checked_at < gap) return s.last_update || null; + const r = await hubReq(`${HUB_HOST}/api/public/installations/check-update`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Api-Key': HUB_API_KEY, 'X-Project-Id': HUB_PROJECT_ID }, + body: JSON.stringify({ machine_id: machineId(), client_version: VERSION, device_info: 'cover-ai' }), + }); + const d = r.data; + if (r.status !== 200 || !d || d.code !== 200 || !d.data) { + saveHubState({ checked_at: now, check_failed: true }); + return s.last_update || null; + } + const u = { + install_id: d.data.install_id ?? null, + latest_version: String(d.data.latest_version || ''), + update_available: !!d.data.update_available, + update_required: !!d.data.update_required || !!d.data.is_force, + changelog: String(d.data.changelog || ''), + download_url: String(d.data.download_url || ''), + checked_at: now, + }; + saveHubState({ checked_at: now, check_failed: false, last_update: u }); + return u; +} + +/* 在线心跳(写 ca_online_logs,服务端按天去重) */ +async function hubHeartbeat(force = false) { + if (!hubReady()) return { ok: false, skipped: true }; + const s = hubState(); + const now = Date.now(); + if (!force && s.beat_at && now - s.beat_at < 30 * 60e3) return { ok: true, throttled: true }; + const r = await hubReq(`${HUB_HOST}/api/public/installations/heartbeat`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Api-Key': HUB_API_KEY, 'X-Project-Id': HUB_PROJECT_ID }, + body: JSON.stringify({ machine_id: machineId(), client_version: VERSION, device_info: 'cover-ai' }), + }); + const ok = r.status === 200 && !!r.data && r.data.code === 200; + if (ok) saveHubState({ beat_at: now, online_at: now }); + return { ok }; +} + +/* 公告:成功即覆盖(返回空也覆盖为空),只有请求失败才保留上次结果 */ +async function hubAnnouncements(force = false) { + if (HUB_DISABLED || !HUB_PROJECT_ID) return { list: [], popup: [] }; + const s = hubState(); + const now = Date.now(); + if (!force && s.ann_at && now - s.ann_at < 60e3) return s.ann || { list: [], popup: [] }; + const r = await hubReq(`${HUB_HOST}/api/public/announcements?target=client&project_id=${encodeURIComponent(HUB_PROJECT_ID)}&limit=20`); + if (r.status !== 200 || !r.data || r.data.code !== 200) return s.ann || { list: [], popup: [] }; + const d = r.data.data || r.data; + const ann = { + list: Array.isArray(d.list) ? d.list : [], + popup: Array.isArray(d.popup) ? d.popup : [], + at: now, + }; + saveHubState({ ann_at: now, ann }); + return ann; +} + /* ---------------- 路由 ---------------- */ const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://localhost'); @@ -215,11 +329,37 @@ const server = http.createServer(async (req, res) => { if (p === '/api/health') { return j(res, 200, { - ok: true, base: DEFAULT_BASE, model: DEFAULT_MODEL, registerUrl: REGISTER_URL, sizes: SIZES, + ok: true, version: VERSION, base: DEFAULT_BASE, model: DEFAULT_MODEL, registerUrl: REGISTER_URL, sizes: SIZES, + hub: HUB_DISABLED ? 'off' : (HUB_PROJECT_ID ? 'on' : 'unconfigured'), note: 'AI 功能需使用者自带 Key,服务端只转发、不保存 Key', }); } + /* ---- 授权中心:版本 / 更新提示 / 公告(全链失败开放,不影响功能) ---- */ + if (p === '/api/hub/status') { + const [up, ann] = await Promise.all([hubCheckUpdate(), hubAnnouncements()]); + return j(res, 200, { + ok: true, + version: VERSION, + disabled: HUB_DISABLED, + configured: !!HUB_PROJECT_ID, + update: up || { update_available: false, latest_version: '', changelog: '', download_url: '' }, + announcements: (ann && ann.list) || [], + popup: (ann && ann.popup) || [], + }); + } + + if (p === '/api/hub/heartbeat' && req.method === 'POST') { + const r = await hubHeartbeat(); + return j(res, 200, r); + } + + /* 手动强刷(管理/调试用,绕过节流) */ + if (p === '/api/hub/refresh' && req.method === 'POST') { + const [up, ann, beat] = await Promise.all([hubCheckUpdate(true), hubAnnouncements(true), hubHeartbeat(true)]); + return j(res, 200, { ok: true, version: VERSION, update: up, announcements: (ann && ann.list) || [], heartbeat: beat }); + } + /* ---- 拉取该接口下的模型列表(需要 Key) ---- */ if (p === '/api/models') { const cfg = cfgOf(req, u.searchParams.get('base') ? { base: u.searchParams.get('base') } : {}); diff --git a/ui.html b/ui.html index c86f125..0aa4cd4 100644 --- a/ui.html +++ b/ui.html @@ -54,6 +54,25 @@ .cmp img{width:100%;border-radius:10px;border:1px solid var(--line)} .mini{font-size:12.5px;color:var(--mut);background:#0b1220;border:1px solid var(--line);border-radius:8px;padding:6px 11px;cursor:pointer;text-decoration:none} .mini:hover{color:var(--acc);border-color:var(--acc)} + /* ---- 授权中心:右上角版本 / 公告 ---- */ + .hright{margin-left:auto;display:flex;align-items:center;gap:8px} + .bell{position:relative;background:#0e1622;border:1px solid var(--line);border-radius:10px;padding:7px 11px;cursor:pointer;font-size:15px;color:var(--txt)} + .bell:hover{border-color:var(--acc)} + .bell .dot{position:absolute;top:4px;right:5px;width:7px;height:7px;border-radius:50%;background:var(--warn);display:none} + .bell .dot.on{display:block} + .vchip{background:#0e1622;border:1px solid var(--line);border-radius:999px;padding:5px 12px;cursor:pointer;font-size:12.5px;color:var(--mut);font-variant-numeric:tabular-nums} + .vchip:hover{border-color:var(--acc);color:var(--acc)} + .vchip.upd{color:var(--warn);border-color:rgba(251,191,36,.55);font-weight:700} + .annpanel{position:fixed;top:64px;right:16px;width:340px;max-width:calc(100vw - 32px);max-height:60vh;overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:14px;z-index:60;box-shadow:0 18px 50px rgba(0,0,0,.5)} + .annpanel .it{border-top:1px solid var(--line);padding:10px 0;font-size:13.5px} + .annpanel .it:first-of-type{border-top:0} + .annpanel .it .t{font-weight:700;color:var(--txt)} + .annpanel .it .c{color:var(--mut);margin-top:4px;white-space:pre-wrap} + .annpanel .it .m{font-size:11.5px;color:#65788f;margin-top:5px} + .annpanel .empty{color:var(--mut);font-size:13px;padding:12px 0} + .modal{position:fixed;inset:0;background:rgba(4,8,14,.66);display:flex;align-items:center;justify-content:center;z-index:70;padding:20px} + .mbox{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px;max-width:460px;width:100%;max-height:74vh;overflow:auto;box-shadow:0 22px 60px rgba(0,0,0,.55)} + .mbox .c{margin-top:10px;color:var(--txt);white-space:pre-wrap;font-size:14px} .loading{display:inline-block;width:14px;height:14px;border:2px solid #33465f;border-top-color:var(--acc);border-radius:50%;animation:sp .8s linear infinite} @keyframes sp{to{transform:rotate(360deg)}} footer{padding:16px 22px;color:var(--mut);font-size:12.5px;border-top:1px solid var(--line);margin-top:26px} @@ -65,9 +84,42 @@ 未配置 API Key mimo-v2.6-flash 生成的图可直接在「快图设计」的素材面板里点用 +
+ + +
+ + + + + +
+ + +
@@ -348,6 +400,94 @@ $('#clearCfg').onclick = () => { }; ['#cfgBase','#cfgKey','#cfgModel'].forEach(s => $(s).addEventListener('keydown', e => { if (e.key === 'Enter') saveCfg(); })); +/* ---------- 授权中心:版本 / 更新提示 / 公告 / 心跳 ---------- */ +const HUB = { version: '…', update: {}, announcements: [], popup: [] }; +const esc = (s) => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); +const annSeen = () => { try { return JSON.parse(localStorage.getItem('coverai.annSeen') || '[]'); } catch { return []; } }; + +function renderUpdate() { + const u = HUB.update || {}; + const has = !!u.update_available && !!u.latest_version; + const dismissed = localStorage.getItem('coverai.updHide') === String(u.latest_version); + const chip = $('#verChip'); + chip.classList.toggle('upd', has && !dismissed); + chip.title = has ? `当前 v${HUB.version} · 发现新版本 v${u.latest_version}` : `当前版本 v${HUB.version}`; + if (has && !dismissed) { + $('#updLatest').textContent = 'v' + u.latest_version; + $('#updLog').textContent = u.changelog || '(更新说明见下载页)'; + const a = $('#updLink'); + if (u.download_url) { a.href = u.download_url; a.style.display = ''; } else a.style.display = 'none'; + $('#updBanner').style.display = ''; + } else { + $('#updBanner').style.display = 'none'; + } +} + +function renderAnn() { + const list = HUB.announcements || []; + $('#annDot').classList.toggle('on', list.length > 0); + $('#annBtn').title = list.length ? `公告(${list.length} 条)` : '暂无公告'; + $('#annList').innerHTML = list.length ? list.map(a => { + const link = a.link || a.url || ''; + return `
+
${esc(a.title || a.subject || '公告')}
+
${esc(a.content || a.body || a.text || '')}
+ ${link ? `查看详情` : ''} +
${esc(a.created_at || a.publish_at || '')}
+
`; + }).join('') : '
暂无公告
'; + if (!list.length) $('#annPanel').style.display = 'none'; // 公告被清空 → 面板跟着关 + const seen = annSeen(); + const pop = (HUB.popup || []).filter(p => !seen.includes(String(p.id))); + if (pop.length) showModal({ id: pop[0].id, title: pop[0].title || pop[0].subject || '公告', content: pop[0].content || pop[0].body || pop[0].text || '', link: pop[0].link || pop[0].url || '' }); +} + +function showModal({ id = null, title, content, link = '' }) { + $('#mTitle').textContent = title || '公告'; + $('#mBody').textContent = content || '(无内容)'; + const l = $('#mLink'); + if (link) { l.href = link; l.style.display = ''; } else l.style.display = 'none'; + $('#annModal').style.display = ''; + $('#mClose').onclick = () => { + $('#annModal').style.display = 'none'; + if (id !== null) { + const seen = annSeen(); seen.push(String(id)); + localStorage.setItem('coverai.annSeen', JSON.stringify(seen.slice(-200))); + } + }; +} + +async function hubLoad() { + try { + const d = await api('/api/hub/status'); + if (!d || !d.ok) return; + HUB.version = d.version || HUB.version; + HUB.update = d.update || {}; + HUB.announcements = Array.isArray(d.announcements) ? d.announcements : []; + HUB.popup = Array.isArray(d.popup) ? d.popup : []; + $('#verNum').textContent = HUB.version; + renderUpdate(); + renderAnn(); + } catch {} +} +function hubBeat() { fetch('/api/hub/heartbeat', { method: 'POST' }).catch(() => {}); } + +$('#annBtn').onclick = () => { const p = $('#annPanel'); p.style.display = p.style.display === 'none' ? '' : 'none'; }; +$('#annClose').onclick = () => { $('#annPanel').style.display = 'none'; }; +$('#updHide').onclick = () => { + localStorage.setItem('coverai.updHide', String((HUB.update || {}).latest_version || '')); + renderUpdate(); +}; +$('#verChip').onclick = () => { + const u = HUB.update || {}; + if (u.update_available && localStorage.getItem('coverai.updHide') !== String(u.latest_version)) { + $('#updBanner').style.display = ''; + $('#updBanner').scrollIntoView({ behavior: 'smooth', block: 'center' }); + } else { + showModal({ title: '版本信息', content: `当前版本:v${HUB.version}\n最新版本:${u.latest_version ? 'v' + u.latest_version : '暂无'}\n${u.update_available ? '有新版本可用,点右上角版本号查看。' : '已是最新版本。'}` }); + } +}; + /* ---------- 初始化 ---------- */ (async function init() { try { @@ -368,6 +508,12 @@ $('#clearCfg').onclick = () => { applyKeyState(); if (!hasKey()) { setS('#cfgStatus', '未配置 API Key:先填 Key 才能用 AI(素材库等基础功能不受影响)。', 'warn'); } + /* 授权中心:开机一次 + 每 60 秒刷公告/版本,每 30 分钟一次心跳 */ + hubLoad(); + hubBeat(); + setInterval(hubLoad, 60000); + setInterval(hubBeat, 30 * 60000); + $('#styleChips').innerHTML = STYLES.map(s => `${s}`).join(''); $('#editChips').innerHTML = EDITS.map(s => `${s}`).join(''); document.querySelectorAll('#styleChips span').forEach(el => el.onclick = () => {