feat: Phase 2e-1 统一通知中心 + 我的 TabBar 聚合未读红点

后端(notify 模块)
- 新增 notify 模块:DAO/Service/Pusher 接口/Controller/Router/CleanupTask
- 数据库 DDL:notify_notifications 表 + 3 索引(user+created/user+is_read/user+category)
- 11 种 type 枚举(好友/群聊 9 种 + meeting_* 2 种预留)+ 4 种 category
- 跨模块集成:contact 3 处 Pusher(friend_request/accepted/rejected)
- 跨模块集成:group 6 处 Pusher(invite/join_request/approved/rejected/kicked/role_changed)
- WS handler 断线补偿:连接建立即推送 notify.unread.total
- 5 REST API(4 用户 + 1 管理员广播)+ 2 WS 事件(notify.new / notify.unread.total)
- 30 天已读通知定时清理(未读永久保留)
- Provider/Wire 依赖注入(NotifyPusher、NotifyConnectHook、UserInfoResolver 接口)

前端
- 新增 notify 模块:API/Pinia Store(5 分类分页缓存 + 未读数 + WS 事件)/NotifyItem/通知中心主页
- profile 入口:铃铛 badge + 菜单项 badge + 数字显示
- App.vue/login 初始化 notifyStore WS 监听;logout 调用 notifyStore.reset() 清缓存
- 清理 contact.js/group.js 中散落 toast 与冗余 notify.friend.request/group.join.request 处理
- CustomTabBar 新增 hasDot() 聚合指示器:我的 Tab 显示纯红点(无数字),
  当前聚合 notifyStore.unreadTotal,未来可扩展「资料待完善/安全提醒/新版本」等

文档
- 新增 Phase 2e 整体路线图 docs/plans/2026-04-20-phase2e-design.md
- 新增 Phase 2e-1 专用设计 docs/plans/2026-04-20-phase2e-1-design.md(§6.4 TabBar 聚合红点)
- 新增 Phase 2e-1 实施计划 docs/plans/2026-04-20-phase2e-1-implementation.plan.md
- 新增 E2E 验证报告 test-report-phase2e-1-notification.md(含 Playwright MCP 2 个现场 Bug 修复记录)
- 更新 docs/progress/CURRENT_STATUS.md、docs/api/README.md、docs/api/frontend/notify.md
- 更新 .cursor/rules/project-context.mdc、docs/plans/2026-02-27-echochat-system-design.md

其他
- .gitignore 排除 .playwright-mcp/ MCP 临时快照

架构决策
- 单端 WS 连接:沿用现有 ws.Hub,多端已读同步推迟到 Phase 2f/二期
- 跨模块依赖:contact/group → notify 严格单向(接口注入模式)
- 降级策略:Pusher 先入库后推送;WS 失败不回滚入库;入库失败仅 Warn 不影响业务

Playwright MCP 回归(4 类场景全通)
- 实时推送(admin 广播 → 1s 内前端自动插入 + 角标 +1)
- Deep-link 跳转(好友申请通知 → contact/request 页)
- 批量清零(全部已读按钮)
- TabBar 聚合红点(有未读亮/全部已读灭)与 notifyStore.unreadTotal 三层同步

Made-with: Cursor
This commit is contained in:
bujinyuan
2026-04-21 10:21:01 +08:00
parent ccfceefdaf
commit f1853f125d
42 changed files with 4493 additions and 97 deletions

View File

@@ -0,0 +1,105 @@
package constants
// 通知类型枚举notify_notifications.type
// 覆盖好友 / 群聊 / 会议 / 系统四大类,其中 meeting_* 在 Phase 2e-1 仅预留枚举,由 Phase 2e-2/2e-3 业务接入
const (
// 好友相关contact 模块触发)
NotifyTypeFriendRequest = "friend_request" // 收到好友申请
NotifyTypeFriendAccepted = "friend_accepted" // 好友申请被接受(通知申请人)
NotifyTypeFriendRejected = "friend_rejected" // 好友申请被拒绝(通知申请人)
// 群聊相关group 模块触发)
NotifyTypeGroupInvite = "group_invite" // 被邀请入群
NotifyTypeGroupJoinRequest = "group_join_request" // 有新入群申请(通知群管理员)
NotifyTypeGroupJoinApproved = "group_join_approved" // 入群申请通过(通知申请人)
NotifyTypeGroupJoinRejected = "group_join_rejected" // 入群申请被拒(通知申请人)
NotifyTypeGroupKicked = "group_kicked" // 被移出群聊
NotifyTypeGroupRoleChanged = "group_role_changed" // 群内角色变更(被设/取消管理员)
// 系统广播admin 触发)
NotifyTypeSystemBroadcast = "system_broadcast" // 管理员全员广播
// 会议相关Phase 2e-1 预留枚举Phase 2e-2/2e-3 业务接入)
NotifyTypeMeetingInvite = "meeting_invite" // 会议邀请
NotifyTypeMeetingReminder = "meeting_reminder" // 会议提醒
)
// NotifyTypeMap 通知类型中文映射
// 用于日志、管理端展示、默认标题兜底
var NotifyTypeMap = map[string]string{
NotifyTypeFriendRequest: "好友申请",
NotifyTypeFriendAccepted: "好友申请通过",
NotifyTypeFriendRejected: "好友申请被拒",
NotifyTypeGroupInvite: "群聊邀请",
NotifyTypeGroupJoinRequest: "入群申请",
NotifyTypeGroupJoinApproved: "入群申请通过",
NotifyTypeGroupJoinRejected: "入群申请被拒",
NotifyTypeGroupKicked: "移出群聊",
NotifyTypeGroupRoleChanged: "群角色变更",
NotifyTypeSystemBroadcast: "系统通知",
NotifyTypeMeetingInvite: "会议邀请",
NotifyTypeMeetingReminder: "会议提醒",
}
// 通知分类(用于前端 5 个 Tab 过滤)
const (
NotifyCategoryAll = "all" // 全部
NotifyCategoryFriend = "friend" // 好友
NotifyCategoryGroup = "group" // 群聊
NotifyCategoryMeeting = "meeting" // 会议
NotifyCategorySystem = "system" // 系统
)
// NotifyCategoryOfType 根据 type 判断所属分类,用于列表按分类筛选
func NotifyCategoryOfType(notifyType string) string {
switch notifyType {
case NotifyTypeFriendRequest, NotifyTypeFriendAccepted, NotifyTypeFriendRejected:
return NotifyCategoryFriend
case NotifyTypeGroupInvite, NotifyTypeGroupJoinRequest, NotifyTypeGroupJoinApproved,
NotifyTypeGroupJoinRejected, NotifyTypeGroupKicked, NotifyTypeGroupRoleChanged:
return NotifyCategoryGroup
case NotifyTypeMeetingInvite, NotifyTypeMeetingReminder:
return NotifyCategoryMeeting
case NotifyTypeSystemBroadcast:
return NotifyCategorySystem
default:
return NotifyCategorySystem
}
}
// NotifyTypesByCategory 分类 → type 列表映射,查询时用于构造 SQL IN 条件
var NotifyTypesByCategory = map[string][]string{
NotifyCategoryFriend: {
NotifyTypeFriendRequest, NotifyTypeFriendAccepted, NotifyTypeFriendRejected,
},
NotifyCategoryGroup: {
NotifyTypeGroupInvite, NotifyTypeGroupJoinRequest, NotifyTypeGroupJoinApproved,
NotifyTypeGroupJoinRejected, NotifyTypeGroupKicked, NotifyTypeGroupRoleChanged,
},
NotifyCategoryMeeting: {
NotifyTypeMeetingInvite, NotifyTypeMeetingReminder,
},
NotifyCategorySystem: {
NotifyTypeSystemBroadcast,
},
}
// 通知业务对象类型notify_notifications.target_type
// 用于前端 deep-link 跳转路由
const (
NotifyTargetUser = "user" // 跳转到用户主页/好友申请页
NotifyTargetGroup = "group" // 跳转到群聊详情
NotifyTargetMeeting = "meeting" // 跳转到会议Phase 2e-2/2e-3
NotifyTargetSystem = "system" // 系统公告,无跳转
)
// 通知清理策略
const (
NotifyRetentionDays = 30 // 已读通知保留天数(未读不清理)
)
// WS 事件常量
const (
WSEventNotifyNew = "notify.new" // 新通知推送S→C
WSEventNotifyUnreadTotal = "notify.unread.total" // 断线重连补偿未读数S→C
)

