Flarum Subscriptions 扩展版本演进全解读:从 CHANGELOG 到源码,读懂"关注讨论"功能的迭代脉络

原创2026-10-11 15:40:521,759 阅读
文章标签:后端前端

Flarum Subscriptions 扩展版本演进全解读:从 CHANGELOG 到源码,读懂"关注讨论"功能的迭代脉络

导读

本文以 Flarum 官方扩展 extensions/subscriptions/CHANGELOG.md 的版本记录为主线,逐版解读该扩展从 v0.1.0-beta.9 到 v1.2.0 的关键变更,并深入其 extend.php、后端监听器与通知任务、前端扩展代码 及 集成测试,还原每一项变更背后的实现动机与落地方案。读完你将掌握:订阅数据模型与 API 读写规则、"回复即通知"的队列化投递链路、is:following / is:ignoring gambit 的查询实现与性能优化、前端订阅菜单/徽章/侧边栏项的挂载方式,以及通知邮件从不可翻译到完全可翻译的演进过程。

扩展定位:让用户"关注"讨论并接收新帖通知

flarum/subscriptions 是 Flarum 生态中的官方扩展,其 composer.json 中的描述为 "Allow users to follow discussions and receive notifications for new posts"。它要求 flarum/core: ^2.0.0,在扩展管理后台归类于 feature 分类(对应 CHANGELOG v0.1.0-beta.16 中"Updated admin category from discussion to feature"的变更),并使用 fas fa-star 星形图标。

它向论坛提供三项核心能力:

  1. 订阅状态:用户可将任意讨论设为 follow(关注)或 ignore(忽略),分别对应"收到新帖通知"与"从讨论列表隐藏"两种行为;
  2. 通知链路:有人回复已关注讨论时,通过队列任务为"下一个待读帖"用户生成通知(站内提醒 + 邮件);
  3. 列表筛选:is:following / is:ignoring gambit 与"我的关注"(/following)专属页面,以及忽略帖的全局隐藏。

扩展的基础数据由迁移 2015_05_11_000000_add_subscription_to_users_discussions_table.php 定义:在 discussion_user 中间表上新增 subscription 列,类型为枚举,仅允许 follow、ignore 两个值且可空。订阅状态始终挂在"用户 × 讨论"这一对关系上,由 extend.php 通过 Extend\Model(UserState::class)->cast('subscription', 'string') 将其类型化为字符串。

v1.2.0:侧边栏订阅项优先级调整

v1.2.0 唯一的变更是 "Set priority on subscription sidebar item"(为订阅菜单设置优先级)。

在 addSubscriptionControls.js 中,订阅菜单通过 extend(DiscussionPage.prototype, 'sidebarItems', ...) 挂载到讨论页侧边栏,并以优先级 80 注册:

items.add('subscription', <SubscriptionMenu discussion={discussion} />, 80);

这一优先级的设定使订阅菜单在侧边栏中稳定出现在指定位置,避免与 tags、sticky 等其他扩展的侧边栏项互相抢占顺序,是扩展间 UI 集成时常见的"顺序契约"写法。

v1.1.0:CSS 变量化徽章与前端工程化

v1.1.0 包含两条变更:"Use css variables for badge"(徽章改用 CSS 变量)与 "Add Prettier config and Update dependencies"(引入 Prettier 配置并更新依赖)。

前者在 less/forum.less 中有完整实现。扩展首先声明跟随态徽章的基准配色变量:

@following-bg: #ffea7b;
@following-color: #de8e00;

:root {
  --following-bg: @following-bg;
  --following-color: @following-color;
  --ignoring-bg: #aaa;
}

随后通过主题数据属性 [data-theme^=light]、[data-theme=light-hc](高对比度)、[data-theme^=dark] 分别定义不同主题下的按钮配色,再将 CSS 变量应用到徽章组件:

.Badge--following {
  --badge-bg: var(--following-bg);
  --badge-color: var(--following-color);
}
.Badge--ignoring {
  --badge-bg: var(--ignoring-bg);
}

