Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c1d43c8ea3 | |||
| 58003e88a0 | |||
| 67951c1862 | |||
| 96146a265e | |||
| b74ab4ec46 | |||
| 2b21ca50e1 | |||
| b53ee25738 | |||
| 4695e47668 | |||
| 1ee2440faf | |||
| 0092af5c0d |
@@ -230,6 +230,7 @@ H5_PUBLIC_BASE_URL=http://127.0.0.1:5173
|
||||
# H5_SCHEDULED_TASK_MAX_ATTEMPTS=3
|
||||
# H5_SCHEDULED_TASK_EXECUTION_TIMEOUT_MS=900000
|
||||
# 新闻早报 · 微信草稿箱自动 worker(默认跟随 H5_REMINDER_WORKER_ENABLED)
|
||||
# 每天自动生成并推草稿:ENABLED + AUTO + AUTO_GENERATE 都要开;时刻以 DB 配置为准。
|
||||
# H5_WECHAT_NEWS_MORNING_DRAFT_ENABLED=1
|
||||
# H5_WECHAT_NEWS_MORNING_DRAFT_AUTO=1
|
||||
# H5_WECHAT_NEWS_MORNING_DRAFT_WORKER_ENABLED=1
|
||||
@@ -530,6 +531,11 @@ VITE_TKMIND_WORKING_DIR=/Users/john/PycharmProjects/tkmind
|
||||
# Template source: /Users/john/Project/searxng-prod/settings.yml.template
|
||||
# Goosed MCP endpoints are automatically rewritten to host.docker.internal.
|
||||
# TKMIND_SEARCH_SEARXNG_URL=http://127.0.0.1:20080/search
|
||||
# 早报预取:默认走通用搜索(Yandex/Bing/360),最多 3 路并行,避免打满连接池和触发验证码。
|
||||
# MEMIND_NEWS_MORNING_SEARXNG_PREFETCH=1
|
||||
# MEMIND_NEWS_MORNING_SEARXNG_NEWS_CATEGORY=0
|
||||
# MEMIND_NEWS_MORNING_SEARXNG_CONCURRENCY=3
|
||||
# MEMIND_NEWS_MORNING_SEARXNG_ENGINES=yandex,bing,360search
|
||||
# Portal 在 web / search-enhanced 技能执行前预取 SearXNG;设为 0 可关闭。
|
||||
# MEMIND_LIVE_SEARCH_PREFETCH=1
|
||||
# TKMIND_SEARCH_MCP_HOST_GATEWAY=host.docker.internal
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# 历史分支处置登记
|
||||
|
||||
## `feature/news002-searxng-fallback`
|
||||
|
||||
**状态:禁止再次引用。已 fast-forward 并入 `origin/main`。**
|
||||
|
||||
审计日期:2026-09-22
|
||||
分支 HEAD:`58003e88`
|
||||
`origin/main` 对应提交:`58003e88`
|
||||
|
||||
### 交付内容
|
||||
|
||||
- news002 agent 输出偏薄时 SearXNG fallback 补栏/换卡
|
||||
- 弱图与不可达配图过滤、头条卡自动晋升、推送闸门放宽
|
||||
- 与 main 侧 news002 本地化/缺图文字卡/微信左上角小图布局整合
|
||||
|
||||
---
|
||||
|
||||
## `feature/searxng-news-morning-throttle`
|
||||
|
||||
**状态:禁止再次引用。已 fast-forward 并入 `origin/main` 并完成 103 Portal 快速发布。**
|
||||
|
||||
审计日期:2026-09-22
|
||||
分支 HEAD:`b74ab4ec`
|
||||
`origin/main` 对应提交:`b74ab4ec`
|
||||
|
||||
### 交付内容
|
||||
|
||||
- news002 微信草稿与静态页统一左上角小图(72~92px 缩略图)
|
||||
- 远程配图本地化到当日 MindSpace `public/`,缺图保留文字卡、禁止默认占位小图
|
||||
- SearXNG 预取与配图 enrichment 链路收紧
|
||||
|
||||
### 103 发布记录
|
||||
|
||||
- Portal runtime:`20260922-074006-b74ab4ec`(快速发布,`STUDIO_HOST=10.10.0.2`)
|
||||
- git_head:`b74ab4ec46924be05c6928438816de5163079dc9`
|
||||
- 发布后:Portal 200;`/auth/login` 401;105 隧道端口 19081 健康
|
||||
|
||||
---
|
||||
|
||||
## `feature/wechat-push-secret-codes`
|
||||
|
||||
**状态:禁止再次引用。已 fast-forward 并入 `origin/main` 并完成 103 Portal 快速发布。**
|
||||
|
||||
@@ -60,9 +60,9 @@ prompt 层的「禁止重复」无法验证,所以在落盘后再做一次程
|
||||
链路:SearXNG `img_src`/`thumbnail` → `normalizeSearchResult()` 透传 `image`/`publishedAt`
|
||||
→ 预取 brief 里以 `图:{URL}` 单独成行 → Agent 写进 `.card .media > img`。
|
||||
|
||||
- 有图:`loading="lazy"` + `referrerpolicy="no-referrer"` + `onerror` 降级为占位
|
||||
- 无图:`<div class="media ph">{栏目 emoji}</div>`,版式不塌
|
||||
- 禁止张冠李戴、禁止编造图片地址、禁止整页长图
|
||||
- 有真实图:必须显示,`loading="lazy"` + `referrerpolicy="no-referrer"`
|
||||
- 无图:先抓来源页 `og:image` / `twitter:image`;仍没有就不放配图,保留文字卡
|
||||
- 禁止默认小图凑数、禁止张冠李戴、禁止编造图片地址、禁止整页长图
|
||||
|
||||
### 4. 视觉与排版
|
||||
|
||||
@@ -99,11 +99,14 @@ CSS 固化在 `NEWS002_STYLE_BLOCK`,直接内嵌进 taskSpec,Agent 照抄即
|
||||
| 导语 | `.subtitle` | `.lede` |
|
||||
|
||||
news002 的卡片图会先上传到微信正文素材接口,再由 inline 渲染器输出微信 CDN 地址。
|
||||
任一新闻卡缺少真实同源图片、图片上传失败、头条不是 3~4 条、事件卡超过 28 条,
|
||||
或页面仍混有 news001 DOM,都会由生成/推送闸门阻断,不允许进入草稿箱。
|
||||
静态页与微信草稿均使用 **左上角 72~92px 小图**(`.card` / `.lead-card` 左侧缩略图),不再用全宽大图。
|
||||
能拿到真实配图的卡片必须显示并上传;没有真实图就只保留文字卡,不放默认小图。
|
||||
远程配图会先下载到当日 MindSpace `public/`,改写成本站相对 URL,避免海外图源在国内打不开。
|
||||
已有配图上传失败、头条不是 3~4 条、事件卡超过 28 条,或页面仍混有 news001 DOM,
|
||||
才会由生成/推送闸门阻断,不允许进入草稿箱。
|
||||
|
||||
真实图片来源按优先级取文章来源的 `og:image:secure_url`、`og:image`、
|
||||
`twitter:image`;不使用与事件无法核验关系的泛图片搜索结果。
|
||||
真实图片来源按优先级取 SearXNG 结果里的 `img_src`/`thumbnail`,以及文章来源的
|
||||
`og:image:secure_url`、`og:image`、`twitter:image`;不使用与事件无法核验关系的泛图片搜索结果。
|
||||
|
||||
## 预览与验证
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ export async function searchSearxng(query, {
|
||||
signal,
|
||||
categories = '',
|
||||
language = '',
|
||||
engines = '',
|
||||
} = {}) {
|
||||
if (!endpoint) throw new Error('SearXNG endpoint is not configured');
|
||||
try { if (!['http:', 'https:'].includes(new URL(endpoint).protocol)) throw new Error('unsupported protocol'); } catch { throw new Error('SearXNG endpoint is not configured safely'); }
|
||||
@@ -17,6 +18,7 @@ export async function searchSearxng(query, {
|
||||
url.searchParams.set('format', 'json');
|
||||
if (categories) url.searchParams.set('categories', String(categories));
|
||||
if (language) url.searchParams.set('language', String(language));
|
||||
if (engines) url.searchParams.set('engines', String(engines));
|
||||
const timeout = AbortSignal.timeout(timeoutMs);
|
||||
const response = await fetchImpl(url, {
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
|
||||
@@ -215,6 +215,19 @@ test('SearXNG adapter can request news category and language', async () => {
|
||||
assert.match(requested, /language=zh-CN/);
|
||||
});
|
||||
|
||||
test('SearXNG adapter can pin engines', async () => {
|
||||
let requested;
|
||||
await searchSearxng('今日热点', {
|
||||
endpoint: 'http://search.local/search',
|
||||
engines: 'yandex,bing',
|
||||
fetchImpl: async (url) => {
|
||||
requested = String(url);
|
||||
return { ok: true, json: async () => ({ results: [] }) };
|
||||
},
|
||||
});
|
||||
assert.match(requested, /engines=yandex%2Cbing|engines=yandex,bing/);
|
||||
});
|
||||
|
||||
test('GitHub code adapter sends bounded queries and normalizes results', async () => {
|
||||
let requested;
|
||||
const result = await searchGithubCode('repo:openai goose', { limit: 50, fetchImpl: async (url, options) => { requested = { url: String(url), options }; return { ok: true, json: async () => ({ items: [{ repository: { full_name: 'openai/goose', description: 'agent' }, path: 'src/goose.rs', html_url: 'https://github.com/openai/goose/blob/main/src/goose.rs' }] }) }; } });
|
||||
|
||||
+14
-13
@@ -186,15 +186,16 @@ export const NEWS002_STYLE_BLOCK = `<style>
|
||||
color:#fff;font-size:11px;font-weight:700;display:flex;align-items:center;
|
||||
justify-content:center;margin-top:3px}
|
||||
.brief a{color:inherit;text-decoration:none;border-bottom:1px solid var(--line)}
|
||||
/* 头条大图卡 */
|
||||
.lead-card{display:block;background:var(--surface);border:1px solid var(--line);
|
||||
border-radius:16px;overflow:hidden;margin-bottom:15px;text-decoration:none;color:inherit;
|
||||
box-shadow:0 8px 22px rgba(52,42,31,.07)}
|
||||
.lead-card .media{position:relative;aspect-ratio:16/9;background:var(--accent-soft)}
|
||||
/* 头条卡:与普通卡一致,左侧小图 + 右侧正文 */
|
||||
.lead-card{display:flex;gap:13px;background:var(--surface);border:1px solid var(--line);
|
||||
border-radius:12px;padding:13px;margin-bottom:10px;text-decoration:none;color:inherit;
|
||||
transition:transform .18s ease,box-shadow .18s ease}
|
||||
.lead-card .media{flex-shrink:0;align-self:flex-start;width:92px;aspect-ratio:4/3;
|
||||
border-radius:8px;overflow:hidden;background:var(--accent-soft)}
|
||||
.lead-card .media img{width:100%;height:100%;object-fit:cover;display:block}
|
||||
.lead-card .body{padding:14px 16px 16px}
|
||||
.lead-card h3{font-family:var(--serif);font-size:19px;font-weight:700;line-height:1.45;margin-bottom:7px}
|
||||
.lead-card p{font-size:14px;color:var(--ink-2)}
|
||||
.lead-card .body{flex:1;min-width:0}
|
||||
.lead-card h3{font-family:var(--serif);font-size:15.5px;font-weight:700;line-height:1.5;margin-bottom:5px}
|
||||
.lead-card p{font-size:13.5px;color:var(--ink-2);line-height:1.65}
|
||||
/* 图文混排卡 */
|
||||
.card{display:flex;gap:13px;background:var(--surface);border:1px solid var(--line);
|
||||
border-radius:12px;padding:13px;margin-bottom:10px;transition:transform .18s ease,box-shadow .18s ease}
|
||||
@@ -209,7 +210,7 @@ export const NEWS002_STYLE_BLOCK = `<style>
|
||||
.card .why{margin-top:7px;padding-left:9px;border-left:2px solid var(--brand);
|
||||
font-size:12.5px;color:var(--ink-2)}
|
||||
.card .why b{color:var(--brand);font-weight:600}
|
||||
/* 占位:无图时用栏目色 + emoji,保持版式不塌 */
|
||||
/* ph 仅作浏览器端 onerror 降级;落盘页由 worker 剔除无图卡,禁止保留 ph 占位卡 */
|
||||
.media.ph{display:flex;align-items:center;justify-content:center;font-size:26px;
|
||||
background:linear-gradient(135deg,var(--brand-soft),var(--accent-soft))}
|
||||
.tag{display:inline-block;font-size:10.5px;font-weight:600;letter-spacing:.06em;
|
||||
@@ -318,11 +319,11 @@ export const NEWS002_TEMPLATE_SPEC = [
|
||||
'',
|
||||
'五、配图(news002 新增,必须做)',
|
||||
'1. 预取 brief 里每条结果若带 `图:{URL}`,就把该 URL 用作这条新闻的配图。',
|
||||
'1b. 正式 news002 的每张新闻卡都必须有与来源文章绑定的真实 https 配图;没有图的候选事件不得入选,core 栏目须换选另一条有图事件,flex 栏目可整节省略。',
|
||||
'2. 有图写 `<div class="media"><img src="{图URL}" alt="{标题}" loading="lazy" referrerpolicy="no-referrer" onerror="this.parentNode.classList.add(\'ph\');this.remove()"></div>`。',
|
||||
'3. `.media.ph` 只允许作为图片加载失败时的视觉降级,正式落盘验收不接受无 `<img>` 的占位卡;禁止为了过闸门编造图片地址。',
|
||||
'1b. 正式 news002 能拿到来源文章真实 https 配图的卡片必须显示该图;没有真实图就不要放 `<img>`、不要用默认小图或 `.media.ph` 占位。没有图的事件也必须保留,禁止因缺图删卡。',
|
||||
'2. 有真实图才写 `<div class="media"><img src="{图URL}" alt="{标题}" loading="lazy" referrerpolicy="no-referrer"></div>`。',
|
||||
'3. 禁止为了过闸门编造图片地址;禁止用默认小图凑数。拿不到图就把 `.media` 整块拿掉,只留文字卡。',
|
||||
'3b. 知识卡片的 emoji 用 `<div class="k-icon">`,否则字号会掉到正文大小。',
|
||||
'4. 头条 3~4 条及所有普通新闻卡必须 100% 有真实配图;配图必须来自对应来源文章的 `og:image` / `twitter:image`,禁止拿甲事件的图配乙事件。',
|
||||
'4. 配图优先用预取 `图:{URL}` 和来源文章的 `og:image` / `twitter:image`;能取到就必须显示,禁止拿甲事件的图配乙事件,禁止因缺图拿掉卡片。',
|
||||
'5. 图片一律 https,禁止 data URI 长图,禁止整页长图截图。',
|
||||
'',
|
||||
'六、视觉(照抄,禁止自创色值)',
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 就地修复 news002 页面:校验/重拉配图,剔除无图卡,写回 public HTML。
|
||||
*
|
||||
* H5_ROOT=/Users/john/Project/Memind node scripts/repair-news002-page-images.mjs
|
||||
* H5_ROOT=... node scripts/repair-news002-page-images.mjs --slug daily-news-0921
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { loadH5Environment } from './load-env.mjs';
|
||||
import {
|
||||
auditNews002ImageCoverage,
|
||||
enrichNews002HtmlWithSourceImages,
|
||||
pruneNews002ImagelessStoryCards,
|
||||
} from '../wechat-news-morning-images.mjs';
|
||||
|
||||
loadH5Environment(import.meta.dirname);
|
||||
|
||||
const DEFAULT_USER = 'a70ff537-8908-486e-9b6c-042e07cc25db';
|
||||
|
||||
async function main() {
|
||||
const slugArg = process.argv.find((arg) => arg.startsWith('--slug='));
|
||||
const slug = slugArg ? slugArg.slice('--slug='.length) : 'daily-news-0921';
|
||||
const userId = process.env.H5_WECHAT_NEWS_MORNING_DRAFT_USER_ID?.trim() || DEFAULT_USER;
|
||||
const h5Root = process.env.H5_ROOT?.trim() || path.join(import.meta.dirname, '..');
|
||||
const pagePath = path.join(h5Root, 'MindSpace', userId, 'public', `${slug}.html`);
|
||||
|
||||
if (!fs.existsSync(pagePath)) {
|
||||
console.error(`page not found: ${pagePath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const before = fs.readFileSync(pagePath, 'utf8');
|
||||
const enriched = await enrichNews002HtmlWithSourceImages(before, {
|
||||
timeoutMs: Number(process.env.MEMIND_NEWS_MORNING_IMAGE_META_TIMEOUT_MS ?? 8000) || 8000,
|
||||
concurrency: Number(process.env.MEMIND_NEWS_MORNING_IMAGE_META_CONCURRENCY ?? 8) || 8,
|
||||
});
|
||||
const display = pruneNews002ImagelessStoryCards(enriched.html);
|
||||
fs.writeFileSync(pagePath, display.html);
|
||||
|
||||
const audit = auditNews002ImageCoverage(display.html, { requireTemplateStructure: true });
|
||||
console.log(JSON.stringify({
|
||||
pagePath,
|
||||
enriched: {
|
||||
resolvedCount: enriched.resolvedCount,
|
||||
rejectedCount: enriched.rejectedCount ?? 0,
|
||||
removedCards: enriched.removedCards ?? 0,
|
||||
},
|
||||
display: {
|
||||
removedCards: display.removedCards,
|
||||
removedSections: display.removedSections,
|
||||
},
|
||||
audit,
|
||||
}, null, 2));
|
||||
|
||||
if (!audit.ok) process.exit(2);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -52,9 +52,6 @@ async function main() {
|
||||
templateId: restoreTemplate ? 'news001' : 'news002',
|
||||
forceGenerateOnce: restoreTemplate ? false : true,
|
||||
taskSpecAppend: restoreTemplate ? (current.taskSpecAppend ?? '') : NEWS002_FORCE_TASK_APPEND,
|
||||
autoPushEnabled: restoreTemplate
|
||||
? current.autoPushEnabled
|
||||
: false,
|
||||
};
|
||||
|
||||
console.log(JSON.stringify({
|
||||
|
||||
+100
-15
@@ -1,4 +1,5 @@
|
||||
import { extractPageTitle } from './wechat/verify/share-preview-repair.mjs';
|
||||
import { isWeakNewsMorningImageUrl } from './wechat-news-morning-images.mjs';
|
||||
|
||||
const MAX_WECHAT_CONTENT_CHARS = 20000;
|
||||
const MAX_WECHAT_CONTENT_TARGET_CHARS = 19600;
|
||||
@@ -44,6 +45,12 @@ const WX = Object.freeze({
|
||||
listWrap: 'margin:0 0 12px',
|
||||
listTitle: `margin:0;font-size:14px;font-weight:700;color:${BRAND.ink};line-height:1.5`,
|
||||
listBody: `margin:5px 0 0;font-size:13px;color:${BRAND.body};line-height:1.75`,
|
||||
compactWrap: 'margin:0 0 12px',
|
||||
compactThumb: 'display:inline-block;vertical-align:top;width:72px;margin-right:10px',
|
||||
compactThumbImg: 'display:block;width:72px;height:54px;object-fit:cover;border-radius:8px',
|
||||
compactBody: 'display:inline-block;vertical-align:top;width:calc(100% - 82px);max-width:calc(100% - 82px)',
|
||||
compactTag: `margin:0 0 4px;font-size:10px;font-weight:700;color:${BRAND.red}`,
|
||||
compactLeadTitle: `margin:0;font-size:15px;font-weight:700;color:${BRAND.ink};line-height:1.5`,
|
||||
rankWrap: `margin:0 0 12px;background:${BRAND.tintRed};border-radius:10px;padding:12px 12px 8px`,
|
||||
rankTitle: `margin:0 0 8px;font-size:14px;font-weight:700;color:${BRAND.ink};line-height:1.5`,
|
||||
rankBody: `margin:0;font-size:13px;color:${BRAND.body};line-height:1.85`,
|
||||
@@ -174,14 +181,23 @@ function extractClassDivBlocks(parentHtml, classPrefix) {
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** feature=渐变头条卡,rank=多行榜单卡,list=带序号的列表条目。 */
|
||||
function classifyCard(cardHtml) {
|
||||
if (detectFeatureTheme(cardHtml)) return 'feature';
|
||||
function isNews002Html(html) {
|
||||
const source = String(html ?? '');
|
||||
if (/\bclass="[^"]*\bmasthead\b/u.test(source)) return true;
|
||||
return /\bclass="[^"]*\blead-card\b/u.test(source) && !/\bclass="hero\b/u.test(source);
|
||||
}
|
||||
|
||||
/** feature=渐变头条卡,rank=多行榜单卡,list=带序号的列表条目,lead=news002 头条小图卡。 */
|
||||
function classifyCard(cardHtml, { news002Mode = false } = {}) {
|
||||
if (news002Mode && /\blead-card\b/u.test(cardHtml)) return 'lead';
|
||||
if (detectFeatureTheme(cardHtml, { news002Mode })) return 'feature';
|
||||
const rawBody = extractInnerHtml(cardHtml, /<p[^>]*>([\s\S]*?)<\/p>/i);
|
||||
return /<br\s*\/?>/i.test(rawBody) ? 'rank' : 'list';
|
||||
}
|
||||
|
||||
function detectFeatureTheme(cardHtml) {
|
||||
function detectFeatureTheme(cardHtml, { news002Mode = false } = {}) {
|
||||
// news002 草稿与静态页统一为左上角小图,不走 news001 渐变头条卡。
|
||||
if (news002Mode && /\blead-card\b/u.test(cardHtml)) return '';
|
||||
// news002 用 .lead-card 取代 news001 的 .highlight-box 系列做头条卡。
|
||||
if (/\blead-card\b/u.test(cardHtml)) return FEATURE_CARD_THEMES['highlight-box'];
|
||||
if (/highlight-box-orange/u.test(cardHtml)) return FEATURE_CARD_THEMES['highlight-box-orange'];
|
||||
@@ -246,13 +262,56 @@ function renderFeatureCard(cardHtml, { theme, title, body, imageUrl = '' }) {
|
||||
}
|
||||
|
||||
function renderListCard({ title, body, index, imageUrl = '' }) {
|
||||
return [
|
||||
`<section style="${WX.listWrap}">`,
|
||||
imageUrl
|
||||
? `<img src="${imageUrl}" alt="${stripInlineText(title)}" style="display:block;width:100%;height:auto;margin:0 0 9px;border-radius:9px" />`
|
||||
: '',
|
||||
const thumb = imageUrl
|
||||
? `<img src="${imageUrl}" alt="${stripInlineText(title)}" style="flex-shrink:0;width:92px;height:69px;object-fit:cover;border-radius:8px;display:block" />`
|
||||
: '';
|
||||
const textBlock = [
|
||||
`<p style="${WX.listTitle}"><span style="color:${BRAND.red}">${formatCardIndex(index)}</span> <strong>${title}</strong></p>`,
|
||||
body ? `<p style="${WX.listBody}">${body}</p>` : '',
|
||||
].filter(Boolean).join('');
|
||||
if (thumb) {
|
||||
return [
|
||||
`<section style="${WX.listWrap};display:flex;gap:10px;align-items:flex-start">`,
|
||||
thumb,
|
||||
`<div style="flex:1;min-width:0">${textBlock}</div>`,
|
||||
'</section>',
|
||||
].join('');
|
||||
}
|
||||
return [
|
||||
`<section style="${WX.listWrap}">`,
|
||||
textBlock,
|
||||
'</section>',
|
||||
].join('');
|
||||
}
|
||||
|
||||
/** news002:左侧 72×54 缩略图 + 右侧标题正文,与静态页 .card/.lead-card 一致。 */
|
||||
function renderNews002CompactCard({
|
||||
title,
|
||||
body,
|
||||
tag = '',
|
||||
index = 0,
|
||||
imageUrl = '',
|
||||
isLead = false,
|
||||
}) {
|
||||
const thumbBlock = imageUrl
|
||||
? [
|
||||
`<span style="${WX.compactThumb}">`,
|
||||
`<img src="${imageUrl}" alt="${stripInlineText(title)}" style="${WX.compactThumbImg}" />`,
|
||||
'</span>',
|
||||
].join('')
|
||||
: '';
|
||||
const titleStyle = isLead ? WX.compactLeadTitle : WX.listTitle;
|
||||
const titleHtml = isLead
|
||||
? `<p style="${titleStyle}"><strong>${title}</strong></p>`
|
||||
: `<p style="${titleStyle}"><span style="color:${BRAND.red}">${formatCardIndex(index)}</span> <strong>${title}</strong></p>`;
|
||||
return [
|
||||
`<section style="${WX.compactWrap}">`,
|
||||
thumbBlock,
|
||||
`<span style="${thumbBlock ? WX.compactBody : 'display:block'}">`,
|
||||
tag ? `<p style="${WX.compactTag}">${tag}</p>` : '',
|
||||
titleHtml,
|
||||
body ? `<p style="${WX.listBody}">${body}</p>` : '',
|
||||
'</span>',
|
||||
'</section>',
|
||||
].filter(Boolean).join('');
|
||||
}
|
||||
@@ -261,11 +320,12 @@ function renderCard(cardHtml, {
|
||||
maxBodyChars = null,
|
||||
index = 0,
|
||||
imageUrlMap = new Map(),
|
||||
news002Mode = false,
|
||||
} = {}) {
|
||||
const title = extractInnerHtml(cardHtml, /<h3[^>]*>([\s\S]*?)<\/h3>/i);
|
||||
if (!title) return '';
|
||||
const rawBody = extractInnerHtml(cardHtml, /<p[^>]*>([\s\S]*?)<\/p>/i);
|
||||
const theme = detectFeatureTheme(cardHtml);
|
||||
const theme = detectFeatureTheme(cardHtml, { news002Mode });
|
||||
|
||||
const rankBody = theme ? '' : renderRankListBody(rawBody);
|
||||
if (rankBody) {
|
||||
@@ -280,20 +340,32 @@ function renderCard(cardHtml, {
|
||||
const body = maxBodyChars
|
||||
? truncatePlainText(rawBody.replace(/<[^>]+>/g, ''), maxBodyChars)
|
||||
: rawBody;
|
||||
const imageUrl = extractMappedCardImage(cardHtml, imageUrlMap);
|
||||
|
||||
if (news002Mode) {
|
||||
return renderNews002CompactCard({
|
||||
title,
|
||||
body,
|
||||
tag: extractTagLabel(cardHtml),
|
||||
index,
|
||||
imageUrl,
|
||||
isLead: /\blead-card\b/u.test(cardHtml),
|
||||
});
|
||||
}
|
||||
|
||||
if (theme) {
|
||||
return renderFeatureCard(cardHtml, {
|
||||
theme,
|
||||
title,
|
||||
body,
|
||||
imageUrl: extractMappedCardImage(cardHtml, imageUrlMap),
|
||||
imageUrl,
|
||||
});
|
||||
}
|
||||
return renderListCard({
|
||||
title,
|
||||
body,
|
||||
index,
|
||||
imageUrl: extractMappedCardImage(cardHtml, imageUrlMap),
|
||||
imageUrl,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -317,7 +389,8 @@ function extractMappedCardImage(cardHtml, imageUrlMap = new Map()) {
|
||||
const src = String(cardHtml ?? '').match(
|
||||
/<div\b[^>]*class="[^"]*\bmedia\b[^"]*"[^>]*>[\s\S]*?<img\b[^>]*src=["']([^"']+)["']/i,
|
||||
)?.[1] ?? '';
|
||||
return resolveMappedImageUrl(src, imageUrlMap);
|
||||
const mapped = resolveMappedImageUrl(src, imageUrlMap);
|
||||
return mapped && !isWeakNewsMorningImageUrl(mapped) && !isWeakNewsMorningImageUrl(src) ? mapped : '';
|
||||
}
|
||||
|
||||
function extractHeroSubtitle(html) {
|
||||
@@ -591,7 +664,13 @@ function splitSections(html) {
|
||||
|
||||
function renderGenericSection(
|
||||
sectionHtml,
|
||||
{ sectionId = '', maxCards = null, maxBodyChars = null, imageUrlMap = new Map() } = {},
|
||||
{
|
||||
sectionId = '',
|
||||
maxCards = null,
|
||||
maxBodyChars = null,
|
||||
imageUrlMap = new Map(),
|
||||
news002Mode = false,
|
||||
} = {},
|
||||
) {
|
||||
const title = extractInnerHtml(sectionHtml, /<div class="section-title"[^>]*>([\s\S]*?)<\/div>/i);
|
||||
if (/近7天新闻早报/u.test(stripInlineText(title))) return '';
|
||||
@@ -622,11 +701,12 @@ function renderGenericSection(
|
||||
maxBodyChars,
|
||||
index: listIndex,
|
||||
imageUrlMap,
|
||||
news002Mode,
|
||||
});
|
||||
if (rendered) {
|
||||
parts.push(rendered);
|
||||
cardCount += 1;
|
||||
if (classifyCard(cardHtml) === 'list') listIndex += 1;
|
||||
if (classifyCard(cardHtml, { news002Mode }) === 'list') listIndex += 1;
|
||||
}
|
||||
}
|
||||
if (cardCount === 0) return '';
|
||||
@@ -880,7 +960,9 @@ function buildWechatInlineContent(html, {
|
||||
imageUrlMap = new Map(),
|
||||
} = {}) {
|
||||
const sections = splitSections(html);
|
||||
const news002Mode = isNews002Html(html);
|
||||
const digest = renderTodayDigest(html);
|
||||
const isNews002 = /class="[^"]*\bmasthead\b/i.test(String(html ?? ''));
|
||||
const bodyParts = [renderHero(html, imageUrlMap, { includeSubtitle: !digest })];
|
||||
if (digest) bodyParts.push(digest);
|
||||
|
||||
@@ -918,6 +1000,7 @@ function buildWechatInlineContent(html, {
|
||||
maxCards: resolveSectionCardLimit(section, trimProfile.sectionCardLimits),
|
||||
maxBodyChars: trimProfile.maxBodyChars,
|
||||
imageUrlMap,
|
||||
news002Mode,
|
||||
});
|
||||
if (rendered) {
|
||||
contentParts.push(rendered);
|
||||
@@ -1115,7 +1198,9 @@ export function convertDailyNewsHtmlToWechatInlineArticle(html, {
|
||||
}
|
||||
|
||||
export const wechatDailyNewsInlineInternals = {
|
||||
isNews002Html,
|
||||
renderCard,
|
||||
renderNews002CompactCard,
|
||||
renderHero,
|
||||
renderTodayDigest,
|
||||
renderBriefStats,
|
||||
|
||||
@@ -162,20 +162,21 @@ const NEWS002_HTML = `<!DOCTYPE html><html><body>
|
||||
</div>
|
||||
</div></body></html>`;
|
||||
|
||||
test('news002 lead-card renders as a feature card in the wechat draft', () => {
|
||||
test('news002 lead-card renders as compact left-thumb card in the wechat draft', () => {
|
||||
const rendered = wechatDailyNewsInlineInternals.renderGenericSection(
|
||||
NEWS002_HTML.match(/<div class="section" id="headlines">[\s\S]*?<\/a>\n<\/div>/)[0],
|
||||
{ sectionId: 'headlines' },
|
||||
{ sectionId: 'headlines', news002Mode: true },
|
||||
);
|
||||
assert.match(rendered, /王毅同鲁比奥通电话/u);
|
||||
assert.match(rendered, /中美关系/u, 'lead-card 的 tag 必须保留');
|
||||
assert.doesNotMatch(rendered, /01<\/span>/u, '头条卡不占列表序号');
|
||||
assert.doesNotMatch(rendered, /calc\(100% \+ 28px\)/u, 'news002 头条不走全宽 feature 大图');
|
||||
});
|
||||
|
||||
test('news002 card with media block still yields title and body', () => {
|
||||
const rendered = wechatDailyNewsInlineInternals.renderGenericSection(
|
||||
NEWS002_HTML.match(/<div class="section" id="domestic">[\s\S]*$/)[0],
|
||||
{ sectionId: 'domestic' },
|
||||
{ sectionId: 'domestic', news002Mode: true },
|
||||
);
|
||||
assert.match(rendered, /沈阳举行九一八纪念活动/u);
|
||||
assert.match(rendered, /国内正文摘要/u, '.media 在前不应挤掉正文 <p>');
|
||||
@@ -190,15 +191,17 @@ test('news002 cards render uploaded source images in the wechat draft', () => {
|
||||
const imageUrlMap = new Map([[sourceImage, wechatImage]]);
|
||||
const lead = wechatDailyNewsInlineInternals.renderGenericSection(
|
||||
html.match(/<div class="section" id="headlines">[\s\S]*?<\/a>\n<\/div>/)[0],
|
||||
{ sectionId: 'headlines', imageUrlMap },
|
||||
{ sectionId: 'headlines', imageUrlMap, news002Mode: true },
|
||||
);
|
||||
const domestic = wechatDailyNewsInlineInternals.renderGenericSection(
|
||||
html.match(/<div class="section" id="domestic">[\s\S]*$/)[0],
|
||||
{ sectionId: 'domestic', imageUrlMap },
|
||||
{ sectionId: 'domestic', imageUrlMap, news002Mode: true },
|
||||
);
|
||||
assert.match(lead, /mmbiz\.qpic\.cn\/wechat-story\.jpg/u);
|
||||
assert.match(domestic, /mmbiz\.qpic\.cn\/wechat-story\.jpg/u);
|
||||
assert.doesNotMatch(lead, /news\.example\/story\.jpg/u);
|
||||
assert.match(lead, /width:72px;height:54px/u, '配图必须是左上角小图');
|
||||
assert.doesNotMatch(domestic, /width:100%;height:auto;margin:0 0 9px/u, '列表卡不再用顶部全宽图');
|
||||
});
|
||||
|
||||
test('renderHero reads news002 masthead meta and lede', () => {
|
||||
|
||||
@@ -10,7 +10,12 @@ import {
|
||||
isNewsMorningPageForToday,
|
||||
isWithinNewsMorningGenerateLeadWindow,
|
||||
} from './wechat-news-morning-draft.mjs';
|
||||
import { prefetchNewsMorningSearxngBrief } from './wechat-news-morning-search.mjs';
|
||||
import { prefetchNewsMorningSearxngBundle } from './wechat-news-morning-search.mjs';
|
||||
import {
|
||||
repairNews002ImagelessCardsFromSearxng,
|
||||
shouldUseNewsMorningSearxngFallback,
|
||||
supplementNews002HtmlFromSearxngGroups,
|
||||
} from './wechat-news-morning-searxng-fallback.mjs';
|
||||
import {
|
||||
dedupeNewsMorningHtml,
|
||||
formatNewsMorningDedupeSummary,
|
||||
@@ -18,6 +23,8 @@ import {
|
||||
import {
|
||||
auditNews002ImageCoverage,
|
||||
enrichNews002HtmlWithSourceImages,
|
||||
localizeNews002CardImages,
|
||||
promoteNews002LeadCards,
|
||||
} from './wechat-news-morning-images.mjs';
|
||||
import {
|
||||
isWechatNewsMorningDraftWorkerEnabled,
|
||||
@@ -65,22 +72,107 @@ function applyNewsMorningDedupe(page, logger) {
|
||||
}
|
||||
}
|
||||
|
||||
async function applyNews002ImageGate(page, config, logger, env = process.env) {
|
||||
async function applyNews002ImageGate(
|
||||
page,
|
||||
config,
|
||||
logger,
|
||||
env = process.env,
|
||||
{ searchGroups = [] } = {},
|
||||
) {
|
||||
if (config?.templateId !== 'news002') return null;
|
||||
if (!page?.localPath || !fs.existsSync(page.localPath)) {
|
||||
throw new Error('news002 配图闸门无法读取生成页面');
|
||||
}
|
||||
const source = fs.readFileSync(page.localPath, 'utf8');
|
||||
const enriched = await enrichNews002HtmlWithSourceImages(source, {
|
||||
let source = fs.readFileSync(page.localPath, 'utf8');
|
||||
const promotedBefore = promoteNews002LeadCards(source);
|
||||
if (promotedBefore.promotedCount > 0) {
|
||||
logger.log?.('[NewsMorningDraft] news002 promoted headline cards', {
|
||||
slug: page.slug,
|
||||
promotedCount: promotedBefore.promotedCount,
|
||||
});
|
||||
source = promotedBefore.html;
|
||||
}
|
||||
let enriched = await enrichNews002HtmlWithSourceImages(source, {
|
||||
timeoutMs: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_TIMEOUT_MS ?? 6000) || 6000,
|
||||
concurrency: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_CONCURRENCY ?? 8) || 8,
|
||||
});
|
||||
fs.writeFileSync(page.localPath, enriched.html);
|
||||
const audit = auditNews002ImageCoverage(enriched.html, { requireTemplateStructure: true });
|
||||
let audit = auditNews002ImageCoverage(enriched.html, { requireTemplateStructure: true });
|
||||
|
||||
if (
|
||||
!audit.ok
|
||||
&& searchGroups.length > 0
|
||||
&& shouldUseNewsMorningSearxngFallback(env)
|
||||
) {
|
||||
const supplemented = supplementNews002HtmlFromSearxngGroups(
|
||||
enriched.html,
|
||||
searchGroups,
|
||||
audit,
|
||||
);
|
||||
if (supplemented.changed) {
|
||||
logger.log?.('[NewsMorningDraft] searxng fallback supplement', {
|
||||
slug: page.slug,
|
||||
...supplemented.stats,
|
||||
});
|
||||
enriched = await enrichNews002HtmlWithSourceImages(supplemented.html, {
|
||||
timeoutMs: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_TIMEOUT_MS ?? 6000) || 6000,
|
||||
concurrency: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_CONCURRENCY ?? 8) || 8,
|
||||
});
|
||||
const promotedAfterSupplement = promoteNews002LeadCards(enriched.html);
|
||||
if (promotedAfterSupplement.promotedCount > 0) {
|
||||
enriched = { ...enriched, html: promotedAfterSupplement.html };
|
||||
logger.log?.('[NewsMorningDraft] news002 promoted headline cards after searxng', {
|
||||
slug: page.slug,
|
||||
promotedCount: promotedAfterSupplement.promotedCount,
|
||||
});
|
||||
}
|
||||
audit = auditNews002ImageCoverage(enriched.html, { requireTemplateStructure: true });
|
||||
}
|
||||
|
||||
if (!audit.ok && audit.missingTitles?.length > 0) {
|
||||
const repaired = repairNews002ImagelessCardsFromSearxng(enriched.html, searchGroups);
|
||||
if (repaired.changed) {
|
||||
logger.log?.('[NewsMorningDraft] searxng fallback image repair', {
|
||||
slug: page.slug,
|
||||
...repaired.stats,
|
||||
});
|
||||
enriched = await enrichNews002HtmlWithSourceImages(repaired.html, {
|
||||
timeoutMs: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_TIMEOUT_MS ?? 6000) || 6000,
|
||||
concurrency: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_CONCURRENCY ?? 8) || 8,
|
||||
});
|
||||
const promotedAfterRepair = promoteNews002LeadCards(enriched.html);
|
||||
if (promotedAfterRepair.promotedCount > 0) {
|
||||
enriched = { ...enriched, html: promotedAfterRepair.html };
|
||||
}
|
||||
audit = auditNews002ImageCoverage(enriched.html, { requireTemplateStructure: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!audit.ok && audit.violations.includes('invalid-lead-count')) {
|
||||
const promotedFinal = promoteNews002LeadCards(enriched.html);
|
||||
if (promotedFinal.promotedCount > 0) {
|
||||
enriched = { ...enriched, html: promotedFinal.html };
|
||||
audit = auditNews002ImageCoverage(enriched.html, { requireTemplateStructure: true });
|
||||
logger.log?.('[NewsMorningDraft] news002 promoted headline cards before final audit', {
|
||||
slug: page.slug,
|
||||
promotedCount: promotedFinal.promotedCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const localized = await localizeNews002CardImages(enriched.html, {
|
||||
publishDir: path.dirname(page.localPath),
|
||||
slug: page.slug,
|
||||
timeoutMs: Number(env.MEMIND_NEWS_MORNING_IMAGE_DOWNLOAD_TIMEOUT_MS ?? 8000) || 8000,
|
||||
});
|
||||
fs.writeFileSync(page.localPath, localized.html);
|
||||
audit = auditNews002ImageCoverage(localized.html, { requireTemplateStructure: true });
|
||||
logger.log?.('[NewsMorningDraft] news002 image audit', {
|
||||
slug: page.slug,
|
||||
attempted: enriched.attemptedCount,
|
||||
resolved: enriched.resolvedCount,
|
||||
localized: localized.localizedCount,
|
||||
localizeFailed: localized.failedCount,
|
||||
...audit,
|
||||
});
|
||||
if (!audit.ok) {
|
||||
@@ -121,7 +213,7 @@ export function startWechatNewsMorningDraftWorker({
|
||||
h5Root = null,
|
||||
env = process.env,
|
||||
executeTask = executeScheduledTask,
|
||||
prefetchNewsSearch = prefetchNewsMorningSearxngBrief,
|
||||
prefetchNewsSearch = prefetchNewsMorningSearxngBundle,
|
||||
logger = console,
|
||||
intervalMs = wechatNewsMorningDraftWorkerIntervalMs(env),
|
||||
executionTimeoutMs = wechatNewsMorningDraftExecutionTimeoutMs(env),
|
||||
@@ -152,12 +244,15 @@ export function startWechatNewsMorningDraftWorker({
|
||||
archiveTodayPageForForce(config, h5Root, now, logger);
|
||||
}
|
||||
let searchBrief = '';
|
||||
let searchGroups = [];
|
||||
try {
|
||||
searchBrief = await prefetchNewsSearch({
|
||||
const searchBundle = await prefetchNewsSearch({
|
||||
now,
|
||||
timezone: config.timezone,
|
||||
env,
|
||||
});
|
||||
searchBrief = String(searchBundle?.brief ?? searchBundle ?? '').trim();
|
||||
searchGroups = Array.isArray(searchBundle?.groups) ? searchBundle.groups : [];
|
||||
} catch (prefetchError) {
|
||||
logger.warn?.(
|
||||
'[NewsMorningDraft] searxng prefetch failed:',
|
||||
@@ -181,7 +276,7 @@ export function startWechatNewsMorningDraftWorker({
|
||||
throw new Error('新闻早报页面生成未完成');
|
||||
}
|
||||
applyNewsMorningDedupe(page, logger);
|
||||
await applyNews002ImageGate(page, config, logger, env);
|
||||
await applyNews002ImageGate(page, config, logger, env, { searchGroups });
|
||||
await wechatNewsMorningDraftService.recordAutoGenerationRun({
|
||||
status: 'success',
|
||||
pageSlug: page.slug,
|
||||
@@ -248,10 +343,10 @@ export function startWechatNewsMorningDraftWorker({
|
||||
const todayPageDegraded = todayPage && isNewsMorningPageDegraded(todayPage);
|
||||
if (
|
||||
todayPageDegraded
|
||||
&& !config.forceGenerateOnce
|
||||
&& generationInFlightDateKey !== dateKey
|
||||
&& (
|
||||
config.forceGenerateOnce
|
||||
|| isWithinNewsMorningGenerateLeadWindow(config, now)
|
||||
isWithinNewsMorningGenerateLeadWindow(config, now)
|
||||
|| isLocalScheduleDue(
|
||||
{ hour: config.pushHour, minute: config.pushMinute, timezone },
|
||||
now,
|
||||
@@ -316,8 +411,6 @@ export function startWechatNewsMorningDraftWorker({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!config.autoPushEnabled) return;
|
||||
|
||||
const shouldGenerate =
|
||||
config.autoGenerateEnabled !== false
|
||||
&& !todayPage
|
||||
@@ -338,6 +431,8 @@ export function startWechatNewsMorningDraftWorker({
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.autoPushEnabled) return;
|
||||
|
||||
if (
|
||||
!isLocalScheduleDue(
|
||||
{ hour: config.pushHour, minute: config.pushMinute, timezone },
|
||||
|
||||
@@ -101,6 +101,69 @@ test('news morning draft worker auto-pushes at configured time', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('runOnce auto-generates in the lead window even if auto-push is off', async () => {
|
||||
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'news-draft-autogen-'));
|
||||
const userId = 'user-news';
|
||||
const publicDir = path.join(tmpRoot, PUBLISH_ROOT_DIR, userId, PUBLIC_ZONE_DIR);
|
||||
fs.mkdirSync(publicDir, { recursive: true });
|
||||
|
||||
const pool = createPool();
|
||||
const service = createWechatNewsMorningDraftService(pool, {
|
||||
mpConfig: { enabled: true, appId: 'app', appSecret: 'secret' },
|
||||
h5Root: tmpRoot,
|
||||
env: {
|
||||
H5_WECHAT_NEWS_MORNING_DRAFT_ENABLED: '1',
|
||||
H5_WECHAT_NEWS_MORNING_DRAFT_USER_ID: userId,
|
||||
},
|
||||
});
|
||||
service.getConfig = async () => ({
|
||||
enabled: true,
|
||||
sourceUserId: userId,
|
||||
autoPushEnabled: false,
|
||||
autoGenerateEnabled: true,
|
||||
generateLeadMinutes: 60,
|
||||
timezone: 'Asia/Shanghai',
|
||||
pushHour: 6,
|
||||
pushMinute: 0,
|
||||
pageSlugPattern: 'daily-news-*',
|
||||
});
|
||||
const pushCalls = [];
|
||||
service.pushDraft = async (options = {}) => {
|
||||
pushCalls.push(options);
|
||||
return { ok: true, draftMediaId: 'draft-should-not-fire' };
|
||||
};
|
||||
const executeCalls = [];
|
||||
const fixedNow = Date.UTC(2026, 8, 10, 21, 15, 0);
|
||||
const originalNow = Date.now;
|
||||
Date.now = () => fixedNow;
|
||||
|
||||
try {
|
||||
const worker = startWechatNewsMorningDraftWorker({
|
||||
wechatNewsMorningDraftService: service,
|
||||
mpConfig: { enabled: true },
|
||||
userAuth: { canUseChat: async () => ({ ok: true }) },
|
||||
tkmindProxy: { id: 'proxy' },
|
||||
h5Root: tmpRoot,
|
||||
env: { H5_WECHAT_NEWS_MORNING_DRAFT_WORKER_ENABLED: '1' },
|
||||
executeTask: async () => {
|
||||
executeCalls.push('generate');
|
||||
fs.writeFileSync(path.join(publicDir, 'daily-news-0911.html'), `${SAMPLE_HTML}<!--lead-->`);
|
||||
},
|
||||
intervalMs: 30_000,
|
||||
runOnStart: false,
|
||||
setIntervalFn: () => ({ unref() {} }),
|
||||
});
|
||||
|
||||
await worker.runOnce();
|
||||
assert.equal(executeCalls.length, 1);
|
||||
assert.equal(pushCalls.length, 0);
|
||||
assert.match(fs.readFileSync(path.join(publicDir, 'daily-news-0911.html'), 'utf8'), /lead/);
|
||||
} finally {
|
||||
Date.now = originalNow;
|
||||
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runOnce honors forceGenerateOnce even when today page exists', async () => {
|
||||
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'news-draft-flag-'));
|
||||
const userId = 'user-news';
|
||||
@@ -212,7 +275,10 @@ test('generateToday skips existing page unless force is set', async () => {
|
||||
executeCalls.push(task.taskSpec);
|
||||
fs.writeFileSync(path.join(publicDir, 'daily-news-0911.html'), `${SAMPLE_HTML}<!--forced-->`);
|
||||
},
|
||||
prefetchNewsSearch: async () => '【专用联网搜索预取】国内国际热门事件',
|
||||
prefetchNewsSearch: async () => ({
|
||||
brief: '【专用联网搜索预取】国内国际热门事件',
|
||||
groups: [],
|
||||
}),
|
||||
intervalMs: 30_000,
|
||||
runOnStart: false,
|
||||
setIntervalFn: () => ({ unref() {} }),
|
||||
|
||||
@@ -25,6 +25,8 @@ import { countNewsMorningStoryCards } from './wechat-news-morning-dedup.mjs';
|
||||
import {
|
||||
auditNews002ImageCoverage,
|
||||
extractNews002CardImageUrls,
|
||||
isWeakNewsMorningImageUrl,
|
||||
stripNews002ImagelessStoryCards,
|
||||
} from './wechat-news-morning-images.mjs';
|
||||
import {
|
||||
NEWS001_FRESH_CONTENT_SPEC,
|
||||
@@ -706,7 +708,10 @@ function collectHtmlBodyImageRefs(html) {
|
||||
refs.push(coverRef);
|
||||
}
|
||||
for (const match of String(html ?? '').matchAll(/<img[^>]+src=["']([^"']+)["']/gi)) {
|
||||
const ref = String(match[1] ?? '').trim();
|
||||
const ref = String(match[1] ?? '')
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/"/gi, '"')
|
||||
.trim();
|
||||
if (!ref || /^data:/i.test(ref) || seen.has(ref)) continue;
|
||||
seen.add(ref);
|
||||
refs.push(ref);
|
||||
@@ -836,11 +841,24 @@ export async function buildDailyNewsWechatDraftArticleForPush({
|
||||
memindLibRoot,
|
||||
});
|
||||
if (/class="[^"]*\bmasthead\b/i.test(String(html ?? ''))) {
|
||||
const audit = auditNews002ImageCoverage(html, { requireTemplateStructure: true });
|
||||
if (!audit.ok) {
|
||||
throw new Error(`news002 页面未通过推送闸门:${audit.violations.join(', ')}`);
|
||||
html = stripNews002ImagelessStoryCards(String(html ?? '')).html;
|
||||
const audit = auditNews002ImageCoverage(html, {
|
||||
requireTemplateStructure: true,
|
||||
requireAllCoreSections: false,
|
||||
requireLeadCount: false,
|
||||
});
|
||||
const pushBlocking = audit.violations.filter((item) => (
|
||||
item === 'story-image-missing'
|
||||
|| item === 'lead-image-missing'
|
||||
|| item === 'too-many-story-cards'
|
||||
|| item === 'legacy-news001-dom'
|
||||
));
|
||||
if (pushBlocking.length > 0) {
|
||||
throw new Error(`news002 页面未通过推送闸门:${pushBlocking.join(', ')}`);
|
||||
}
|
||||
const missingUploads = extractNews002CardImageUrls(html).filter((ref) => (
|
||||
!isWeakNewsMorningImageUrl(ref)
|
||||
)).filter((ref) => (
|
||||
!imageUrlMap.has(ref)
|
||||
&& !imageUrlMap.has(ref.replace(/^\.\//, ''))
|
||||
&& !imageUrlMap.has(ref.replace(/^\//, ''))
|
||||
@@ -1541,6 +1559,7 @@ export function createWechatNewsMorningDraftService(
|
||||
accessToken,
|
||||
wechatFetch,
|
||||
memindLibRoot,
|
||||
publishDir: path.dirname(page.localPath),
|
||||
})
|
||||
: preview.article;
|
||||
if (articleTitleOverride) {
|
||||
|
||||
+410
-30
@@ -1,7 +1,16 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 6000;
|
||||
const DEFAULT_USER_AGENT =
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 '
|
||||
+ '(KHTML, like Gecko) Chrome/126.0 Safari/537.36 TKMind-NewsBot/1.0';
|
||||
const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const NEWS002_CARD_FALLBACK_FILENAME = 'news002-card-fallback.svg';
|
||||
const NEWS002_LOCAL_IMAGE_MAX_BYTES = 2.5 * 1024 * 1024;
|
||||
|
||||
function decodeHtmlAttribute(value) {
|
||||
return String(value ?? '')
|
||||
@@ -94,6 +103,13 @@ export function extractNews002StoryCards(html) {
|
||||
return cards;
|
||||
}
|
||||
|
||||
/** 站点 logo、作者头像、favicon 等不宜作为新闻配图。 */
|
||||
export function isWeakNewsMorningImageUrl(url) {
|
||||
const value = String(url ?? '').toLowerCase();
|
||||
if (!value) return true;
|
||||
return /favicon|\/icon(?:\/|$)|logo\.png|globalissues\.png|_share\.png|versant_share|siteicon|default.*\.(?:png|jpe?g|webp)|wikimedia\.org|resize,w_200|generate_sharing_image|social-preview-default|scidaily-icon|arxiv-logo|static\/logo\.png|\/150\.jpg|-100x100\.|\/100x100\.|unsplash\.com|pexels\.com|placeholder/.test(value);
|
||||
}
|
||||
|
||||
export function normalizeNewsMorningImageUrl(value, { pageUrl = '' } = {}) {
|
||||
const raw = decodeHtmlAttribute(value).trim();
|
||||
if (!raw || /^data:/i.test(raw)) return '';
|
||||
@@ -107,6 +123,29 @@ export function normalizeNewsMorningImageUrl(value, { pageUrl = '' } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeNewsMorningLocalImageRef(value) {
|
||||
const raw = decodeHtmlAttribute(value).trim();
|
||||
if (!raw || /^data:/i.test(raw) || /^https?:/i.test(raw)) return '';
|
||||
if (raw.includes('..') || raw.includes('\\')) return '';
|
||||
const pathname = raw.split('?')[0].split('#')[0].replace(/^\.\//, '').replace(/^\/+/, '');
|
||||
if (!pathname || !/\.(webp|png|jpe?g|gif|svg)$/i.test(pathname)) return '';
|
||||
if (!/^[A-Za-z0-9._/-]+$/.test(pathname)) return '';
|
||||
return pathname.slice(0, 400);
|
||||
}
|
||||
|
||||
function isPlaceholderCardImage(value) {
|
||||
const raw = String(value ?? '').toLowerCase();
|
||||
return /news002-card-fallback|data-image-source=["']default["']/.test(raw);
|
||||
}
|
||||
|
||||
function acceptCardImageSrc(value, { pageUrl = '' } = {}) {
|
||||
const accepted = normalizeNewsMorningImageUrl(value, { pageUrl })
|
||||
|| normalizeNewsMorningLocalImageRef(value);
|
||||
return accepted && !isPlaceholderCardImage(accepted) && !isWeakNewsMorningImageUrl(accepted)
|
||||
? accepted
|
||||
: '';
|
||||
}
|
||||
|
||||
function readMetaContent(html, key, value) {
|
||||
const source = String(html ?? '');
|
||||
const tags = source.match(/<meta\b[^>]*>/gi) ?? [];
|
||||
@@ -134,6 +173,40 @@ export function extractNewsMorningSourceImage(html, pageUrl = '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
export async function isFetchableNewsMorningImageUrl(
|
||||
imageUrl,
|
||||
{
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
userAgent = DEFAULT_USER_AGENT,
|
||||
} = {},
|
||||
) {
|
||||
const normalized = normalizeNewsMorningImageUrl(imageUrl);
|
||||
if (!normalized) return false;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
let response = await fetchImpl(normalized, {
|
||||
method: 'HEAD',
|
||||
redirect: 'follow',
|
||||
signal: controller.signal,
|
||||
headers: { 'User-Agent': userAgent, Accept: 'image/*,*/*;q=0.8' },
|
||||
});
|
||||
if (response.status === 405 || response.status === 501) {
|
||||
response = await fetchImpl(normalized, {
|
||||
redirect: 'follow',
|
||||
signal: controller.signal,
|
||||
headers: { 'User-Agent': userAgent, Accept: 'image/*,*/*;q=0.8' },
|
||||
});
|
||||
}
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveNewsMorningSourceImage(
|
||||
pageUrl,
|
||||
{
|
||||
@@ -211,11 +284,115 @@ export async function enrichNewsMorningSearchGroupsWithImages(
|
||||
return { groups: cloned, attemptedCount: pending.length, resolvedCount };
|
||||
}
|
||||
|
||||
function extractCardImage(cardRaw) {
|
||||
export function extractCardImage(cardRaw) {
|
||||
const media = String(cardRaw ?? '').match(
|
||||
/<div\b[^>]*class="[^"]*\bmedia\b[^"]*"[^>]*>[\s\S]*?<img\b[^>]*src=["']([^"']+)["']/i,
|
||||
);
|
||||
return normalizeNewsMorningImageUrl(media?.[1] ?? '');
|
||||
return acceptCardImageSrc(media?.[1] ?? '');
|
||||
}
|
||||
|
||||
/** 无真实 https 配图或仅有 ph 占位时视为不可展示。 */
|
||||
export function cardHasDisplayableImage(cardRaw) {
|
||||
const raw = String(cardRaw ?? '');
|
||||
if (/\bmedia\s+ph\b/i.test(raw) || /<div\b[^>]*class="[^"]*\bmedia\b[^"]*\bph\b/i.test(raw)) {
|
||||
return false;
|
||||
}
|
||||
const image = extractCardImage(raw);
|
||||
return Boolean(image) && !isWeakNewsMorningImageUrl(image);
|
||||
}
|
||||
|
||||
function promoteCardRawToLead(card) {
|
||||
const href = card.url || card.raw.match(/href=["'](https?:\/\/[^"']+)["']/i)?.[1] || '#';
|
||||
if (/^<a\b/i.test(card.raw)) {
|
||||
return card.raw.replace(/class="[^"]*"/i, 'class="lead-card"');
|
||||
}
|
||||
if (/^<div class="card"/i.test(card.raw)) {
|
||||
return card.raw
|
||||
.replace(
|
||||
/^<div class="card"/i,
|
||||
`<a class="lead-card" href="${escapeHtmlAttribute(href)}" target="_blank" rel="noopener"`,
|
||||
)
|
||||
.replace(/<\/div>\s*$/i, '</a>');
|
||||
}
|
||||
return card.raw.replace(/\bcard\b/, 'lead-card');
|
||||
}
|
||||
|
||||
/** Agent 常把头条写成 div.card;晋升 3~4 条有图卡为 a.lead-card 以满足结构闸门。 */
|
||||
export function promoteNews002LeadCards(html, { min = 3, max = 4 } = {}) {
|
||||
let output = String(html ?? '');
|
||||
const leads = extractNews002StoryCards(output).filter(
|
||||
(card) => card.isLead && cardHasDisplayableImage(card.raw),
|
||||
);
|
||||
if (leads.length >= min && leads.length <= max) {
|
||||
return { html: output, promotedCount: 0 };
|
||||
}
|
||||
|
||||
output = output.replace(
|
||||
/<a\b[^>]*class="[^"]*\blead-card\b[^"]*"[^>]*>[\s\S]*?<\/a>\s*(?=<ol class="brief")/i,
|
||||
'',
|
||||
);
|
||||
|
||||
const candidates = extractNews002StoryCards(output)
|
||||
.filter((card) => card.title && cardHasDisplayableImage(card.raw) && !card.isLead)
|
||||
.slice(0, max);
|
||||
const needCount = Math.max(0, min - leads.length);
|
||||
const toPromote = candidates.slice(0, needCount);
|
||||
for (const card of [...toPromote].sort((a, b) => b.start - a.start)) {
|
||||
const promoted = promoteCardRawToLead(card);
|
||||
output = output.slice(0, card.start) + promoted + output.slice(card.end);
|
||||
}
|
||||
return { html: output, promotedCount: toPromote.length };
|
||||
}
|
||||
|
||||
const NEWS002_KEEP_EMPTY_SECTION_IDS = new Set(['weather', 'history', 'brief']);
|
||||
|
||||
function pruneEmptyNews002Sections(html) {
|
||||
let output = String(html ?? '');
|
||||
const re = /<div\b[^>]*class=["'][^"']*\bsection\b[^"']*["'][^>]*id=["']([^"']+)["'][^>]*>/gi;
|
||||
const matches = [...output.matchAll(re)];
|
||||
let removedSections = 0;
|
||||
for (const match of [...matches].reverse()) {
|
||||
const sectionId = match[1];
|
||||
if (NEWS002_KEEP_EMPTY_SECTION_IDS.has(sectionId)) continue;
|
||||
const { start, end } = sliceBalancedBlock(
|
||||
output,
|
||||
'div',
|
||||
match.index,
|
||||
match.index + match[0].length,
|
||||
);
|
||||
const slice = output.slice(start, end);
|
||||
const cards = extractNews002StoryCards(slice).filter((card) => cardHasDisplayableImage(card.raw));
|
||||
const hasDeep = /<div\b[^>]*class=["'][^"']*\bdeep\b/i.test(slice);
|
||||
if (cards.length === 0 && !hasDeep) {
|
||||
output = output.slice(0, start) + output.slice(end);
|
||||
removedSections += 1;
|
||||
}
|
||||
}
|
||||
return { html: output, removedSections };
|
||||
}
|
||||
|
||||
/** 仅移除无图故事卡,不删空栏目(闸门阶段用,避免 fallback 补栏后被误删)。 */
|
||||
export function stripNews002ImagelessStoryCards(html) {
|
||||
let output = String(html ?? '');
|
||||
let removedCards = 0;
|
||||
const imageless = extractNews002StoryCards(output)
|
||||
.filter((card) => card.title && !cardHasDisplayableImage(card.raw));
|
||||
for (const card of [...imageless].sort((a, b) => b.start - a.start)) {
|
||||
output = output.slice(0, card.start) + output.slice(card.end);
|
||||
removedCards += 1;
|
||||
}
|
||||
return { html: output, removedCards, removedSections: 0 };
|
||||
}
|
||||
|
||||
/** 移除无图故事卡并清理空栏目(推送/展示前用,保证页面协调)。 */
|
||||
export function pruneNews002ImagelessStoryCards(html) {
|
||||
const stripped = stripNews002ImagelessStoryCards(html);
|
||||
const prunedSections = pruneEmptyNews002Sections(stripped.html);
|
||||
return {
|
||||
html: prunedSections.html,
|
||||
removedCards: stripped.removedCards,
|
||||
removedSections: prunedSections.removedSections,
|
||||
};
|
||||
}
|
||||
|
||||
export function extractNews002CardImageUrls(html) {
|
||||
@@ -253,26 +430,212 @@ function ensureBodyWrapper(inner) {
|
||||
return `<div class="body">${source}</div>`;
|
||||
}
|
||||
|
||||
function renderCardMedia(card, image) {
|
||||
const parts = splitCardRaw(card);
|
||||
if (!parts) return card.raw;
|
||||
const cleanedInner = ensureBodyWrapper(removeExistingMedia(parts.inner));
|
||||
if (!image) {
|
||||
return `${parts.open}${cleanedInner}${parts.close}`;
|
||||
}
|
||||
return `${parts.open}<div class="media"><img src="${escapeHtmlAttribute(image)}" alt="${escapeHtmlAttribute(card.title)}" loading="lazy" referrerpolicy="no-referrer"></div>${cleanedInner}${parts.close}`;
|
||||
}
|
||||
|
||||
export function resolveNews002CardFallbackAssetPath({ memindLibRoot = process.cwd() } = {}) {
|
||||
const candidates = [
|
||||
path.join(THIS_DIR, 'wechat/assets', NEWS002_CARD_FALLBACK_FILENAME),
|
||||
path.join(memindLibRoot, 'wechat/assets', NEWS002_CARD_FALLBACK_FILENAME),
|
||||
path.join(process.cwd(), 'wechat/assets', NEWS002_CARD_FALLBACK_FILENAME),
|
||||
];
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
|
||||
}
|
||||
|
||||
function looksLikeImageBuffer(buffer) {
|
||||
if (!Buffer.isBuffer(buffer) || buffer.length < 12) return false;
|
||||
if (buffer[0] === 0xff && buffer[1] === 0xd8) return true;
|
||||
if (buffer[0] === 0x89 && buffer[1] === 0x50) return true;
|
||||
if (buffer[0] === 0x47 && buffer[1] === 0x49) return true;
|
||||
return buffer.slice(0, 4).toString('ascii') === 'RIFF'
|
||||
&& buffer.slice(8, 12).toString('ascii') === 'WEBP';
|
||||
}
|
||||
|
||||
function news002LocalImageFilename(slug, imageUrl) {
|
||||
const safeSlug = String(slug || 'daily-news').replace(/[^A-Za-z0-9_-]/g, '').slice(0, 40) || 'daily-news';
|
||||
const hash = createHash('sha1').update(String(imageUrl)).digest('hex').slice(0, 12);
|
||||
return `${safeSlug}-img-${hash}.jpg`;
|
||||
}
|
||||
|
||||
async function downloadNewsMorningImageBytes(imageUrl, {
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
referrer = '',
|
||||
} = {}) {
|
||||
const normalized = normalizeNewsMorningImageUrl(imageUrl);
|
||||
if (!normalized) return null;
|
||||
try {
|
||||
const response = await fetchImpl(normalized, {
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
headers: {
|
||||
'User-Agent': DEFAULT_USER_AGENT,
|
||||
Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
...(referrer ? { Referer: referrer } : {}),
|
||||
},
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
if (buffer.length > NEWS002_LOCAL_IMAGE_MAX_BYTES || !looksLikeImageBuffer(buffer)) return null;
|
||||
return buffer;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function encodeNews002LocalCardImage(buffer) {
|
||||
return sharp(buffer)
|
||||
.rotate()
|
||||
.resize({ width: 1200, height: 1200, fit: 'inside', withoutEnlargement: true })
|
||||
.jpeg({ quality: 78, mozjpeg: true })
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
export async function localizeNews002CardImages(
|
||||
html,
|
||||
{
|
||||
publishDir = '',
|
||||
slug = 'daily-news',
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = 8000,
|
||||
concurrency = 4,
|
||||
} = {},
|
||||
) {
|
||||
const source = String(html ?? '');
|
||||
if (!publishDir) {
|
||||
return { html: source, localizedCount: 0, failedCount: 0, reusedCount: 0 };
|
||||
}
|
||||
fs.mkdirSync(publishDir, { recursive: true });
|
||||
const cards = extractNews002StoryCards(source).filter((card) => card.title);
|
||||
const remoteCards = [];
|
||||
for (const card of cards) {
|
||||
const image = extractCardImage(card.raw);
|
||||
if (!image || !/^https:\/\//i.test(image)) continue;
|
||||
remoteCards.push({ card, image });
|
||||
}
|
||||
|
||||
const localByRemote = new Map();
|
||||
const failed = new Set();
|
||||
const claimed = new Set();
|
||||
let cursor = 0;
|
||||
let localizedCount = 0;
|
||||
let reusedCount = 0;
|
||||
|
||||
async function worker() {
|
||||
while (cursor < remoteCards.length) {
|
||||
const item = remoteCards[cursor];
|
||||
cursor += 1;
|
||||
if (claimed.has(item.image)) continue;
|
||||
claimed.add(item.image);
|
||||
const filename = news002LocalImageFilename(slug, item.image);
|
||||
const dest = path.join(publishDir, filename);
|
||||
if (fs.existsSync(dest) && fs.statSync(dest).size > 32) {
|
||||
localByRemote.set(item.image, filename);
|
||||
reusedCount += 1;
|
||||
continue;
|
||||
}
|
||||
const bytes = await downloadNewsMorningImageBytes(item.image, {
|
||||
fetchImpl,
|
||||
timeoutMs,
|
||||
referrer: item.card.url || '',
|
||||
});
|
||||
if (!bytes) {
|
||||
failed.add(item.image);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const encoded = await encodeNews002LocalCardImage(bytes);
|
||||
fs.writeFileSync(dest, encoded);
|
||||
localByRemote.set(item.image, filename);
|
||||
localizedCount += 1;
|
||||
} catch {
|
||||
failed.add(item.image);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(Math.max(1, concurrency), remoteCards.length || 1) }, () => worker()),
|
||||
);
|
||||
|
||||
let output = source;
|
||||
for (const card of [...cards].sort((a, b) => b.start - a.start)) {
|
||||
const current = extractCardImage(card.raw);
|
||||
if (!current) continue;
|
||||
if (!/^https:\/\//i.test(current)) continue;
|
||||
const local = localByRemote.get(current) || '';
|
||||
const replacement = renderCardMedia(card, local);
|
||||
output = output.slice(0, card.start) + replacement + output.slice(card.end);
|
||||
}
|
||||
|
||||
return {
|
||||
html: output,
|
||||
localizedCount,
|
||||
failedCount: failed.size,
|
||||
reusedCount,
|
||||
};
|
||||
}
|
||||
|
||||
export function materializeNews002CardFallbackImage(publishDir, options = {}) {
|
||||
const sourcePath = resolveNews002CardFallbackAssetPath(options);
|
||||
if (!sourcePath) throw new Error('缺少 news002 默认卡片图');
|
||||
if (!publishDir) throw new Error('缺少 news002 默认卡片图输出目录');
|
||||
fs.mkdirSync(publishDir, { recursive: true });
|
||||
const dest = path.join(publishDir, NEWS002_CARD_FALLBACK_FILENAME);
|
||||
fs.copyFileSync(sourcePath, dest);
|
||||
return NEWS002_CARD_FALLBACK_FILENAME;
|
||||
}
|
||||
|
||||
export async function enrichNews002HtmlWithSourceImages(
|
||||
html,
|
||||
{
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
concurrency = 8,
|
||||
fallbackImage: _unusedFallbackImage = '',
|
||||
} = {},
|
||||
) {
|
||||
const source = String(html ?? '');
|
||||
const cards = extractNews002StoryCards(source);
|
||||
const unresolved = cards.filter((card) => card.title && !extractCardImage(card.raw) && card.url);
|
||||
const cards = extractNews002StoryCards(source).filter((card) => card.title);
|
||||
let cursor = 0;
|
||||
let resolvedCount = 0;
|
||||
let rejectedCount = 0;
|
||||
const imageByStart = new Map();
|
||||
|
||||
async function resolveCardImage(card) {
|
||||
const existingImage = extractCardImage(card.raw);
|
||||
if (
|
||||
existingImage
|
||||
&& !isWeakNewsMorningImageUrl(existingImage)
|
||||
&& await isFetchableNewsMorningImageUrl(existingImage, { fetchImpl, timeoutMs })
|
||||
) {
|
||||
return existingImage;
|
||||
}
|
||||
if (existingImage) rejectedCount += 1;
|
||||
if (!card.url) return '';
|
||||
const fromSource = await resolveNewsMorningSourceImage(card.url, { fetchImpl, timeoutMs });
|
||||
if (
|
||||
fromSource
|
||||
&& !isWeakNewsMorningImageUrl(fromSource)
|
||||
&& await isFetchableNewsMorningImageUrl(fromSource, { fetchImpl, timeoutMs })
|
||||
) {
|
||||
return fromSource;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
async function worker() {
|
||||
while (cursor < unresolved.length) {
|
||||
const card = unresolved[cursor];
|
||||
while (cursor < cards.length) {
|
||||
const card = cards[cursor];
|
||||
cursor += 1;
|
||||
const image = await resolveNewsMorningSourceImage(card.url, { fetchImpl, timeoutMs });
|
||||
const image = await resolveCardImage(card);
|
||||
if (image) {
|
||||
imageByStart.set(card.start, image);
|
||||
resolvedCount += 1;
|
||||
@@ -280,46 +643,44 @@ export async function enrichNews002HtmlWithSourceImages(
|
||||
}
|
||||
}
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(Math.max(1, concurrency), unresolved.length || 1) }, () => worker()),
|
||||
Array.from({ length: Math.min(Math.max(1, concurrency), cards.length || 1) }, () => worker()),
|
||||
);
|
||||
|
||||
let output = source;
|
||||
for (const card of [...cards].sort((a, b) => b.start - a.start)) {
|
||||
const parts = splitCardRaw(card);
|
||||
if (!parts) continue;
|
||||
const existingImage = extractCardImage(card.raw);
|
||||
const image = existingImage || imageByStart.get(card.start) || '';
|
||||
const cleanedInner = ensureBodyWrapper(removeExistingMedia(parts.inner));
|
||||
const media = image
|
||||
? `<div class="media"><img src="${escapeHtmlAttribute(image)}" alt="${escapeHtmlAttribute(card.title)}" loading="lazy" referrerpolicy="no-referrer"></div>`
|
||||
: '<div class="media ph">📰</div>';
|
||||
const replacement = `${parts.open}${media}${cleanedInner}${parts.close}`;
|
||||
const image = imageByStart.get(card.start) || '';
|
||||
const replacement = renderCardMedia(card, image);
|
||||
output = output.slice(0, card.start) + replacement + output.slice(card.end);
|
||||
}
|
||||
|
||||
return {
|
||||
html: output,
|
||||
cardCount: cards.filter((card) => card.title).length,
|
||||
attemptedCount: unresolved.length,
|
||||
cardCount: cards.length,
|
||||
attemptedCount: cards.length,
|
||||
resolvedCount,
|
||||
rejectedCount,
|
||||
fallbackCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function auditNews002ImageCoverage(
|
||||
html,
|
||||
{ maxStoryCards = 28, requireTemplateStructure = false } = {},
|
||||
{
|
||||
maxStoryCards = 28,
|
||||
requireTemplateStructure = false,
|
||||
requireAllCoreSections = true,
|
||||
requireLeadCount = true,
|
||||
} = {},
|
||||
) {
|
||||
const source = String(html ?? '');
|
||||
const cards = extractNews002StoryCards(source).filter((card) => card.title);
|
||||
const missingImages = cards.filter((card) => !extractCardImage(card.raw));
|
||||
const missingImages = cards.filter((card) => !cardHasDisplayableImage(card.raw));
|
||||
const leads = cards.filter((card) => card.isLead);
|
||||
const missingLeadImages = leads.filter((card) => !extractCardImage(card.raw));
|
||||
const missingLeadImages = leads.filter((card) => !cardHasDisplayableImage(card.raw));
|
||||
const violations = [];
|
||||
if (!/class="[^"]*\bmasthead\b/i.test(source)) violations.push('missing-masthead');
|
||||
if (cards.length > maxStoryCards) violations.push('too-many-story-cards');
|
||||
if (cards.length > 0 && missingImages.length > 0) violations.push('story-image-missing');
|
||||
if (leads.length < 3 || leads.length > 4) violations.push('invalid-lead-count');
|
||||
if (missingLeadImages.length > 0) violations.push('lead-image-missing');
|
||||
if (requireLeadCount && (leads.length < 3 || leads.length > 4)) violations.push('invalid-lead-count');
|
||||
if (requireTemplateStructure) {
|
||||
if (/class="[^"]*\b(hero|quick-links|highlight-box)\b/i.test(source)) {
|
||||
violations.push('legacy-news001-dom');
|
||||
@@ -329,6 +690,11 @@ export function auditNews002ImageCoverage(
|
||||
if (!/#C8362F/i.test(source) || !/#FAF7F2/i.test(source) || !/#1B3A6B/i.test(source)) {
|
||||
violations.push('noncanonical-palette');
|
||||
}
|
||||
const sectionAliases = {
|
||||
brief: ['brief'],
|
||||
business: ['business', 'finance'],
|
||||
deepdive: ['deepdive', 'deep'],
|
||||
};
|
||||
const requiredSectionIds = [
|
||||
'brief',
|
||||
'headlines',
|
||||
@@ -341,11 +707,25 @@ export function auditNews002ImageCoverage(
|
||||
'knowledge',
|
||||
'history',
|
||||
];
|
||||
const missingSections = requiredSectionIds.filter((id) => (
|
||||
!new RegExp(`<div\\b[^>]*class=["'][^"']*\\bsection\\b[^"']*["'][^>]*id=["']${id}["']`, 'i')
|
||||
.test(source)
|
||||
));
|
||||
if (missingSections.length > 0) violations.push(`missing-sections:${missingSections.join('|')}`);
|
||||
const hasNews002Section = (id) => {
|
||||
const aliases = sectionAliases[id] ?? [id];
|
||||
for (const alias of aliases) {
|
||||
if (alias === 'brief') {
|
||||
if (/<ol\b[^>]*\bbrief\b[^>]*\bid=["']brief["']/i.test(source)) return true;
|
||||
if (/<div\b[^>]*\bsection\b[^>]*\bid=["']brief["']/i.test(source)) return true;
|
||||
continue;
|
||||
}
|
||||
if (new RegExp(`<div\\b[^>]*class=["'][^"']*\\bsection\\b[^"']*["'][^>]*id=["']${alias}["']`, 'i')
|
||||
.test(source)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
if (requireAllCoreSections) {
|
||||
const missingSections = requiredSectionIds.filter((id) => !hasNews002Section(id));
|
||||
if (missingSections.length > 0) violations.push(`missing-sections:${missingSections.join('|')}`);
|
||||
}
|
||||
if (cards.some((card) => !card.eventKey)) violations.push('missing-event-key');
|
||||
if (cards.some((card) => !card.url)) violations.push('missing-source-url');
|
||||
if (cards.some((card) => !/class="[^"]*\bbody\b/i.test(card.raw))) {
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
auditNews002ImageCoverage,
|
||||
cardHasDisplayableImage,
|
||||
isWeakNewsMorningImageUrl,
|
||||
enrichNews002HtmlWithSourceImages,
|
||||
enrichNewsMorningSearchGroupsWithImages,
|
||||
extractNewsMorningSourceImage,
|
||||
localizeNews002CardImages,
|
||||
materializeNews002CardFallbackImage,
|
||||
NEWS002_CARD_FALLBACK_FILENAME,
|
||||
normalizeNewsMorningImageUrl,
|
||||
normalizeNewsMorningLocalImageRef,
|
||||
pruneNews002ImagelessStoryCards,
|
||||
} from './wechat-news-morning-images.mjs';
|
||||
|
||||
const TINY_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
);
|
||||
|
||||
function htmlResponse(html, url = 'https://news.example/story') {
|
||||
return {
|
||||
ok: true,
|
||||
@@ -79,7 +94,7 @@ test('enrichNews002HtmlWithSourceImages inserts media and body wrappers', async
|
||||
});
|
||||
});
|
||||
|
||||
test('auditNews002ImageCoverage blocks missing images and excess cards', () => {
|
||||
test('auditNews002ImageCoverage blocks excess cards but keeps imageless stories', () => {
|
||||
const cards = Array.from({ length: 29 }, (_, index) => (
|
||||
`<div class="card" data-event-key="k${index}"><h3>事件标题${index}</h3></div>`
|
||||
)).join('');
|
||||
@@ -88,7 +103,41 @@ test('auditNews002ImageCoverage blocks missing images and excess cards', () => {
|
||||
);
|
||||
assert.equal(audit.ok, false);
|
||||
assert.ok(audit.violations.includes('too-many-story-cards'));
|
||||
assert.ok(audit.violations.includes('story-image-missing'));
|
||||
assert.equal(audit.violations.includes('story-image-missing'), false);
|
||||
assert.equal(audit.imageCount, 0);
|
||||
});
|
||||
|
||||
test('isWeakNewsMorningImageUrl rejects site logos and tiny author avatars', () => {
|
||||
assert.equal(isWeakNewsMorningImageUrl('https://static.globalissues.org/globalissues.png'), true);
|
||||
assert.equal(isWeakNewsMorningImageUrl('https://static.globalissues.org/ips/2026/09/foo-100x100.jpg'), true);
|
||||
assert.equal(isWeakNewsMorningImageUrl('https://cdn.example.com/news/photo-1200.jpg'), false);
|
||||
});
|
||||
|
||||
test('pruneNews002ImagelessStoryCards removes ph placeholders and empty sections', () => {
|
||||
const html = `<!doctype html><html><body>
|
||||
<div class="masthead"><h1>每日新闻早报</h1></div>
|
||||
<div class="section" id="headlines">
|
||||
<a class="lead-card" data-event-key="k1" href="https://news.example/a">
|
||||
<div class="media"><img src="https://cdn.example/a.jpg" alt="有图"></div>
|
||||
<div class="body"><h3>有图头条</h3></div>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k2" href="https://news.example/b">
|
||||
<div class="media ph">📰</div>
|
||||
<div class="body"><h3>无图头条</h3></div>
|
||||
</a>
|
||||
</div>
|
||||
<div class="section" id="world">
|
||||
<div class="section-title"><h2>国际</h2></div>
|
||||
<div class="card" data-event-key="k3"><div class="media ph">🌍</div><div class="body"><h3>无图国际</h3></div></div>
|
||||
</div>
|
||||
</body></html>`;
|
||||
const result = pruneNews002ImagelessStoryCards(html);
|
||||
assert.equal(result.removedCards, 2);
|
||||
assert.ok(result.removedSections >= 1);
|
||||
assert.match(result.html, /有图头条/u);
|
||||
assert.doesNotMatch(result.html, /无图头条/u);
|
||||
assert.doesNotMatch(result.html, /id="world"/u);
|
||||
assert.equal(cardHasDisplayableImage('<div class="media ph">📰</div>'), false);
|
||||
});
|
||||
|
||||
test('strict news002 audit rejects legacy or incomplete template structure', () => {
|
||||
@@ -102,3 +151,143 @@ test('strict news002 audit rejects legacy or incomplete template structure', ()
|
||||
assert.ok(audit.violations.some((item) => item.startsWith('missing-sections:')));
|
||||
assert.ok(audit.violations.includes('noncanonical-palette'));
|
||||
});
|
||||
|
||||
test('normalizeNewsMorningLocalImageRef accepts public card assets', () => {
|
||||
assert.equal(normalizeNewsMorningLocalImageRef('./daily-news-0922-card.webp'), 'daily-news-0922-card.webp');
|
||||
assert.equal(normalizeNewsMorningLocalImageRef('news002-card-fallback.svg'), 'news002-card-fallback.svg');
|
||||
assert.equal(normalizeNewsMorningLocalImageRef('../secret.png'), '');
|
||||
assert.equal(normalizeNewsMorningLocalImageRef('https://cdn.example/a.jpg'), '');
|
||||
});
|
||||
|
||||
test('auditNews002ImageCoverage ignores default thumbnails and does not require images', () => {
|
||||
const html = `<div class="masthead"></div>
|
||||
<a class="lead-card" data-event-key="k1" href="https://news.example/a">
|
||||
<div class="media"><img src="news002-card-fallback.svg" alt="头条一"></div>
|
||||
<div class="body"><h3>头条一真实新闻</h3></div>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k2" href="https://news.example/b">
|
||||
<div class="body"><h3>头条二真实新闻</h3></div>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k3" href="https://news.example/c">
|
||||
<div class="body"><h3>头条三真实新闻</h3></div>
|
||||
</a>
|
||||
<div class="card" data-event-key="k4">
|
||||
<div class="body"><h3>普通真实新闻标题</h3></div>
|
||||
</div>`;
|
||||
assert.deepEqual(auditNews002ImageCoverage(html), {
|
||||
ok: true,
|
||||
violations: [],
|
||||
cardCount: 4,
|
||||
imageCount: 0,
|
||||
leadCount: 3,
|
||||
leadImageCount: 0,
|
||||
missingTitles: ['头条一真实新闻', '头条二真实新闻', '头条三真实新闻', '普通真实新闻标题'],
|
||||
});
|
||||
});
|
||||
|
||||
test('enrichNews002HtmlWithSourceImages keeps imageless cards without a placeholder image', async () => {
|
||||
const source = `<!doctype html><html><body>
|
||||
<div class="masthead"><h1>每日新闻早报</h1></div>
|
||||
<div class="section" id="headlines">
|
||||
<a class="lead-card" data-event-key="k1" href="https://news.example/a">
|
||||
<h3>真实头条新闻标题</h3><p>摘要</p>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k2" href="https://news.example/b">
|
||||
<h3>第二条真实头条新闻</h3><p>摘要</p>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k3" href="https://news.example/c">
|
||||
<h3>第三条真实头条新闻</h3><p>摘要</p>
|
||||
</a>
|
||||
</div>
|
||||
<div class="card" data-event-key="k4"><h3>普通真实新闻标题</h3><p>摘要</p>
|
||||
<div class="source"><a href="https://news.example/d">来源</a></div>
|
||||
</div>
|
||||
</body></html>`;
|
||||
const result = await enrichNews002HtmlWithSourceImages(source, {
|
||||
fallbackImage: NEWS002_CARD_FALLBACK_FILENAME,
|
||||
fetchImpl: async () => htmlResponse('<html><body>no image</body></html>'),
|
||||
});
|
||||
assert.equal(result.resolvedCount, 0);
|
||||
assert.equal(result.fallbackCount, 0);
|
||||
assert.equal(result.cardCount, 4);
|
||||
assert.match(result.html, /data-event-key="k1"/);
|
||||
assert.match(result.html, /data-event-key="k2"/);
|
||||
assert.match(result.html, /data-event-key="k3"/);
|
||||
assert.match(result.html, /data-event-key="k4"/);
|
||||
assert.doesNotMatch(result.html, /news002-card-fallback/);
|
||||
assert.doesNotMatch(result.html, /class="media"/);
|
||||
assert.equal(auditNews002ImageCoverage(result.html).imageCount, 0);
|
||||
});
|
||||
|
||||
test('enrichNews002HtmlWithSourceImages never drops imageless story cards', async () => {
|
||||
const source = `<div class="masthead"></div>
|
||||
<a class="lead-card" data-event-key="keep-1" href="https://news.example/a"><h3>保留头条一新闻标题</h3></a>
|
||||
<a class="lead-card" data-event-key="keep-2" href="https://news.example/b"><h3>保留头条二新闻标题</h3></a>
|
||||
<a class="lead-card" data-event-key="keep-3" href="https://news.example/c"><h3>保留头条三新闻标题</h3></a>
|
||||
<div class="card" data-event-key="keep-4"><h3>保留普通新闻标题七字</h3>
|
||||
<div class="source"><a href="https://news.example/d">来源</a></div>
|
||||
</div>`;
|
||||
const result = await enrichNews002HtmlWithSourceImages(source, {
|
||||
fallbackImage: NEWS002_CARD_FALLBACK_FILENAME,
|
||||
fetchImpl: async () => htmlResponse('<html></html>'),
|
||||
});
|
||||
assert.equal(result.cardCount, 4);
|
||||
assert.equal(result.resolvedCount, 0);
|
||||
assert.equal(result.fallbackCount, 0);
|
||||
assert.doesNotMatch(result.html, /class="media"/);
|
||||
assert.equal((result.html.match(/data-event-key="keep-\d"/g) || []).length, 4);
|
||||
});
|
||||
|
||||
test('localizeNews002CardImages downloads remote images onto the publish host', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'news002-localize-'));
|
||||
const source = `<div class="masthead"></div>
|
||||
<a class="lead-card" data-event-key="k1" href="https://news.example/a">
|
||||
<div class="media"><img src="https://cdn.example/story.jpg" alt="头条一"></div>
|
||||
<div class="body"><h3>头条一真实新闻</h3></div>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k2" href="https://news.example/b">
|
||||
<div class="media"><img src="https://blocked.example/need-proxy.jpg" alt="头条二"></div>
|
||||
<div class="body"><h3>头条二真实新闻</h3></div>
|
||||
</a>
|
||||
<a class="lead-card" data-event-key="k3" href="https://news.example/c">
|
||||
<div class="body"><h3>头条三真实新闻</h3></div>
|
||||
</a>`;
|
||||
try {
|
||||
const result = await localizeNews002CardImages(source, {
|
||||
publishDir: tmp,
|
||||
slug: 'daily-news-0922',
|
||||
fetchImpl: async (url) => {
|
||||
if (String(url).includes('blocked.example')) {
|
||||
return { ok: false, status: 401, arrayBuffer: async () => new ArrayBuffer(0) };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
arrayBuffer: async () => TINY_PNG,
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal(result.localizedCount, 1);
|
||||
assert.equal(result.failedCount, 1);
|
||||
assert.match(result.html, /daily-news-0922-img-[a-f0-9]{12}\.jpg/);
|
||||
assert.doesNotMatch(result.html, /cdn\.example\/story\.jpg/);
|
||||
assert.doesNotMatch(result.html, /blocked\.example/);
|
||||
assert.match(result.html, /data-event-key="k2"/);
|
||||
const files = fs.readdirSync(tmp).filter((name) => name.endsWith('.jpg'));
|
||||
assert.equal(files.length, 1);
|
||||
assert.ok(fs.statSync(path.join(tmp, files[0])).size > 32);
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('materializeNews002CardFallbackImage copies the shared default thumbnail once', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'news002-fallback-'));
|
||||
try {
|
||||
const filename = materializeNews002CardFallbackImage(tmp);
|
||||
assert.equal(filename, NEWS002_CARD_FALLBACK_FILENAME);
|
||||
assert.equal(fs.existsSync(path.join(tmp, filename)), true);
|
||||
assert.match(fs.readFileSync(path.join(tmp, filename), 'utf8'), /svg/i);
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -25,6 +25,36 @@ export function shouldPrefetchNewsMorningSearxng(env = process.env) {
|
||||
return envFlag(env.MEMIND_NEWS_MORNING_SEARXNG_PREFETCH, true);
|
||||
}
|
||||
|
||||
export function shouldUseNewsMorningNewsCategory(env = process.env) {
|
||||
return envFlag(env.MEMIND_NEWS_MORNING_SEARXNG_NEWS_CATEGORY, false);
|
||||
}
|
||||
|
||||
export function resolveNewsMorningSearxngEngines(env = process.env) {
|
||||
return String(env.MEMIND_NEWS_MORNING_SEARXNG_ENGINES ?? 'yandex,bing,360search').trim();
|
||||
}
|
||||
|
||||
export function resolveNewsMorningSearxngConcurrency(env = process.env) {
|
||||
const raw = Number(env.MEMIND_NEWS_MORNING_SEARXNG_CONCURRENCY ?? 3);
|
||||
if (!Number.isFinite(raw) || raw < 1) return 3;
|
||||
return Math.min(8, Math.floor(raw));
|
||||
}
|
||||
|
||||
async function mapWithConcurrency(items, concurrency, mapper) {
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
const results = new Array(list.length);
|
||||
let next = 0;
|
||||
const workerCount = Math.max(1, Math.min(Number(concurrency) || 1, list.length || 1));
|
||||
async function worker() {
|
||||
while (next < list.length) {
|
||||
const index = next;
|
||||
next += 1;
|
||||
results[index] = await mapper(list[index], index);
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
||||
return results;
|
||||
}
|
||||
|
||||
export function buildNewsMorningSearchQueries(dateLabel) {
|
||||
const day = String(dateLabel?.iso ?? '').trim();
|
||||
const label = String(dateLabel?.label ?? day).trim() || day;
|
||||
@@ -206,24 +236,27 @@ async function searchNewsThenGeneral(query, {
|
||||
searchImpl,
|
||||
limit,
|
||||
timeoutMs,
|
||||
useNewsCategory = false,
|
||||
engines = '',
|
||||
}) {
|
||||
const newsHits = await searchImpl(query, {
|
||||
endpoint,
|
||||
limit,
|
||||
timeoutMs,
|
||||
categories: 'news',
|
||||
language: 'zh-CN',
|
||||
}).catch(() => []);
|
||||
if (Array.isArray(newsHits) && newsHits.length > 0) return newsHits;
|
||||
return searchImpl(query, {
|
||||
const common = {
|
||||
endpoint,
|
||||
limit,
|
||||
timeoutMs,
|
||||
language: 'zh-CN',
|
||||
}).catch(() => []);
|
||||
...(engines ? { engines } : {}),
|
||||
};
|
||||
if (useNewsCategory) {
|
||||
const newsHits = await searchImpl(query, {
|
||||
...common,
|
||||
categories: 'news',
|
||||
}).catch(() => []);
|
||||
if (Array.isArray(newsHits) && newsHits.length > 0) return newsHits;
|
||||
}
|
||||
return searchImpl(query, common).catch(() => []);
|
||||
}
|
||||
|
||||
export async function prefetchNewsMorningSearxngBrief({
|
||||
export async function prefetchNewsMorningSearxngBundle({
|
||||
now = Date.now(),
|
||||
timezone = 'Asia/Shanghai',
|
||||
env = process.env,
|
||||
@@ -233,31 +266,34 @@ export async function prefetchNewsMorningSearxngBrief({
|
||||
} = {}) {
|
||||
const dateLabel = formatLocalDateParts(now, timezone);
|
||||
const queries = buildNewsMorningSearchQueries(dateLabel);
|
||||
const emptyBrief = formatNewsMorningSearchBrief(
|
||||
queries.map((item) => ({ ...item, results: [] })),
|
||||
{ dateLabel },
|
||||
);
|
||||
const emptyGroups = queries.map((item) => ({ ...item, results: [] }));
|
||||
const emptyBrief = formatNewsMorningSearchBrief(emptyGroups, { dateLabel });
|
||||
if (!shouldPrefetchNewsMorningSearxng(env)) {
|
||||
return emptyBrief;
|
||||
return { brief: emptyBrief, groups: emptyGroups, dateLabel, dedupeRemovedCount: 0 };
|
||||
}
|
||||
const endpoint = resolvePortalSearxngEndpoint(env);
|
||||
if (!endpoint) {
|
||||
return emptyBrief;
|
||||
return { brief: emptyBrief, groups: emptyGroups, dateLabel, dedupeRemovedCount: 0 };
|
||||
}
|
||||
const timeoutMs = Number(env.TKMIND_SEARCH_TIMEOUT_MS ?? 8000) || 8000;
|
||||
const groups = await Promise.all(queries.map(async (item) => {
|
||||
const useNewsCategory = shouldUseNewsMorningNewsCategory(env);
|
||||
const engines = resolveNewsMorningSearxngEngines(env);
|
||||
const concurrency = resolveNewsMorningSearxngConcurrency(env);
|
||||
const groups = await mapWithConcurrency(queries, concurrency, async (item) => {
|
||||
const raw = await searchNewsThenGeneral(item.query, {
|
||||
endpoint,
|
||||
searchImpl,
|
||||
limit: limit + 3,
|
||||
timeoutMs,
|
||||
useNewsCategory,
|
||||
engines,
|
||||
});
|
||||
const results = filterFreshNewsMorningSearchResults(
|
||||
Array.isArray(raw) ? raw : [],
|
||||
{ year: dateLabel.year },
|
||||
).slice(0, limit);
|
||||
return { ...item, results };
|
||||
}));
|
||||
});
|
||||
const { groups: dedupedGroups, removedCount } = dedupeNewsMorningSearchGroups(groups);
|
||||
const imageEnrichment = await enrichNewsMorningSearchGroupsWithImages(dedupedGroups, {
|
||||
fetchImpl,
|
||||
@@ -265,8 +301,18 @@ export async function prefetchNewsMorningSearxngBrief({
|
||||
maxItems: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_MAX_ITEMS ?? 48) || 48,
|
||||
concurrency: Number(env.MEMIND_NEWS_MORNING_IMAGE_META_CONCURRENCY ?? 8) || 8,
|
||||
});
|
||||
return formatNewsMorningSearchBrief(imageEnrichment.groups, {
|
||||
return {
|
||||
brief: formatNewsMorningSearchBrief(imageEnrichment.groups, {
|
||||
dateLabel,
|
||||
dedupeRemovedCount: removedCount,
|
||||
}),
|
||||
groups: imageEnrichment.groups,
|
||||
dateLabel,
|
||||
dedupeRemovedCount: removedCount,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export async function prefetchNewsMorningSearxngBrief(options = {}) {
|
||||
const bundle = await prefetchNewsMorningSearxngBundle(options);
|
||||
return bundle.brief;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
formatNewsMorningSearchBrief,
|
||||
isDuplicateNewsMorningStory,
|
||||
prefetchNewsMorningSearxngBrief,
|
||||
prefetchNewsMorningSearxngBundle,
|
||||
resolveNewsMorningSearxngConcurrency,
|
||||
shouldUseNewsMorningNewsCategory,
|
||||
} from './wechat-news-morning-search.mjs';
|
||||
|
||||
test('buildNewsMorningSearchQueries covers core and extended channels', () => {
|
||||
@@ -75,15 +78,37 @@ test('formatNewsMorningSearchBrief requires dual search even when empty', () =>
|
||||
assert.match(text, /已剔除 2 条重复/);
|
||||
});
|
||||
|
||||
test('prefetch defaults skip the news category and cap concurrency', () => {
|
||||
assert.equal(shouldUseNewsMorningNewsCategory({}), false);
|
||||
assert.equal(resolveNewsMorningSearxngConcurrency({}), 3);
|
||||
assert.equal(resolveNewsMorningSearxngConcurrency({
|
||||
MEMIND_NEWS_MORNING_SEARXNG_CONCURRENCY: '2',
|
||||
}), 2);
|
||||
});
|
||||
|
||||
test('prefetchNewsMorningSearxngBrief queries news category then falls back', async () => {
|
||||
const calls = [];
|
||||
let seq = 0;
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
const brief = await prefetchNewsMorningSearxngBrief({
|
||||
now: Date.parse('2026-09-15T05:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
env: { TKMIND_SEARCH_SEARXNG_URL: 'http://127.0.0.1:20080/search' },
|
||||
env: {
|
||||
TKMIND_SEARCH_SEARXNG_URL: 'http://127.0.0.1:20080/search',
|
||||
MEMIND_NEWS_MORNING_SEARXNG_NEWS_CATEGORY: '1',
|
||||
MEMIND_NEWS_MORNING_SEARXNG_CONCURRENCY: '2',
|
||||
},
|
||||
searchImpl: async (query, options) => {
|
||||
calls.push({ query, categories: options.categories || '' });
|
||||
inFlight += 1;
|
||||
maxInFlight = Math.max(maxInFlight, inFlight);
|
||||
calls.push({
|
||||
query,
|
||||
categories: options.categories || '',
|
||||
engines: options.engines || '',
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
inFlight -= 1;
|
||||
const slug = `${++seq}-${options.categories || 'general'}`;
|
||||
if (options.categories === 'news' && /国内/.test(query)) {
|
||||
return [];
|
||||
@@ -102,6 +127,8 @@ test('prefetchNewsMorningSearxngBrief queries news category then falls back', as
|
||||
});
|
||||
assert.ok(calls.some((item) => item.categories === 'news'));
|
||||
assert.ok(calls.some((item) => item.categories === '' && /国内/.test(item.query)));
|
||||
assert.ok(calls.every((item) => item.engines === 'yandex,bing,360search'));
|
||||
assert.ok(maxInFlight <= 2);
|
||||
assert.match(brief, /## 国际[\s\S]*新闻源/);
|
||||
assert.match(brief, /## 国内[\s\S]*通用源/);
|
||||
assert.match(brief, /全页去重/);
|
||||
@@ -109,6 +136,46 @@ test('prefetchNewsMorningSearxngBrief queries news category then falls back', as
|
||||
assert.match(brief, /图:https:\/\/cdn\.example\/news\.jpg/u);
|
||||
});
|
||||
|
||||
test('prefetchNewsMorningSearxngBundle returns structured groups for fallback', async () => {
|
||||
const bundle = await prefetchNewsMorningSearxngBundle({
|
||||
now: Date.parse('2026-09-15T05:00:00+08:00'),
|
||||
env: { TKMIND_SEARCH_SEARXNG_URL: 'http://127.0.0.1:20080/search' },
|
||||
searchImpl: async () => ([
|
||||
{ title: '样例新闻', url: 'https://news.example/story', snippet: '摘要' },
|
||||
]),
|
||||
fetchImpl: async () => ({
|
||||
ok: true,
|
||||
headers: { get: () => 'text/html' },
|
||||
text: async () => '<meta property="og:image" content="https://cdn.example/story.jpg">',
|
||||
}),
|
||||
});
|
||||
assert.ok(Array.isArray(bundle.groups));
|
||||
assert.ok(bundle.groups.length > 10);
|
||||
assert.ok(bundle.groups.some((group) => group.results.length > 0));
|
||||
assert.match(bundle.brief, /专用联网搜索预取/);
|
||||
});
|
||||
|
||||
test('prefetchNewsMorningSearxngBrief skips news category by default', async () => {
|
||||
const calls = [];
|
||||
const brief = await prefetchNewsMorningSearxngBrief({
|
||||
now: Date.parse('2026-09-15T05:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
env: { TKMIND_SEARCH_SEARXNG_URL: 'http://127.0.0.1:20080/search' },
|
||||
searchImpl: async (query, options) => {
|
||||
calls.push({ query, categories: options.categories || '' });
|
||||
return [{ title: `通用 ${query}`, url: 'https://web.example/a', snippet: '摘要' }];
|
||||
},
|
||||
fetchImpl: async () => ({
|
||||
ok: true,
|
||||
headers: { get: () => 'text/html' },
|
||||
text: async () => '',
|
||||
}),
|
||||
});
|
||||
assert.equal(calls.some((item) => item.categories === 'news'), false);
|
||||
assert.ok(calls.length > 0);
|
||||
assert.match(brief, /专用联网搜索预取/);
|
||||
});
|
||||
|
||||
test('prefetchNewsMorningSearxngBrief skips live calls without endpoint', async () => {
|
||||
const brief = await prefetchNewsMorningSearxngBrief({
|
||||
now: Date.parse('2026-09-15T05:00:00+08:00'),
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
import { NEWS002_MAX_STORY_CARDS, NEWS002_SECTIONS } from './news-morning-templates.mjs';
|
||||
import {
|
||||
extractCardImage,
|
||||
extractNews002StoryCards,
|
||||
isWeakNewsMorningImageUrl,
|
||||
normalizeNewsMorningImageUrl,
|
||||
} from './wechat-news-morning-images.mjs';
|
||||
import {
|
||||
isDuplicateNewsMorningStory,
|
||||
normalizeNewsMorningTitle,
|
||||
normalizeNewsMorningUrl,
|
||||
} from './wechat-news-morning-search.mjs';
|
||||
|
||||
const SECTION_BY_ID = new Map(NEWS002_SECTIONS.map((item) => [item.id, item]));
|
||||
|
||||
/** SearXNG 预取分组 → news002 栏目 id(core 优先)。 */
|
||||
export const SEARXNG_GROUP_TO_NEWS002_SECTION = {
|
||||
lead: 'headlines',
|
||||
domestic: 'domestic',
|
||||
world: 'world',
|
||||
finance: 'business',
|
||||
tech: 'tech',
|
||||
sports: 'culture',
|
||||
science: 'science',
|
||||
culture: 'culture',
|
||||
local_life: 'living',
|
||||
policy: 'domestic',
|
||||
ai_chips: 'tech',
|
||||
global_markets: 'business',
|
||||
geopolitics: 'world',
|
||||
official_feeds: 'world',
|
||||
};
|
||||
|
||||
const SECTION_SEARCH_POOLS = {
|
||||
headlines: ['lead', 'domestic', 'world', 'finance', 'tech', 'official_feeds'],
|
||||
domestic: ['domestic', 'policy', 'local_life'],
|
||||
world: ['world', 'geopolitics', 'official_feeds', 'asia_pacific'],
|
||||
business: ['finance', 'global_markets', 'commodities'],
|
||||
tech: ['tech', 'ai_chips', 'science'],
|
||||
deepdive: ['lead', 'domestic', 'world', 'finance'],
|
||||
culture: ['culture', 'sports'],
|
||||
science: ['science', 'ai_chips'],
|
||||
living: ['local_life', 'domestic'],
|
||||
knowledge: ['science', 'culture'],
|
||||
};
|
||||
|
||||
const SECTION_ALIASES = {
|
||||
business: ['business', 'finance'],
|
||||
deepdive: ['deepdive', 'deep'],
|
||||
};
|
||||
|
||||
function envFlag(value, fallback = true) {
|
||||
const raw = String(value ?? '').trim().toLowerCase();
|
||||
if (!raw) return fallback;
|
||||
return ['1', 'true', 'yes', 'on'].includes(raw);
|
||||
}
|
||||
|
||||
export function shouldUseNewsMorningSearxngFallback(env = process.env) {
|
||||
return envFlag(env.MEMIND_NEWS_MORNING_SEARXNG_FALLBACK, true);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function escapeAttr(value) {
|
||||
return escapeHtml(value).replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function sliceBalancedBlock(html, tagName, openStart, openEnd) {
|
||||
const open = new RegExp(`<${tagName}\\b`, 'gi');
|
||||
const close = new RegExp(`</${tagName}\\s*>`, 'gi');
|
||||
let depth = 1;
|
||||
let cursor = openEnd;
|
||||
while (depth > 0 && cursor < html.length) {
|
||||
open.lastIndex = cursor;
|
||||
close.lastIndex = cursor;
|
||||
const nextOpen = open.exec(html);
|
||||
const nextClose = close.exec(html);
|
||||
if (!nextClose) return { start: openStart, end: html.length };
|
||||
if (nextOpen && nextOpen.index < nextClose.index) {
|
||||
depth += 1;
|
||||
cursor = nextOpen.index + nextOpen[0].length;
|
||||
} else {
|
||||
depth -= 1;
|
||||
cursor = nextClose.index + nextClose[0].length;
|
||||
}
|
||||
}
|
||||
return { start: openStart, end: cursor };
|
||||
}
|
||||
|
||||
function hasNews002Section(html, sectionId) {
|
||||
const source = String(html ?? '');
|
||||
const aliases = SECTION_ALIASES[sectionId] ?? [sectionId];
|
||||
for (const alias of aliases) {
|
||||
if (alias === 'brief') {
|
||||
if (/<ol\b[^>]*\bbrief\b[^>]*\bid=["']brief["']/i.test(source)) return true;
|
||||
if (/<div\b[^>]*\bsection\b[^>]*\bid=["']brief["']/i.test(source)) return true;
|
||||
continue;
|
||||
}
|
||||
if (new RegExp(`<div\\b[^>]*class=["'][^"']*\\bsection\\b[^"']*["'][^>]*id=["']${alias}["']`, 'i')
|
||||
.test(source)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractSectionBlock(html, sectionId) {
|
||||
const aliases = SECTION_ALIASES[sectionId] ?? [sectionId];
|
||||
for (const alias of aliases) {
|
||||
const re = new RegExp(
|
||||
`<div\\b[^>]*class=["'][^"']*\\bsection\\b[^"']*["'][^>]*id=["']${alias}["'][^>]*>`,
|
||||
'i',
|
||||
);
|
||||
const match = re.exec(String(html ?? ''));
|
||||
if (!match) continue;
|
||||
const start = match.index;
|
||||
const end = sliceBalancedBlock(html, 'div', start, start + match[0].length).end;
|
||||
return { id: alias, start, end, openEnd: start + match[0].length };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseMissingSectionIds(violations = []) {
|
||||
const ids = new Set();
|
||||
for (const violation of violations) {
|
||||
if (!String(violation).startsWith('missing-sections:')) continue;
|
||||
for (const id of String(violation).slice('missing-sections:'.length).split('|')) {
|
||||
if (id.trim()) ids.add(id.trim());
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function hostLabel(url) {
|
||||
try {
|
||||
return new URL(String(url)).hostname.replace(/^www\./i, '');
|
||||
} catch {
|
||||
return '来源';
|
||||
}
|
||||
}
|
||||
|
||||
export function buildNewsMorningEventKey(title, used = new Set()) {
|
||||
let base = String(title ?? '')
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 40) || 'story';
|
||||
let key = base;
|
||||
let index = 2;
|
||||
while (used.has(key)) {
|
||||
key = `${base}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
used.add(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
function truncateText(value, max) {
|
||||
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
|
||||
if (!text) return '';
|
||||
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
||||
}
|
||||
|
||||
function flattenSearchGroups(groups = []) {
|
||||
const map = new Map();
|
||||
for (const group of Array.isArray(groups) ? groups : []) {
|
||||
const id = String(group?.id ?? '').trim();
|
||||
if (!id) continue;
|
||||
map.set(id, {
|
||||
id,
|
||||
title: String(group?.title ?? id).trim(),
|
||||
results: Array.isArray(group?.results) ? group.results : [],
|
||||
});
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function collectExistingStoryKeys(html) {
|
||||
const cards = extractNews002StoryCards(html).filter((card) => card.title);
|
||||
return {
|
||||
cards,
|
||||
seenTitles: cards.map((card) => ({
|
||||
urlKey: normalizeNewsMorningUrl(card.url),
|
||||
title: normalizeNewsMorningTitle(card.title),
|
||||
})),
|
||||
usedEventKeys: new Set(cards.map((card) => card.eventKey).filter(Boolean)),
|
||||
};
|
||||
}
|
||||
|
||||
function pickSearchCandidates(groupMap, poolIds, seenTitles, { requireImage = true } = {}) {
|
||||
const picked = [];
|
||||
for (const groupId of poolIds) {
|
||||
const group = groupMap.get(groupId);
|
||||
if (!group) continue;
|
||||
for (const item of group.results) {
|
||||
const title = String(item?.title ?? '').trim();
|
||||
const url = String(item?.url ?? '').trim();
|
||||
if (!title || !url) continue;
|
||||
if (isDuplicateNewsMorningStory(seenTitles, { title, url })) continue;
|
||||
const image = normalizeNewsMorningImageUrl(item?.image || '');
|
||||
if (requireImage && (!image || isWeakNewsMorningImageUrl(image))) continue;
|
||||
picked.push({
|
||||
title,
|
||||
url,
|
||||
image,
|
||||
snippet: truncateText(item?.snippet, 160),
|
||||
tag: truncateText(group.title, 12),
|
||||
groupId,
|
||||
});
|
||||
seenTitles.push({
|
||||
urlKey: normalizeNewsMorningUrl(url),
|
||||
title: normalizeNewsMorningTitle(title),
|
||||
});
|
||||
}
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
/** 先取带图候选,不足时再放宽为无图(后续 enrichment 会从来源页补 og:image)。 */
|
||||
function pickSearchCandidatesWithFallback(groupMap, poolIds, seenTitles, needCount) {
|
||||
if (needCount <= 0) return [];
|
||||
const workingSeen = [...seenTitles];
|
||||
const withImage = pickSearchCandidates(groupMap, poolIds, workingSeen, { requireImage: true });
|
||||
let merged = withImage;
|
||||
if (merged.length < needCount) {
|
||||
const withoutImage = pickSearchCandidates(groupMap, poolIds, workingSeen, { requireImage: false });
|
||||
const usedUrls = new Set(merged.map((item) => item.url));
|
||||
for (const item of withoutImage) {
|
||||
if (merged.length >= needCount) break;
|
||||
if (usedUrls.has(item.url)) continue;
|
||||
merged.push(item);
|
||||
usedUrls.add(item.url);
|
||||
}
|
||||
}
|
||||
const picked = merged.slice(0, needCount);
|
||||
for (const item of picked) {
|
||||
seenTitles.push({
|
||||
urlKey: normalizeNewsMorningUrl(item.url),
|
||||
title: normalizeNewsMorningTitle(item.title),
|
||||
});
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
function buildLeadCardHtml(item, eventKey) {
|
||||
const title = escapeHtml(item.title);
|
||||
const snippet = escapeHtml(truncateText(item.snippet || item.title, 120));
|
||||
const tag = escapeHtml(item.tag || '要闻');
|
||||
const url = escapeAttr(item.url);
|
||||
const image = escapeAttr(item.image);
|
||||
return [
|
||||
`<a class="lead-card" href="${url}" target="_blank" rel="noopener" data-event-key="${escapeAttr(eventKey)}">`,
|
||||
`<div class="media"><img src="${image}" alt="${title}" loading="lazy" referrerpolicy="no-referrer"></div>`,
|
||||
`<div class="body"><span class="tag">${tag}</span><h3>${title}</h3><p>${snippet}</p>`,
|
||||
`<div class="source"><a href="${url}" target="_blank" rel="noopener">${escapeHtml(hostLabel(item.url))}</a></div>`,
|
||||
'</div></a>',
|
||||
].join('');
|
||||
}
|
||||
|
||||
function buildStoryCardHtml(item, eventKey) {
|
||||
const title = escapeHtml(item.title);
|
||||
const snippet = escapeHtml(truncateText(item.snippet || item.title, 140));
|
||||
const tag = escapeHtml(item.tag || '要闻');
|
||||
const url = escapeAttr(item.url);
|
||||
const image = escapeAttr(item.image);
|
||||
const why = escapeHtml(truncateText(`来自 ${hostLabel(item.url)} 的当日报道,建议纳入速览。`, 38));
|
||||
return [
|
||||
`<div class="card" data-event-key="${escapeAttr(eventKey)}">`,
|
||||
`<div class="media"><img src="${image}" alt="${title}" loading="lazy" referrerpolicy="no-referrer"></div>`,
|
||||
`<div class="body"><span class="tag">${tag}</span><h3>${title}</h3><p>${snippet}</p>`,
|
||||
`<div class="why"><b>为什么重要</b>:${why}</div>`,
|
||||
`<div class="source"><a href="${url}" target="_blank" rel="noopener">${escapeHtml(hostLabel(item.url))}</a></div>`,
|
||||
'</div></div>',
|
||||
].join('');
|
||||
}
|
||||
|
||||
function buildSectionShell(sectionId) {
|
||||
const meta = SECTION_BY_ID.get(sectionId);
|
||||
if (!meta) return '';
|
||||
return [
|
||||
`<div class="section" id="${sectionId}">`,
|
||||
`<div class="section-title"><span class="icon">${meta.icon}</span><h2>${escapeHtml(meta.label)}</h2></div>`,
|
||||
].join('');
|
||||
}
|
||||
|
||||
function insertBeforeAnchor(html, anchorPattern, chunk) {
|
||||
const source = String(html ?? '');
|
||||
const match = anchorPattern.exec(source);
|
||||
if (!match) return `${source}\n${chunk}`;
|
||||
return `${source.slice(0, match.index)}${chunk}\n${source.slice(match.index)}`;
|
||||
}
|
||||
|
||||
function ensureBriefList(html, candidates, stats) {
|
||||
if (hasNews002Section(html, 'brief')) return html;
|
||||
const items = candidates.slice(0, 6).map((item, index) => (
|
||||
`<li><span class="n">${index + 1}</span><span>${escapeHtml(truncateText(item.title, 32))}</span></li>`
|
||||
)).join('');
|
||||
if (!items) return html;
|
||||
stats.addedBriefItems = items.split('<li>').length - 1;
|
||||
const block = `<ol class="brief" id="brief">${items}</ol>`;
|
||||
return insertBeforeAnchor(html, /<div class="section" id="headlines"/i, block);
|
||||
}
|
||||
|
||||
function appendIntoSection(html, sectionId, cardsHtml) {
|
||||
const block = extractSectionBlock(html, sectionId);
|
||||
if (!block) return html;
|
||||
return `${html.slice(0, block.end - 6)}${cardsHtml}${html.slice(block.end - 6)}`;
|
||||
}
|
||||
|
||||
function createAndInsertSection(html, sectionId, cardsHtml) {
|
||||
const shell = buildSectionShell(sectionId);
|
||||
if (!shell) return html;
|
||||
const chunk = `${shell}${cardsHtml}</div>`;
|
||||
const anchor = /<div class="section" id="history"/i.test(html)
|
||||
? /<div class="section" id="history"/i
|
||||
: /<div class="footer"/i;
|
||||
return insertBeforeAnchor(html, anchor, chunk);
|
||||
}
|
||||
|
||||
function countLeadCardsInHeadlines(html) {
|
||||
const block = extractSectionBlock(html, 'headlines');
|
||||
if (!block) return 0;
|
||||
const slice = html.slice(block.start, block.end);
|
||||
return (slice.match(/\blead-card\b/g) ?? []).length;
|
||||
}
|
||||
|
||||
function countStoryCardsInSection(html, sectionId) {
|
||||
const block = extractSectionBlock(html, sectionId);
|
||||
if (!block) return 0;
|
||||
const slice = html.slice(block.start, block.end);
|
||||
return (slice.match(/\bdata-event-key=/g) ?? []).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent 产出不足时,用 SearXNG 预取分组程序化补栏(仅补缺失 core 栏目 / 头条 / brief)。
|
||||
*/
|
||||
export function supplementNews002HtmlFromSearxngGroups(
|
||||
html,
|
||||
groups = [],
|
||||
audit = {},
|
||||
{ maxAdds = NEWS002_MAX_STORY_CARDS } = {},
|
||||
) {
|
||||
const source = String(html ?? '');
|
||||
const groupMap = flattenSearchGroups(groups);
|
||||
if (!groupMap.size) {
|
||||
return { html: source, changed: false, stats: { reason: 'empty-groups' } };
|
||||
}
|
||||
|
||||
const { seenTitles, usedEventKeys, cards: existingCards } = collectExistingStoryKeys(source);
|
||||
const stats = {
|
||||
addedLeadCards: 0,
|
||||
addedStoryCards: 0,
|
||||
addedSections: [],
|
||||
addedBriefItems: 0,
|
||||
};
|
||||
let output = source;
|
||||
const missingSections = parseMissingSectionIds(audit?.violations ?? []);
|
||||
const needLeads = (audit?.violations ?? []).includes('invalid-lead-count')
|
||||
|| countLeadCardsInHeadlines(output) < 3;
|
||||
let remainingBudget = Math.max(0, maxAdds - existingCards.length);
|
||||
|
||||
if (needLeads && remainingBudget > 0) {
|
||||
const currentLeads = countLeadCardsInHeadlines(output);
|
||||
const needCount = Math.max(0, 3 - currentLeads);
|
||||
const toAdd = pickSearchCandidatesWithFallback(
|
||||
groupMap,
|
||||
SECTION_SEARCH_POOLS.headlines,
|
||||
seenTitles,
|
||||
Math.min(needCount, remainingBudget),
|
||||
);
|
||||
if (toAdd.length) {
|
||||
const cardsHtml = toAdd.map((item) => (
|
||||
buildLeadCardHtml(item, buildNewsMorningEventKey(item.title, usedEventKeys))
|
||||
)).join('');
|
||||
if (hasNews002Section(output, 'headlines')) {
|
||||
output = appendIntoSection(output, 'headlines', cardsHtml);
|
||||
} else {
|
||||
output = createAndInsertSection(output, 'headlines', cardsHtml);
|
||||
stats.addedSections.push('headlines');
|
||||
}
|
||||
stats.addedLeadCards = toAdd.length;
|
||||
remainingBudget -= toAdd.length;
|
||||
}
|
||||
}
|
||||
|
||||
const sectionIds = new Set([
|
||||
...missingSections,
|
||||
...['domestic', 'world', 'business', 'tech', 'deepdive', 'knowledge'].filter((id) => {
|
||||
const meta = SECTION_BY_ID.get(id);
|
||||
if (!meta) return false;
|
||||
if (id === 'deepdive') return !hasNews002Section(output, id);
|
||||
return countStoryCardsInSection(output, id) < meta.min;
|
||||
}),
|
||||
]);
|
||||
|
||||
for (const sectionId of sectionIds) {
|
||||
if (remainingBudget <= 0) break;
|
||||
const meta = SECTION_BY_ID.get(sectionId);
|
||||
if (!meta || sectionId === 'headlines' || sectionId === 'brief' || sectionId === 'weather' || sectionId === 'history') {
|
||||
if (sectionId === 'deepdive' && !hasNews002Section(output, 'deepdive')) {
|
||||
output = createAndInsertSection(output, 'deepdive', '');
|
||||
stats.addedSections.push('deepdive');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const existingCount = sectionId === 'headlines'
|
||||
? countLeadCardsInHeadlines(output)
|
||||
: countStoryCardsInSection(output, sectionId);
|
||||
const needCount = Math.max(0, meta.min - existingCount);
|
||||
if (!needCount && hasNews002Section(output, sectionId)) continue;
|
||||
|
||||
const pool = SECTION_SEARCH_POOLS[sectionId] ?? [SEARXNG_GROUP_TO_NEWS002_SECTION[sectionId]].filter(Boolean);
|
||||
const targetCount = Math.min(needCount || meta.min, remainingBudget);
|
||||
const toAdd = pickSearchCandidatesWithFallback(groupMap, pool, seenTitles, targetCount);
|
||||
const sectionMissing = missingSections.includes(sectionId) || !hasNews002Section(output, sectionId);
|
||||
|
||||
if (!toAdd.length) {
|
||||
if (sectionMissing) {
|
||||
output = createAndInsertSection(output, sectionId, '');
|
||||
stats.addedSections.push(sectionId);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const cardsHtml = toAdd.map((item) => (
|
||||
buildStoryCardHtml(item, buildNewsMorningEventKey(item.title, usedEventKeys))
|
||||
)).join('');
|
||||
|
||||
if (hasNews002Section(output, sectionId)) {
|
||||
output = appendIntoSection(output, sectionId, cardsHtml);
|
||||
} else {
|
||||
output = createAndInsertSection(output, sectionId, cardsHtml);
|
||||
stats.addedSections.push(sectionId);
|
||||
}
|
||||
stats.addedStoryCards += toAdd.length;
|
||||
remainingBudget -= toAdd.length;
|
||||
}
|
||||
|
||||
if (!hasNews002Section(output, 'brief')) {
|
||||
const briefCandidates = pickSearchCandidates(
|
||||
groupMap,
|
||||
['lead', 'domestic', 'world', 'finance', 'tech'],
|
||||
[...seenTitles],
|
||||
{ requireImage: false },
|
||||
);
|
||||
output = ensureBriefList(output, briefCandidates, stats);
|
||||
}
|
||||
|
||||
for (const sectionId of ['weather', 'history']) {
|
||||
if (!hasNews002Section(output, sectionId)) {
|
||||
output = createAndInsertSection(output, sectionId, '');
|
||||
stats.addedSections.push(sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
const changed = output !== source;
|
||||
return { html: output, changed, stats };
|
||||
}
|
||||
|
||||
const IMAGE_REPAIR_POOL = [
|
||||
'lead',
|
||||
'domestic',
|
||||
'world',
|
||||
'finance',
|
||||
'tech',
|
||||
'science',
|
||||
'culture',
|
||||
'geopolitics',
|
||||
'official_feeds',
|
||||
'ai_chips',
|
||||
];
|
||||
|
||||
function findSectionIdForCard(html, cardStart) {
|
||||
const before = String(html ?? '').slice(0, cardStart);
|
||||
const matches = [...before.matchAll(/<div\b[^>]*class=["'][^"']*\bsection\b[^"']*["'][^>]*id=["']([^"']+)["']/gi)];
|
||||
return matches.length ? matches[matches.length - 1][1] : 'domestic';
|
||||
}
|
||||
|
||||
/**
|
||||
* enrichment 仍缺图时:移除无图卡并用 SearXNG 候选替换(优先带图)。
|
||||
*/
|
||||
export function repairNews002ImagelessCardsFromSearxng(html, groups = []) {
|
||||
const source = String(html ?? '');
|
||||
const groupMap = flattenSearchGroups(groups);
|
||||
if (!groupMap.size) {
|
||||
return { html: source, changed: false, stats: { reason: 'empty-groups' } };
|
||||
}
|
||||
|
||||
const { seenTitles, usedEventKeys } = collectExistingStoryKeys(source);
|
||||
const imageless = extractNews002StoryCards(source)
|
||||
.filter((card) => card.title && !extractCardImage(card.raw));
|
||||
if (!imageless.length) {
|
||||
return { html: source, changed: false, stats: { removed: 0, replaced: 0 } };
|
||||
}
|
||||
|
||||
const stats = { removed: 0, replaced: 0, replacedLeads: 0 };
|
||||
let output = source;
|
||||
|
||||
for (const card of [...imageless].sort((a, b) => b.start - a.start)) {
|
||||
const sectionId = findSectionIdForCard(output, card.start);
|
||||
output = output.slice(0, card.start) + output.slice(card.end);
|
||||
stats.removed += 1;
|
||||
|
||||
const pool = card.isLead
|
||||
? SECTION_SEARCH_POOLS.headlines
|
||||
: (SECTION_SEARCH_POOLS[sectionId] ?? IMAGE_REPAIR_POOL);
|
||||
const [replacement] = pickSearchCandidatesWithFallback(groupMap, pool, seenTitles, 1);
|
||||
if (!replacement) continue;
|
||||
|
||||
const eventKey = buildNewsMorningEventKey(replacement.title, usedEventKeys);
|
||||
const cardHtml = card.isLead
|
||||
? buildLeadCardHtml(replacement, eventKey)
|
||||
: buildStoryCardHtml(replacement, eventKey);
|
||||
|
||||
if (card.isLead && hasNews002Section(output, 'headlines')) {
|
||||
output = appendIntoSection(output, 'headlines', cardHtml);
|
||||
stats.replacedLeads += 1;
|
||||
} else if (hasNews002Section(output, sectionId)) {
|
||||
output = appendIntoSection(output, sectionId, cardHtml);
|
||||
} else {
|
||||
output = createAndInsertSection(output, sectionId, cardHtml);
|
||||
}
|
||||
stats.replaced += 1;
|
||||
}
|
||||
|
||||
return { html: output, changed: output !== source, stats };
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildNewsMorningEventKey,
|
||||
repairNews002ImagelessCardsFromSearxng,
|
||||
supplementNews002HtmlFromSearxngGroups,
|
||||
} from './wechat-news-morning-searxng-fallback.mjs';
|
||||
import { auditNews002ImageCoverage } from './wechat-news-morning-images.mjs';
|
||||
|
||||
const THIN_AGENT_HTML = `<!doctype html><html><head>${[
|
||||
'<style>:root{--brand:#C8362F;--paper:#FAF7F2;--accent:#1B3A6B;}</style>',
|
||||
].join('')}</head><body>
|
||||
<div class="masthead"><h1>每日新闻早报</h1></div>
|
||||
<div class="lede">今日导读</div>
|
||||
<div class="container">
|
||||
<div class="section" id="headlines">
|
||||
<div class="section-title"><span class="icon">📰</span><h2>今日头条</h2></div>
|
||||
<a class="lead-card" href="https://news.example/a" data-event-key="a">
|
||||
<div class="media"><img src="https://cdn.example/a.jpg" alt="已有头条"></div>
|
||||
<div class="body"><span class="tag">国内</span><h3>已有头条</h3><p>摘要</p><div class="source"><a href="https://news.example/a">example</a></div></div>
|
||||
</a>
|
||||
</div>
|
||||
<div class="section" id="business">
|
||||
<div class="section-title"><span class="icon">💰</span><h2>财经</h2></div>
|
||||
<div class="card" data-event-key="biz-1">
|
||||
<div class="media"><img src="https://cdn.example/biz.jpg" alt="财经一"></div>
|
||||
<div class="body"><span class="tag">财经</span><h3>财经一</h3><p>摘要</p><div class="why"><b>为什么重要</b>:测试</div><div class="source"><a href="https://news.example/biz">example</a></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div></body></html>`;
|
||||
|
||||
const SEARCH_GROUPS = [
|
||||
{
|
||||
id: 'lead',
|
||||
title: '头条必读',
|
||||
results: [
|
||||
{ title: '补栏头条二', url: 'https://news.example/lead2', image: 'https://cdn.example/lead2.jpg', snippet: '第二条' },
|
||||
{ title: '补栏头条三', url: 'https://news.example/lead3', image: 'https://cdn.example/lead3.jpg', snippet: '第三条' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'domestic',
|
||||
title: '国内',
|
||||
results: [
|
||||
{ title: '国内补栏一', url: 'https://news.example/dom1', image: 'https://cdn.example/dom1.jpg', snippet: '国内一' },
|
||||
{ title: '国内补栏二', url: 'https://news.example/dom2', image: 'https://cdn.example/dom2.jpg', snippet: '国内二' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'world',
|
||||
title: '国际',
|
||||
results: [
|
||||
{ title: '国际补栏一', url: 'https://news.example/w1', image: 'https://cdn.example/w1.jpg', snippet: '国际一' },
|
||||
{ title: '国际补栏二', url: 'https://news.example/w2', image: 'https://cdn.example/w2.jpg', snippet: '国际二' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'tech',
|
||||
title: '科技',
|
||||
results: [
|
||||
{ title: '科技补栏一', url: 'https://news.example/t1', image: 'https://cdn.example/t1.jpg', snippet: '科技一' },
|
||||
{ title: '科技补栏二', url: 'https://news.example/t2', image: 'https://cdn.example/t2.jpg', snippet: '科技二' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'finance',
|
||||
title: '财经',
|
||||
results: [
|
||||
{ title: '财经补栏二', url: 'https://news.example/f2', image: 'https://cdn.example/f2.jpg', snippet: '财经二' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
test('buildNewsMorningEventKey deduplicates keys', () => {
|
||||
const used = new Set(['same-title']);
|
||||
assert.equal(buildNewsMorningEventKey('Same Title', used), 'same-title-2');
|
||||
});
|
||||
|
||||
test('supplementNews002HtmlFromSearxngGroups fills sections without prefetch images', () => {
|
||||
const groupsNoImage = [
|
||||
{
|
||||
id: 'world',
|
||||
title: '国际',
|
||||
results: [
|
||||
{ title: '国际无图一', url: 'https://news.example/w-no1', snippet: '国际一' },
|
||||
{ title: '国际无图二', url: 'https://news.example/w-no2', snippet: '国际二' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'tech',
|
||||
title: '科技',
|
||||
results: [
|
||||
{ title: '科技无图一', url: 'https://news.example/t-no1', snippet: '科技一' },
|
||||
{ title: '科技无图二', url: 'https://news.example/t-no2', snippet: '科技二' },
|
||||
],
|
||||
},
|
||||
];
|
||||
const result = supplementNews002HtmlFromSearxngGroups(
|
||||
THIN_AGENT_HTML,
|
||||
groupsNoImage,
|
||||
{ violations: ['missing-sections:world|tech'] },
|
||||
);
|
||||
assert.equal(result.changed, true);
|
||||
assert.match(result.html, /id="world"/u);
|
||||
assert.match(result.html, /id="tech"/u);
|
||||
assert.match(result.html, /国际无图一/u);
|
||||
assert.match(result.html, /科技无图一/u);
|
||||
});
|
||||
|
||||
test('repairNews002ImagelessCardsFromSearxng swaps imageless cards for searxng candidates', () => {
|
||||
const html = `${THIN_AGENT_HTML.replace('</div></body>', '')}
|
||||
<div class="section" id="domestic">
|
||||
<div class="section-title"><span class="icon">🇨🇳</span><h2>国内</h2></div>
|
||||
<div class="card" data-event-key="no-img">
|
||||
<div class="media ph">📰</div>
|
||||
<div class="body"><span class="tag">国内</span><h3>无图稿件</h3><p>摘要</p>
|
||||
<div class="why"><b>为什么重要</b>:测试</div>
|
||||
<div class="source"><a href="https://news.example/none">example</a></div></div>
|
||||
</div>
|
||||
</div></div></body></html>`;
|
||||
const result = repairNews002ImagelessCardsFromSearxng(html, SEARCH_GROUPS);
|
||||
assert.equal(result.changed, true);
|
||||
assert.ok(result.stats.replaced >= 1);
|
||||
assert.doesNotMatch(result.html, /无图稿件/u);
|
||||
assert.match(result.html, /国内补栏一/u);
|
||||
});
|
||||
|
||||
test('supplementNews002HtmlFromSearxngGroups fills missing core sections and leads', () => {
|
||||
const beforeAudit = auditNews002ImageCoverage(THIN_AGENT_HTML, { requireTemplateStructure: true });
|
||||
assert.equal(beforeAudit.ok, false);
|
||||
|
||||
const result = supplementNews002HtmlFromSearxngGroups(
|
||||
THIN_AGENT_HTML,
|
||||
SEARCH_GROUPS,
|
||||
beforeAudit,
|
||||
);
|
||||
assert.equal(result.changed, true);
|
||||
assert.ok(result.stats.addedLeadCards >= 2);
|
||||
assert.ok(result.stats.addedStoryCards >= 4);
|
||||
assert.match(result.html, /id="domestic"/u);
|
||||
assert.match(result.html, /id="world"/u);
|
||||
assert.match(result.html, /id="tech"/u);
|
||||
assert.match(result.html, /补栏头条二/u);
|
||||
assert.match(result.html, /国内补栏一/u);
|
||||
});
|
||||
Reference in New Issue
Block a user