View File

@@ -6,10 +6,11 @@ import (
"errors"
"sort"
"github.com/echochat/backend/app/constants"
"github.com/echochat/backend/app/contact/dao"
"github.com/echochat/backend/app/dto"
notifyService "github.com/echochat/backend/app/notify/service"
"github.com/echochat/backend/pkg/logs"
"github.com/echochat/backend/pkg/ws"
"go.uber.org/zap"
"gorm.io/gorm"
)
@@ -30,26 +31,33 @@ type OnlineChecker interface {
BatchCheckOnline(ctx context.Context, userIDs []int64) map[int64]bool
}
// NotifyPusher 通知推送接口
// 由 notify.service.NotifyService 隐式实现contact → notify 单向依赖
// 此处以接口形式注入,便于测试替换并明确调用契约
type NotifyPusher interface {
Push(ctx context.Context, payload *notifyService.PushPayload)
}
// ContactService 联系人业务服务
type ContactService struct {
friendshipDAO *dao.FriendshipDAO
friendGroupDAO *dao.FriendGroupDAO
pubsub *ws.PubSub
onlineChecker OnlineChecker
notifyPusher NotifyPusher
}
// NewContactService 创建 ContactService 实例
func NewContactService(
friendshipDAO *dao.FriendshipDAO,
friendGroupDAO *dao.FriendGroupDAO,
pubsub *ws.PubSub,
onlineChecker OnlineChecker,
notifyPusher NotifyPusher,
) *ContactService {
return &ContactService{
friendshipDAO: friendshipDAO,
friendGroupDAO: friendGroupDAO,
pubsub: pubsub,
onlineChecker: onlineChecker,
notifyPusher: notifyPusher,
}
}
@@ -99,12 +107,20 @@ func (s *ContactService) SendFriendRequest(ctx context.Context, userID, targetID
}
}
push := ws.NewPushMessage("notify.friend.request", map[string]interface{}{
"from_user_id": userID,
"message": message,
})
if pubErr := s.pubsub.PublishToUser(ctx, targetID, push); pubErr != nil {
logs.Warn(ctx, funcName, "推送好友申请通知失败", zap.Error(pubErr))
if s.notifyPusher != nil {
actorID := userID
targetUser := targetID
s.notifyPusher.Push(ctx, &notifyService.PushPayload{
UserID: targetID,
Type: constants.NotifyTypeFriendRequest,
Content: message,
ActorID: &actorID,
TargetType: constants.NotifyTargetUser,
TargetID: &targetUser,
Extra: map[string]interface{}{
"message": message,
},
})
}
return nil
@@ -132,11 +148,20 @@ func (s *ContactService) AcceptFriendRequest(ctx context.Context, requestID, use
return err
}
push := ws.NewPushMessage("contact.request.accepted", map[string]interface{}{
"user_id": userID,
})
if pubErr := s.pubsub.PublishToUser(ctx, req.UserID, push); pubErr != nil {
logs.Warn(ctx, funcName, "推送申请接受通知失败", zap.Error(pubErr))
if s.notifyPusher != nil {
actorID := userID
targetUser := userID
s.notifyPusher.Push(ctx, &notifyService.PushPayload{
UserID: req.UserID,
Type: constants.NotifyTypeFriendAccepted,
Content: "对方已接受你的好友申请",
ActorID: &actorID,
TargetType: constants.NotifyTargetUser,
TargetID: &targetUser,
Extra: map[string]interface{}{
"request_id": requestID,
},
})
}
return nil
@@ -148,11 +173,41 @@ func (s *ContactService) RejectFriendRequest(ctx context.Context, requestID, use
logs.Info(ctx, funcName, "拒绝好友申请",
zap.Int64("request_id", requestID), zap.Int64("user_id", userID))
err := s.friendshipDAO.RejectRequest(ctx, requestID, userID)
if errors.Is(err, gorm.ErrRecordNotFound) {
req, err := s.friendshipDAO.GetRequestByID(ctx, requestID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRequestNotFound
}
return err
}
if req.FriendID != userID {
return ErrRequestNotFound
}
return err
if err := s.friendshipDAO.RejectRequest(ctx, requestID, userID); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRequestNotFound
}
return err
}
if s.notifyPusher != nil {
actorID := userID
targetUser := userID
s.notifyPusher.Push(ctx, &notifyService.PushPayload{
UserID: req.UserID,
Type: constants.NotifyTypeFriendRejected,
Content: "对方拒绝了你的好友申请",
ActorID: &actorID,
TargetType: constants.NotifyTargetUser,
TargetID: &targetUser,
Extra: map[string]interface{}{
"request_id": requestID,
},
})
}
return nil
}
// GetFriendList 获取好友列表(包含在线状态)

View File

@@ -0,0 +1,67 @@
package dto
// ====== 通知基础 DTO ======
// NotificationDTO 通知传输对象
// 前端列表渲染使用,字段顺序与 notify_notifications 一一对应
type NotificationDTO struct {
ID int64 `json:"id"` // 通知 ID
Type string `json:"type"` // 通知类型常量
Category string `json:"category"` // 前端分类friend / group / meeting / system由 type 计算得出
Title string `json:"title"` // 标题
Content string `json:"content"` // 副文案
Extra *string `json:"extra,omitempty"` // 扩展数据 JSON 字符串(前端按需解析)
ActorID *int64 `json:"actor_id,omitempty"` // 触发用户 ID
ActorName string `json:"actor_name,omitempty"` // 触发用户昵称(后端按需补全)
ActorAvatar string `json:"actor_avatar,omitempty"` // 触发用户头像
TargetType string `json:"target_type"` // 业务对象类型
TargetID *int64 `json:"target_id,omitempty"` // 业务对象 ID
IsRead bool `json:"is_read"` // 是否已读
ReadAt string `json:"read_at,omitempty"` // 已读时间(未读为空)
CreatedAt string `json:"created_at"` // 创建时间
}
// ====== REST API 请求/响应 DTO ======
// GetNotificationsRequest 通知列表查询参数
// GET /api/v1/notifications
type GetNotificationsRequest struct {
Category string `form:"category"` // 分类过滤all/friend/group/meeting/system空视为 all
IsRead *bool `form:"is_read"` // 已读状态过滤nil=全部true=已读false=未读
BeforeID int64 `form:"before_id"` // 游标分页:小于此 ID 的记录
Limit int `form:"limit"` // 页大小(默认 20最大 100
}
// NotificationListResponse 通知列表响应
type NotificationListResponse struct {
List []NotificationDTO `json:"list"` // 通知列表(按 created_at DESC 返回)
HasMore bool `json:"has_more"` // 是否还有更多数据
}
// UnreadCountResponse 未读数响应
type UnreadCountResponse struct {
Total int `json:"total"` // 未读总数
ByCategory map[string]int `json:"by_category"` // 按分类未读数friend/group/meeting/system
}
// MarkReadResponse 标记已读响应
type MarkReadResponse struct {
Affected int `json:"affected"` // 实际被标记为已读的记录数
}
// ====== 管理端广播 DTO ======
// BroadcastNotificationRequest 管理员发起系统广播请求
// POST /api/v1/admin/notifications/broadcast
type BroadcastNotificationRequest struct {
Title string `json:"title" binding:"required,max=100"` // 广播标题
Content string `json:"content" binding:"required,max=500"` // 广播正文
TargetType string `json:"target_type"` // 业务对象类型,通常为 system
TargetID *int64 `json:"target_id"` // 业务对象 ID可选
Extra *string `json:"extra"` // 扩展 JSON
}
// BroadcastNotificationResponse 广播结果响应
type BroadcastNotificationResponse struct {
Affected int `json:"affected"` // 成功入库的用户数
}

