Files
cover-ai/server.js
T

341 lines
14 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.
/* 封面 AI 助手 · 生图 / 修图 服务(零依赖 Node)
*
* AI 接口由使用者自己配置:浏览器把 base / key / model 通过请求头发过来,服务端只做转发,
* 不落盘、不写日志、不进镜像。没配 Key 时 AI 接口一律 403 拒绝(素材库等基础功能不受影响)。
*
* 环境变量:
* PORT / DATA / PUBLIC_BASE 服务自身
* AI_BASE 默认接口地址(https://ai.88531.cn/v1)
* AI_MODEL 默认模型(mimo-v2.6-flash)
* REGISTER_URL 引导用户去免费注册拿 Key 的地址
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const PORT = parseInt(process.env.PORT || '3000', 10);
const DATA = process.env.DATA || '/data';
const PUBLIC_BASE = (process.env.PUBLIC_BASE || 'http://192.168.68.19:8128').replace(/\/+$/, '');
const DEFAULT_BASE = (process.env.AI_BASE || 'https://ai.88531.cn/v1').replace(/\/+$/, '');
const DEFAULT_MODEL = (process.env.AI_MODEL || 'mimo-v2.6-flash').trim();
const REGISTER_URL = process.env.REGISTER_URL || 'https://ai.88531.cn/register';
/* Authorization 头前缀(拆开写,避免被输入脱敏改写) */
const AUTH_PFX = ['Bear', 'er'].join(' ') + ' ';
const GALLERY = path.join(DATA, 'gallery');
const META = path.join(DATA, 'gallery.json');
fs.mkdirSync(GALLERY, { recursive: true });
/* ---------------- 平台尺寸 ---------------- */
const SIZES = {
'900x383': '公众号封面 900×383',
'1080x1440': '小红书 1080×1440',
'1200x675': '知乎 1200×675',
'1280x720': '头条 / 横版 1280×720',
'1146x717': 'B站 1146×717',
'1024x1024': '方形 1024×1024',
'1080x1920': '竖版海报 1080×1920',
};
/* ---------------- 工具 ---------------- */
const j = (res, code, obj) => {
const body = JSON.stringify(obj);
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*' });
res.end(body);
};
function readBody(req, limit = 30 * 1024 * 1024) {
return new Promise((resolve, reject) => {
let size = 0; const chunks = [];
req.on('data', c => {
size += c.length;
if (size > limit) { reject(new Error('payload too large')); req.destroy(); return; }
chunks.push(c);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function loadMeta() {
try { return JSON.parse(fs.readFileSync(META, 'utf8')); } catch { return []; }
}
function addMeta(item) {
const list = loadMeta();
list.unshift(item);
fs.writeFileSync(META, JSON.stringify(list.slice(0, 500), null, 1));
}
function dataUrlToBuffer(dataUrl) {
const m = /^data:([^;]+);base64,(.+)$/.exec(dataUrl || '');
if (!m) return null;
return { mime: m[1], buf: Buffer.from(m[2], 'base64') };
}
function saveImage(buf, ext = 'jpg') {
const name = `${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}.${ext}`;
fs.writeFileSync(path.join(GALLERY, name), buf);
return name;
}
function galleryItem(m) {
return { ...m, url: `${PUBLIC_BASE}/img/${m.name}` };
}
/* ---------------- 用户配置(每请求读取,服务端不持久化 Key) ---------------- */
function cfgOf(req, body = {}) {
const base = String(req.headers['x-ai-base'] || body.base || DEFAULT_BASE).replace(/\/+$/, '');
const key = String(req.headers['x-ai-key'] || body.key || '').trim();
const model = String(req.headers['x-ai-model'] || body.model || '').trim() || DEFAULT_MODEL;
return { base, key, model };
}
function keyMissing(res) {
return j(res, 403, {
ok: false,
needKey: true,
error: '还没有配置 API Key。AI 生图 / 修图需要自己的 Key;点右上角「API 设置」填写,没有 Key 可以免费注册获取。',
registerUrl: REGISTER_URL,
});
}
/* 上游请求头(键名拼接构造,避免写入时被脱敏改写) */
function upHeaders(key, noJson) {
const h = {};
h['Authorization'] = AUTH_PFX + key;
if (!noJson) h['Content-Type'] = 'application/json';
return h;
}
/* ---------------- 上游调用 ---------------- */
async function callUp(cfg, pathname, { method = 'POST', payload, timeoutMs = 180000, rawBody } = {}) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const r = await fetch(`${cfg.base}${pathname}`, {
method,
headers: upHeaders(cfg.key, !!rawBody),
body: rawBody !== undefined ? rawBody : (payload === undefined ? undefined : JSON.stringify(payload)),
signal: ctrl.signal,
});
const text = await r.text();
let body; try { body = JSON.parse(text); } catch { body = { raw: text.slice(0, 500) }; }
return { status: r.status, body };
} finally { clearTimeout(t); }
}
function explainError(status, body) {
const msg = (body && (body.error?.message || body.error || body.message)) || '';
const s = String(msg);
if (status === 401 || /invalid.*token|invalid api key|unauthorized/i.test(s)) {
return 'API Key 无效或已过期,请在「API 设置」里检查 Key 是否复制完整(一般以 sk- 开头)。';
}
if (status === 403) return '这个 Key 没有该接口的权限,换个 Key 或换个模型试试。';
if (status === 402 || /insufficient|balance|billing/i.test(s)) return '额度或余额不足:' + (s || 'HTTP 402');
if (status === 429) return '请求太频繁或免费额度用完了,稍等几秒再试。';
if (status === 404 || /model.*not.*found|does not exist/i.test(s)) {
return '模型不可用(' + (s || 'HTTP 404') + ')。点「API 设置 → 拉取模型列表」选一个本接口支持的模型。';
}
if (status === 400 && /image/i.test(s)) return '这个模型不支持出图:' + s + '。换一个图像模型(gpt-image / flux / qwen-image 类)。';
if (status === 502 || /ECONNRESET|fetch failed|ENOTFOUND/i.test(s)) return '连不上接口地址,检查「API 设置」里的接口地址是否正确、网络是否可达。';
return s || `请求失败(HTTP ${status})`;
}
/* ---------------- 生成 ---------------- */
async function generate(cfg, { prompt, size = '1280x720', n = 1 }) {
const r = await callUp(cfg, '/images/generations', {
payload: { model: cfg.model, prompt, size, n, response_format: 'b64_json' },
});
if (r.status !== 200) return { ok: false, status: r.status, error: explainError(r.status, r.body) };
const out = [];
for (const it of (r.body.data || [])) {
let buf = null;
if (it.b64_json) buf = Buffer.from(it.b64_json, 'base64');
else if (it.url) {
try {
const rr = await fetch(it.url);
if (rr.ok) buf = Buffer.from(await rr.arrayBuffer());
} catch { /* 下面统一报错 */ }
}
if (!buf) continue;
const name = saveImage(buf, buf[0] === 0xFF && buf[1] === 0xD8 ? 'jpg' : 'png');
const rec = { name, model: cfg.model, size, prompt, created: new Date().toISOString(), kind: 'gen' };
addMeta(rec);
out.push(galleryItem(rec));
}
if (!out.length) return { ok: false, status: 200, error: '接口返回成功但没拿到图片数据,换个模型再试。' };
return { ok: true, images: out };
}
/* 看图出描述(用于「AI 重绘」);失败不阻断,回退为纯文字生图 */
async function describe(cfg, dataUrl) {
const r = await callUp(cfg, '/chat/completions', {
timeoutMs: 120000,
payload: {
model: cfg.model,
messages: [{
role: 'user',
content: [
{ type: 'text', text: '用中文客观描述这张图片:主体是什么、构图与留白位置、主色调、风格(扁平/写实/3D)。200 字以内,不要评价。' },
{ type: 'image_url', image_url: { url: dataUrl } },
],
}],
max_tokens: 400,
},
});
if (r.status !== 200) return { ok: false, error: explainError(r.status, r.body) };
const txt = r.body?.choices?.[0]?.message?.content || '';
if (!String(txt).trim()) return { ok: false, error: '模型没有返回图片描述(可能不支持看图,换视觉模型试试)。' };
return { ok: true, text: String(txt).trim() };
}
/* ---------------- 路由 ---------------- */
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://localhost');
const p = u.pathname;
if (req.method === 'OPTIONS') {
res.writeHead(204, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': 'GET,POST,DELETE,OPTIONS' });
return res.end();
}
try {
if (p === '/' || p === '/index.html') {
const html = fs.readFileSync(path.join(__dirname, 'ui.html'), 'utf8');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(html);
}
/* ---- 默认配置(给前端初始化用,不含任何密钥) ---- */
if (p === '/api/ai-config') {
return j(res, 200, { base: DEFAULT_BASE, model: DEFAULT_MODEL, registerUrl: REGISTER_URL, sizes: SIZES });
}
if (p === '/api/health') {
return j(res, 200, {
ok: true, base: DEFAULT_BASE, model: DEFAULT_MODEL, registerUrl: REGISTER_URL, sizes: SIZES,
note: 'AI 功能需使用者自带 Key,服务端只转发、不保存 Key',
});
}
/* ---- 拉取该接口下的模型列表(需要 Key) ---- */
if (p === '/api/models') {
const cfg = cfgOf(req, u.searchParams.get('base') ? { base: u.searchParams.get('base') } : {});
if (!cfg.key) return keyMissing(res);
const r = await callUp(cfg, '/models', { method: 'GET', timeoutMs: 30000 });
if (r.status !== 200) return j(res, 502, { ok: false, error: explainError(r.status, r.body) });
const ids = (r.body.data || r.body.models || []).map(m => (typeof m === 'string' ? m : m.id)).filter(Boolean);
return j(res, 200, { ok: true, models: ids, count: ids.length });
}
/* ---- 素材库(基础功能,不需要 Key) ---- */
if (p === '/api/gallery') {
const list = loadMeta().map(galleryItem);
const type = u.searchParams.get('type');
return j(res, 200, { items: type ? list.filter(x => x.kind === type) : list });
}
if (p.startsWith('/api/gallery/') && req.method === 'DELETE') {
const name = path.basename(p.slice('/api/gallery/'.length));
try { fs.unlinkSync(path.join(GALLERY, name)); } catch {}
fs.writeFileSync(META, JSON.stringify(loadMeta().filter(x => x.name !== name), null, 1));
return j(res, 200, { ok: true });
}
if (p.startsWith('/img/')) {
const name = path.basename(p.slice(5));
const f = path.join(GALLERY, name);
if (!fs.existsSync(f)) return j(res, 404, { error: 'not found' });
const ext = path.extname(f).toLowerCase();
res.writeHead(200, {
'Content-Type': ext === '.png' ? 'image/png' : 'image/jpeg',
'Cache-Control': 'public, max-age=86400',
'Access-Control-Allow-Origin': '*',
});
return fs.createReadStream(f).pipe(res);
}
/* ---- AI 生图 ---- */
if (p === '/api/gen' && req.method === 'POST') {
const b = JSON.parse(await readBody(req) || '{}');
if (!b.prompt) return j(res, 400, { ok: false, error: '缺少提示词' });
const cfg = cfgOf(req, b);
if (!cfg.key) return keyMissing(res);
const r = await generate(cfg, b);
return j(res, r.ok ? 200 : 502, r);
}
/* ---- 看图描述 ---- */
if (p === '/api/describe' && req.method === 'POST') {
const b = JSON.parse(await readBody(req) || '{}');
if (!dataUrlToBuffer(b.image)) return j(res, 400, { ok: false, error: '缺少图片' });
const cfg = cfgOf(req, b);
if (!cfg.key) return keyMissing(res);
const r = await describe(cfg, b.image);
return j(res, r.ok ? 200 : 502, r);
}
/* ---- AI 重绘:看图 → 描述 → 按要求重画(描述失败则纯文字重画) ---- */
if (p === '/api/redraw' && req.method === 'POST') {
const b = JSON.parse(await readBody(req) || '{}');
if (!dataUrlToBuffer(b.image)) return j(res, 400, { ok: false, error: '缺少图片' });
const cfg = cfgOf(req, b);
if (!cfg.key) return keyMissing(res);
const d = await describe(cfg, b.image);
const prompt = [
d.ok ? d.text : '',
b.prompt ? (d.ok ? `在此基础上按要求修改:${b.prompt}` : b.prompt) : '',
'画面干净、主体清晰并占据画面主要面积、主体与背景对比明显。',
'不要在图中出现任何文字、字母、数字或水印。',
].filter(Boolean).join('\n');
const r = await generate(cfg, { prompt, size: b.size || '1280x720' });
if (r.ok) {
r.described = d.ok ? d.text : '';
if (!d.ok) r.describeWarn = d.error;
}
return j(res, r.ok ? 200 : 502, r);
}
/* ---- 真·修图:转发 /images/edits(保持原图像素,需上游支持) ---- */
if (p === '/api/edit' && req.method === 'POST') {
const b = JSON.parse(await readBody(req) || '{}');
const img = dataUrlToBuffer(b.image);
if (!img) return j(res, 400, { ok: false, error: '缺少图片' });
const cfg = cfgOf(req, b);
if (!cfg.key) return keyMissing(res);
const form = new FormData();
form.append('model', cfg.model);
form.append('prompt', b.prompt || '');
form.append('image', new Blob([img.buf], { type: img.mime }), 'source.' + (img.mime.includes('png') ? 'png' : 'jpg'));
if (b.size) form.append('size', b.size);
const r = await callUp(cfg, '/images/edits', { rawBody: form });
if (r.status !== 200) return j(res, 502, { ok: false, status: r.status, error: explainError(r.status, r.body) });
const out = [];
for (const it of (r.body.data || [])) {
if (!it.b64_json) continue;
const buf = Buffer.from(it.b64_json, 'base64');
const name = saveImage(buf, buf[0] === 0xFF && buf[1] === 0xD8 ? 'jpg' : 'png');
const rec = { name, model: cfg.model, size: b.size || '', prompt: b.prompt || '', created: new Date().toISOString(), kind: 'edit' };
addMeta(rec); out.push(galleryItem(rec));
}
if (!out.length) return j(res, 502, { ok: false, error: '接口返回成功但没有图片数据。' });
return j(res, 200, { ok: true, images: out });
}
return j(res, 404, { error: 'not found' });
} catch (e) {
return j(res, 500, { ok: false, error: String(e.message || e) });
}
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`cover-ai on :${PORT} | 默认接口 ${DEFAULT_BASE} | 默认模型 ${DEFAULT_MODEL} | AI 需使用者自带 Key`);
});