这种"设计令牌(design token)"式的写法让 Badge--following / Badge--ignoring 徽章能够随主题切换自动取色,也是后续暗色模式按钮颜色修复(v0.1.0-beta.14)的实现基础。前端工程化方面,扩展在 js/package.json 中引入 @flarum/prettier-config,并提供 format / format-check 脚本,将代码风格统一纳入 CI 检查。

v1.0.0:兼容 Flarum 1.0 与两处关键修复

v1.0.0 标志着扩展随 Flarum v1.0.0 正式发布。它同时包含两处修复:

  1. Tooltips generate a deprecation warning:Bootstrap tooltip 相关废弃警告。对应前端代码中,SubscriptionMenu.tsx 在保存订阅状态后手动调用 .tooltip('hide') 关闭提示,而在 v1.0.0 修复后,提示文本的生成与销毁逻辑得到收敛(tooltip 由 notifyEmail || notifyAlert 且订阅为 null 时展示)。

  2. Inconsistent data for subscribed provided by API:API 返回的订阅字段数据不一致。这一问题由 Api/UserResourceFields.php 解决。它作为 DiscussionResource 的附加字段提供者注册(见 extend.php):

Schema\Str::make('subscription')
    ->writable(fn (Discussion $discussion, Context $context) => $context->updating())
    ->nullable()
    ->get(fn (Discussion $discussion) => $discussion->state?->subscription)
    ->set(function (Discussion $discussion, ?string $subscription, Context $context) {
        $actor = $context->getActor();
        $state = $discussion->stateFor($actor);

        if (! in_array($subscription, ['follow', 'ignore'])) {
            $subscription = null;
        }

        $state->subscription = $subscription;
    }),

该 Schema 明确定义了 subscription 字段的完整读写契约:仅允许 follow / ignore / null 三态,读取时从当前用户的状态行取值,写入时落库到 discussion_user。这与 Listener/SaveSubscriptionToDatabase.php 中基于 Saving 事件的兜底写入逻辑一致(两者对非法值都回退为 null)。集成测试 SubscribeTest.php 通过 PATCH /api/discussions/{id} 携带 subscription 属性验证三种状态均可正确落库,并专门测试了"不带任何 attributes 的 PATCH(如仅移动讨论到其他标签)不会改动订阅状态"这一边界场景。

v0.1.0-beta.16:管理后台分类、语言包迁移与列表状态持久化

该版本包含两条变更与一条修复:

  • Updated admin category from discussion to feature:扩展在管理后台的归属分类从 discussion 调整为 feature,体现在 composer.json 的 extra.flarum-extension.category = "feature"。
  • Moved locale files from translation pack to extension:语言文件从外部翻译包迁入扩展自身,即当前 locale/en.yml。该文件按 forum / email / lib / ref 命名空间组织,涵盖徽章 tooltip、讨论控制按钮、订阅菜单、设置项、通知文本与邮件正文等全部文案,并由 extend.php 的 new Extend\Locales(__DIR__.'/locale') 注册。
  • User state for discussion list persists across different discussion pages:讨论列表中的订阅状态在不同讨论页面间保持持久。对应实现位于 addSubscriptionFilter.js:扩展通过 extend(GlobalSearchState.prototype, 'params', ...) 在进入 /following 路由时设置 params.onFollowing,并在 DiscussionListState.prototype.requestParams 中据此注入 params.filter.subscription = 'following',从而保证切页时筛选条件不丢失。

v0.1.0-beta.15:适配新管理后台与新一代 extenders

该版本更新了 composer.json 和管理后台 JavaScript,以适配 Flarum 新的管理后台区域,并全面改用最新的 extenders 体系。这在当前代码中表现为:extend.php 全程使用 Flarum\Extend 下的声明式扩展器(Extend\Frontend、Extend\Model、Extend\Notification、Extend\ApiResource、Extend\Event、Extend\SearchDriver、Extend\User、Extend\Locales、Extend\View),而前端 js/src/forum/extend.ts 也改为声明式 extenders,例如:

new Extend.Routes().add('following', '/following', IndexPage),
new Extend.Notification().add('newPost', NewPostNotification),
new Extend.Model(Discussion).attribute('subscription'),

