From 96eb07db65425d488919c49dbce3425e261e0d8b Mon Sep 17 00:00:00 2001 From: Austin Lee Date: Sat, 21 Nov 2026 09:48:40 +0800 Subject: [PATCH] feat(say): support active-theme page templates --- packages/say/README.md | 99 ++++++++++++ packages/say/lib/comment-render.js | 3 +- packages/say/lib/comments.js | 3 +- packages/say/lib/frontend-publish.js | 5 +- packages/say/lib/render.js | 79 ++++++++-- packages/say/lib/urls.js | 11 ++ packages/say/plugin.js | 22 ++- packages/say/test/theme-templates.test.js | 174 ++++++++++++++++++++++ 8 files changed, 369 insertions(+), 27 deletions(-) create mode 100644 packages/say/lib/urls.js create mode 100644 packages/say/test/theme-templates.test.js diff --git a/packages/say/README.md b/packages/say/README.md index 5a99fb5..6c0fb70 100644 --- a/packages/say/README.md +++ b/packages/say/README.md @@ -552,3 +552,102 @@ QQ 附件下载失败时,参考编号对应日志中的 `download` 会记录 单条碎语详情底部、评论区域上方显示「上一条 / 下一条」。上一条指向更早发布的公开碎语,下一条指向更晚发布的公开碎语;同一发布时间按 ID 排序。私密、隐藏以及其他内容类型不参与导航,无相邻条目时不显示对应链接。 飞书、QQ 的 OpenID 白名单配置与过滤已移除(不是改为可选),历史 `feishuAllowedOpenIds` / `qqAllowedOpenIds` 值不再生效。任何能向该机器人发送合规消息的人,都可触发以配置作者发布;平台签名、Token、AppID 校验、机器人接收范围、去重及 `/whoami` 保留。微信公众号的 OpenID 白名单不受此调整影响。 + +## 用主题模板接管公开页面 + +在支持站点路由 `renderTheme` 的 Firekylin 核心上,当前启用主题可以覆盖 Say 的三种页面: + +| 请求 | 主题内的文件 | +| --- | --- | +| `/says` | `plugins/say/list.eta` | +| `/says/tag/:tag`,或兼容入口 `/says?tag=标签` | `plugins/say/tag.eta` | +| `/says/:id` | `plugins/say/detail.eta` | + +例如,独立项目的文件可放在 `themes/你的主题/plugins/say/list.eta`;旧目录部署放在 `www/theme/你的主题/plugins/say/list.eta`。只读取**当前启用主题**中的文件。 + +可以只覆盖其中一个页面。对应文件不存在时,Say 继续输出原来的内置页面;旧核心没有 `renderTheme` 时也保持原样。已有模板的语法错误、include/布局错误会正常报错,不会悄悄回退。空文件输出空页面。模板输出完整 HTML,可按当前主题的结构使用 Eta 布局、include、Widget 和公共主题上下文。此能力不改变 JSON API、发布接口、后台页面或已有 `say.list` / `Widget_Plugin_Say`。 + +### 页面数据:`firekylin.say` + +三种模板读取同一结构,数据和链接由 Say 准备,不需要主题重新访问数据库或拼接路由: + +- `view`:`list`、`tag` 或 `detail`。 +- `title`、`heading`、`tag`:文档标题、页面标题、当前标签;无标签时 `tag` 为空字符串。 +- `items`:当前页的公开碎语。保留内容字段:`id`、`pathname`、`kind`、`status`、`text`、`tags`、`images`、`mediaUrl`、`latitude`、`longitude`、`label`、`url`、`title`、`description`、`artist`、`cover`、`source`、`createdAt`、`updatedAt`、`allowComments`、`commentCount`。另提供 `detailUrl` 和 `tagLinks`(`{name, url}` 数组)。某种内容没有的字段可能为空或不存在。 +- `item`:详情页的当前碎语,列表和标签页为 `null`。 +- `pagination`:`page`、`pageSize`、`total`、`totalPages`、`previousUrl`、`nextUrl`。没有对应页时链接为 `null`。 +- `navigation`:详情的 `previous` / `next`,值为 `{id, url}` 或 `null`。上一条为更早、下一条为更新的公开碎语,同一发布时间按 ID 排序;列表页两项均为 `null`。 +- `urls`:`list` 是 `/says`,`tag` 是当前标签路径或 `null`,`current` 是当前内容/列表页生成的 URL。 +- `html.items`:已转义的内置碎语组件,含媒体、标签及详情链接。样式由主题提供。 +- `html.composer`:原有登录/管理员发布组件;详情页为空。包含当前请求所需的 CSRF 信息,不要跨请求缓存或重复插入。 +- `html.comments`:详情的原生评论组件,或“评论已关闭”提示;列表页为空。保留存储 pathname 和 `type=3` 的评论目标,不要把它改成单独的数字 ID。 + +`html.*` 是可以使用 `<%~ ... %>` 输出的现有组件。正文等普通字段必须使用 `<%= ... %>` 转义,不要当 HTML 原样输出。页面模型不包含平台配置、发布 API Key、JWT、SMTP 密码或原始登录身份。高德 Web 服务 Key 也不会传给主题,所以 `html.items` 对位置碎语只输出位置文本;主题可以用经纬度自行实现地图。缺少模板时,原内置页面仍保留原来的静态地图。 + +公开/隐藏规则仍在模板渲染前由插件执行:非公开或不存在的详情返回 404,关闭插件后不显示公开数据。模板只改变展示,不授予发布或评论权限。列表继续发送 `Cache-Control: private, no-store`,详情继续 `no-store`,不能把含发布框的页面放入共享缓存。 + +### 最小完整模板 + +下面可直接作为 `plugins/say/list.eta`,也可复制成 `tag.eta` 和 `detail.eta` 后分别调整布局。保留 `html.composer` / `html.comments` 可保留原发布和评论交互;不插入某组件就不会显示它。 + +```eta +<% const say = firekylin.say; %> + + + + + + <%= say.title %> + + +
+ 全部碎语 +

