Files
kuaitu-editor/server/index.js
T

195 lines
9.0 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';
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((req, res) => {
const u = new URL(req.url, 'http://localhost');
const p = u.pathname;
const q = u.searchParams;
// ---------- 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));