View File

@@ -12,6 +12,7 @@ import (
"github.com/echochat/backend/app/group/dao"
"github.com/echochat/backend/app/group/model"
imModel "github.com/echochat/backend/app/im/model"
notifyService "github.com/echochat/backend/app/notify/service"
"github.com/echochat/backend/pkg/logs"
"github.com/echochat/backend/pkg/ws"
"go.uber.org/zap"
@@ -46,6 +47,12 @@ type MessageWriter interface {
Create(ctx context.Context, msg *imModel.Message) error
}
// NotifyPusher 通知推送接口
// 由 notify.service.NotifyService 隐式实现group → notify 单向依赖
type NotifyPusher interface {
Push(ctx context.Context, payload *notifyService.PushPayload)
}
// GroupService 群聊业务服务
type GroupService struct {
groupDAO *dao.GroupDAO
@@ -53,6 +60,7 @@ type GroupService struct {
userInfo UserInfoProvider
pubsub *ws.PubSub
msgWriter MessageWriter
notifyPusher NotifyPusher
}
// NewGroupService 创建 GroupService 实例
@@ -62,6 +70,7 @@ func NewGroupService(
userInfo UserInfoProvider,
pubsub *ws.PubSub,
msgWriter MessageWriter,
notifyPusher NotifyPusher,
) *GroupService {
return &GroupService{
groupDAO: groupDAO,
@@ -69,6 +78,7 @@ func NewGroupService(
userInfo: userInfo,
pubsub: pubsub,
msgWriter: msgWriter,
notifyPusher: notifyPusher,
}
}
@@ -308,6 +318,17 @@ func (s *GroupService) InviteMembers(ctx context.Context, userID, groupID int64,
"user_ids": addedIDs,
"operator_id": userID,
})
// 向被邀请的每个用户推送入群通知,由通知中心持久化 + WS 实时弹出
s.pushGroupNotify(ctx, addedIDs, userID, constants.NotifyTypeGroupInvite,
fmt.Sprintf("%s 邀请你加入「%s」", inviterName, group.Name),
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"conversation_id": group.ConversationID,
"inviter_id": userID,
"inviter_name": inviterName,
})
}
return nil
@@ -357,6 +378,16 @@ func (s *GroupService) KickMember(ctx context.Context, userID, groupID, targetID
"operator_id": userID,
})
// 通知被踢用户:持久化到通知中心
operatorName := s.getUserNickname(ctx, userID)
s.pushGroupNotify(ctx, []int64{targetID}, userID, constants.NotifyTypeGroupKicked,
fmt.Sprintf("%s 将你移出了群聊「%s」", operatorName, group.Name),
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"operator_id": userID,
})
return nil
}
@@ -402,6 +433,22 @@ func (s *GroupService) SetMemberRole(ctx context.Context, userID, groupID, targe
"operator_id": userID,
})
// 通知被设置角色的用户:持久化到通知中心
var content string
if role == constants.GroupRoleAdmin {
content = fmt.Sprintf("你已被设为群聊「%s」的管理员", group.Name)
} else {
content = fmt.Sprintf("你的群聊「%s」管理员身份已被取消", group.Name)
}
s.pushGroupNotify(ctx, []int64{targetID}, userID, constants.NotifyTypeGroupRoleChanged,
content,
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"role": role,
"operator_id": userID,
})
return nil
}
@@ -585,6 +632,18 @@ func (s *GroupService) SubmitJoinRequest(ctx context.Context, userID, groupID in
"message": message,
})
// 向群管理员持久化通知:需要审批的入群申请
s.pushGroupNotify(ctx, adminIDs, userID, constants.NotifyTypeGroupJoinRequest,
fmt.Sprintf("%s 申请加入群聊「%s」", userName, group.Name),
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"request_id": req.ID,
"applicant_id": userID,
"applicant_name": userName,
"message": message,
})
return nil
}
@@ -692,10 +751,33 @@ func (s *GroupService) ReviewJoinRequest(ctx context.Context, userID, groupID, r
"user_ids": []int64{req.UserID},
})
// 通知申请人:入群申请已通过
s.pushGroupNotify(ctx, []int64{req.UserID}, userID, constants.NotifyTypeGroupJoinApproved,
fmt.Sprintf("你加入群聊「%s」的申请已通过", group.Name),
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"conversation_id": group.ConversationID,
"request_id": requestID,
})
return nil
}
return s.joinRequestDAO.Reject(ctx, requestID, userID)
if err := s.joinRequestDAO.Reject(ctx, requestID, userID); err != nil {
return err
}
// 通知申请人:入群申请被拒绝
s.pushGroupNotify(ctx, []int64{req.UserID}, userID, constants.NotifyTypeGroupJoinRejected,
fmt.Sprintf("你加入群聊「%s」的申请已被拒绝", group.Name),
groupID, map[string]interface{}{
"group_id": groupID,
"group_name": group.Name,
"request_id": requestID,
})
return nil
}
// SearchGroups 搜索公开群
@@ -858,6 +940,52 @@ func (s *GroupService) pushToGroupMembers(ctx context.Context, conversationID in
s.pushToMembers(ctx, memberIDs, excludeUID, event, data)
}
// pushGroupNotify 向多个用户批量投递群聊相关通知(持久化 + WS
// notifyPusher 内部自动写入通知中心并推送 notify.new 事件
func (s *GroupService) pushGroupNotify(
ctx context.Context,
userIDs []int64,
actorID int64,
notifyType string,
content string,
groupID int64,
extra map[string]interface{},
) {
if s.notifyPusher == nil || len(userIDs) == 0 {
return
}
gid := groupID
actor := actorID
payloads := make([]*notifyService.PushPayload, 0, len(userIDs))
for _, uid := range userIDs {
if uid <= 0 || uid == actorID {
continue
}
payloads = append(payloads, &notifyService.PushPayload{
UserID: uid,
Type: notifyType,
Content: content,
ActorID: &actor,
TargetType: constants.NotifyTargetGroup,
TargetID: &gid,
Extra: extra,
})
}
if len(payloads) == 0 {
return
}
// 使用批量接口,减少数据库往返
if batch, ok := s.notifyPusher.(interface {
PushBatch(ctx context.Context, payloads []*notifyService.PushPayload)
}); ok {
batch.PushBatch(ctx, payloads)
return
}
for _, p := range payloads {
s.notifyPusher.Push(ctx, p)
}
}
// writeSystemMessage 写入系统消息到群会话
func (s *GroupService) writeSystemMessage(ctx context.Context, conversationID int64, content string) {
if s.msgWriter == nil {

View File

@@ -0,0 +1,136 @@
// Package controller 提供 notify 模块的 HTTP 接口
package controller
import (
"errors"
"strconv"
"github.com/echochat/backend/app/dto"
"github.com/echochat/backend/app/notify/service"
"github.com/echochat/backend/pkg/middleware"
"github.com/echochat/backend/pkg/utils"
"github.com/gin-gonic/gin"
)
// NotificationController 通知控制器REST API
type NotificationController struct {
notifyService *service.NotifyService
}
// NewNotificationController 创建 NotificationController 实例
func NewNotificationController(notifyService *service.NotifyService) *NotificationController {
return &NotificationController{notifyService: notifyService}
}
// GetList 获取通知列表
// GET /api/v1/notifications?category=&is_read=&before_id=&limit=
func (ctl *NotificationController) GetList(c *gin.Context) {
ctx := c.Request.Context()
userID, ok := middleware.GetCurrentUserID(c)
if !ok {
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
return
}
var req dto.GetNotificationsRequest
if err := c.ShouldBindQuery(&req); err != nil {
utils.ResponseBadRequest(c, "请求参数错误: "+err.Error())
return
}
resp, err := ctl.notifyService.GetList(ctx, userID, &req)
if err != nil {
utils.ResponseError(c, "获取通知列表失败")
return
}
utils.ResponseOK(c, resp)
}
// GetUnreadCount 获取未读数(总数 + 按分类)
// GET /api/v1/notifications/unread-count
func (ctl *NotificationController) GetUnreadCount(c *gin.Context) {
ctx := c.Request.Context()
userID, ok := middleware.GetCurrentUserID(c)
if !ok {
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
return
}
resp, err := ctl.notifyService.GetUnreadCount(ctx, userID)
if err != nil {
utils.ResponseError(c, "获取未读数失败")
return
}
utils.ResponseOK(c, resp)
}
// MarkRead 标记单条通知为已读
// PUT /api/v1/notifications/:id/read
func (ctl *NotificationController) MarkRead(c *gin.Context) {
ctx := c.Request.Context()
userID, ok := middleware.GetCurrentUserID(c)
if !ok {
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
return
}
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
utils.ResponseBadRequest(c, "通知 ID 格式错误")
return
}
if err := ctl.notifyService.MarkRead(ctx, userID, id); err != nil {
if errors.Is(err, service.ErrNotificationNotFound) {
utils.ResponseNotFound(c, err.Error())
return
}
utils.ResponseError(c, "标记已读失败")
return
}
utils.ResponseOK(c, nil)
}
// MarkAllRead 一键清零未读
// PUT /api/v1/notifications/read-all?category=
func (ctl *NotificationController) MarkAllRead(c *gin.Context) {
ctx := c.Request.Context()
userID, ok := middleware.GetCurrentUserID(c)
if !ok {
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
return
}
category := c.Query("category")
affected, err := ctl.notifyService.MarkAllRead(ctx, userID, category)
if err != nil {
utils.ResponseError(c, "批量标记已读失败")
return
}
utils.ResponseOK(c, dto.MarkReadResponse{Affected: int(affected)})
}
// Broadcast 管理员发起全员广播
// POST /api/v1/admin/notifications/broadcast
// 需要 admin/super_admin 角色,由路由层中间件保证
func (ctl *NotificationController) Broadcast(c *gin.Context) {
ctx := c.Request.Context()
operatorID, ok := middleware.GetCurrentUserID(c)
if !ok {
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
return
}
var req dto.BroadcastNotificationRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ResponseBadRequest(c, "请求参数错误: "+err.Error())
return
}
affected, err := ctl.notifyService.Broadcast(ctx, operatorID, &req)
if err != nil {
utils.ResponseError(c, "广播失败")
return
}
utils.ResponseOK(c, dto.BroadcastNotificationResponse{Affected: affected})
}