<%= say.heading %>

+ <%~ say.html.composer %> + <% if (say.items.length) { %> + <%~ say.html.items %> + <% } else { %> +

暂无碎语

+ <% } %> + <% if (say.view === 'detail') { %> + + <% } else { %> + + <% } %> + <%~ say.html.comments %> +
+ + +``` + +要自行排版正文,可以将 `html.items` 替换成对 `say.items` 的循环,例如: + +```eta +<% for (const item of say.items) { %> +
+

<%= item.text %>

+ <% for (const tag of item.tagLinks) { %> + #<%= tag.name %> + <% } %> + 详情 / 评论 <%= item.commentCount %> +
+<% } %> +``` + +此示例只排版文字,图片/语音/链接等可按 `kind` 自行渲染,或继续使用完整的 `html.items`。 + +链接规则保持兼容:详情始终为 `/says/ID`,标签链接为 URL 编码后的 `/says/tag/标签`;分页保留当前列表路径,并保留既有 `page` 和 `tag` 查询参数。`/says?tag=标签` 的分页仍指向 `/says?page=N&tag=标签`,不会被改成标签路径。主题直接使用提供的 URL,无需自行编码标签或猜测相邻条目。 diff --git a/packages/say/lib/comment-render.js b/packages/say/lib/comment-render.js index e39d8ac..048bbe8 100644 --- a/packages/say/lib/comment-render.js +++ b/packages/say/lib/comment-render.js @@ -1,5 +1,6 @@ 'use strict'; const {escapeHtml: esc} = require('./render'); +const {detailUrl} = require('./urls'); function renderComments(id, result, config) { const captcha = config.captcha; @@ -63,7 +64,7 @@ function renderWalineComments(item, {options, public: publicConfig}) { } // Waline 3.16 decodes path once before sending it. Protect query-value escapes // so core receives the stored pathname, not an ID or a partially decoded value. - const path = `/says/${item.id}?pathname=${encodeURIComponent(item.pathname)}&type=3`; + const path = `${detailUrl(item.id)}?pathname=${encodeURIComponent(item.pathname)}&type=3`; const settings = options.comment || {}; const config = { path: encodeURI(path), diff --git a/packages/say/lib/comments.js b/packages/say/lib/comments.js index 6c6d70d..492ab55 100644 --- a/packages/say/lib/comments.js +++ b/packages/say/lib/comments.js @@ -1,6 +1,7 @@ 'use strict'; const {strings} = require('./say-service'); +const {detailUrl} = require('./urls'); function fail(status, message) { throw Object.assign(new Error(message), {status, publicCommentError: true}) } function idOf(value) { @@ -79,7 +80,7 @@ class SayComments { async create(id, body, request) { const item = await this.target(id, true); - const path = `/says/${item.id}`; + const path = detailUrl(item.id); const {options, captcha, captchaConfig} = await this.configuration(); const host = this.getService('comment'); if (!host?.create || !host?.context || !host?.validateCommentInput) fail(503, '当前核心缺少兼容的评论服务。'); diff --git a/packages/say/lib/frontend-publish.js b/packages/say/lib/frontend-publish.js index 8157696..ef3f38e 100644 --- a/packages/say/lib/frontend-publish.js +++ b/packages/say/lib/frontend-publish.js @@ -1,5 +1,6 @@ 'use strict'; const {escapeHtml: esc} = require('./render'); +const {listUrl} = require('./urls'); class FrontendPublish { constructor({say, getModel, getService}) { Object.assign(this, {say, getModel, getService}) } @@ -36,7 +37,7 @@ class FrontendPublish { function renderComposer(identity, enabled) { if (!enabled) return ''; - if (!identity.loggedIn) return '
登录
'; + if (!identity.loggedIn) return `
登录
`; if (!identity.canPublish) return ''; return `

发布微博

@@ -56,7 +57,7 @@ function renderComposer(identity, enabled) { const response = await fetch('/api/plugins/say/frontend-publish', {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': form.dataset.csrf}, body: JSON.stringify({text: form.elements.text.value})}); - if (response.ok && (await response.json()).success) { location.assign('/says'); return; } + if (response.ok && (await response.json()).success) { location.assign('${listUrl}'); return; } result.textContent = response.status === 403 ? '无法发布,请确认登录账号和发布权限,刷新页面后重试。' : response.status === 400 ? '请输入 1 至 20000 字的微博内容。' : '发布未确认,请先刷新列表核对,勿立即重发。'; } catch { result.textContent = '发布未确认,请先刷新列表核对,勿立即重发。'; } diff --git a/packages/say/lib/render.js b/packages/say/lib/render.js index 9c3be5c..741a4ae 100644 --- a/packages/say/lib/render.js +++ b/packages/say/lib/render.js @@ -1,5 +1,7 @@ 'use strict'; +const {listUrl, detailUrl, tagUrl, pageUrl} = require('./urls'); + function escapeHtml(value) { return String(value === null || typeof value === 'undefined' ? '' : value).replace(/[&<>'"]/g, character => ({ '&': '&', '<': '<', '>': '>', '\'': ''', '"': '"' @@ -33,29 +35,76 @@ function media(item, options = {}) { return ''; } -function renderSayPage(result, {title = '碎语', tag = '', amapKey = '', section = '', composer = '', navigation = null} = {}) { - const items = result.items.map(item => `
+// Keep the template contract explicit: never spread settings, identities or model rows. +function publicItem(item) { + const data = {}; + for (const key of ['id', 'pathname', 'allowComments', 'commentCount', 'kind', 'status', 'text', + 'source', 'mediaUrl', 'latitude', 'longitude', 'label', 'url', 'title', 'description', + 'artist', 'cover', 'createdAt', 'updatedAt']) { + if (item[key] !== undefined) data[key] = item[key]; + } + data.images = [...(item.images || [])]; + data.tags = [...(item.tags || [])]; + data.detailUrl = detailUrl(item.id); + data.tagLinks = data.tags.map(name => ({name, url: tagUrl(name)})); + return data; +} + +function renderItems(items, options = {}) { + return items.map(item => ``).join(''); - const previous = result.page > 1 ? `上一页` : ''; - const next = result.page * result.pageSize < result.total - ? `下一页` : ''; - const detailNavigation = navigation && (navigation.previous || navigation.next) - ? `` : ''; +} + +function createSayViewModel(result, {title = '碎语', tag = '', section = '', composer = '', + navigation = null, view = navigation ? 'detail' : tag ? 'tag' : 'list', listPath = listUrl} = {}) { + const items = result.items.map(publicItem); + const neighbor = id => id ? {id: Number(id), url: detailUrl(id)} : null; + return { + view, + title: tag ? `#${tag} - ${title}` : title, + heading: tag ? `#${tag}` : title, + tag, + items, + item: view === 'detail' ? items[0] || null : null, + pagination: { + page: result.page, pageSize: result.pageSize, total: result.total, + totalPages: Math.ceil(result.total / result.pageSize), + previousUrl: result.page > 1 ? pageUrl(result.page - 1, tag, listPath) : null, + nextUrl: result.page * result.pageSize < result.total ? pageUrl(result.page + 1, tag, listPath) : null + }, + navigation: {previous: neighbor(navigation?.previous), next: neighbor(navigation?.next)}, + urls: {list: listUrl, tag: tag ? tagUrl(tag) : null, + current: view === 'detail' ? items[0]?.detailUrl || null : pageUrl(result.page, tag, listPath)}, + // Reuse escaped components, never raw credentials. Custom themes receive location + // data/text, not the configured map service key embedded by the legacy page. + html: {items: renderItems(items), composer, comments: section} + }; +} + +function renderSayPage(result, {amapKey = '', viewModel, ...options} = {}) { + const page = viewModel || createSayViewModel(result, options); + const items = amapKey ? renderItems(page.items, {amapKey}) : page.html.items; + const {previousUrl, nextUrl} = page.pagination; + const previous = previousUrl ? `上一页` : ''; + const next = nextUrl ? `下一页` : ''; + const navigation = page.navigation; + const detailNavigation = navigation.previous || navigation.next + ? `` : ''; return ` - ${escapeHtml(tag ? `#${tag} - ${title}` : title)}
-

${escapeHtml(tag ? `#${tag}` : title)}

${composer}${items || '

暂无碎语

'}${navigation ? detailNavigation : ``} - ${section}
`; +

${escapeHtml(page.heading)}

${page.html.composer}${items || '

暂无碎语

'}${page.view === 'detail' ? detailNavigation : ``} + ${page.html.comments}`; } -module.exports = {escapeHtml, renderSayPage}; +module.exports = {escapeHtml, renderSayPage, createSayViewModel}; diff --git a/packages/say/lib/urls.js b/packages/say/lib/urls.js new file mode 100644 index 0000000..b8e91cd --- /dev/null +++ b/packages/say/lib/urls.js @@ -0,0 +1,11 @@ +'use strict'; + +const listUrl = '/says'; +const detailUrl = id => `${listUrl}/${Number(id)}`; +const tagUrl = tag => `${listUrl}/tag/${encodeURIComponent(tag)}`; +// Retain the existing tag query on both list and tag-path pagination. Do not +// carry arbitrary request queries (tokens, preview flags, etc.) into public links. +const pageUrl = (page, tag = '', pathname = listUrl) => + `${pathname}?page=${page}${tag ? `&tag=${encodeURIComponent(tag)}` : ''}`; + +module.exports = {listUrl, detailUrl, tagUrl, pageUrl}; diff --git a/packages/say/plugin.js b/packages/say/plugin.js index caa12d8..a195dd2 100644 --- a/packages/say/plugin.js +++ b/packages/say/plugin.js @@ -8,7 +8,8 @@ const feishuReply = require('./lib/feishu-reply'); const feedback = require('./lib/publish-feedback'); const {whoami} = require('./lib/commands'); const {createQqWebhook} = require('./lib/qq-webhook'); -const {renderSayPage} = require('./lib/render'); +const {renderSayPage, createSayViewModel} = require('./lib/render'); +const {listUrl, tagUrl} = require('./lib/urls'); const {renderWalineComments} = require('./lib/comment-render'); const {SayComments} = require('./lib/comments'); const {FrontendPublish, renderComposer} = require('./lib/frontend-publish'); @@ -413,27 +414,29 @@ module.exports = { handler: request => wechatCallback(request, mediaClient)}); ctx.routes.register({method: 'POST', path: '/feishu', csrf: false, handler: request => feishuCallback(request, mediaClient)}); - const renderPage = async(request, query, tag = '') => { + const renderPage = async(request, query, tag = '', renderTheme, listPath = listUrl) => { const settings = await service.settings(); const result = await service.list({...query, tag, publicOnly: true}); const options = await think.model('options').getOptions(); const identity = await publisher.identity(request); request.set('Cache-Control', 'private, no-store'); request.type = 'text/html; charset=utf-8'; - request.body = renderSayPage(result, {title: `${options.title || ''} · 碎语`, tag, amapKey: settings.amapKey, + const viewModel = createSayViewModel(result, {title: `${options.title || ''} · 碎语`, tag, listPath, composer: renderComposer(identity, settings.enabled)}); + const html = typeof renderTheme === 'function' ? await renderTheme(viewModel.view, {say: viewModel}) : undefined; + request.body = html === undefined ? renderSayPage(result, {viewModel, amapKey: settings.amapKey}) : html; }; ctx.routes.register({method: 'GET', path: '/says', scope: 'site', csrf: false, - handler: async({ctx: request, query}) => renderPage(request, query, String(query.tag || ''))}); + handler: async({ctx: request, query, renderTheme}) => renderPage(request, query, String(query.tag || ''), renderTheme)}); ctx.routes.register({method: 'GET', path: '/says/tag/:tag', scope: 'site', csrf: false, - handler: async({ctx: request, query, params}) => renderPage(request, query, params.tag)}); + handler: async({ctx: request, query, params, renderTheme}) => renderPage(request, query, params.tag, renderTheme, tagUrl(params.tag))}); ctx.routes.register({method: 'GET', path: '/comments/:id', csrf: false, handler: async({ctx: request, params, query}) => comments.handle(() => comments.list(params.id, query.page), request)}); ctx.routes.register({method: 'POST', path: '/comments/:id', csrf: false, handler: async({ctx: request, params, body}) => comments.handle(() => comments.submit(params.id, body, request), request)}); ctx.routes.register({method: 'GET', path: '/says/:id', scope: 'site', csrf: false, - handler: async({ctx: request, params, query}) => { + handler: async({ctx: request, params, renderTheme}) => { if (!/^[1-9]\d{0,14}$/.test(params.id)) return request.throw(404); const settings = await service.settings(); const item = await service.get(params.id); @@ -445,8 +448,11 @@ module.exports = { } request.type = 'text/html'; request.set('Cache-Control', 'no-store'); - request.body = renderSayPage({items: [item], page: 1, pageSize: 1, total: 1}, - {title: `碎语 #${item.id}`, amapKey: settings.amapKey, section, navigation: await service.publicNeighbors(item.id)}); + const result = {items: [item], page: 1, pageSize: 1, total: 1}; + const viewModel = createSayViewModel(result, {view: 'detail', title: `碎语 #${item.id}`, section, + navigation: await service.publicNeighbors(item.id)}); + const html = typeof renderTheme === 'function' ? await renderTheme('detail', {say: viewModel}) : undefined; + request.body = html === undefined ? renderSayPage(result, {viewModel, amapKey: settings.amapKey}) : html; }}); ctx.admin.registerPanel({id: 'say', title: '微博列表', icon: 'comment', order: 74}); diff --git a/packages/say/test/theme-templates.test.js b/packages/say/test/theme-templates.test.js new file mode 100644 index 0000000..e0d6e41 --- /dev/null +++ b/packages/say/test/theme-templates.test.js @@ -0,0 +1,174 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {SayService} = require('../lib/say-service'); +const {SayComments} = require('../lib/comments'); +const {FrontendPublish} = require('../lib/frontend-publish'); +const {createSayViewModel} = require('../lib/render'); +const {detailUrl, tagUrl, pageUrl} = require('../lib/urls'); + +function setup(t) { + const item = (id, status = 'public') => ({id, status, pathname: `stored-${id}`, + kind: 'text', text: `Say ${id}