402 lines
21 KiB
JavaScript
402 lines
21 KiB
JavaScript
// public-api.js — 给网站(Astro 构建)用的只读产品接口
|
||
// 位置:/opt/customer-crm/server/public-api.js
|
||
//
|
||
// 接入方法(server.js 里加三行,放在后台登录校验中间件之前):
|
||
// const mountPublicApi = require('./public-api');
|
||
// mountPublicApi(app, { dataFile: DATA_FILE, uploadsDir: UPLOADS_DIR, requireAuth,
|
||
// ai: { loadAiConfig, callDeepSeekWithRetry, extractJson } });
|
||
// ai:server.js 里现成的 DeepSeek 函数,用来把英文介绍/卖点自动翻译成其他语言(不传就不翻译,网站显示英文)。
|
||
// requireAuth = 现有的后台登录校验中间件,只用于"发布到网站"按钮那个接口。
|
||
// 如果 server.js 用的是 import 写法,把 require / module.exports 换成 import / export default。
|
||
//
|
||
// 配置项(环境变量或 site-config.json):
|
||
// SITE_BUILD_KEY 网站构建时携带的密钥(一串长随机字符)
|
||
// CF_DEPLOY_HOOK Cloudflare Pages 的 Deploy Hook 地址
|
||
// PUBLIC_BASE_URL https://b2b.google-helper.com
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const crypto = require('crypto');
|
||
|
||
const PRODUCTS_KEY = 'crm:products';
|
||
|
||
// 白名单:对外字段名 → 产品记录里的字段名。
|
||
// 不在这里的字段一律不输出:costPrice、notes(含采购价)、id、productImageOriginalName 等。
|
||
const FIELDS = {
|
||
model: 'name',
|
||
brand: 'brand',
|
||
category: 'category',
|
||
type: 'type', // 中文值,如"迷你UPS",网站端按词典翻译
|
||
machineVariant: 'machineVariant',// 中文值,如"标机"
|
||
outputPower: 'powerOrCapacity',
|
||
ratedPower: 'ratedPower',
|
||
ratedPowerUnit: 'ratedPowerUnit',
|
||
powerFactor: 'powerFactor',
|
||
inputVoltage: 'voltage',
|
||
outputPortCount: 'outputPortCount',
|
||
outputPorts: 'outputPorts', // [{ type, voltage, current }]
|
||
batterySpec: 'batterySpec',
|
||
dimensions: 'dimensions',
|
||
netWeight: 'netWeight',
|
||
extraSpecs: 'extraSpecs',
|
||
sellingPoints: 'sellingPoints',
|
||
// —— 以下是需要在产品表单里新增的字段 ——
|
||
youtube: 'youtubeUrl', // YouTube 链接,输出时只保留视频 ID
|
||
description: 'webDescription', // { en, es?, ru? }:只需填 en,其他语言自动翻译;手动填了的语言优先用手动的
|
||
sale: 'webSale', // { mode: 'group'|'stock', stock, minPrice, maxPrice }
|
||
// —— 离线式 / 在线互动式 UPS 的参数(迷你UPS 一般不填,空的不输出)——
|
||
acInputVoltage: 'inputVoltage', // 离线式UPS 的输入电压(迷你UPS 用上面的 inputVoltage ← voltage)
|
||
inputVoltageRange: 'inputVoltageRange',
|
||
inputFrequency: 'inputFrequency',
|
||
outputVoltage: 'outputVoltage',
|
||
outputVoltageRange: 'outputVoltageRange',
|
||
transferTime: 'transferTime',
|
||
waveform: 'waveform',
|
||
frequencyRangeBatteryMode: 'frequencyRangeBatteryMode',
|
||
batteryVoltage: 'batteryVoltage',
|
||
chargeCurrent: 'chargeCurrent',
|
||
chargeTime: 'chargeTime',
|
||
lcdDisplay: 'lcdDisplay',
|
||
ledDisplay: 'ledDisplay',
|
||
fullProtection: 'fullProtection',
|
||
alarmInfo: 'alarmInfo',
|
||
interfacePort: 'interfacePort',
|
||
humidity: 'humidity',
|
||
noiseLevel: 'noiseLevel',
|
||
sockets: 'webSockets', // 网站展示的默认插座配置 [{ type: 'SCHUKO'|'NEMA'|'UK'|'UNIVERSAL'|'IEC'|'AU', count }]
|
||
};
|
||
const PUBLISH_FLAG = 'publishToWeb'; // 新增:"发布到网站"开关
|
||
const IMAGES_FIELD = 'webImages'; // 新增:主图文件名数组,最多 6 张;为空时用现有的 productImageFileName
|
||
const DETAIL_FIELD = 'webDetailImages'; // 新增:详情图文件名数组,最多 20 张,显示在规格表下方
|
||
const TEMPLATES_KEY = 'crm:webDetailTemplates'; // 详情模板:[{ id, name, images: [文件名] }],图片在 uploads/<模板id>/
|
||
const TEMPLATE_IDS_FIELD = 'webDetailTemplateIds'; // 产品引用的模板id,按顺序显示在详情图下方
|
||
// —— 网站管理(非产品内容)——
|
||
const SITE_ASSETS_KEY = 'crm:webAssets'; // { 图片位id: [文件名 或 { file, caption:{en,es?,ru?} }] },文件在 uploads/site_assets/
|
||
const SITE_ASSETS_DIR = 'site_assets';
|
||
const SITE_NEWS_KEY = 'crm:webNews'; // [{ id, date:'2025-12', title:{en,es?,ru?}, text:{en,es?,ru?}, youtubeUrl }]
|
||
|
||
// 配置:优先读环境变量,没有就读同目录下的 site-config.json(不用改进程启动方式)
|
||
// { "SITE_BUILD_KEY": "...", "CF_DEPLOY_HOOK": "...", "PUBLIC_BASE_URL": "https://b2b.google-helper.com" }
|
||
function conf(name) {
|
||
if (process.env[name]) return process.env[name];
|
||
try { return JSON.parse(fs.readFileSync(path.join(__dirname, 'site-config.json'), 'utf8'))[name] || ''; }
|
||
catch { return ''; }
|
||
}
|
||
|
||
// —— 自动翻译 ——
|
||
// 英文是源语言;这里列出要自动翻译出来的语言。以后加语言:这里加一项,网站 src/config.mjs 的 LANGS 也加上。
|
||
const WEB_TRANSLATE_LANGS = {
|
||
es: 'Latin American Spanish (neutral, for Venezuela/Colombia buyers; say "UPS", never "SAI")',
|
||
ru: 'Russian',
|
||
};
|
||
// 译文缓存:英文没改就不重复调用 DeepSeek(省钱、构建也快)。单独一个文件,不碰 data.json。
|
||
const TRANSLATION_CACHE_FILE = path.join(__dirname, 'web-translations.json');
|
||
const cacheKey = (lang, text) => crypto.createHash('sha256').update(lang + '\n' + text).digest('hex').slice(0, 32);
|
||
function loadCache() { try { return JSON.parse(fs.readFileSync(TRANSLATION_CACHE_FILE, 'utf8')); } catch { return {}; } }
|
||
function saveCache(c) {
|
||
const tmp = TRANSLATION_CACHE_FILE + '.tmp';
|
||
fs.writeFileSync(tmp, JSON.stringify(c));
|
||
fs.renameSync(tmp, TRANSLATION_CACHE_FILE);
|
||
}
|
||
|
||
async function translateBatch(ai, texts, langDesc, srcLang = 'English') {
|
||
const cfg = ai.loadAiConfig();
|
||
if (!cfg.apiKey) throw new Error('DeepSeek API key not configured');
|
||
const system = `You translate B2B product copy for a power-equipment manufacturer (UPS, mini UPS, batteries) from ${srcLang} into ${langDesc}.
|
||
Rules: keep model numbers, brand names, units and numbers exactly as written (e.g. POE-36E-LFP-48V, 24V/48V, 5000mAh, PoE, LiFePO4, USB, DC). Use natural commercial wording, not word-for-word.
|
||
Input is a JSON array of strings. Return ONLY a JSON array of the translated strings, same length and same order, no markdown, no extra text.`;
|
||
const content = await ai.callDeepSeekWithRetry(cfg.apiKey, [
|
||
{ role: 'system', content: system },
|
||
{ role: 'user', content: JSON.stringify(texts) },
|
||
], { maxTokens: 4000, temperature: 0.2 });
|
||
const { data } = ai.extractJson(content);
|
||
if (!Array.isArray(data) || data.length !== texts.length) throw new Error('translation result has wrong shape');
|
||
return data.map(String);
|
||
}
|
||
|
||
// 通用:把一批英文字符串翻译成各语言,返回 { lang: { 英文: 译文 } }(走同一个译文缓存)
|
||
async function translateStrings(ai, strings) {
|
||
const out = {};
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) out[lang] = {};
|
||
const uniq = [...new Set(strings.filter((x) => x && x.trim()))];
|
||
if (!uniq.length) return out;
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
if (ai) {
|
||
for (const [lang, langDesc] of Object.entries(WEB_TRANSLATE_LANGS)) {
|
||
const need = uniq.filter((t) => !cache[cacheKey(lang, t)]);
|
||
for (let i = 0; i < need.length; i += 20) {
|
||
const chunk = need.slice(i, i + 20);
|
||
try {
|
||
const res = await translateBatch(ai, chunk, langDesc);
|
||
chunk.forEach((src, j) => { cache[cacheKey(lang, src)] = res[j]; });
|
||
dirty = true;
|
||
} catch (e) { console.warn(`[public-api] 网站文字翻译成 ${lang} 失败:${e.message}`); }
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) {} }
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) for (const t of uniq) if (cache[cacheKey(lang, t)]) out[lang][t] = cache[cacheKey(lang, t)];
|
||
return out;
|
||
}
|
||
|
||
// 参数值里带中文的(比如"8小时恢复到90%容量"、LCD 显示说明),自动翻译成英语 / 西语 / 俄语。
|
||
// 结果放在 specI18n: { 字段: { en, es, ru } },网站按语言取用;翻译失败的字段网站上不显示(不会露出中文)。
|
||
const SPEC_TRANSLATE_FIELDS = ['inputVoltage', 'acInputVoltage', 'inputVoltageRange', 'inputFrequency', 'outputVoltage', 'outputVoltageRange', 'transferTime', 'waveform',
|
||
'frequencyRangeBatteryMode', 'batteryVoltage', 'chargeCurrent', 'chargeTime', 'lcdDisplay', 'ledDisplay', 'fullProtection', 'alarmInfo', 'interfacePort',
|
||
'humidity', 'noiseLevel', 'outputPower', 'powerFactor', 'batterySpec', 'dimensions', 'netWeight'];
|
||
const ZH_TARGETS = { en: 'English', ...WEB_TRANSLATE_LANGS };
|
||
const hasZh = (s) => /[\u4e00-\u9fff]/.test(String(s || ''));
|
||
async function translateSpecs(ai, products) {
|
||
const need = new Set();
|
||
for (const p of products) for (const f of SPEC_TRANSLATE_FIELDS) if (typeof p[f] === 'string' && hasZh(p[f])) need.add(p[f]);
|
||
if (!need.size) return;
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
if (ai) {
|
||
for (const [lang, desc] of Object.entries(ZH_TARGETS)) {
|
||
const list = [...need].filter((t) => !cache[cacheKey('zh>' + lang, t)]);
|
||
for (let i = 0; i < list.length; i += 20) {
|
||
const chunk = list.slice(i, i + 20);
|
||
try {
|
||
const out = await translateBatch(ai, chunk, desc, 'Chinese');
|
||
chunk.forEach((src, j) => { cache[cacheKey('zh>' + lang, src)] = out[j]; });
|
||
dirty = true;
|
||
} catch (e) { console.warn(`[public-api] 参数翻译成 ${lang} 失败:${e.message}`); }
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) {} }
|
||
for (const p of products) {
|
||
for (const f of SPEC_TRANSLATE_FIELDS) {
|
||
if (typeof p[f] !== 'string' || !hasZh(p[f])) continue;
|
||
const t = {};
|
||
for (const lang of Object.keys(ZH_TARGETS)) { const v = cache[cacheKey('zh>' + lang, p[f])]; if (v) t[lang] = v; }
|
||
if (Object.keys(t).length) (p.specI18n = p.specI18n || {})[f] = t;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 给一批产品补齐各语言的介绍和卖点。翻译失败不影响构建:那一项网站上显示英文。
|
||
async function translateProducts(ai, products) {
|
||
try { await translateSpecs(ai, products); } catch (e) { console.warn('[public-api] 参数翻译失败:', e.message); }
|
||
if (!ai) {
|
||
for (const p of products) { if (p._points.length) p.sellingPointsI18n = { en: p._points }; delete p._points; }
|
||
return products;
|
||
}
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
for (const [lang, langDesc] of Object.entries(WEB_TRANSLATE_LANGS)) {
|
||
const need = new Set();
|
||
for (const p of products) {
|
||
const en = p.description && p.description.en;
|
||
if (en && !(p.description[lang] || '').trim() && !cache[cacheKey(lang, en)]) need.add(en);
|
||
for (const line of p._points) if (!cache[cacheKey(lang, line)]) need.add(line);
|
||
}
|
||
const list = [...need];
|
||
for (let i = 0; i < list.length; i += 20) {
|
||
const chunk = list.slice(i, i + 20);
|
||
try {
|
||
const out = await translateBatch(ai, chunk, langDesc);
|
||
chunk.forEach((src, j) => { cache[cacheKey(lang, src)] = out[j]; });
|
||
dirty = true;
|
||
} catch (e) {
|
||
console.warn(`[public-api] 翻译成 ${lang} 失败:${e.message}`);
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) { console.warn('[public-api] 译文缓存写入失败:', e.message); } }
|
||
|
||
for (const p of products) {
|
||
const en = p.description && p.description.en;
|
||
if (en) {
|
||
const d = { en };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) {
|
||
const manual = (p.description[lang] || '').trim();
|
||
d[lang] = manual || cache[cacheKey(lang, en)] || '';
|
||
}
|
||
p.description = d;
|
||
}
|
||
if (p._points.length) {
|
||
p.sellingPointsI18n = { en: p._points };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) {
|
||
p.sellingPointsI18n[lang] = p._points.map((l) => cache[cacheKey(lang, l)] || l);
|
||
}
|
||
}
|
||
delete p._points;
|
||
}
|
||
return products;
|
||
}
|
||
|
||
const slugify =(s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||
const parse = (v) => { try { return typeof v === 'string' ? JSON.parse(v) : v; } catch { return v; } };
|
||
|
||
function readKey(dataFile, key) {
|
||
const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
|
||
const raw = data[key];
|
||
const list = parse(raw && raw.value !== undefined ? raw.value : raw);
|
||
return Array.isArray(list) ? list : [];
|
||
}
|
||
const readProducts = (dataFile) => readKey(dataFile, PRODUCTS_KEY);
|
||
const readTemplates = (dataFile) => readKey(dataFile, TEMPLATES_KEY);
|
||
function readObj(dataFile, key) {
|
||
const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
|
||
const raw = data[key];
|
||
const v = parse(raw && raw.value !== undefined ? raw.value : raw);
|
||
return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
||
}
|
||
const safeSlot = (k) => /^[A-Za-z0-9_-]{1,40}$/.test(k);
|
||
// 图片位条目:普通图片位是文件名;图集(生产线、研发、仓库)是 { file, caption },可以有多张
|
||
function siteAssetItems(dataFile) {
|
||
const a = readObj(dataFile, SITE_ASSETS_KEY);
|
||
const out = {};
|
||
for (const [k, list] of Object.entries(a)) {
|
||
if (!safeSlot(k) || !Array.isArray(list)) continue;
|
||
const items = list
|
||
.map((x) => (typeof x === 'string' ? { file: x, caption: {} } : x && typeof x.file === 'string' ? { file: x.file, caption: x.caption || {} } : null))
|
||
.filter((x) => x && x.file && x.file === path.basename(x.file))
|
||
.slice(0, 20);
|
||
if (items.length) out[k] = items;
|
||
}
|
||
return out;
|
||
}
|
||
function siteAssetFiles(dataFile) {
|
||
const out = {};
|
||
for (const [k, items] of Object.entries(siteAssetItems(dataFile))) out[k] = items.map((x) => x.file);
|
||
return out;
|
||
}
|
||
const tplImagesOf = (t) => (Array.isArray(t && t.images) ? t.images : []).filter(Boolean).slice(0, 10);
|
||
// 产品引用的模板(按产品里选的顺序;已删除的模板自动忽略)
|
||
const templatesOf = (p, templates) => (Array.isArray(p[TEMPLATE_IDS_FIELD]) ? p[TEMPLATE_IDS_FIELD] : [])
|
||
.map((id) => templates.find((t) => t.id === id)).filter(Boolean);
|
||
|
||
const youtubeId = (url) => {
|
||
const m = String(url || '').match(/(?:youtu\.be\/|v=|embed\/|shorts\/)([\w-]{11})/);
|
||
return m ? m[1] : null;
|
||
};
|
||
|
||
const imagesOf = (p) => {
|
||
const list = Array.isArray(p[IMAGES_FIELD]) && p[IMAGES_FIELD].length
|
||
? p[IMAGES_FIELD] : [p.productImageFileName];
|
||
return list.filter(Boolean).slice(0, 6);
|
||
};
|
||
const detailsOf = (p) => (Array.isArray(p[DETAIL_FIELD]) ? p[DETAIL_FIELD] : []).filter(Boolean).slice(0, 20);
|
||
|
||
function toPublic(p, templates = []) {
|
||
const slug = slugify(p.name);
|
||
const out = { slug };
|
||
for (const [pub, src] of Object.entries(FIELDS)) {
|
||
const v = p[src];
|
||
if (v === undefined || v === '' || (Array.isArray(v) && !v.length)) continue;
|
||
out[pub] = v;
|
||
}
|
||
if (!out.ratedPower) delete out.ratedPowerUnit;
|
||
// 卖点:英文、每行一条(含中文的行不对外)
|
||
out._points = String(p.sellingPoints || '').split('\n').map((l) => l.trim()).filter((l) => l && !/[\u4e00-\u9fff]/.test(l)); // 没填额定功率时,单位单独出现没有意义
|
||
if (out.youtube) out.youtube = youtubeId(out.youtube);
|
||
const base = conf('PUBLIC_BASE_URL');
|
||
out.images = imagesOf(p).map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
|
||
out.detailImages = detailsOf(p).map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
|
||
// 模板图片:同一个模板被多个产品引用时 URL 相同,网站构建时只下载一次
|
||
const tplUrls = templatesOf(p, templates).flatMap((t) => tplImagesOf(t)
|
||
.map((f) => `${base}/api/public/tplmedia/${encodeURIComponent(t.id)}/${encodeURIComponent(f)}`));
|
||
if (tplUrls.length) out.templateImages = tplUrls;
|
||
return out;
|
||
}
|
||
|
||
function checkKey(req, res, next) {
|
||
const want = conf('SITE_BUILD_KEY');
|
||
const got = req.get('x-site-key') || '';
|
||
const ok = want && got.length === want.length &&
|
||
crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
|
||
if (!ok) return res.status(403).json({ error: 'forbidden' });
|
||
next();
|
||
}
|
||
|
||
module.exports = function mountPublicApi(app, { dataFile, uploadsDir, requireAuth, ai }) {
|
||
const published = () => readProducts(dataFile).filter((p) => p[PUBLISH_FLAG]);
|
||
const findBySlug = (slug) => published().find((p) => slugify(p.name) === slug);
|
||
|
||
// 网站构建时调用:全部已发布产品
|
||
app.get('/api/public/products', checkKey, async (req, res) => {
|
||
try {
|
||
const templates = readTemplates(dataFile);
|
||
res.json(await translateProducts(ai, published().map((p) => toPublic(p, templates))));
|
||
}
|
||
catch (e) { res.status(500).json({ error: e.message }); }
|
||
});
|
||
|
||
// 单个产品
|
||
app.get('/api/public/products/:slug', checkKey, (req, res) => {
|
||
const p = findBySlug(req.params.slug);
|
||
if (!p) return res.status(404).json({ error: 'not found' });
|
||
translateProducts(ai, [toPublic(p, readTemplates(dataFile))]).then(([x]) => res.json(x), (e) => res.status(500).json({ error: e.message }));
|
||
});
|
||
|
||
// 产品图片:只允许读取"已发布产品自己的图片",防止借这个接口读到别的文件
|
||
app.get('/api/public/media/:slug/:file', checkKey, (req, res) => {
|
||
const p = findBySlug(req.params.slug);
|
||
const file = path.basename(req.params.file);
|
||
if (!p || !(imagesOf(p).includes(file) || detailsOf(p).includes(file))) return res.status(404).end();
|
||
// 图片按产品 id 分目录存放:uploads/<产品id>/<文件名>
|
||
res.sendFile(path.resolve(uploadsDir, path.basename(String(p.id)), file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 模板图片:只允许读取"被已发布产品引用的模板"里的图片
|
||
app.get('/api/public/tplmedia/:tplId/:file', checkKey, (req, res) => {
|
||
const tplId = String(req.params.tplId);
|
||
const file = path.basename(req.params.file);
|
||
const t = readTemplates(dataFile).find((x) => x.id === tplId);
|
||
const used = t && published().some((p) => Array.isArray(p[TEMPLATE_IDS_FIELD]) && p[TEMPLATE_IDS_FIELD].includes(tplId));
|
||
if (!used || !tplImagesOf(t).includes(file) || !/^[A-Za-z0-9_-]+$/.test(tplId)) return res.status(404).end();
|
||
res.sendFile(path.resolve(uploadsDir, tplId, file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 网站管理:图片位 + 近期动态(标题、说明自动翻译;手动填了的语言优先)
|
||
app.get('/api/public/site', checkKey, async (req, res) => {
|
||
try {
|
||
const base = conf('PUBLIC_BASE_URL');
|
||
const items = siteAssetItems(dataFile);
|
||
const rawNews = readKey(dataFile, SITE_NEWS_KEY).filter((n) => n && n.title && String(n.title.en || '').trim());
|
||
const captionsEn = Object.values(items).flat().map((x) => String((x.caption && x.caption.en) || '').trim());
|
||
const tr = await translateStrings(ai, [...rawNews.flatMap((n) => [n.title.en, (n.text && n.text.en) || '']), ...captionsEn]);
|
||
const i18n = (o) => {
|
||
const en = String((o && o.en) || '').trim();
|
||
const r = { en };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) r[lang] = String((o && o[lang]) || '').trim() || (en && tr[lang][en]) || en;
|
||
return r;
|
||
};
|
||
// 图片位:{ url, caption:{en,es,ru} },没写标题的 caption 为空
|
||
const assets = {};
|
||
for (const [k, list] of Object.entries(items)) {
|
||
assets[k] = list.map((x) => ({ url: `${base}/api/public/site-media/${encodeURIComponent(x.file)}`, caption: i18n(x.caption) }));
|
||
}
|
||
const news = rawNews
|
||
.map((n) => ({ date: String(n.date || '').slice(0, 10), title: i18n(n.title), text: i18n(n.text), youtube: youtubeId(n.youtubeUrl) || undefined }))
|
||
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
|
||
res.json({ assets, news });
|
||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||
});
|
||
|
||
// 网站管理的图片:只允许读取"已分配到某个图片位"的文件
|
||
app.get('/api/public/site-media/:file', checkKey, (req, res) => {
|
||
const file = path.basename(req.params.file);
|
||
const used = Object.values(siteAssetFiles(dataFile)).some((list) => list.includes(file));
|
||
if (!used) return res.status(404).end();
|
||
res.sendFile(path.resolve(uploadsDir, SITE_ASSETS_DIR, file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 后台"发布到网站"按钮:触发 Cloudflare Pages 重新构建(需要后台登录)
|
||
app.post('/api/site/deploy', requireAuth, async (req, res) => {
|
||
if (!conf('CF_DEPLOY_HOOK')) return res.status(500).json({ error: '未配置 CF_DEPLOY_HOOK' });
|
||
try {
|
||
const r = await fetch(conf('CF_DEPLOY_HOOK'), { method: 'POST' });
|
||
// 304:Cloudflare 没有新建构建任务——通常是刚刚已经触发过、上一次构建还在排队或进行中
|
||
// (短时间内连点、或者刚推送过代码)。不算失败,等那一次构建跑完就行。
|
||
if (r.status === 304) return res.json({ ok: true, note: '已有一次更新在进行中,稍等1~2分钟即可生效;如果之后网站还没变化,再点一次' });
|
||
if (!r.ok) throw new Error(`Cloudflare 返回 HTTP ${r.status}`);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(502).json({ error: e.message }); }
|
||
});
|
||
};
|