Files
monkey-ai-web/src/pages/WebsiteSettings/insightsModel.js
T
2026-11-14 18:53:31 +08:00

220 lines
6.8 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.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from '../../components/common/ui/richTextImages.js';
import {
ARTICLE_BODY_LIMIT,
countArticleHtml,
} from '../../components/common/ui/richTextLength.js';
export const emptyInsights = () => ({
categories: [
{ id: 'company', name: '公司动态' },
{ id: 'product', name: '产品更新' },
{ id: 'industry', name: '行业洞察' },
],
articles: [],
});
export function createContentId() {
// randomUUID requires HTTPS; getRandomValues also works on HTTP admin sites.
return (
globalThis.crypto.randomUUID?.() ??
Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('')
);
}
export function categoryError(name, categories, id) {
const value = String(name ?? '').trim();
if (!value) return '请输入分类名称';
if (value.length > 12) return '分类名称不能超过 12 个字符';
if (
['全部内容', '全部分类'].includes(value) ||
categories.some((c) => c.id !== id && c.name === value)
)
return '分类名称已存在,请使用其他名称';
return '';
}
const pad = (value) => String(value).padStart(2, '0');
// Publish time is stored as local "YYYY-MM-DD HH:mm:ss"; legacy "YYYY-MM-DD" stays valid.
export function isValidPublishDate(value) {
const match = /^(\d{4})-(\d{2})-(\d{2})(?: (\d{2}):(\d{2}):(\d{2}))?$/.exec(
value,
);
if (!match) return false;
const [year, month, day, hour = 0, minute = 0, second = 0] = match
.slice(1)
.map((part) => (part === undefined ? undefined : Number(part)));
const date = new Date(year, month - 1, day, hour, minute, second);
return (
date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day &&
date.getHours() === hour &&
date.getMinutes() === minute &&
date.getSeconds() === second
);
}
export function newArticle(category = 'all') {
const now = new Date();
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
return {
id: '',
title: '',
category,
date,
subtitle: '',
summary: '',
tag: '',
body: '',
toc: true,
related: [],
};
}
export function articleErrors(article, insights) {
const errors = {};
for (const [key, label, limit, required] of [
['title', '文章标题', 80, true],
['summary', '卡片摘要', 200, true],
['subtitle', '详情副标题', 160, false],
['tag', '角标标签', 12, false],
]) {
const text = String(article[key] ?? '').trim();
if (required && !text) errors[key] = `请输入${label}`;
else if (text.length > limit)
errors[key] = `${label}不能超过 ${limit} 个字符`;
}
if (
article.category !== 'all' &&
!insights.categories.some((c) => c.id === article.category)
)
errors.category = '请选择所属分类';
const date = String(article.date ?? '');
if (!isValidPublishDate(date))
errors.date = date ? '请选择有效的发布日期' : '请选择发布日期';
const body = String(article.body ?? '');
if (
!body.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;|\s/g, '') &&
!/<img\s/i.test(body)
)
errors.body = '请输入文章正文';
else if (countArticleHtml(body) > ARTICLE_BODY_LIMIT)
errors.body = `文章正文不能超过 ${ARTICLE_BODY_LIMIT} 字`;
if (
/<(?:script|style|iframe|object|svg|math)\b|\son\w+\s*=|(?:javascript|blob):/i.test(
body,
) ||
[...body.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']*)["'][^>]*>/gi)].some(
(match) => !articleImageSource(match[1]),
)
)
errors.body = '正文包含不支持的内容,请清除格式后重试';
if (
!Array.isArray(article.related) ||
article.related.length > 3 ||
new Set(article.related).size !== article.related.length ||
article.related.some(
(id) => id === article.id || !insights.articles.some((a) => a.id === id),
)
)
errors.related = '最多选择 3 篇有效的其他文章';
return errors;
}
export function normalizeInsights(value) {
const data = value ?? emptyInsights();
return {
...data,
categories: (data.categories || []).map((c) => ({
...c,
id: String(c.id),
name: String(c.name ?? '').trim(),
})),
articles: (data.articles || []).map((a) => ({
...a,
...Object.fromEntries(
[
'id',
'title',
'category',
'date',
'subtitle',
'summary',
'tag',
'body',
].map((key) => [key, String(a[key] ?? '').trim()]),
),
toc: a.toc !== false,
related: [...(a.related || [])],
})),
};
}
export function validateInsights(value) {
if (!value) return '';
if (!Array.isArray(value.categories) || !Array.isArray(value.articles))
return '动态与洞察配置格式不正确';
const { categories, articles } = value;
if (
categories.some(
(c) =>
!c?.id || c.id === 'all' || categoryError(c.name, categories, c.id),
) ||
new Set(categories.map((c) => c.id)).size !== categories.length
)
return '请检查内容分类配置';
if (new Set(articles.map((a) => a?.id)).size !== articles.length)
return '文章标识不能重复';
for (const article of articles) {
if (!article?.id) return '文章标识不能为空';
const errors = articleErrors(article, value);
if (Object.keys(errors).length)
return `${article.title || '未命名文章'}:${Object.values(errors)[0]}`;
}
return '';
}
export function removeArticle(insights, id) {
return {
...insights,
articles: insights.articles
.filter((a) => a.id !== id)
.map((a) => ({
...a,
related: a.related.filter((other) => other !== id),
})),
};
}
export function filterArticles(insights, keyword, category) {
const query = keyword.trim().toLocaleLowerCase();
return insights.articles
.filter(
(a) =>
(category === 'all' || a.category === category) &&
`${a.title} ${a.summary}`.toLocaleLowerCase().includes(query),
)
.sort((a, b) => b.date.localeCompare(a.date));
}