管理后台侧 js/src/admin/index.ts 仅导出自身 extend 配置;由于扩展不需要管理后台界面,其 composer.json 中 flarum-cli.modules.admin 为 false。

v0.1.0-beta.14:跟随页元标题、Mithril 2、可翻译邮件与暗色模式配色

这是功能密度较高的一个版本,包含两条新增、两条变更与一条修复:

  1. Meta title now available for following page:/following 页面现在拥有独立的浏览器标题。实现于 addSubscriptionFilter.js:
extend(IndexPage.prototype, 'setTitle', function () {
  if (app.current.get('routeName') === 'following') {
    app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text'));
  }
});

对应语言键为 locale/en.yml 中的 forum.following.meta_title_text。

  1. Updated mithril to version 2:前端框架 Mithril 升级到 v2。当前 SubscriptionMenu.tsx 使用 Mithril 2 的 JSX / 类组件语法(view()、attrs),并基于 SplitDropdown 与 DetailedDropdownItem 构建"跟随/忽略/不关注"三态下拉菜单。

  2. Load language strings correctly on en-/disable:启用/禁用扩展时语言字符串能正确加载,得益于 Extend\Locales 的声明式注册。

  3. Notification emails now are translatable:通知邮件实现可翻译化。后端由 Notification/NewPostBlueprint.php 承担:

public function getEmailSubject(TranslatorInterface $translator): string
{
    return $translator->trans('flarum-subscriptions.email.new_post.subject', ['{title}' => $this->post->discussion->title]);
}

public function getEmailViews(): array
{
    return [
        'text' => 'flarum-subscriptions::emails.plain.newPost',
        'html' => 'flarum-subscriptions::emails.html.newPost',
    ];
}