View File

@@ -0,0 +1,200 @@
// Package dao 提供 notify 模块的数据库访问操作
package dao
import (
"context"
"time"
"github.com/echochat/backend/app/constants"
"github.com/echochat/backend/app/notify/model"
"github.com/echochat/backend/pkg/logs"
"go.uber.org/zap"
"gorm.io/gorm"
)
// NotificationDAO 通知记录数据访问对象
type NotificationDAO struct {
db *gorm.DB
}
// NewNotificationDAO 创建 NotificationDAO 实例
func NewNotificationDAO(db *gorm.DB) *NotificationDAO {
return &NotificationDAO{db: db}
}
// Create 新增一条通知(单用户)
func (d *NotificationDAO) Create(ctx context.Context, n *model.Notification) error {
funcName := "dao.notification_dao.Create"
err := d.db.WithContext(ctx).Create(n).Error
if err != nil {
logs.Error(ctx, funcName, "写入通知失败",
zap.Int64("user_id", n.UserID), zap.String("type", n.Type), zap.Error(err))
}
return err
}
// BatchCreate 批量新增通知(管理员广播场景)
// 使用 GORM 的 CreateInBatches 拆分为 500/批次,避免单次参数过多
func (d *NotificationDAO) BatchCreate(ctx context.Context, list []*model.Notification) error {
funcName := "dao.notification_dao.BatchCreate"
if len(list) == 0 {
return nil
}
err := d.db.WithContext(ctx).CreateInBatches(list, 500).Error
if err != nil {
logs.Error(ctx, funcName, "批量写入通知失败",
zap.Int("count", len(list)), zap.Error(err))
}
return err
}
// GetByID 根据 ID 获取单条通知
func (d *NotificationDAO) GetByID(ctx context.Context, id int64) (*model.Notification, error) {
var n model.Notification
err := d.db.WithContext(ctx).First(&n, id).Error
if err != nil {
return nil, err
}
return &n, nil
}
// ListRequest 列表查询条件
type ListRequest struct {
UserID int64 // 接收者用户 ID必填
Types []string // type 过滤(空则不限)
IsRead *bool // 已读状态过滤nil 则不限)
BeforeID int64 // 游标(小于此 ID 的记录0 表示不限
Limit int // 单页条数
}
// List 按条件分页查询通知(按 ID DESC 返回)
// 使用游标分页id < beforeID避免 OFFSET 随数据增长变慢
func (d *NotificationDAO) List(ctx context.Context, req *ListRequest) ([]model.Notification, error) {
funcName := "dao.notification_dao.List"
q := d.db.WithContext(ctx).Model(&model.Notification{}).
Where("user_id = ?", req.UserID)
if len(req.Types) > 0 {
q = q.Where("type IN ?", req.Types)
}
if req.IsRead != nil {
q = q.Where("is_read = ?", *req.IsRead)
}
if req.BeforeID > 0 {
q = q.Where("id < ?", req.BeforeID)
}
limit := req.Limit
if limit <= 0 {
limit = 20
}
if limit > 100 {
limit = 100
}
var list []model.Notification
err := q.Order("id DESC").Limit(limit).Find(&list).Error
if err != nil {
logs.Error(ctx, funcName, "查询通知列表失败",
zap.Int64("user_id", req.UserID), zap.Error(err))
}
return list, err
}
// CountUnread 统计未读总数
func (d *NotificationDAO) CountUnread(ctx context.Context, userID int64) (int64, error) {
var total int64
err := d.db.WithContext(ctx).Model(&model.Notification{}).
Where("user_id = ? AND is_read = false", userID).
Count(&total).Error
return total, err
}
// CountUnreadByType 按 type 统计未读数(用于按分类汇总)
// 返回 type -> count
func (d *NotificationDAO) CountUnreadByType(ctx context.Context, userID int64) (map[string]int64, error) {
type row struct {
Type string
Cnt int64
}
var rows []row
err := d.db.WithContext(ctx).Model(&model.Notification{}).
Select("type, COUNT(*) as cnt").
Where("user_id = ? AND is_read = false", userID).
Group("type").
Scan(&rows).Error
if err != nil {
return nil, err
}
result := make(map[string]int64, len(rows))
for _, r := range rows {
result[r.Type] = r.Cnt
}
return result, nil
}
// MarkRead 将指定通知标记为已读(仅限本人)
// 返回受影响行数0 表示无效 ID 或非本人
func (d *NotificationDAO) MarkRead(ctx context.Context, id, userID int64) (int64, error) {
funcName := "dao.notification_dao.MarkRead"
now := time.Now()
res := d.db.WithContext(ctx).Model(&model.Notification{}).
Where("id = ? AND user_id = ? AND is_read = false", id, userID).
Updates(map[string]interface{}{
"is_read": true,
"read_at": now,
})
if res.Error != nil {
logs.Error(ctx, funcName, "标记已读失败",
zap.Int64("id", id), zap.Int64("user_id", userID), zap.Error(res.Error))
}
return res.RowsAffected, res.Error
}
// MarkAllRead 将用户所有未读通知标记为已读
// 可选按 types 过滤(为空则全部类型)
func (d *NotificationDAO) MarkAllRead(ctx context.Context, userID int64, types []string) (int64, error) {
funcName := "dao.notification_dao.MarkAllRead"
now := time.Now()
q := d.db.WithContext(ctx).Model(&model.Notification{}).
Where("user_id = ? AND is_read = false", userID)
if len(types) > 0 {
q = q.Where("type IN ?", types)
}
res := q.Updates(map[string]interface{}{
"is_read": true,
"read_at": now,
})
if res.Error != nil {
logs.Error(ctx, funcName, "批量标记已读失败",
zap.Int64("user_id", userID), zap.Error(res.Error))
}
return res.RowsAffected, res.Error
}
// DeleteExpired 清理已读过期通知(保留时长由 constants.NotifyRetentionDays 决定)
// 未读通知无论多久都不清理,避免用户漏看
// 返回清理的行数
func (d *NotificationDAO) DeleteExpired(ctx context.Context) (int64, error) {
funcName := "dao.notification_dao.DeleteExpired"
cutoff := time.Now().AddDate(0, 0, -constants.NotifyRetentionDays)
res := d.db.WithContext(ctx).
Where("is_read = true AND created_at < ?", cutoff).
Delete(&model.Notification{})
if res.Error != nil {
logs.Error(ctx, funcName, "清理过期通知失败", zap.Error(res.Error))
}
return res.RowsAffected, res.Error
}
// ListAllActiveUserIDs 查询系统中所有正常状态的用户 ID用于管理员广播
// 此处直接查 auth_users 表,避免广播时循环依赖 user_dao
func (d *NotificationDAO) ListAllActiveUserIDs(ctx context.Context) ([]int64, error) {
funcName := "dao.notification_dao.ListAllActiveUserIDs"
var ids []int64
err := d.db.WithContext(ctx).
Table("auth_users").
Where("status = ?", constants.UserStatusActive).
Pluck("id", &ids).Error
if err != nil {
logs.Error(ctx, funcName, "查询全量用户 ID 失败", zap.Error(err))
}
return ids, err
}

