Files
kuaitu-editor/server/index.js
T

321 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 快图设计 · 本地模板接口(Strapi 兼容,无外网依赖) */
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = path.join(__dirname, '..');
const DIST = path.join(ROOT, 'dist');
const DATA = process.env.TEMPLATE_DIR || path.join(ROOT, 'data');
const INDEX = JSON.parse(fs.readFileSync(path.join(DATA, 'index.json'), 'utf8'));
// 封面 AI 助手(AI 生图/修图服务),素材面板从这里取图
const COVER_AI = process.env.COVER_AI || 'http://192.168.68.19:8128';
/* ---------------- 授权中心(CardAuth:安装统计 / 在线数 / 公告 / 版本推送) ----------------
* 失败开放:授权中心挂了 → 版本照常显示、公告保留上次、更新提示消失,功能零影响。
* 机器码只存 DATA/hub.json,不进浏览器;关上报:HUB_DISABLED=1。
* 节流:更新检查 6h(失败 30min 重试)、心跳 30min、公告 60s。 */
const APP_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; }
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 { /* 非 JSON */ }
resolve({ status: r.status, data: d });
})
.catch((e) => { clearTimeout(t); resolve({ status: 0, error: String(e.message || e) }); });
});
}
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: APP_VERSION, device_info: 'kuaitu-editor' }),
});
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;
}
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: APP_VERSION, device_info: 'kuaitu-editor' }),
});
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 TYPES = [
{ id: 20, name: '公众号封面' },
{ id: 21, name: '小红书' },
{ id: 22, name: '知乎' },
{ id: 23, name: '头条' },
{ id: 24, name: 'B站' },
{ id: 25, name: '方形通用' },
{ id: 26, name: '竖版海报' },
{ id: 27, name: '视频封面' },
{ id: 28, name: '朋友圈' },
{ id: 29, name: '横版头图' },
];
/* 模板面板修复:iView 懒加载需要元素有实际面积,原始 .tmpl-img-box 高度为 0 导致
IntersectionObserver 永不触发,缩略图一直不显示 */
const APP_PATCH = `<style>
#aiFab{position:fixed;right:20px;bottom:22px;z-index:99999;display:flex;align-items:center;gap:8px;
padding:12px 18px;border-radius:999px;cursor:pointer;color:#08131f;font:700 14px/1 -apple-system,"Microsoft YaHei",sans-serif;
background:linear-gradient(90deg,#38bdf8,#a78bfa);box-shadow:0 8px 24px rgba(56,189,248,.35);user-select:none}
#aiFab:hover{filter:brightness(1.06)}
#aiMask{position:fixed;inset:0;z-index:99998;background:rgba(4,8,15,.72);display:none}
#aiMask .box{position:absolute;inset:3% 3.5%;background:#0b0f17;border-radius:14px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.5)}
#aiMask iframe{width:100%;height:100%;border:0;display:block}
#aiMask .cls{position:absolute;right:10px;top:8px;z-index:2;width:34px;height:34px;border-radius:50%;border:0;cursor:pointer;
background:#1b2637;color:#e6edf7;font:20px/1 sans-serif}
</style>
<div id="aiFab">✨ AI 生图 / 修图</div>
<div id="aiMask"><div class="box"><button class="cls" title="关闭">&times;</button>
<iframe src="${COVER_AI}/" loading="lazy"></iframe></div></div>
<script>
(function(){
var fab=document.getElementById('aiFab'), mask=document.getElementById('aiMask');
if(!fab||!mask) return;
fab.addEventListener('click', function(){ mask.style.display='block'; });
mask.addEventListener('click', function(e){ if(e.target===mask||e.target.classList.contains('cls')) mask.style.display='none'; });
document.addEventListener('keydown', function(e){ if(e.key==='Escape') mask.style.display='none'; });
})();
</script>`;
const CSS_PATCH = `<style>
.tmpl-img-box{height:112px !important;background:#0f172a}
.tmpl-img-box .ivu-image{height:100% !important;width:100%}
.tmpl-img-box .ivu-image-img{width:100%;height:100%;object-fit:contain}
.list-box{align-items:flex-start}
.list-box .tmpl-img-box{margin-bottom:12px}
</style>`;
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
'.json': 'application/json; charset=utf-8', '.ico': 'image/x-icon', '.map': 'application/json' };
const send = (res, code, body, type) => {
res.writeHead(code, { 'Content-Type': type || 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*' });
res.end(typeof body === 'string' ? body : JSON.stringify(body));
};
function imgOf(m) {
const url = `/preview/${m.id}.png`;
return { data: { id: m.id, attributes: { url, formats: { small: { url } } } } };
}
function listItem(m) {
return { id: m.id, attributes: { name: m.name, desc: m.desc, templ_type: m.type, img: imgOf(m) } };
}
let indexHtml = null;
function loadIndex() {
if (!indexHtml) {
let html = fs.readFileSync(path.join(DIST, 'index.html'), 'utf8');
indexHtml = html.includes('</head>') ? html.replace('</head>', CSS_PATCH + '\n</head>') : html;
indexHtml = indexHtml.includes('</body>')
? indexHtml.replace('</body>', APP_PATCH + '\n</body>')
: indexHtml + APP_PATCH;
}
return indexHtml;
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://localhost');
const p = u.pathname;
const q = u.searchParams;
// ---------- 授权中心(版本 / 更新提示 / 公告,前端角标与铃铛读这里) ----------
if (p === '/api/hub/status') {
const [up, ann] = await Promise.all([hubCheckUpdate(), hubAnnouncements()]);
return send(res, 200, {
ok: true,
version: APP_VERSION,
hub: HUB_DISABLED ? 'off' : (hubReady() ? 'on' : 'unconfigured'),
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') {
return send(res, 200, await hubHeartbeat());
}
if (p === '/api/hub/refresh' && req.method === 'POST') {
const [up, ann, beat] = await Promise.all([hubCheckUpdate(true), hubAnnouncements(true), hubHeartbeat(true)]);
return send(res, 200, { ok: true, version: APP_VERSION, update: up, announcements: (ann && ann.list) || [], heartbeat: beat });
}
// ---------- API ----------
if (p === '/api/templ-types') return send(res, 200, { data: TYPES.map(t => ({ id: t.id, attributes: { name: t.name } })) });
if (p === '/api/web-site') {
return send(res, 200, { data: { id: 1, attributes: {
name: '米图设计 · 封面工坊', url: '/', logo: { data: { attributes: { url: '/logo.svg' } } },
} } });
}
// ---------- 素材面板:AI 生成的图 ----------
if (p === '/api/material-types') {
return send(res, 200, { data: [{ id: 1, attributes: { name: 'AI 生成' } }] });
}
if (p === '/api/materials') {
return fetch(`${COVER_AI}/api/gallery`).then(r => r.json()).then(d => {
const items = (d.items || []).map((it, i) => ({
id: i + 1,
attributes: {
name: ((it.prompt || 'AI 图').replace(/[*#`\n]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 16) || 'AI 图')
+ (it.kind === 'edit' ? '·修图' : '·生图'),
desc: it.model || '', templ_type: 1,
img: { data: { attributes: { url: `/ai-img/${it.name}`, formats: { small: { url: `/ai-img/${it.name}` } } } } },
},
}));
send(res, 200, { data: items, meta: { pagination: { page: 1, pageSize: items.length || 1, pageCount: 1, total: items.length } } });
}).catch(() => send(res, 200, { data: [], meta: { pagination: { page: 1, pageSize: 1, pageCount: 0, total: 0 } } }));
}
if (p.startsWith('/ai-img/')) {
const name = path.basename(p.slice('/ai-img/'.length));
return fetch(`${COVER_AI}/img/${name}`).then(r => r.arrayBuffer()).then(buf => {
res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Cache-Control': 'public, max-age=3600', 'Access-Control-Allow-Origin': '*' });
res.end(Buffer.from(buf));
}).catch(() => send(res, 404, 'not found', 'text/plain; charset=utf-8'));
}
if (p === '/api/templs') {
const typeEq = q.get('filters[templ_type][$eq]');
const kw = q.get('filters[name][$contains]');
const page = parseInt(q.get('pagination[page]') || '1', 10);
const pageSize = parseInt(q.get('pagination[pageSize]') || '10', 10);
let list = INDEX.slice();
if (typeEq) list = list.filter(m => String(m.type) === String(typeEq));
if (kw) list = list.filter(m => m.name.includes(kw));
const total = list.length;
const pageCount = Math.max(1, Math.ceil(total / pageSize));
const slice = list.slice((page - 1) * pageSize, page * pageSize);
return send(res, 200, {
data: slice.map(listItem),
meta: { pagination: { page, pageSize, pageCount, total } },
});
}
const mt = p.match(/^\/api\/templs\/(\d+)$/);
if (mt) {
const m = INDEX.find(x => String(x.id) === mt[1]);
if (!m) return send(res, 404, { data: null, error: { status: 404, message: 'Not Found' } });
const json = JSON.parse(fs.readFileSync(path.join(DATA, 'tmpl', `${m.id}.json`), 'utf8'));
return send(res, 200, { data: { id: m.id, attributes: { name: m.name, desc: m.desc, templ_type: m.type, json, img: imgOf(m) } } });
}
// 其余 Strapi 接口返回空集,避免编辑器报错
if (p.startsWith('/api/')) {
if (p === '/api/sizes') {
const sizes = [...new Set(INDEX.map(m => `${m.w}x${m.h}`))].map((s, i) => {
const [w, h] = s.split('x').map(Number);
return { id: i + 1, attributes: { name: `${w}×${h}`, width: w, height: h } };
});
return send(res, 200, { data: sizes });
}
return send(res, 200, { data: [], meta: { pagination: { page: 1, pageSize: 25, pageCount: 0, total: 0 } } });
}
if (p === '/logo.svg') {
const f = path.join(DATA, 'logo.svg');
if (fs.existsSync(f)) { res.writeHead(200, { 'Content-Type': 'image/svg+xml' }); return fs.createReadStream(f).pipe(res); }
}
// ---------- 预览图 ----------
if (p.startsWith('/preview/')) {
const f = path.join(DATA, 'preview', path.basename(p));
if (fs.existsSync(f)) {
res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=3600' });
return fs.createReadStream(f).pipe(res);
}
}
// ---------- 静态资源 / SPA 回退 ----------
if (p === '/' || p === '/index.html') {
res.writeHead(200, { 'Content-Type': MIME['.html'] });
return res.end(loadIndex());
}
let file = path.join(DIST, decodeURIComponent(p));
if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) file = path.join(DIST, 'index.html');
if (!file.startsWith(DIST) || !fs.existsSync(file)) return send(res, 404, 'not found', 'text/plain; charset=utf-8');
const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': type });
return fs.createReadStream(file).pipe(res);
});
server.listen(80, '0.0.0.0', () => console.log('kuaitu-editor on :80, templates:', INDEX.length));