邮件正文由 views/emails/plain/newPost.blade.php 与 views/emails/html/newPost.blade.php 两个 Blade 模板渲染,文本全部取自 locale/en.yml 的 email.new_post 段(主题 <a href="https://link.gitcode.com/i/028b14318695e61673956b94fc31eb9c" target="_blank">New Post] {title}、正文、HTML 版本),由 [extend.php 的 Extend\View->namespace('flarum-subscriptions', ...) 注册视图命名空间。集成测试 NotificationEmailInjectionTest.php 使用 fixtures/views/email-body.blade.php 验证邮件内容的正确渲染。

  1. Button colors for dark mode were too vague:修复暗色模式下按钮颜色过于模糊的问题。对应 less/forum.less 中 [data-theme^=dark] 分支专门定义了暗色按钮变量(#784d00 / #fbb94c),并通过 .Button--color-vars(..., 'button--follow') 生成主题相关按钮样式;高对比度主题(light-hc / dark-hc)还会对基准色做 darken(@following-color, 23%) 加深处理。

v0.1.0-beta.13:新帖邮件进入队列

"Send 'new post' email through queue"(将新帖邮件投递到队列)是本扩展通知性能的关键转折点,由 Listener/SendNotificationWhenReplyIsPosted.php 实现:

public function handle(Posted|PostWasApproved $event): void
{
    $this->queue->push(
        new SendReplyNotification($event->post, $event->post->discussion->last_post_number)
    );
}

它监听 Posted 与 PostWasApproved(后者来自可选的 flarum/approval 扩展)两个事件,将"查找订阅者 + 生成通知"的耗时工作压入队列,避免在请求线程内同步执行。队列任务 Job/SendReplyNotification.php 是投递逻辑的核心:

$followers = $discussion->readers()
    ->select('users.id', 'users.preferences', 'discussion_user.last_read_post_number')
    ->where('users.id', '!=', $post->user_id)
    ->where('discussion_user.subscription', 'follow');

$followers->chunk(150, function (Collection $followers) use (&$usersToNotify) {
    // 1. 偏好 notify_for_all_posts 的用户:始终通知
    // 2. 其余用户:仅当 last_read_post_number === lastPostNumber - 1 时通知(即下一个待读帖)
});

lastPostNumber 在入队时捕获(即 discussion->last_post_number),因此即便队列延迟执行期间又有新帖,比较基准也不会漂移。订阅者按每 150 条分块读取,避免一次性加载过多用户。这一"只提醒下一个待读帖"的语义对应 locale/en.yml 中设置项 notify_for_all_posts_label 的说明 "Notify about every new post instead of only the last in a discussion",并由集成测试 ReplyNotificationTest.php 覆盖:默认用户收到 1 条通知,而开启 flarum-subscriptions.notify_for_all_posts 的用户在 5 次回复后收到 5 条。

通知最终通过 NotificationSyncer::sync() 写入 NewPostBlueprint 对应的通知记录。发送前还有一道可见性防线 Notification/FilterVisiblePostsBeforeSending.php:因为该通知的主题是讨论(而非帖子),Flarum 内置的主题级访问控制不够精确,故对每个收件人执行 $blueprint->post->isVisibleTo($recipient) 检查,防止用户通过订阅窥探无权访问的隐藏回复——这一点由 ReplyNotificationTest.php 中的 replying_to_a_discussion_with_a_restricted_post_only_sends_notifications_to_allowed_users 用例直接验证。

v0.1.0-beta.12:following gambit 的查询性能修复

"WhereExists performed extremely bad, impacting the following gambit"(WhereExists 子查询性能极差,影响 is:following gambit)。CHANGELOG 明确指出了该版本对筛选查询的重写,当前实现可见两处:

  1. gambit 侧:Filter/SubscriptionFilter.php 使用正则 '/^(follow|ignor)(?:ing|ed)$/i' 归一化输入(兼容 following / ignored 等拼写),然后执行:
$method = $negate ? 'whereNotIn' : 'whereIn';
$query->$method('discussions.id', function ($query) use ($actor, $subscriptionType) {
    $query->select('discussion_id')
        ->from('discussion_user')
        ->where('user_id', $actor->id)
        ->where('subscription', $subscriptionType === 'follow' ? 'follow' : 'ignore');
});

即改用 id IN (子查询) 关联 discussion_user,由数据库优化器直接利用索引,替代此前低效的逐行 EXISTS 判断。

  1. 隐藏忽略帖侧:HideIgnoredFromAllDiscussionsPage.php 在"全部讨论"页(无激活过滤器且非全文搜索时)注入 whereNotExists 子查询,将 subscription = 'ignore' 的讨论从列表剔除;代码中的 TODO 注释也提示未来可能改写成 id IN (subquery) 以进一步提升性能。

前端侧,js/src/common/query/discussions/SubscriptionGambit.ts 是 is:following / is:ignoring gambit 的入口:它把翻译键(lib.gambits.discussions.subscription.following_key / ignoring_key)映射为 subscription 过滤器键,并仅在登录用户下启用。

v0.1.0-beta.9:监听器取代事件订阅器、邮件代码块修复与依赖安全

该版本的三条记录分别对应架构、渲染与安全三个维度:

  1. Replace event subscribers (that resolve services too early) with listeners:将事件订阅器(会在服务容器早期解析服务)替换为普通监听器。当前 extend.php 中全部事件均以 ->listen(EventClass::class, ListenerClass::class) 形式注册:Saving → SaveSubscriptionToDatabase、Posted / PostWasApproved → SendNotificationWhenReplyIsPosted、Hidden / Deleted → DeleteNotificationWhenPostIsHiddenOrDeleted、Restored → RestoreNotificationWhenPostIsRestored、Posted → FollowAfterReply、Started → FollowAfterCreate。前/后台隐藏或删除帖子时,DeleteNotificationWhenPostIsHiddenOrDeleted.php 通过 NotificationSyncer::delete() 撤回对应通知,恢复时再由 RestoreNotificationWhenPostIsRestored.php 的 restore() 复原——这一"隐藏/删除/恢复"闭环正是 Flarum 审核机制与通知系统协同的典型实现。

  2. Post content with code blocks could corrupt notification emails:含代码块的帖子内容曾破坏通知邮件。修复后在 views/emails/html/newPost.blade.php 中,邮件正文先经翻译再交给 $formatter->convert(...) 渲染(HTML 版本),纯文本版本在 views/emails/plain/newPost.blade.php 中直接注入 {content},两者分别规避了代码块在富文本/纯文本场景下的格式污染。

  3. JS: Vulnerable lodash dependency:升级存在漏洞的 lodash 依赖,是前端依赖安全治理的常规操作。

其他关键机制速览(源码佐证)

除 CHANGELOG 条目外,以下几处实现与该文档主题直接相关,可作为深入阅读的起点:

  • 自动关注偏好:设置页 addSubscriptionSettings.tsx 提供三个开关,对应 extend.php 注册的三项用户偏好:followAfterReply(回复后自动关注)、followAfterCreate(发帖后自动关注)、flarum-subscriptions.notify_for_all_posts(每个新帖都通知)。后端 FollowAfterReply.php 与 FollowAfterCreate.php 在事件触发时读取偏好并写入订阅状态,FollowAfterReplyTest.php 与 FollowAfterCreateTest.php 对此有集成测试覆盖。
  • 订阅菜单 UI:SubscriptionMenu.tsx 提供"不关注 / 跟随 / 忽略"三态选择,主按钮在已关注/已忽略时单击可快捷取消;addSubscriptionBadge.js 在讨论列表为 follow / ignore 状态分别渲染星形与禁眼徽章(tooltip 文案见 locale/en.yml 的 forum.badge 段)。
  • 通知详情页:NewPostNotification.js 将站内通知渲染为星形图标,点击跳转到 app.route.discussion(discussion, content.postNumber)(带 postNumber 定位,数据来自蓝图的 getData())。
  • 可选依赖集成:extendDeck.ts 在启用 flarum/deck 时注册一个"Following"列,通过 DiscussionListSource({ filter: { subscription: 'following' } }) 复用同一筛选逻辑;composer.json 将 flarum/approval 与 flarum/deck 声明为 optional-dependencies。
  • 本地测试:composer.json 提供 composer test(依次运行单元与集成测试)、composer test:setup(一次性初始化集成测试数据库)等脚本,其中集成测试由 tests/integration/setup.php 与 tests/phpunit.integration.xml 驱动。

版本演进时间线小结

版本 核心变更 对应源码位置
v1.2.0 订阅菜单侧边栏优先级 addSubscriptionControls.js
v1.1.0 徽章 CSS 变量化;Prettier 配置 less/forum.less;js/package.json
v1.0.0 Flarum 1.0 兼容;tooltip 警告修复;API 订阅字段一致性 UserResourceFields.php
v0.1.0-beta.16 管理分类改 feature;语言包内迁;跟随列表跨页持久 composer.json;locale/en.yml;addSubscriptionFilter.js
v0.1.0-beta.15 适配新管理后台与新 extenders extend.php;js/src/forum/extend.ts
v0.1.0-beta.14 跟随页 meta title;Mithril 2;邮件可翻译;暗色配色 NewPostBlueprint.php;views/emails;less/forum.less
v0.1.0-beta.13 新帖邮件队列化 SendNotificationWhenReplyIsPosted.php;SendReplyNotification.php
v0.1.0-beta.12 following gambit 查询性能修复 SubscriptionFilter.php;HideIgnoredFromAllDiscussionsPage.php
v0.1.0-beta.9 监听器化;邮件代码块修复;lodash 漏洞升级 extend.php;views/emails

从这张时间线可以看出,Subscriptions 扩展的演进主线清晰:功能上从基础订阅状态走向"按需通知 + 忽略隐藏 + 自动关注偏好"的完整产品闭环;工程上经历事件订阅器→监听器、同步发信→队列化任务、散落样式→CSS 变量设计令牌、硬编码文案→可翻译语言包的多次重构;性能上针对 discussion_user 中间表的查询模式持续打磨(whereIn 子查询、whereNotExists、按 150 条分块处理订阅者)。这份 CHANGELOG 既是扩展的使用手册,也是一份浓缩的 Flarum 扩展开发最佳实践清单。

登录后查看全文
framework