View File

@@ -0,0 +1,29 @@
// Package model 提供 notify 模块的数据库模型
package model
import (
"time"
)
// Notification 通知记录,对应 notify_notifications 表
// 通知系统的核心持久化载体,覆盖好友 / 群聊 / 会议 / 系统广播四大类型
// 每条通知对应单个接收者,不做跨用户共享
type Notification struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"` // 通知唯一标识
UserID int64 `json:"user_id" gorm:"not null;index:idx_notify_user_time,priority:1;index:idx_notify_user_unread,priority:1"` // 接收者用户 ID
Type string `json:"type" gorm:"size:50;not null"` // 通知类型常量,见 constants.NotifyType*
Title string `json:"title" gorm:"size:100;not null;default:''"` // 通知标题(前端列表主文案)
Content string `json:"content" gorm:"size:500;not null;default:''"` // 通知副文案
Extra *string `json:"extra" gorm:"type:jsonb"` // 扩展数据 JSON 字符串,保存类型相关的业务参数
ActorID *int64 `json:"actor_id"` // 触发主体用户 ID申请人/邀请人等),系统广播为 nil
TargetType string `json:"target_type" gorm:"size:30;not null;default:''"` // 业务对象类型user / group / meeting / system
TargetID *int64 `json:"target_id"` // 业务对象 ID
IsRead bool `json:"is_read" gorm:"not null;default:false"` // 是否已读false=未读true=已读
ReadAt *time.Time `json:"read_at"` // 已读时间
CreatedAt time.Time `json:"created_at" gorm:"not null;autoCreateTime;type:timestamp(0)"` // 通知生成时间
}
// TableName 指定数据库表名
func (Notification) TableName() string {
return "notify_notifications"
}

View File

@@ -0,0 +1,23 @@
// Package notify 通知中心模块
// 统一持久化好友 / 群聊 / 会议 / 系统广播四类通知,并通过 WS 实时推送
package notify
import (
"github.com/echochat/backend/app/notify/controller"
"github.com/echochat/backend/app/notify/dao"
"github.com/echochat/backend/app/notify/service"
"github.com/echochat/backend/app/notify/task"
"github.com/google/wire"
)
// NotifySet 通知模块 Wire Provider Set
// 对外暴露:
// - *service.NotifyService —— 业务服务,同时实现 Pusher / ConnectHook 接口,供上游模块绑定注入
// - *controller.NotificationController —— REST API 控制器
// - *task.CleanupTask —— 过期通知清理定时任务
var NotifySet = wire.NewSet(
dao.NewNotificationDAO,
service.NewNotifyService,
controller.NewNotificationController,
task.NewCleanupTask,
)

View File

@@ -0,0 +1,29 @@
package notify
import (
"github.com/echochat/backend/app/constants"
"github.com/echochat/backend/app/notify/controller"
"github.com/echochat/backend/pkg/middleware"
"github.com/gin-gonic/gin"
)
// RegisterRoutes 注册 notify 模块的所有路由
// 前台用户接口需 JWT后台广播接口额外要求 admin/super_admin 角色
func RegisterRoutes(r *gin.Engine, ctrl *controller.NotificationController, jwtAuth gin.HandlerFunc) {
// 前台用户接口
authed := r.Group("/api/v1")
authed.Use(jwtAuth)
{
authed.GET("/notifications", ctrl.GetList)
authed.GET("/notifications/unread-count", ctrl.GetUnreadCount)
authed.PUT("/notifications/:id/read", ctrl.MarkRead)
authed.PUT("/notifications/read-all", ctrl.MarkAllRead)
}
// 管理端广播接口JWT + admin/super_admin 角色
adminGroup := r.Group("/api/v1/admin")
adminGroup.Use(jwtAuth, middleware.RequireRole(constants.RoleAdmin, constants.RoleSuperAdmin))
{
adminGroup.POST("/notifications/broadcast", ctrl.Broadcast)
}
}

View File

@@ -0,0 +1,420 @@
package service
import (
"context"
"errors"
"time"
authModel "github.com/echochat/backend/app/auth/model"
"github.com/echochat/backend/app/constants"
"github.com/echochat/backend/app/dto"
"github.com/echochat/backend/app/notify/dao"
"github.com/echochat/backend/app/notify/model"
"github.com/echochat/backend/pkg/logs"
"github.com/echochat/backend/pkg/ws"
"go.uber.org/zap"
"gorm.io/gorm"
)
var (
ErrNotificationNotFound = errors.New("通知不存在")
)
// NotifyService 通知业务服务
// 负责:
// 1. 面向用户的列表 / 未读数 / 已读操作REST API 层调用)
// 2. 面向上游业务的 Pusher 接口实现(持久化 + WS 推送)
// 3. 断线重连时的未读补偿推送
type NotifyService struct {
notifyDAO *dao.NotificationDAO
pubsub *ws.PubSub
userResolver UserInfoResolver
}
// NewNotifyService 创建 NotifyService 实例
func NewNotifyService(
notifyDAO *dao.NotificationDAO,
pubsub *ws.PubSub,
userResolver UserInfoResolver,
) *NotifyService {
return &NotifyService{
notifyDAO: notifyDAO,
pubsub: pubsub,
userResolver: userResolver,
}
}
// ====== 面向用户的查询与操作 ======
// GetList 分页查询通知列表
func (s *NotifyService) GetList(ctx context.Context, userID int64, req *dto.GetNotificationsRequest) (*dto.NotificationListResponse, error) {
funcName := "service.notify_service.GetList"
types := typesByCategory(req.Category)
limit := req.Limit
if limit <= 0 {
limit = 20
}
if limit > 100 {
limit = 100
}
list, err := s.notifyDAO.List(ctx, &dao.ListRequest{
UserID: userID,
Types: types,
IsRead: req.IsRead,
BeforeID: req.BeforeID,
Limit: limit + 1, // 多查一条判断是否还有下一页
})
if err != nil {
return nil, err
}
hasMore := false
if len(list) > limit {
hasMore = true
list = list[:limit]
}
items := s.toNotificationDTOs(ctx, list)
logs.Debug(ctx, funcName, "查询通知列表",
zap.Int64("user_id", userID), zap.Int("count", len(items)), zap.Bool("has_more", hasMore))
return &dto.NotificationListResponse{
List: items,
HasMore: hasMore,
}, nil
}
// GetUnreadCount 查询未读数(总数 + 按分类)
func (s *NotifyService) GetUnreadCount(ctx context.Context, userID int64) (*dto.UnreadCountResponse, error) {
countMap, err := s.notifyDAO.CountUnreadByType(ctx, userID)
if err != nil {
return nil, err
}
total := 0
byCat := map[string]int{
constants.NotifyCategoryFriend: 0,
constants.NotifyCategoryGroup: 0,
constants.NotifyCategoryMeeting: 0,
constants.NotifyCategorySystem: 0,
}
for t, c := range countMap {
total += int(c)
byCat[constants.NotifyCategoryOfType(t)] += int(c)
}
return &dto.UnreadCountResponse{
Total: total,
ByCategory: byCat,
}, nil
}
// MarkRead 标记单条通知为已读
func (s *NotifyService) MarkRead(ctx context.Context, userID, id int64) error {
affected, err := s.notifyDAO.MarkRead(ctx, id, userID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrNotificationNotFound
}
return err
}
if affected == 0 {
return ErrNotificationNotFound
}
return nil
}
// MarkAllRead 将用户某分类(或全部)通知标记为已读
// category 为空或 all 时清空全部未读
func (s *NotifyService) MarkAllRead(ctx context.Context, userID int64, category string) (int64, error) {
types := typesByCategory(category)
return s.notifyDAO.MarkAllRead(ctx, userID, types)
}
// PushUnreadTotalOnConnect 向刚建立连接的用户推送未读总数补偿
// 由 WS handler 的 OnConnected 钩子调用(通过 NotifyConnectHook 接口适配)
func (s *NotifyService) PushUnreadTotalOnConnect(ctx context.Context, userID int64) {
funcName := "service.notify_service.PushUnreadTotalOnConnect"
resp, err := s.GetUnreadCount(ctx, userID)
if err != nil {
logs.Warn(ctx, funcName, "查询未读数失败", zap.Int64("user_id", userID), zap.Error(err))
return
}
if resp.Total == 0 {
return
}
s.publishWS(ctx, userID, constants.WSEventNotifyUnreadTotal, map[string]interface{}{
"total": resp.Total,
"by_category": resp.ByCategory,
})
}
// ====== Pusher 接口实现 ======
// Push 写入通知并推送 WS单用户
// 实现策略:
// 1. 同步入库(保证持久化)
// 2. 异步 WS 推送(避免阻塞上游业务事务)
// 3. 任一步失败不回滚另一步,全部仅记录 Warn 日志
func (s *NotifyService) Push(ctx context.Context, payload *PushPayload) {
funcName := "service.notify_service.Push"
if payload == nil || payload.UserID <= 0 || payload.Type == "" {
logs.Warn(ctx, funcName, "无效的推送载荷", zap.Any("payload", payload))
return
}
n := s.buildModel(payload)
if err := s.notifyDAO.Create(ctx, n); err != nil {
logs.Warn(ctx, funcName, "通知入库失败,放弃 WS 推送",
zap.Int64("user_id", payload.UserID), zap.String("type", payload.Type), zap.Error(err))
return
}
go s.safePushWS(n, payload)
}
// PushBatch 批量写入通知并推送 WS
// 适用于管理员广播 / 群操作批量通知场景
// 优化:一次 BatchCreate 入库,然后分别 WS 推送
func (s *NotifyService) PushBatch(ctx context.Context, payloads []*PushPayload) {
funcName := "service.notify_service.PushBatch"
if len(payloads) == 0 {
return
}
models := make([]*model.Notification, 0, len(payloads))
valid := make([]*PushPayload, 0, len(payloads))
for _, p := range payloads {
if p == nil || p.UserID <= 0 || p.Type == "" {
continue
}
models = append(models, s.buildModel(p))
valid = append(valid, p)
}
if err := s.notifyDAO.BatchCreate(ctx, models); err != nil {
logs.Warn(ctx, funcName, "通知批量入库失败,放弃 WS 推送",
zap.Int("count", len(models)), zap.Error(err))
return
}
// 入库成功后逐条异步推送
for i, n := range models {
go s.safePushWS(n, valid[i])
}
}
// ====== 内部辅助 ======
// buildModel 由 PushPayload 构造 Notification 持久化模型
// 空 Title 使用类型默认文案;空 TargetType 按业务类型映射为默认值
func (s *NotifyService) buildModel(p *PushPayload) *model.Notification {
title := p.Title
if title == "" {
if zh, ok := constants.NotifyTypeMap[p.Type]; ok {
title = zh
}
}
targetType := p.TargetType
if targetType == "" {
targetType = defaultTargetType(p.Type)
}
return &model.Notification{
UserID: p.UserID,
Type: p.Type,
Title: title,
Content: p.Content,
Extra: marshalExtra(p.Extra),
ActorID: p.ActorID,
TargetType: targetType,
TargetID: p.TargetID,
IsRead: false,
}
}
// safePushWS 序列化并通过 Redis Pub/Sub 推送 notify.new 事件
// 失败仅记录 Warn不影响持久化的通知记录
func (s *NotifyService) safePushWS(n *model.Notification, p *PushPayload) {
defer func() {
if r := recover(); r != nil {
logs.Warn(context.Background(), "service.notify_service.safePushWS",
"推送协程 panic", zap.Any("panic", r))
}
}()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
dtoItem := s.toNotificationDTO(ctx, n)
s.publishWS(ctx, n.UserID, constants.WSEventNotifyNew, dtoItem)
}
// publishWS 序列化推送消息并发布到用户频道
func (s *NotifyService) publishWS(ctx context.Context, userID int64, event string, data interface{}) {
if s.pubsub == nil {
return
}
push := ws.NewPushMessage(event, data)
bytes, err := ws.MarshalPush(push)
if err != nil {
logs.Warn(ctx, "service.notify_service.publishWS", "序列化推送失败",
zap.String("event", event), zap.Error(err))
return
}
if err := s.pubsub.Publish(ctx, userID, bytes); err != nil {
logs.Warn(ctx, "service.notify_service.publishWS", "WS 推送失败",
zap.Int64("user_id", userID), zap.String("event", event), zap.Error(err))
}
}
// toNotificationDTO 将 model 转为对外 DTO补全 actor 信息
func (s *NotifyService) toNotificationDTO(ctx context.Context, n *model.Notification) dto.NotificationDTO {
item := dto.NotificationDTO{
ID: n.ID,
Type: n.Type,
Category: constants.NotifyCategoryOfType(n.Type),
Title: n.Title,
Content: n.Content,
Extra: n.Extra,
ActorID: n.ActorID,
TargetType: n.TargetType,
TargetID: n.TargetID,
IsRead: n.IsRead,
CreatedAt: n.CreatedAt.Format("2006-01-02 15:04:05"),
}
if n.ReadAt != nil {
item.ReadAt = n.ReadAt.Format("2006-01-02 15:04:05")
}
if n.ActorID != nil && *n.ActorID > 0 && s.userResolver != nil {
users, err := s.userResolver.GetUsersByIDs(ctx, []int64{*n.ActorID})
if err == nil && len(users) > 0 {
item.ActorName = users[0].Nickname
item.ActorAvatar = users[0].Avatar
}
}
return item
}
// toNotificationDTOs 批量转换 DTO 并一次性补全 actor 信息,避免 N+1 查询
func (s *NotifyService) toNotificationDTOs(ctx context.Context, list []model.Notification) []dto.NotificationDTO {
items := make([]dto.NotificationDTO, 0, len(list))
if len(list) == 0 {
return items
}
actorSet := make(map[int64]struct{})
for i := range list {
if list[i].ActorID != nil && *list[i].ActorID > 0 {
actorSet[*list[i].ActorID] = struct{}{}
}
}
userMap := make(map[int64]*authModel.User)
if len(actorSet) > 0 && s.userResolver != nil {
ids := make([]int64, 0, len(actorSet))
for id := range actorSet {
ids = append(ids, id)
}
users, err := s.userResolver.GetUsersByIDs(ctx, ids)
if err == nil {
for i := range users {
userMap[users[i].ID] = &users[i]
}
}
}
for i := range list {
n := &list[i]
item := dto.NotificationDTO{
ID: n.ID,
Type: n.Type,
Category: constants.NotifyCategoryOfType(n.Type),
Title: n.Title,
Content: n.Content,
Extra: n.Extra,
ActorID: n.ActorID,
TargetType: n.TargetType,
TargetID: n.TargetID,
IsRead: n.IsRead,
CreatedAt: n.CreatedAt.Format("2006-01-02 15:04:05"),
}
if n.ReadAt != nil {
item.ReadAt = n.ReadAt.Format("2006-01-02 15:04:05")
}
if n.ActorID != nil {
if u, ok := userMap[*n.ActorID]; ok {
item.ActorName = u.Nickname
item.ActorAvatar = u.Avatar
}
}
items = append(items, item)
}
return items
}
// typesByCategory 把前端的 category 参数转换为 type 列表
// all 或空字符串返回 nil不按类型过滤
func typesByCategory(category string) []string {
if category == "" || category == constants.NotifyCategoryAll {
return nil
}
if list, ok := constants.NotifyTypesByCategory[category]; ok {
return list
}
return nil
}
// defaultTargetType 根据通知类型推导默认业务对象类型
// 用于 PushPayload.TargetType 为空时的兜底
func defaultTargetType(notifyType string) string {
switch constants.NotifyCategoryOfType(notifyType) {
case constants.NotifyCategoryFriend:
return constants.NotifyTargetUser
case constants.NotifyCategoryGroup:
return constants.NotifyTargetGroup
case constants.NotifyCategoryMeeting:
return constants.NotifyTargetMeeting
default:
return constants.NotifyTargetSystem
}
}
// ====== 管理员广播 ======
// Broadcast 向所有正常用户发送系统公告
// 查询活跃用户 ID → 构造 payload → 批量入库 + 推送
// 返回受影响用户数
func (s *NotifyService) Broadcast(ctx context.Context, operatorID int64, req *dto.BroadcastNotificationRequest) (int, error) {
funcName := "service.notify_service.Broadcast"
logs.Info(ctx, funcName, "管理员广播",
zap.Int64("operator_id", operatorID), zap.String("title", req.Title))
userIDs, err := s.notifyDAO.ListAllActiveUserIDs(ctx)
if err != nil {
return 0, err
}
if len(userIDs) == 0 {
return 0, nil
}
targetType := req.TargetType
if targetType == "" {
targetType = constants.NotifyTargetSystem
}
payloads := make([]*PushPayload, 0, len(userIDs))
for _, uid := range userIDs {
payloads = append(payloads, &PushPayload{
UserID: uid,
Type: constants.NotifyTypeSystemBroadcast,
Title: req.Title,
Content: req.Content,
ActorID: &operatorID,
TargetType: targetType,
TargetID: req.TargetID,
Extra: req.Extra,
})
}
s.PushBatch(ctx, payloads)
return len(payloads), nil
}

View File

@@ -0,0 +1,66 @@
// Package service 提供 notify 模块的业务逻辑
package service
import (
"context"
"encoding/json"
authModel "github.com/echochat/backend/app/auth/model"
)
// PushPayload 跨模块推送通知的统一入参
// 由上游业务模块contact/group/admin/meeting构造并传递给 Pusher
type PushPayload struct {
UserID int64 // 接收者用户 ID必填
Type string // 通知类型常量,见 constants.NotifyType*
Title string // 通知标题(可选,为空时使用类型默认文案)
Content string // 通知副文案
ActorID *int64 // 触发主体用户 ID申请人/邀请人等),系统广播为 nil
TargetType string // 业务对象类型user / group / meeting / system
TargetID *int64 // 业务对象 ID
Extra interface{} // 扩展数据,内部会序列化为 JSON 字符串存入 extra 列
}
// Pusher 通知推送接口
// 由 notify 模块实现,供 contact / group / admin / meeting 等上游模块注入调用
// 实现原则:
// 1. 入库 + WS 推送 双动作WS 推送失败不回滚入库(降级策略)
// 2. 同步调用可能阻塞业务,实现内部使用 goroutine 异步处理
// 3. 一个 PushPayload 对应单个接收者;批量场景请多次调用
type Pusher interface {
Push(ctx context.Context, payload *PushPayload)
PushBatch(ctx context.Context, payloads []*PushPayload)
}
// UserInfoResolver 查询用户昵称 / 头像的接口,用于补全通知中的 actor 信息
// 由 contact.FriendshipDAO 隐式实现(已有 GetUsersByIDs 方法)
type UserInfoResolver interface {
GetUsersByIDs(ctx context.Context, userIDs []int64) ([]authModel.User, error)
}
// marshalExtra 将 Extra 字段序列化为 JSON 字符串,供 DAO 写入 jsonb 列
// 空值返回 nil若调用方已传入合法 JSON 字符串string 或 *string直接透传其余类型走 json.Marshal
func marshalExtra(extra interface{}) *string {
if extra == nil {
return nil
}
switch v := extra.(type) {
case string:
if v == "" {
return nil
}
return &v
case *string:
if v == nil || *v == "" {
return nil
}
cp := *v
return &cp
}
bytes, err := json.Marshal(extra)
if err != nil {
return nil
}
s := string(bytes)
return &s
}

View File

@@ -0,0 +1,83 @@
// Package task 提供 notify 模块的后台定时任务
package task
import (
"context"
"time"
"github.com/echochat/backend/app/notify/dao"
"github.com/echochat/backend/pkg/logs"
"go.uber.org/zap"
)
// 默认每日凌晨 3 点执行一次,通过固定周期 24h 近似实现
// 如需精确到凌晨可在未来引入 robfig/cron 库替换 Ticker
const defaultInterval = 24 * time.Hour
// CleanupTask 过期通知清理任务
// 周期扫描 notify_notifications删除已读且超过 constants.NotifyRetentionDays 天的记录
// 未读通知无论多久都不清理
type CleanupTask struct {
notifyDAO *dao.NotificationDAO
interval time.Duration
stopCh chan struct{}
}
// NewCleanupTask 创建 CleanupTask 实例
// 默认周期 24 小时
func NewCleanupTask(notifyDAO *dao.NotificationDAO) *CleanupTask {
return &CleanupTask{
notifyDAO: notifyDAO,
interval: defaultInterval,
stopCh: make(chan struct{}),
}
}
// Start 启动定时任务(非阻塞)
// 应在 main 进程启动后调用,进程退出时调用 Stop 释放 goroutine
func (t *CleanupTask) Start() {
funcName := "task.cleanup_task.Start"
logs.Info(nil, funcName, "启动通知清理任务", zap.Duration("interval", t.interval))
go func() {
// 启动时延迟 30s 再执行,避免与启动迁移 / 初始化竞争资源
warmup := time.NewTimer(30 * time.Second)
select {
case <-t.stopCh:
warmup.Stop()
return
case <-warmup.C:
}
t.runOnce()
ticker := time.NewTicker(t.interval)
defer ticker.Stop()
for {
select {
case <-t.stopCh:
return
case <-ticker.C:
t.runOnce()
}
}
}()
}
// Stop 停止定时任务
func (t *CleanupTask) Stop() {
close(t.stopCh)
}
// runOnce 执行一次清理,带独立超时控制
func (t *CleanupTask) runOnce() {
funcName := "task.cleanup_task.runOnce"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
affected, err := t.notifyDAO.DeleteExpired(ctx)
if err != nil {
logs.Warn(ctx, funcName, "通知清理失败", zap.Error(err))
return
}
logs.Info(ctx, funcName, "通知清理完成", zap.Int64("deleted", affected))
}

View File

@@ -11,6 +11,9 @@ import (
groupController "github.com/echochat/backend/app/group/controller"
imController "github.com/echochat/backend/app/im/controller"
imHandler "github.com/echochat/backend/app/im/handler"
notifyController "github.com/echochat/backend/app/notify/controller"
notifyService "github.com/echochat/backend/app/notify/service"
notifyTask "github.com/echochat/backend/app/notify/task"
wsApp "github.com/echochat/backend/app/ws"
"github.com/echochat/backend/config"
"github.com/echochat/backend/pkg/db"
@@ -46,6 +49,9 @@ type App struct {
OfflinePusher *imHandler.OfflinePusher // 离线消息推送器
FileController *fileController.FileController // 文件上传控制器
GroupController *groupController.GroupController // 群聊管理控制器
NotifyService *notifyService.NotifyService // 通知业务服务(兼 Pusher、ConnectHook
NotifyController *notifyController.NotificationController // 通知控制器
NotifyCleanupTask *notifyTask.CleanupTask // 通知清理定时任务
}
// NewApp 创建应用实例
@@ -72,9 +78,12 @@ func NewApp(
offlinePusher *imHandler.OfflinePusher,
fileCtrl *fileController.FileController,
groupCtrl *groupController.GroupController,
notifySvc *notifyService.NotifyService,
notifyCtrl *notifyController.NotificationController,
notifyCleanup *notifyTask.CleanupTask,
) *App {
// 注入离线消息推送器到 WS Handler
wsHandler.SetOfflinePusher(offlinePusher)
wsHandler.SetNotifyConnectHook(notifySvc)
return &App{
Config: cfg,
@@ -99,6 +108,9 @@ func NewApp(
OfflinePusher: offlinePusher,
FileController: fileCtrl,
GroupController: groupCtrl,
NotifyService: notifySvc,
NotifyController: notifyCtrl,
NotifyCleanupTask: notifyCleanup,
}
}

View File

@@ -17,6 +17,8 @@ import (
imApp "github.com/echochat/backend/app/im"
imDAO "github.com/echochat/backend/app/im/dao"
imService "github.com/echochat/backend/app/im/service"
notifyApp "github.com/echochat/backend/app/notify"
notifyService "github.com/echochat/backend/app/notify/service"
wsApp "github.com/echochat/backend/app/ws"
"github.com/echochat/backend/config"
"github.com/google/wire"
@@ -33,6 +35,7 @@ func InitializeApp(cfg *config.Config) (*App, error) {
imApp.IMSet,
fileApp.FileSet,
groupApp.GroupSet,
notifyApp.NotifySet,
wire.Bind(new(wsApp.FriendIDsGetter), new(*contactDAO.FriendshipDAO)),
wire.Bind(new(groupService.UserInfoProvider), new(*contactDAO.FriendshipDAO)),
wire.Bind(new(imService.GroupInfoGetter), new(*groupDAO.GroupDAO)),
@@ -42,6 +45,9 @@ func InitializeApp(cfg *config.Config) (*App, error) {
wire.Bind(new(imService.UserInfoGetter), new(*contactDAO.FriendshipDAO)),
wire.Bind(new(contactService.OnlineChecker), new(*wsApp.OnlineService)),
wire.Bind(new(groupService.MessageWriter), new(*imDAO.MessageDAO)),
wire.Bind(new(notifyService.UserInfoResolver), new(*contactDAO.FriendshipDAO)),
wire.Bind(new(contactService.NotifyPusher), new(*notifyService.NotifyService)),
wire.Bind(new(groupService.NotifyPusher), new(*notifyService.NotifyService)),
)
return nil, nil
}

View File

@@ -22,6 +22,10 @@ import (
dao4 "github.com/echochat/backend/app/group/dao"
service5 "github.com/echochat/backend/app/group/service"
imApp "github.com/echochat/backend/app/im"
controller6 "github.com/echochat/backend/app/notify/controller"
dao5 "github.com/echochat/backend/app/notify/dao"
service6 "github.com/echochat/backend/app/notify/service"
task2 "github.com/echochat/backend/app/notify/task"
"github.com/echochat/backend/app/ws"
"github.com/echochat/backend/config"
"github.com/echochat/backend/pkg/db"
@@ -67,7 +71,14 @@ func InitializeApp(cfg *config.Config) (*App, error) {
contactManageController := controller2.NewContactManageController(contactManageService)
handler := ws.ProvideWSHandler(hub, pubSub, jwtConfig, onlineService, authService)
friendGroupDAO := dao3.NewFriendGroupDAO(gormDB)
contactService := service3.NewContactService(friendshipDAO, friendGroupDAO, pubSub, onlineService)
// Notify 模块初始化contact/group 依赖 NotifyPusher
notificationDAO := dao5.NewNotificationDAO(gormDB)
notifyService := service6.NewNotifyService(notificationDAO, pubSub, friendshipDAO)
notificationController := controller6.NewNotificationController(notifyService)
notifyCleanupTask := task2.NewCleanupTask(notificationDAO)
contactService := service3.NewContactService(friendshipDAO, friendGroupDAO, onlineService, notifyService)
contactController := controller3.NewContactController(contactService)
// IM 模块初始化
@@ -86,7 +97,7 @@ func InitializeApp(cfg *config.Config) (*App, error) {
// Group 模块初始化
joinRequestDAO := dao4.NewJoinRequestDAO(gormDB)
groupService := service5.NewGroupService(groupDAO, joinRequestDAO, friendshipDAO, pubSub, messageDAO)
groupService := service5.NewGroupService(groupDAO, joinRequestDAO, friendshipDAO, pubSub, messageDAO, notifyService)
groupController := controller5.NewGroupController(groupService)
// Admin 群组管理初始化
@@ -98,6 +109,6 @@ func InitializeApp(cfg *config.Config) (*App, error) {
messageManageService := service2.NewMessageManageService(messageManageDAO, userDAO, conversationDAO, pubSub)
messageManageController := controller2.NewMessageManageController(messageManageService)
app := NewApp(cfg, gormDB, client, minioClient, authService, authController, adminAuthController, userManageController, onlineController, contactManageController, groupManageController, messageManageController, handler, hub, pubSub, onlineService, contactController, imController, imEventHandler, offlinePusher, fileController, groupController)
app := NewApp(cfg, gormDB, client, minioClient, authService, authController, adminAuthController, userManageController, onlineController, contactManageController, groupManageController, messageManageController, handler, hub, pubSub, onlineService, contactController, imController, imEventHandler, offlinePusher, fileController, groupController, notifyService, notificationController, notifyCleanupTask)
return app, nil
}

View File

@@ -27,6 +27,14 @@ type OfflineMessagePusher interface {
PushOfflineMessages(ctx context.Context, userID int64)
}
// NotifyConnectHook 通知未读补偿钩子接口
// 由 notify.service.NotifyService 隐式实现
// WebSocket 连接建立后触发,向客户端推送 notify.unread.total 事件
// 用于断线重连场景下的徽标状态同步
type NotifyConnectHook interface {
PushUnreadTotalOnConnect(ctx context.Context, userID int64)
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
@@ -37,12 +45,13 @@ var upgrader = websocket.Upgrader{
// Handler WebSocket 连接处理器
type Handler struct {
hub *ws.Hub
pubsub *ws.PubSub
jwtCfg *config.JWTConfig
onlineService *OnlineService
tokenValidator TokenValidator
offlinePusher OfflineMessagePusher
hub *ws.Hub
pubsub *ws.PubSub
jwtCfg *config.JWTConfig
onlineService *OnlineService
tokenValidator TokenValidator
offlinePusher OfflineMessagePusher
notifyConnectHook NotifyConnectHook
}
// NewHandler 创建 WebSocket Handler 实例
@@ -61,6 +70,11 @@ func (h *Handler) SetOfflinePusher(pusher OfflineMessagePusher) {
h.offlinePusher = pusher
}
// SetNotifyConnectHook 设置通知未读补偿钩子(由 notify 模块在初始化时注入)
func (h *Handler) SetNotifyConnectHook(hook NotifyConnectHook) {
h.notifyConnectHook = hook
}
// Upgrade 处理 WebSocket 升级请求
// GET /ws?token=xxx → JWT 认证 → 升级连接 → 注册 Hub → 订阅 Redis 频道
func (h *Handler) Upgrade(c *gin.Context) {
@@ -121,6 +135,10 @@ func (h *Handler) Upgrade(c *gin.Context) {
if h.offlinePusher != nil {
go h.offlinePusher.PushOfflineMessages(context.Background(), claims.UserID)
}
if h.notifyConnectHook != nil {
go h.notifyConnectHook.PushUnreadTotalOnConnect(context.Background(), claims.UserID)
}
}
// createReadHandler 创建带生命周期管理的消息处理函数