feat(phase2c): 群聊与已读回执功能完整实现
Phase 2c 全部 14 个 Task 完成,包含: 后端(Go): - MinIO 文件存储服务集成(Docker + Go SDK + 通用上传 API) - Group 模块完整实现(DAO + Service + Controller + Router + Wire) - 18 个群管理 REST API + 11 个 WS 群事件推送 - 群创建/解散/邀请/踢人/退出/转让群主/设管理员/禁言/全体禁言/群公告/群昵称/免打扰/搜索 - IM Service 扩展(群消息发送/撤回 + @提醒 + 管理员无时限撤回) - 已读回执后端(单聊会话级 last_read_msg_id + 群聊消息级 im_message_reads) - 管理端群组管理(列表/详情/解散) - 数据库迁移(3 张新表 + 2 张表字段扩展) 前端(uni-app): - 群聊 Store + API 封装 + 11 个 WS 事件监听 - 已读回执 UI(单聊已读/未读标记 + 群聊 X人已读 + 已读详情页) - 7 个群聊页面(对话/创建/设置/成员/邀请/审批/搜索) - 会话列表改造(全部/单聊/群聊 Tab + @标记 + 免打扰标识) 管理端(Vue 3 + Element Plus): - 群组列表页(搜索/分页/详情弹窗/解散群聊) - 侧边栏群组管理入口 文档同步:进度/架构/设计/API/规范文档全部更新 Made-with: Cursor
This commit is contained in:
542
backend/go-service/app/group/controller/group_controller.go
Normal file
542
backend/go-service/app/group/controller/group_controller.go
Normal file
@@ -0,0 +1,542 @@
|
||||
// Package controller 提供 group 模块的 HTTP 接口处理
|
||||
package controller
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/echochat/backend/app/dto"
|
||||
"github.com/echochat/backend/app/group/service"
|
||||
"github.com/echochat/backend/pkg/middleware"
|
||||
"github.com/echochat/backend/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GroupController 群聊管理控制器(REST API)
|
||||
type GroupController struct {
|
||||
groupService *service.GroupService
|
||||
}
|
||||
|
||||
// NewGroupController 创建 GroupController 实例
|
||||
func NewGroupController(groupService *service.GroupService) *GroupController {
|
||||
return &GroupController{groupService: groupService}
|
||||
}
|
||||
|
||||
// CreateGroup 创建群聊
|
||||
// POST /api/v1/groups
|
||||
func (ctl *GroupController) CreateGroup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateGroupRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := ctl.groupService.CreateGroup(ctx, userID, &req)
|
||||
if err != nil {
|
||||
ctl.handleError(c, err, "创建群聊失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, result)
|
||||
}
|
||||
|
||||
// GetGroupDetail 获取群详情
|
||||
// GET /api/v1/groups/:id
|
||||
func (ctl *GroupController) GetGroupDetail(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := ctl.groupService.GetGroupDetail(ctx, userID, groupID)
|
||||
if err != nil {
|
||||
ctl.handleError(c, err, "获取群详情失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, result)
|
||||
}
|
||||
|
||||
// UpdateGroup 更新群信息
|
||||
// PUT /api/v1/groups/:id
|
||||
func (ctl *GroupController) UpdateGroup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.UpdateGroupRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.UpdateGroup(ctx, userID, groupID, &req); err != nil {
|
||||
ctl.handleError(c, err, "更新群信息失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// DissolveGroup 解散群聊
|
||||
// DELETE /api/v1/groups/:id
|
||||
func (ctl *GroupController) DissolveGroup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.DissolveGroup(ctx, userID, groupID); err != nil {
|
||||
ctl.handleError(c, err, "解散群聊失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// GetMembers 获取群成员列表
|
||||
// GET /api/v1/groups/:id/members
|
||||
func (ctl *GroupController) GetMembers(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := ctl.groupService.GetMembers(ctx, userID, groupID)
|
||||
if err != nil {
|
||||
ctl.handleError(c, err, "获取成员列表失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, result)
|
||||
}
|
||||
|
||||
// InviteMembers 邀请入群
|
||||
// POST /api/v1/groups/:id/members
|
||||
func (ctl *GroupController) InviteMembers(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.InviteMembersRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.InviteMembers(ctx, userID, groupID, req.UserIDs); err != nil {
|
||||
ctl.handleError(c, err, "邀请入群失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// KickMember 踢出成员
|
||||
// DELETE /api/v1/groups/:id/members/:uid
|
||||
func (ctl *GroupController) KickMember(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
targetID, err := strconv.ParseInt(c.Param("uid"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "用户 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.KickMember(ctx, userID, groupID, targetID); err != nil {
|
||||
ctl.handleError(c, err, "踢出成员失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// SetMemberRole 设置/取消管理员
|
||||
// PUT /api/v1/groups/:id/members/:uid/role
|
||||
func (ctl *GroupController) SetMemberRole(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
targetID, err := strconv.ParseInt(c.Param("uid"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "用户 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.SetRoleRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.SetMemberRole(ctx, userID, groupID, targetID, req.Role); err != nil {
|
||||
ctl.handleError(c, err, "设置角色失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// MuteMember 禁言/解除禁言
|
||||
// PUT /api/v1/groups/:id/members/:uid/mute
|
||||
func (ctl *GroupController) MuteMember(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
targetID, err := strconv.ParseInt(c.Param("uid"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "用户 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.MuteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.MuteMember(ctx, userID, groupID, targetID, req.IsMuted); err != nil {
|
||||
ctl.handleError(c, err, "操作失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// TransferOwner 转让群主
|
||||
// PUT /api/v1/groups/:id/transfer
|
||||
func (ctl *GroupController) TransferOwner(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.TransferOwnerRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.TransferOwner(ctx, userID, groupID, req.NewOwnerID); err != nil {
|
||||
ctl.handleError(c, err, "转让群主失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// LeaveGroup 退出群聊
|
||||
// DELETE /api/v1/groups/:id/members/me
|
||||
func (ctl *GroupController) LeaveGroup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.LeaveGroup(ctx, userID, groupID); err != nil {
|
||||
ctl.handleError(c, err, "退出群聊失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// UpdateNickname 修改群内昵称
|
||||
// PUT /api/v1/groups/:id/members/me/nickname
|
||||
func (ctl *GroupController) UpdateNickname(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.UpdateNicknameRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.UpdateNickname(ctx, userID, groupID, req.Nickname); err != nil {
|
||||
ctl.handleError(c, err, "修改昵称失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// SubmitJoinRequest 申请入群
|
||||
// POST /api/v1/groups/:id/join-requests
|
||||
func (ctl *GroupController) SubmitJoinRequest(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.JoinGroupRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.SubmitJoinRequest(ctx, userID, groupID, req.Message); err != nil {
|
||||
ctl.handleError(c, err, "申请入群失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// GetJoinRequests 获取入群申请列表
|
||||
// GET /api/v1/groups/:id/join-requests
|
||||
func (ctl *GroupController) GetJoinRequests(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := ctl.groupService.GetJoinRequests(ctx, userID, groupID)
|
||||
if err != nil {
|
||||
ctl.handleError(c, err, "获取入群申请失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, result)
|
||||
}
|
||||
|
||||
// ReviewJoinRequest 审批入群申请
|
||||
// PUT /api/v1/groups/:id/join-requests/:rid
|
||||
func (ctl *GroupController) ReviewJoinRequest(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
requestID, err := strconv.ParseInt(c.Param("rid"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "申请 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.ReviewJoinRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.ReviewJoinRequest(ctx, userID, groupID, requestID, req.Action); err != nil {
|
||||
ctl.handleError(c, err, "审批失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// SearchGroups 搜索群聊
|
||||
// GET /api/v1/groups/search?keyword=xx&page=1&page_size=20
|
||||
func (ctl *GroupController) SearchGroups(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
_, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.SearchGroupRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := ctl.groupService.SearchGroups(ctx, &req)
|
||||
if err != nil {
|
||||
ctl.handleError(c, err, "搜索群聊失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, result)
|
||||
}
|
||||
|
||||
// SetAllMuted 设置全体禁言
|
||||
// PUT /api/v1/groups/:id/all-mute
|
||||
func (ctl *GroupController) SetAllMuted(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID, ok := middleware.GetCurrentUserID(c)
|
||||
if !ok {
|
||||
utils.ResponseUnauthorized(c, "无法获取当前用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
utils.ResponseBadRequest(c, "群 ID 格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
IsAllMuted bool `json:"is_all_muted"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
utils.ResponseBadRequest(c, "参数校验失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctl.groupService.SetAllMuted(ctx, userID, groupID, body.IsAllMuted); err != nil {
|
||||
ctl.handleError(c, err, "设置全体禁言失败")
|
||||
return
|
||||
}
|
||||
utils.ResponseOK(c, nil)
|
||||
}
|
||||
|
||||
// handleError 统一业务错误映射
|
||||
// 已知业务错误 → 返回 Service 层定义的具体提示
|
||||
// 未知错误 → 返回 fallbackMsg(未传则默认"服务器内部错误")
|
||||
func (ctl *GroupController) handleError(c *gin.Context, err error, fallbackMsg ...string) {
|
||||
switch err {
|
||||
case service.ErrGroupNotFound:
|
||||
utils.ResponseNotFound(c, err.Error())
|
||||
case service.ErrGroupDissolved:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrNotGroupMember:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrNotGroupOwner:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrNotGroupAdmin:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrGroupFull:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrAlreadyMember:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrCannotKickHigherRole:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrOwnerCannotLeave:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrCannotMuteSelf:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrAlreadyMuted:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrUserMuted:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrGroupAllMuted:
|
||||
utils.ResponseForbidden(c, err.Error())
|
||||
case service.ErrPendingRequestExists:
|
||||
utils.ResponseBadRequest(c, err.Error())
|
||||
case service.ErrJoinRequestNotFound:
|
||||
utils.ResponseNotFound(c, err.Error())
|
||||
default:
|
||||
msg := "服务器内部错误"
|
||||
if len(fallbackMsg) > 0 && fallbackMsg[0] != "" {
|
||||
msg = fallbackMsg[0]
|
||||
}
|
||||
utils.ResponseError(c, msg)
|
||||
}
|
||||
}
|
||||
346
backend/go-service/app/group/dao/group_dao.go
Normal file
346
backend/go-service/app/group/dao/group_dao.go
Normal file
@@ -0,0 +1,346 @@
|
||||
// Package dao 提供 group 模块的数据库访问操作
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/app/constants"
|
||||
"github.com/echochat/backend/app/dto"
|
||||
"github.com/echochat/backend/app/group/model"
|
||||
imModel "github.com/echochat/backend/app/im/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GroupDAO 群聊数据访问对象
|
||||
type GroupDAO struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewGroupDAO 创建 GroupDAO 实例
|
||||
func NewGroupDAO(db *gorm.DB) *GroupDAO {
|
||||
return &GroupDAO{db: db}
|
||||
}
|
||||
|
||||
// CreateGroupWithMembers 在事务中创建群聊(会话 + 群信息 + 群成员)
|
||||
// 创建者自动成为群主(role=2)
|
||||
func (d *GroupDAO) CreateGroupWithMembers(ctx context.Context, ownerID int64, name, avatar string, memberIDs []int64) (*model.Group, error) {
|
||||
funcName := "dao.group_dao.CreateGroupWithMembers"
|
||||
logs.Info(ctx, funcName, "创建群聊",
|
||||
zap.Int64("owner_id", ownerID), zap.String("name", name), zap.Int("member_count", len(memberIDs)+1))
|
||||
|
||||
var group model.Group
|
||||
err := d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
conv := &imModel.Conversation{
|
||||
Type: constants.ConversationTypeGroup,
|
||||
CreatorID: ownerID,
|
||||
}
|
||||
if err := tx.Create(conv).Error; err != nil {
|
||||
logs.Error(ctx, funcName, "创建会话失败", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
group = model.Group{
|
||||
ConversationID: conv.ID,
|
||||
Name: name,
|
||||
Avatar: avatar,
|
||||
OwnerID: ownerID,
|
||||
MaxMembers: constants.GroupDefaultMaxMembers,
|
||||
Status: constants.GroupStatusNormal,
|
||||
}
|
||||
if err := tx.Create(&group).Error; err != nil {
|
||||
logs.Error(ctx, funcName, "创建群信息失败", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
ownerMember := &imModel.ConversationMember{
|
||||
ConversationID: conv.ID,
|
||||
UserID: ownerID,
|
||||
Role: constants.GroupRoleOwner,
|
||||
JoinedAt: &now,
|
||||
}
|
||||
if err := tx.Create(ownerMember).Error; err != nil {
|
||||
logs.Error(ctx, funcName, "创建群主成员记录失败", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
for _, uid := range memberIDs {
|
||||
member := &imModel.ConversationMember{
|
||||
ConversationID: conv.ID,
|
||||
UserID: uid,
|
||||
Role: constants.GroupRoleNormal,
|
||||
JoinedAt: &now,
|
||||
}
|
||||
if err := tx.Create(member).Error; err != nil {
|
||||
logs.Error(ctx, funcName, "创建群成员记录失败",
|
||||
zap.Int64("user_id", uid), zap.Error(err))
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "创建群聊失败", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// GetByID 根据群 ID 获取群信息
|
||||
func (d *GroupDAO) GetByID(ctx context.Context, groupID int64) (*model.Group, error) {
|
||||
funcName := "dao.group_dao.GetByID"
|
||||
logs.Debug(ctx, funcName, "获取群信息", zap.Int64("group_id", groupID))
|
||||
|
||||
var group model.Group
|
||||
err := d.db.WithContext(ctx).First(&group, groupID).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// GetByConversationID 根据会话 ID 获取群信息
|
||||
func (d *GroupDAO) GetByConversationID(ctx context.Context, conversationID int64) (*model.Group, error) {
|
||||
funcName := "dao.group_dao.GetByConversationID"
|
||||
logs.Debug(ctx, funcName, "按会话 ID 获取群信息", zap.Int64("conversation_id", conversationID))
|
||||
|
||||
var group model.Group
|
||||
err := d.db.WithContext(ctx).Where("conversation_id = ?", conversationID).First(&group).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// UpdateGroupInfo 更新群基本信息(名称/头像/公告/可搜索性)
|
||||
func (d *GroupDAO) UpdateGroupInfo(ctx context.Context, groupID int64, updates map[string]interface{}) error {
|
||||
funcName := "dao.group_dao.UpdateGroupInfo"
|
||||
logs.Info(ctx, funcName, "更新群信息", zap.Int64("group_id", groupID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&model.Group{}).
|
||||
Where("id = ?", groupID).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
// DissolveGroup 解散群聊(标记状态为已解散)
|
||||
func (d *GroupDAO) DissolveGroup(ctx context.Context, groupID int64) error {
|
||||
funcName := "dao.group_dao.DissolveGroup"
|
||||
logs.Info(ctx, funcName, "解散群聊", zap.Int64("group_id", groupID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&model.Group{}).
|
||||
Where("id = ?", groupID).
|
||||
Update("status", constants.GroupStatusDissolved).Error
|
||||
}
|
||||
|
||||
// TransferOwner 转让群主
|
||||
func (d *GroupDAO) TransferOwner(ctx context.Context, groupID, oldOwnerID, newOwnerID int64, conversationID int64) error {
|
||||
funcName := "dao.group_dao.TransferOwner"
|
||||
logs.Info(ctx, funcName, "转让群主",
|
||||
zap.Int64("group_id", groupID), zap.Int64("old_owner", oldOwnerID), zap.Int64("new_owner", newOwnerID))
|
||||
|
||||
return d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&model.Group{}).
|
||||
Where("id = ?", groupID).
|
||||
Update("owner_id", newOwnerID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, oldOwnerID).
|
||||
Update("role", constants.GroupRoleNormal).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, newOwnerID).
|
||||
Update("role", constants.GroupRoleOwner).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetAllMuted 设置/取消全体禁言
|
||||
func (d *GroupDAO) SetAllMuted(ctx context.Context, groupID int64, isMuted bool) error {
|
||||
funcName := "dao.group_dao.SetAllMuted"
|
||||
logs.Info(ctx, funcName, "设置全体禁言", zap.Int64("group_id", groupID), zap.Bool("is_muted", isMuted))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&model.Group{}).
|
||||
Where("id = ?", groupID).
|
||||
Update("is_all_muted", isMuted).Error
|
||||
}
|
||||
|
||||
// GetGroupBrief 获取群简要信息(满足 im/service.GroupInfoGetter 接口)
|
||||
func (d *GroupDAO) GetGroupBrief(ctx context.Context, conversationID int64) (*dto.GroupBrief, error) {
|
||||
funcName := "dao.group_dao.GetGroupBrief"
|
||||
logs.Debug(ctx, funcName, "获取群简要信息", zap.Int64("conversation_id", conversationID))
|
||||
|
||||
var group model.Group
|
||||
err := d.db.WithContext(ctx).Where("conversation_id = ?", conversationID).First(&group).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.GroupBrief{
|
||||
ID: group.ID,
|
||||
Name: group.Name,
|
||||
Avatar: group.Avatar,
|
||||
IsAllMuted: group.IsAllMuted,
|
||||
Status: group.Status,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetMemberCount 获取群成员数量
|
||||
func (d *GroupDAO) GetMemberCount(ctx context.Context, conversationID int64) (int64, error) {
|
||||
var count int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ?", conversationID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetMember 获取指定群成员记录
|
||||
func (d *GroupDAO) GetMember(ctx context.Context, conversationID, userID int64) (*imModel.ConversationMember, error) {
|
||||
funcName := "dao.group_dao.GetMember"
|
||||
logs.Debug(ctx, funcName, "查询群成员",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID))
|
||||
|
||||
var member imModel.ConversationMember
|
||||
err := d.db.WithContext(ctx).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, userID).
|
||||
First(&member).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &member, nil
|
||||
}
|
||||
|
||||
// GetMembers 获取群所有成员列表
|
||||
func (d *GroupDAO) GetMembers(ctx context.Context, conversationID int64) ([]imModel.ConversationMember, error) {
|
||||
funcName := "dao.group_dao.GetMembers"
|
||||
logs.Debug(ctx, funcName, "获取群成员列表", zap.Int64("conversation_id", conversationID))
|
||||
|
||||
var members []imModel.ConversationMember
|
||||
err := d.db.WithContext(ctx).
|
||||
Where("conversation_id = ?", conversationID).
|
||||
Order("role DESC, joined_at ASC").
|
||||
Find(&members).Error
|
||||
return members, err
|
||||
}
|
||||
|
||||
// GetMemberIDs 获取群所有成员 ID
|
||||
func (d *GroupDAO) GetMemberIDs(ctx context.Context, conversationID int64) ([]int64, error) {
|
||||
var ids []int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ?", conversationID).
|
||||
Pluck("user_id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// GetAdminIDs 获取群主和管理员 ID 列表(用于推送入群申请通知)
|
||||
func (d *GroupDAO) GetAdminIDs(ctx context.Context, conversationID int64) ([]int64, error) {
|
||||
var ids []int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND role >= ?", conversationID, constants.GroupRoleAdmin).
|
||||
Pluck("user_id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// AddMember 添加群成员
|
||||
func (d *GroupDAO) AddMember(ctx context.Context, conversationID, userID int64, role int) error {
|
||||
funcName := "dao.group_dao.AddMember"
|
||||
logs.Info(ctx, funcName, "添加群成员",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID))
|
||||
|
||||
now := time.Now()
|
||||
member := &imModel.ConversationMember{
|
||||
ConversationID: conversationID,
|
||||
UserID: userID,
|
||||
Role: role,
|
||||
JoinedAt: &now,
|
||||
}
|
||||
return d.db.WithContext(ctx).Create(member).Error
|
||||
}
|
||||
|
||||
// RemoveMember 移除群成员
|
||||
func (d *GroupDAO) RemoveMember(ctx context.Context, conversationID, userID int64) error {
|
||||
funcName := "dao.group_dao.RemoveMember"
|
||||
logs.Info(ctx, funcName, "移除群成员",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, userID).
|
||||
Delete(&imModel.ConversationMember{}).Error
|
||||
}
|
||||
|
||||
// UpdateMemberRole 更新成员角色
|
||||
func (d *GroupDAO) UpdateMemberRole(ctx context.Context, conversationID, userID int64, role int) error {
|
||||
funcName := "dao.group_dao.UpdateMemberRole"
|
||||
logs.Info(ctx, funcName, "更新成员角色",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID), zap.Int("role", role))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, userID).
|
||||
Update("role", role).Error
|
||||
}
|
||||
|
||||
// UpdateMemberMuted 更新成员禁言状态
|
||||
func (d *GroupDAO) UpdateMemberMuted(ctx context.Context, conversationID, userID int64, isMuted bool) error {
|
||||
funcName := "dao.group_dao.UpdateMemberMuted"
|
||||
logs.Info(ctx, funcName, "更新成员禁言状态",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID), zap.Bool("is_muted", isMuted))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, userID).
|
||||
Update("is_muted", isMuted).Error
|
||||
}
|
||||
|
||||
// UpdateMemberNickname 更新成员群内昵称
|
||||
func (d *GroupDAO) UpdateMemberNickname(ctx context.Context, conversationID, userID int64, nickname string) error {
|
||||
funcName := "dao.group_dao.UpdateMemberNickname"
|
||||
logs.Info(ctx, funcName, "更新群昵称",
|
||||
zap.Int64("conversation_id", conversationID), zap.Int64("user_id", userID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&imModel.ConversationMember{}).
|
||||
Where("conversation_id = ? AND user_id = ?", conversationID, userID).
|
||||
Update("nickname", nickname).Error
|
||||
}
|
||||
|
||||
// SearchGroups 搜索可发现的群聊(按群名称全文搜索)
|
||||
func (d *GroupDAO) SearchGroups(ctx context.Context, keyword string, offset, limit int) ([]model.Group, int64, error) {
|
||||
funcName := "dao.group_dao.SearchGroups"
|
||||
logs.Debug(ctx, funcName, "搜索群聊", zap.String("keyword", keyword))
|
||||
|
||||
var total int64
|
||||
query := d.db.WithContext(ctx).
|
||||
Model(&model.Group{}).
|
||||
Where("status = ? AND is_searchable = true AND to_tsvector('simple', name) @@ plainto_tsquery('simple', ?)",
|
||||
constants.GroupStatusNormal, keyword)
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
logs.Error(ctx, funcName, "搜索计数失败", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var groups []model.Group
|
||||
err := query.Offset(offset).Limit(limit).Order("created_at DESC").Find(&groups).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "搜索查询失败", zap.Error(err))
|
||||
return nil, 0, err
|
||||
}
|
||||
return groups, total, nil
|
||||
}
|
||||
112
backend/go-service/app/group/dao/join_request_dao.go
Normal file
112
backend/go-service/app/group/dao/join_request_dao.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/echochat/backend/app/constants"
|
||||
"github.com/echochat/backend/app/group/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// JoinRequestDAO 入群申请数据访问对象
|
||||
type JoinRequestDAO struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewJoinRequestDAO 创建 JoinRequestDAO 实例
|
||||
func NewJoinRequestDAO(db *gorm.DB) *JoinRequestDAO {
|
||||
return &JoinRequestDAO{db: db}
|
||||
}
|
||||
|
||||
// Create 创建入群申请
|
||||
func (d *JoinRequestDAO) Create(ctx context.Context, groupID, userID int64, message string) (*model.GroupJoinRequest, error) {
|
||||
funcName := "dao.join_request_dao.Create"
|
||||
logs.Info(ctx, funcName, "创建入群申请",
|
||||
zap.Int64("group_id", groupID), zap.Int64("user_id", userID))
|
||||
|
||||
req := &model.GroupJoinRequest{
|
||||
GroupID: groupID,
|
||||
UserID: userID,
|
||||
Message: message,
|
||||
Status: constants.JoinRequestStatusPending,
|
||||
}
|
||||
err := d.db.WithContext(ctx).Create(req).Error
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "创建入群申请失败", zap.Error(err))
|
||||
}
|
||||
return req, err
|
||||
}
|
||||
|
||||
// GetByID 根据 ID 获取入群申请
|
||||
func (d *JoinRequestDAO) GetByID(ctx context.Context, id int64) (*model.GroupJoinRequest, error) {
|
||||
var req model.GroupJoinRequest
|
||||
err := d.db.WithContext(ctx).First(&req, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &req, nil
|
||||
}
|
||||
|
||||
// GetPendingByGroupAndUser 查找用户对某群的待处理申请
|
||||
func (d *JoinRequestDAO) GetPendingByGroupAndUser(ctx context.Context, groupID, userID int64) (*model.GroupJoinRequest, error) {
|
||||
funcName := "dao.join_request_dao.GetPendingByGroupAndUser"
|
||||
logs.Debug(ctx, funcName, "查找待处理申请",
|
||||
zap.Int64("group_id", groupID), zap.Int64("user_id", userID))
|
||||
|
||||
var req model.GroupJoinRequest
|
||||
err := d.db.WithContext(ctx).
|
||||
Where("group_id = ? AND user_id = ? AND status = ?", groupID, userID, constants.JoinRequestStatusPending).
|
||||
First(&req).Error
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &req, nil
|
||||
}
|
||||
|
||||
// GetListByGroup 获取群的入群申请列表
|
||||
func (d *JoinRequestDAO) GetListByGroup(ctx context.Context, groupID int64) ([]model.GroupJoinRequest, error) {
|
||||
funcName := "dao.join_request_dao.GetListByGroup"
|
||||
logs.Debug(ctx, funcName, "获取入群申请列表", zap.Int64("group_id", groupID))
|
||||
|
||||
var requests []model.GroupJoinRequest
|
||||
err := d.db.WithContext(ctx).
|
||||
Where("group_id = ?", groupID).
|
||||
Order("created_at DESC").
|
||||
Find(&requests).Error
|
||||
return requests, err
|
||||
}
|
||||
|
||||
// Approve 通过入群申请
|
||||
func (d *JoinRequestDAO) Approve(ctx context.Context, id, reviewerID int64) error {
|
||||
funcName := "dao.join_request_dao.Approve"
|
||||
logs.Info(ctx, funcName, "通过入群申请",
|
||||
zap.Int64("request_id", id), zap.Int64("reviewer_id", reviewerID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&model.GroupJoinRequest{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": constants.JoinRequestStatusApproved,
|
||||
"reviewer_id": reviewerID,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// Reject 拒绝入群申请
|
||||
func (d *JoinRequestDAO) Reject(ctx context.Context, id, reviewerID int64) error {
|
||||
funcName := "dao.join_request_dao.Reject"
|
||||
logs.Info(ctx, funcName, "拒绝入群申请",
|
||||
zap.Int64("request_id", id), zap.Int64("reviewer_id", reviewerID))
|
||||
|
||||
return d.db.WithContext(ctx).
|
||||
Model(&model.GroupJoinRequest{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": constants.JoinRequestStatusRejected,
|
||||
"reviewer_id": reviewerID,
|
||||
}).Error
|
||||
}
|
||||
129
backend/go-service/app/group/dao/message_read_dao.go
Normal file
129
backend/go-service/app/group/dao/message_read_dao.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/echochat/backend/app/group/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// MessageReadDAO 消息已读记录数据访问对象
|
||||
type MessageReadDAO struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMessageReadDAO 创建 MessageReadDAO 实例
|
||||
func NewMessageReadDAO(db *gorm.DB) *MessageReadDAO {
|
||||
return &MessageReadDAO{db: db}
|
||||
}
|
||||
|
||||
// BatchCreate 批量创建已读记录(忽略重复冲突)
|
||||
func (d *MessageReadDAO) BatchCreate(ctx context.Context, reads []model.MessageRead) error {
|
||||
funcName := "dao.message_read_dao.BatchCreate"
|
||||
logs.Info(ctx, funcName, "批量创建已读记录", zap.Int("count", len(reads)))
|
||||
|
||||
if len(reads) == 0 {
|
||||
return nil
|
||||
}
|
||||
return d.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&reads).Error
|
||||
}
|
||||
|
||||
// GetReadCount 获取消息的已读人数
|
||||
func (d *MessageReadDAO) GetReadCount(ctx context.Context, messageID int64) (int64, error) {
|
||||
var count int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&model.MessageRead{}).
|
||||
Where("message_id = ?", messageID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetReadCountBatch 批量获取多条消息的已读人数
|
||||
func (d *MessageReadDAO) GetReadCountBatch(ctx context.Context, messageIDs []int64) (map[int64]int, error) {
|
||||
funcName := "dao.message_read_dao.GetReadCountBatch"
|
||||
logs.Debug(ctx, funcName, "批量获取已读计数", zap.Int("count", len(messageIDs)))
|
||||
|
||||
type result struct {
|
||||
MessageID int64 `gorm:"column:message_id"`
|
||||
ReadCount int `gorm:"column:read_count"`
|
||||
}
|
||||
|
||||
var results []result
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&model.MessageRead{}).
|
||||
Select("message_id, COUNT(*) as read_count").
|
||||
Where("message_id IN ?", messageIDs).
|
||||
Group("message_id").
|
||||
Scan(&results).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m := make(map[int64]int, len(results))
|
||||
for _, r := range results {
|
||||
m[r.MessageID] = r.ReadCount
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// GetReadUsers 获取消息的已读用户列表
|
||||
func (d *MessageReadDAO) GetReadUsers(ctx context.Context, messageID int64) ([]model.MessageRead, error) {
|
||||
funcName := "dao.message_read_dao.GetReadUsers"
|
||||
logs.Debug(ctx, funcName, "获取已读用户列表", zap.Int64("message_id", messageID))
|
||||
|
||||
var reads []model.MessageRead
|
||||
err := d.db.WithContext(ctx).
|
||||
Where("message_id = ?", messageID).
|
||||
Order("read_at ASC").
|
||||
Find(&reads).Error
|
||||
return reads, err
|
||||
}
|
||||
|
||||
// BatchCreateReads 批量标记消息已读(满足 im/service.MessageReadRecorder 接口)
|
||||
func (d *MessageReadDAO) BatchCreateReads(ctx context.Context, messageIDs []int64, userID int64) error {
|
||||
funcName := "dao.message_read_dao.BatchCreateReads"
|
||||
logs.Info(ctx, funcName, "批量标记已读",
|
||||
zap.Int64("user_id", userID), zap.Int("count", len(messageIDs)))
|
||||
|
||||
if len(messageIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
reads := make([]model.MessageRead, 0, len(messageIDs))
|
||||
for _, msgID := range messageIDs {
|
||||
reads = append(reads, model.MessageRead{
|
||||
MessageID: msgID,
|
||||
UserID: userID,
|
||||
})
|
||||
}
|
||||
return d.BatchCreate(ctx, reads)
|
||||
}
|
||||
|
||||
// GetReadUserIDs 获取消息的已读用户 ID 列表(满足 im/service.MessageReadRecorder 接口)
|
||||
func (d *MessageReadDAO) GetReadUserIDs(ctx context.Context, messageID int64) ([]int64, error) {
|
||||
funcName := "dao.message_read_dao.GetReadUserIDs"
|
||||
logs.Debug(ctx, funcName, "获取已读用户 ID 列表", zap.Int64("message_id", messageID))
|
||||
|
||||
var ids []int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&model.MessageRead{}).
|
||||
Where("message_id = ?", messageID).
|
||||
Pluck("user_id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// HasRead 检查用户是否已读某消息
|
||||
func (d *MessageReadDAO) HasRead(ctx context.Context, messageID, userID int64) (bool, error) {
|
||||
var count int64
|
||||
err := d.db.WithContext(ctx).
|
||||
Model(&model.MessageRead{}).
|
||||
Where("message_id = ? AND user_id = ?", messageID, userID).
|
||||
Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
27
backend/go-service/app/group/model/group.go
Normal file
27
backend/go-service/app/group/model/group.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Package model 定义 group 模块的数据库模型
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// Group 群聊信息模型,对应 im_groups 表
|
||||
// 与 im_conversations (type=2) 一对一关联
|
||||
// Status: 1=正常,2=已解散
|
||||
type Group struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"` // 群唯一标识
|
||||
ConversationID int64 `json:"conversation_id" gorm:"not null;uniqueIndex"` // 关联 im_conversations.id
|
||||
Name string `json:"name" gorm:"size:100;not null;default:''"` // 群名称
|
||||
Avatar string `json:"avatar" gorm:"size:500;default:''"` // 群头像 URL(MinIO)
|
||||
OwnerID int64 `json:"owner_id" gorm:"not null;index:idx_im_groups_owner"` // 群主用户 ID
|
||||
Notice string `json:"notice" gorm:"type:text;default:''"` // 群公告内容
|
||||
MaxMembers int `json:"max_members" gorm:"not null;default:200"` // 最大成员数
|
||||
IsSearchable bool `json:"is_searchable" gorm:"not null;default:true"` // 是否可被搜索发现
|
||||
IsAllMuted bool `json:"is_all_muted" gorm:"not null;default:false"` // 是否全体禁言
|
||||
Status int `json:"status" gorm:"not null;default:1"` // 群状态:1=正常,2=已解散
|
||||
CreatedAt time.Time `json:"created_at" gorm:"not null;autoCreateTime;type:timestamp(0)"` // 创建时间
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"not null;autoUpdateTime;type:timestamp(0)"` // 更新时间
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (Group) TableName() string {
|
||||
return "im_groups"
|
||||
}
|
||||
21
backend/go-service/app/group/model/join_request.go
Normal file
21
backend/go-service/app/group/model/join_request.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// GroupJoinRequest 入群申请模型,对应 im_group_join_requests 表
|
||||
// Status: 0=待审批,1=通过,2=拒绝
|
||||
type GroupJoinRequest struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"` // 申请唯一标识
|
||||
GroupID int64 `json:"group_id" gorm:"not null;index:idx_group_join_req_group"` // 目标群 ID
|
||||
UserID int64 `json:"user_id" gorm:"not null;index:idx_group_join_req_user"` // 申请人用户 ID
|
||||
Message string `json:"message" gorm:"type:text;default:''"` // 申请附言
|
||||
ReviewerID *int64 `json:"reviewer_id"` // 审批人用户 ID
|
||||
Status int `json:"status" gorm:"not null;default:0"` // 状态:0=待审批,1=通过,2=拒绝
|
||||
CreatedAt time.Time `json:"created_at" gorm:"not null;autoCreateTime;type:timestamp(0)"` // 申请时间
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"not null;autoUpdateTime;type:timestamp(0)"` // 更新时间
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (GroupJoinRequest) TableName() string {
|
||||
return "im_group_join_requests"
|
||||
}
|
||||
16
backend/go-service/app/group/model/message_read.go
Normal file
16
backend/go-service/app/group/model/message_read.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// MessageRead 群聊消息已读记录模型,对应 im_message_reads 表
|
||||
// 复合主键 (message_id, user_id),记录每条群消息的已读用户
|
||||
type MessageRead struct {
|
||||
MessageID int64 `json:"message_id" gorm:"primaryKey"` // 消息 ID
|
||||
UserID int64 `json:"user_id" gorm:"primaryKey"` // 已读用户 ID
|
||||
ReadAt time.Time `json:"read_at" gorm:"not null;autoCreateTime;type:timestamp(0)"` // 已读时间
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (MessageRead) TableName() string {
|
||||
return "im_message_reads"
|
||||
}
|
||||
18
backend/go-service/app/group/provider.go
Normal file
18
backend/go-service/app/group/provider.go
Normal file
@@ -0,0 +1,18 @@
|
||||
// Package group 群聊管理模块
|
||||
package group
|
||||
|
||||
import (
|
||||
"github.com/echochat/backend/app/group/controller"
|
||||
"github.com/echochat/backend/app/group/dao"
|
||||
"github.com/echochat/backend/app/group/service"
|
||||
"github.com/google/wire"
|
||||
)
|
||||
|
||||
// GroupSet 群聊模块 Wire Provider Set
|
||||
var GroupSet = wire.NewSet(
|
||||
dao.NewGroupDAO,
|
||||
dao.NewJoinRequestDAO,
|
||||
dao.NewMessageReadDAO,
|
||||
service.NewGroupService,
|
||||
controller.NewGroupController,
|
||||
)
|
||||
38
backend/go-service/app/group/router.go
Normal file
38
backend/go-service/app/group/router.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"github.com/echochat/backend/app/group/controller"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RegisterRoutes 注册 group 模块的所有路由(需要 JWT 中间件)
|
||||
func RegisterRoutes(r *gin.Engine, ctrl *controller.GroupController, jwtAuth gin.HandlerFunc) {
|
||||
authed := r.Group("/api/v1")
|
||||
authed.Use(jwtAuth)
|
||||
{
|
||||
// 群聊管理
|
||||
authed.POST("/groups", ctrl.CreateGroup)
|
||||
authed.GET("/groups/search", ctrl.SearchGroups)
|
||||
authed.GET("/groups/:id", ctrl.GetGroupDetail)
|
||||
authed.PUT("/groups/:id", ctrl.UpdateGroup)
|
||||
authed.DELETE("/groups/:id", ctrl.DissolveGroup)
|
||||
|
||||
// 群成员管理
|
||||
authed.GET("/groups/:id/members", ctrl.GetMembers)
|
||||
authed.POST("/groups/:id/members", ctrl.InviteMembers)
|
||||
authed.DELETE("/groups/:id/members/me", ctrl.LeaveGroup)
|
||||
authed.DELETE("/groups/:id/members/:uid", ctrl.KickMember)
|
||||
authed.PUT("/groups/:id/members/me/nickname", ctrl.UpdateNickname)
|
||||
authed.PUT("/groups/:id/members/:uid/role", ctrl.SetMemberRole)
|
||||
authed.PUT("/groups/:id/members/:uid/mute", ctrl.MuteMember)
|
||||
|
||||
// 群主转让 + 全体禁言
|
||||
authed.PUT("/groups/:id/transfer", ctrl.TransferOwner)
|
||||
authed.PUT("/groups/:id/all-mute", ctrl.SetAllMuted)
|
||||
|
||||
// 入群申请
|
||||
authed.POST("/groups/:id/join-requests", ctrl.SubmitJoinRequest)
|
||||
authed.GET("/groups/:id/join-requests", ctrl.GetJoinRequests)
|
||||
authed.PUT("/groups/:id/join-requests/:rid", ctrl.ReviewJoinRequest)
|
||||
}
|
||||
}
|
||||
940
backend/go-service/app/group/service/group_service.go
Normal file
940
backend/go-service/app/group/service/group_service.go
Normal file
@@ -0,0 +1,940 @@
|
||||
// Package service 提供 group 模块的业务逻辑
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
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/group/dao"
|
||||
"github.com/echochat/backend/app/group/model"
|
||||
imModel "github.com/echochat/backend/app/im/model"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/echochat/backend/pkg/ws"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrGroupNotFound = errors.New("群聊不存在")
|
||||
ErrGroupDissolved = errors.New("群聊已解散")
|
||||
ErrNotGroupMember = errors.New("你不是该群成员")
|
||||
ErrNotGroupOwner = errors.New("仅群主可执行此操作")
|
||||
ErrNotGroupAdmin = errors.New("仅群主或管理员可执行此操作")
|
||||
ErrGroupFull = errors.New("群成员已满")
|
||||
ErrAlreadyMember = errors.New("该用户已是群成员")
|
||||
ErrCannotKickHigherRole = errors.New("不能操作同级或更高权限的成员")
|
||||
ErrOwnerCannotLeave = errors.New("群主不能退出群聊,请先转让群主")
|
||||
ErrCannotMuteSelf = errors.New("不能禁言自己")
|
||||
ErrAlreadyMuted = errors.New("该成员已被禁言")
|
||||
ErrUserMuted = errors.New("你已被禁言,无法发送消息")
|
||||
ErrGroupAllMuted = errors.New("当前群已开启全体禁言")
|
||||
ErrPendingRequestExists = errors.New("已有待处理的入群申请")
|
||||
ErrJoinRequestNotFound = errors.New("入群申请不存在")
|
||||
)
|
||||
|
||||
// UserInfoProvider 获取用户信息的接口(通过接口注入,由 contact.FriendshipDAO 隐式实现)
|
||||
type UserInfoProvider interface {
|
||||
GetUsersByIDs(ctx context.Context, userIDs []int64) ([]authModel.User, error)
|
||||
}
|
||||
|
||||
// MessageWriter 写入系统消息的接口(由 im.MessageDAO 隐式实现)
|
||||
type MessageWriter interface {
|
||||
Create(ctx context.Context, msg *imModel.Message) error
|
||||
}
|
||||
|
||||
// GroupService 群聊业务服务
|
||||
type GroupService struct {
|
||||
groupDAO *dao.GroupDAO
|
||||
joinRequestDAO *dao.JoinRequestDAO
|
||||
userInfo UserInfoProvider
|
||||
pubsub *ws.PubSub
|
||||
msgWriter MessageWriter
|
||||
}
|
||||
|
||||
// NewGroupService 创建 GroupService 实例
|
||||
func NewGroupService(
|
||||
groupDAO *dao.GroupDAO,
|
||||
joinRequestDAO *dao.JoinRequestDAO,
|
||||
userInfo UserInfoProvider,
|
||||
pubsub *ws.PubSub,
|
||||
msgWriter MessageWriter,
|
||||
) *GroupService {
|
||||
return &GroupService{
|
||||
groupDAO: groupDAO,
|
||||
joinRequestDAO: joinRequestDAO,
|
||||
userInfo: userInfo,
|
||||
pubsub: pubsub,
|
||||
msgWriter: msgWriter,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateGroup 创建群聊
|
||||
func (s *GroupService) CreateGroup(ctx context.Context, ownerID int64, req *dto.CreateGroupRequest) (*dto.GroupDTO, error) {
|
||||
funcName := "service.group_service.CreateGroup"
|
||||
logs.Info(ctx, funcName, "创建群聊",
|
||||
zap.Int64("owner_id", ownerID), zap.String("name", req.Name), zap.Int("member_count", len(req.MemberIDs)))
|
||||
|
||||
group, err := s.groupDAO.CreateGroupWithMembers(ctx, ownerID, req.Name, req.Avatar, req.MemberIDs)
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "创建群聊失败", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 创建了群聊", s.getUserNickname(ctx, ownerID)))
|
||||
|
||||
allMemberIDs := append([]int64{ownerID}, req.MemberIDs...)
|
||||
s.pushToMembers(ctx, allMemberIDs, 0, "group.created", map[string]interface{}{
|
||||
"group_id": group.ID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"name": group.Name,
|
||||
"owner_id": ownerID,
|
||||
})
|
||||
|
||||
return s.toGroupDTO(group, int(len(req.MemberIDs)+1)), nil
|
||||
}
|
||||
|
||||
// GetGroupDetail 获取群详情(需要是群成员)
|
||||
func (s *GroupService) GetGroupDetail(ctx context.Context, userID, groupID int64) (*dto.GroupDTO, error) {
|
||||
funcName := "service.group_service.GetGroupDetail"
|
||||
logs.Debug(ctx, funcName, "获取群详情",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.groupDAO.GetByID(ctx, groupID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrGroupNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotGroupMember
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
count, _ := s.groupDAO.GetMemberCount(ctx, group.ConversationID)
|
||||
return s.toGroupDTO(group, int(count)), nil
|
||||
}
|
||||
|
||||
// UpdateGroup 更新群信息(群主或管理员)
|
||||
func (s *GroupService) UpdateGroup(ctx context.Context, userID, groupID int64, req *dto.UpdateGroupRequest) error {
|
||||
funcName := "service.group_service.UpdateGroup"
|
||||
logs.Info(ctx, funcName, "更新群信息",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, _, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
updates := make(map[string]interface{})
|
||||
if req.Name != nil {
|
||||
updates["name"] = *req.Name
|
||||
}
|
||||
if req.Avatar != nil {
|
||||
updates["avatar"] = *req.Avatar
|
||||
}
|
||||
if req.Notice != nil {
|
||||
updates["notice"] = *req.Notice
|
||||
}
|
||||
if req.IsSearchable != nil {
|
||||
updates["is_searchable"] = *req.IsSearchable
|
||||
}
|
||||
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := s.groupDAO.UpdateGroupInfo(ctx, groupID, updates); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.Notice != nil {
|
||||
s.writeSystemMessage(ctx, group.ConversationID,
|
||||
fmt.Sprintf("%s 更新了群公告", s.getUserNickname(ctx, userID)))
|
||||
}
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.info.update", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"operator_id": userID,
|
||||
"updates": updates,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DissolveGroup 解散群聊(仅群主)
|
||||
func (s *GroupService) DissolveGroup(ctx context.Context, userID, groupID int64) error {
|
||||
funcName := "service.group_service.DissolveGroup"
|
||||
logs.Info(ctx, funcName, "解散群聊",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if group.OwnerID != userID {
|
||||
return ErrNotGroupOwner
|
||||
}
|
||||
|
||||
memberIDs, _ := s.groupDAO.GetMemberIDs(ctx, group.ConversationID)
|
||||
|
||||
if err := s.groupDAO.DissolveGroup(ctx, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.writeSystemMessage(ctx, group.ConversationID, "群聊已解散")
|
||||
|
||||
s.pushToMembers(ctx, memberIDs, 0, "group.dissolved", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"operator_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMembers 获取群成员列表(需要是群成员)
|
||||
func (s *GroupService) GetMembers(ctx context.Context, userID, groupID int64) ([]dto.GroupMemberDTO, error) {
|
||||
funcName := "service.group_service.GetMembers"
|
||||
logs.Debug(ctx, funcName, "获取群成员列表",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotGroupMember
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
members, err := s.groupDAO.GetMembers(ctx, group.ConversationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userIDs := make([]int64, 0, len(members))
|
||||
for _, m := range members {
|
||||
userIDs = append(userIDs, m.UserID)
|
||||
}
|
||||
|
||||
userMap := make(map[int64]*authModel.User)
|
||||
if len(userIDs) > 0 && s.userInfo != nil {
|
||||
users, uErr := s.userInfo.GetUsersByIDs(ctx, userIDs)
|
||||
if uErr != nil {
|
||||
logs.Error(ctx, funcName, "批量查询用户信息失败", zap.Error(uErr))
|
||||
} else {
|
||||
for i := range users {
|
||||
userMap[users[i].ID] = &users[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list := make([]dto.GroupMemberDTO, 0, len(members))
|
||||
for _, m := range members {
|
||||
item := dto.GroupMemberDTO{
|
||||
UserID: m.UserID,
|
||||
Nickname: m.Nickname,
|
||||
Role: m.Role,
|
||||
IsMuted: m.IsMuted,
|
||||
}
|
||||
if m.JoinedAt != nil {
|
||||
item.JoinedAt = m.JoinedAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
if user, ok := userMap[m.UserID]; ok {
|
||||
item.UserNickname = user.Nickname
|
||||
item.Avatar = user.Avatar
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// InviteMembers 邀请用户入群(群主/管理员)
|
||||
func (s *GroupService) InviteMembers(ctx context.Context, userID, groupID int64, targetIDs []int64) error {
|
||||
funcName := "service.group_service.InviteMembers"
|
||||
logs.Info(ctx, funcName, "邀请入群",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID), zap.Int("count", len(targetIDs)))
|
||||
|
||||
group, _, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
count, err := s.groupDAO.GetMemberCount(ctx, group.ConversationID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int(count)+len(targetIDs) > group.MaxMembers {
|
||||
return ErrGroupFull
|
||||
}
|
||||
|
||||
addedIDs := make([]int64, 0, len(targetIDs))
|
||||
for _, uid := range targetIDs {
|
||||
existing, _ := s.groupDAO.GetMember(ctx, group.ConversationID, uid)
|
||||
if existing != nil {
|
||||
continue
|
||||
}
|
||||
if err := s.groupDAO.AddMember(ctx, group.ConversationID, uid, constants.GroupRoleNormal); err != nil {
|
||||
logs.Error(ctx, funcName, "添加成员失败", zap.Int64("target_id", uid), zap.Error(err))
|
||||
return err
|
||||
}
|
||||
addedIDs = append(addedIDs, uid)
|
||||
}
|
||||
|
||||
if len(addedIDs) > 0 {
|
||||
inviterName := s.getUserNickname(ctx, userID)
|
||||
addedNames := s.getUserNicknames(ctx, addedIDs)
|
||||
s.writeSystemMessage(ctx, group.ConversationID,
|
||||
fmt.Sprintf("%s 邀请 %s 加入了群聊", inviterName, joinNames(addedNames)))
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.member.join", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_ids": addedIDs,
|
||||
"operator_id": userID,
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// KickMember 踢出群成员(群主/管理员,不能操作同级或更高权限的成员)
|
||||
func (s *GroupService) KickMember(ctx context.Context, userID, groupID, targetID int64) error {
|
||||
funcName := "service.group_service.KickMember"
|
||||
logs.Info(ctx, funcName, "踢出成员",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID), zap.Int64("target_id", targetID))
|
||||
|
||||
group, operatorMember, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetMember, err := s.groupDAO.GetMember(ctx, group.ConversationID, targetID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if targetMember.Role >= operatorMember.Role {
|
||||
return ErrCannotKickHigherRole
|
||||
}
|
||||
|
||||
if err := s.groupDAO.RemoveMember(ctx, group.ConversationID, targetID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetName := s.getUserNickname(ctx, targetID)
|
||||
s.writeSystemMessage(ctx, group.ConversationID,
|
||||
fmt.Sprintf("%s 被移出了群聊", targetName))
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.member.kicked", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_id": targetID,
|
||||
"operator_id": userID,
|
||||
})
|
||||
s.pushToUser(ctx, targetID, "group.member.kicked", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_id": targetID,
|
||||
"operator_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMemberRole 设置/取消管理员(仅群主)
|
||||
func (s *GroupService) SetMemberRole(ctx context.Context, userID, groupID, targetID int64, role int) error {
|
||||
funcName := "service.group_service.SetMemberRole"
|
||||
logs.Info(ctx, funcName, "设置成员角色",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID),
|
||||
zap.Int64("target_id", targetID), zap.Int("role", role))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if group.OwnerID != userID {
|
||||
return ErrNotGroupOwner
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, targetID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.groupDAO.UpdateMemberRole(ctx, group.ConversationID, targetID, role); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetName := s.getUserNickname(ctx, targetID)
|
||||
if role == constants.GroupRoleAdmin {
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 被设为管理员", targetName))
|
||||
} else {
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 被取消管理员", targetName))
|
||||
}
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.role.update", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_id": targetID,
|
||||
"role": role,
|
||||
"operator_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MuteMember 禁言/解除禁言成员(群主/管理员)
|
||||
func (s *GroupService) MuteMember(ctx context.Context, userID, groupID, targetID int64, isMuted bool) error {
|
||||
funcName := "service.group_service.MuteMember"
|
||||
logs.Info(ctx, funcName, "更新禁言状态",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID),
|
||||
zap.Int64("target_id", targetID), zap.Bool("is_muted", isMuted))
|
||||
|
||||
if userID == targetID {
|
||||
return ErrCannotMuteSelf
|
||||
}
|
||||
|
||||
group, operatorMember, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetMember, err := s.groupDAO.GetMember(ctx, group.ConversationID, targetID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if targetMember.Role >= operatorMember.Role {
|
||||
return ErrCannotKickHigherRole
|
||||
}
|
||||
|
||||
if err := s.groupDAO.UpdateMemberMuted(ctx, group.ConversationID, targetID, isMuted); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.mute.update", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_id": targetID,
|
||||
"is_muted": isMuted,
|
||||
"operator_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LeaveGroup 退出群聊(群主不能退出,需先转让)
|
||||
func (s *GroupService) LeaveGroup(ctx context.Context, userID, groupID int64) error {
|
||||
funcName := "service.group_service.LeaveGroup"
|
||||
logs.Info(ctx, funcName, "退出群聊",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if group.OwnerID == userID {
|
||||
return ErrOwnerCannotLeave
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.groupDAO.RemoveMember(ctx, group.ConversationID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
userName := s.getUserNickname(ctx, userID)
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 退出了群聊", userName))
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.member.leave", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// TransferOwner 转让群主(仅群主)
|
||||
func (s *GroupService) TransferOwner(ctx context.Context, userID, groupID, newOwnerID int64) error {
|
||||
funcName := "service.group_service.TransferOwner"
|
||||
logs.Info(ctx, funcName, "转让群主",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID), zap.Int64("new_owner", newOwnerID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if group.OwnerID != userID {
|
||||
return ErrNotGroupOwner
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, newOwnerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.groupDAO.TransferOwner(ctx, groupID, userID, newOwnerID, group.ConversationID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
oldOwnerName := s.getUserNickname(ctx, userID)
|
||||
newOwnerName := s.getUserNickname(ctx, newOwnerID)
|
||||
s.writeSystemMessage(ctx, group.ConversationID,
|
||||
fmt.Sprintf("%s 将群主转让给了 %s", oldOwnerName, newOwnerName))
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.owner.transfer", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"old_owner_id": userID,
|
||||
"new_owner_id": newOwnerID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateNickname 修改群内昵称
|
||||
func (s *GroupService) UpdateNickname(ctx context.Context, userID, groupID int64, nickname string) error {
|
||||
funcName := "service.group_service.UpdateNickname"
|
||||
logs.Info(ctx, funcName, "修改群昵称",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotGroupMember
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return s.groupDAO.UpdateMemberNickname(ctx, group.ConversationID, userID, nickname)
|
||||
}
|
||||
|
||||
// SubmitJoinRequest 提交入群申请
|
||||
func (s *GroupService) SubmitJoinRequest(ctx context.Context, userID, groupID int64, message string) error {
|
||||
funcName := "service.group_service.SubmitJoinRequest"
|
||||
logs.Info(ctx, funcName, "提交入群申请",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existing, _ := s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if existing != nil {
|
||||
return ErrAlreadyMember
|
||||
}
|
||||
|
||||
pending, _ := s.joinRequestDAO.GetPendingByGroupAndUser(ctx, groupID, userID)
|
||||
if pending != nil {
|
||||
return ErrPendingRequestExists
|
||||
}
|
||||
|
||||
req, err := s.joinRequestDAO.Create(ctx, groupID, userID, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
adminIDs, _ := s.groupDAO.GetAdminIDs(ctx, group.ConversationID)
|
||||
userName := s.getUserNickname(ctx, userID)
|
||||
s.pushToMembers(ctx, adminIDs, 0, "group.join.request", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"request_id": req.ID,
|
||||
"user_id": userID,
|
||||
"user_nickname": userName,
|
||||
"message": message,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetJoinRequests 获取入群申请列表(群主/管理员)
|
||||
func (s *GroupService) GetJoinRequests(ctx context.Context, userID, groupID int64) ([]dto.JoinRequestDTO, error) {
|
||||
funcName := "service.group_service.GetJoinRequests"
|
||||
logs.Debug(ctx, funcName, "获取入群申请列表",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID))
|
||||
|
||||
_, _, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
requests, err := s.joinRequestDAO.GetListByGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userIDs := make([]int64, 0, len(requests))
|
||||
for _, r := range requests {
|
||||
userIDs = append(userIDs, r.UserID)
|
||||
}
|
||||
|
||||
userMap := make(map[int64]*authModel.User)
|
||||
if len(userIDs) > 0 && s.userInfo != nil {
|
||||
users, uErr := s.userInfo.GetUsersByIDs(ctx, userIDs)
|
||||
if uErr != nil {
|
||||
logs.Error(ctx, funcName, "批量查询用户信息失败", zap.Error(uErr))
|
||||
} else {
|
||||
for i := range users {
|
||||
userMap[users[i].ID] = &users[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list := make([]dto.JoinRequestDTO, 0, len(requests))
|
||||
for _, r := range requests {
|
||||
item := dto.JoinRequestDTO{
|
||||
ID: r.ID,
|
||||
GroupID: r.GroupID,
|
||||
UserID: r.UserID,
|
||||
Message: r.Message,
|
||||
Status: r.Status,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if user, ok := userMap[r.UserID]; ok {
|
||||
item.UserNickname = user.Nickname
|
||||
item.UserAvatar = user.Avatar
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// ReviewJoinRequest 审批入群申请(群主/管理员)
|
||||
func (s *GroupService) ReviewJoinRequest(ctx context.Context, userID, groupID, requestID int64, action string) error {
|
||||
funcName := "service.group_service.ReviewJoinRequest"
|
||||
logs.Info(ctx, funcName, "审批入群申请",
|
||||
zap.Int64("user_id", userID), zap.Int64("request_id", requestID), zap.String("action", action))
|
||||
|
||||
group, _, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := s.joinRequestDAO.GetByID(ctx, requestID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if req.GroupID != groupID || req.Status != constants.JoinRequestStatusPending {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
|
||||
if action == "approve" {
|
||||
count, _ := s.groupDAO.GetMemberCount(ctx, group.ConversationID)
|
||||
if int(count) >= group.MaxMembers {
|
||||
return ErrGroupFull
|
||||
}
|
||||
|
||||
if err := s.joinRequestDAO.Approve(ctx, requestID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.groupDAO.AddMember(ctx, group.ConversationID, req.UserID, constants.GroupRoleNormal); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newMemberName := s.getUserNickname(ctx, req.UserID)
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 加入了群聊", newMemberName))
|
||||
|
||||
s.pushToUser(ctx, req.UserID, "group.join.approved", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"request_id": requestID,
|
||||
})
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.member.join", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"user_ids": []int64{req.UserID},
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.joinRequestDAO.Reject(ctx, requestID, userID)
|
||||
}
|
||||
|
||||
// SearchGroups 搜索公开群
|
||||
func (s *GroupService) SearchGroups(ctx context.Context, req *dto.SearchGroupRequest) (*dto.SearchGroupResponse, error) {
|
||||
funcName := "service.group_service.SearchGroups"
|
||||
logs.Debug(ctx, funcName, "搜索群聊", zap.String("keyword", req.Keyword))
|
||||
|
||||
page := req.Page
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := req.PageSize
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
groups, total, err := s.groupDAO.SearchGroups(ctx, req.Keyword, offset, pageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := make([]dto.GroupDTO, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
count, _ := s.groupDAO.GetMemberCount(ctx, g.ConversationID)
|
||||
list = append(list, *s.toGroupDTO(&g, int(count)))
|
||||
}
|
||||
|
||||
return &dto.SearchGroupResponse{List: list, Total: total}, nil
|
||||
}
|
||||
|
||||
// SetAllMuted 设置/取消全体禁言(群主/管理员)
|
||||
func (s *GroupService) SetAllMuted(ctx context.Context, userID, groupID int64, isMuted bool) error {
|
||||
funcName := "service.group_service.SetAllMuted"
|
||||
logs.Info(ctx, funcName, "设置全体禁言",
|
||||
zap.Int64("user_id", userID), zap.Int64("group_id", groupID), zap.Bool("is_muted", isMuted))
|
||||
|
||||
group, _, err := s.checkGroupAdmin(ctx, groupID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.groupDAO.SetAllMuted(ctx, groupID, isMuted); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
operatorName := s.getUserNickname(ctx, userID)
|
||||
if isMuted {
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 开启了全体禁言", operatorName))
|
||||
} else {
|
||||
s.writeSystemMessage(ctx, group.ConversationID, fmt.Sprintf("%s 关闭了全体禁言", operatorName))
|
||||
}
|
||||
|
||||
s.pushToGroupMembers(ctx, group.ConversationID, 0, "group.mute.update", map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"conversation_id": group.ConversationID,
|
||||
"is_all_muted": isMuted,
|
||||
"operator_id": userID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ====== 内部辅助方法 ======
|
||||
|
||||
// getActiveGroup 获取群聊并校验是否存在且未解散
|
||||
func (s *GroupService) getActiveGroup(ctx context.Context, groupID int64) (*model.Group, error) {
|
||||
group, err := s.groupDAO.GetByID(ctx, groupID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrGroupNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if group.Status == constants.GroupStatusDissolved {
|
||||
return nil, ErrGroupDissolved
|
||||
}
|
||||
return group, nil
|
||||
}
|
||||
|
||||
// checkGroupAdmin 校验用户是群主或管理员
|
||||
func (s *GroupService) checkGroupAdmin(ctx context.Context, groupID, userID int64) (*model.Group, *imMember, error) {
|
||||
group, err := s.getActiveGroup(ctx, groupID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
member, err := s.groupDAO.GetMember(ctx, group.ConversationID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil, ErrNotGroupMember
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if member.Role < constants.GroupRoleAdmin {
|
||||
return nil, nil, ErrNotGroupAdmin
|
||||
}
|
||||
|
||||
return group, &imMember{
|
||||
UserID: member.UserID,
|
||||
Role: member.Role,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// imMember 内部使用的成员简要信息
|
||||
type imMember struct {
|
||||
UserID int64
|
||||
Role int
|
||||
}
|
||||
|
||||
// ====== 推送和系统消息辅助方法 ======
|
||||
|
||||
// pushToUser 向单个用户推送通知
|
||||
func (s *GroupService) pushToUser(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.Error(ctx, "service.group_service.pushToUser", "序列化推送消息失败", zap.Error(err))
|
||||
return
|
||||
}
|
||||
if err := s.pubsub.Publish(ctx, userID, bytes); err != nil {
|
||||
logs.Error(ctx, "service.group_service.pushToUser", "推送失败",
|
||||
zap.Int64("user_id", userID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// pushToMembers 向指定用户列表推送通知(排除 excludeUID)
|
||||
func (s *GroupService) pushToMembers(ctx context.Context, memberIDs []int64, excludeUID int64, event string, data interface{}) {
|
||||
if s.pubsub == nil || len(memberIDs) == 0 {
|
||||
return
|
||||
}
|
||||
push := ws.NewPushMessage(event, data)
|
||||
bytes, err := ws.MarshalPush(push)
|
||||
if err != nil {
|
||||
logs.Error(ctx, "service.group_service.pushToMembers", "序列化推送消息失败", zap.Error(err))
|
||||
return
|
||||
}
|
||||
for _, uid := range memberIDs {
|
||||
if uid == excludeUID {
|
||||
continue
|
||||
}
|
||||
if pErr := s.pubsub.Publish(ctx, uid, bytes); pErr != nil {
|
||||
logs.Error(ctx, "service.group_service.pushToMembers", "推送失败",
|
||||
zap.Int64("user_id", uid), zap.Error(pErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pushToGroupMembers 向群所有成员推送通知(通过 conversationID 查成员)
|
||||
func (s *GroupService) pushToGroupMembers(ctx context.Context, conversationID int64, excludeUID int64, event string, data interface{}) {
|
||||
memberIDs, err := s.groupDAO.GetMemberIDs(ctx, conversationID)
|
||||
if err != nil {
|
||||
logs.Error(ctx, "service.group_service.pushToGroupMembers", "获取成员列表失败", zap.Error(err))
|
||||
return
|
||||
}
|
||||
s.pushToMembers(ctx, memberIDs, excludeUID, event, data)
|
||||
}
|
||||
|
||||
// writeSystemMessage 写入系统消息到群会话
|
||||
func (s *GroupService) writeSystemMessage(ctx context.Context, conversationID int64, content string) {
|
||||
if s.msgWriter == nil {
|
||||
return
|
||||
}
|
||||
msg := &imModel.Message{
|
||||
ConversationID: conversationID,
|
||||
SenderID: 0,
|
||||
Type: constants.MessageTypeSystem,
|
||||
Content: content,
|
||||
Status: constants.MessageStatusNormal,
|
||||
}
|
||||
if err := s.msgWriter.Create(ctx, msg); err != nil {
|
||||
logs.Error(ctx, "service.group_service.writeSystemMessage", "写入系统消息失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// getUserNickname 获取单个用户昵称(推送文案使用,查询失败返回默认值)
|
||||
func (s *GroupService) getUserNickname(ctx context.Context, userID int64) string {
|
||||
if s.userInfo == nil {
|
||||
return "用户"
|
||||
}
|
||||
users, err := s.userInfo.GetUsersByIDs(ctx, []int64{userID})
|
||||
if err != nil || len(users) == 0 {
|
||||
return "用户"
|
||||
}
|
||||
return users[0].Nickname
|
||||
}
|
||||
|
||||
// getUserNicknames 批量获取用户昵称列表
|
||||
func (s *GroupService) getUserNicknames(ctx context.Context, userIDs []int64) []string {
|
||||
if s.userInfo == nil || len(userIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
users, err := s.userInfo.GetUsersByIDs(ctx, userIDs)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
nameMap := make(map[int64]string, len(users))
|
||||
for _, u := range users {
|
||||
nameMap[u.ID] = u.Nickname
|
||||
}
|
||||
names := make([]string, 0, len(userIDs))
|
||||
for _, id := range userIDs {
|
||||
if n, ok := nameMap[id]; ok {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// joinNames 将名称列表用顿号连接(中文习惯)
|
||||
func joinNames(names []string) string {
|
||||
if len(names) == 0 {
|
||||
return ""
|
||||
}
|
||||
result := names[0]
|
||||
for i := 1; i < len(names); i++ {
|
||||
result += "、" + names[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// toGroupDTO 将 model.Group 转换为 dto.GroupDTO
|
||||
func (s *GroupService) toGroupDTO(g *model.Group, memberCount int) *dto.GroupDTO {
|
||||
return &dto.GroupDTO{
|
||||
ID: g.ID,
|
||||
ConversationID: g.ConversationID,
|
||||
Name: g.Name,
|
||||
Avatar: g.Avatar,
|
||||
OwnerID: g.OwnerID,
|
||||
Notice: g.Notice,
|
||||
MaxMembers: g.MaxMembers,
|
||||
MemberCount: memberCount,
|
||||
IsSearchable: g.IsSearchable,
|
||||
IsAllMuted: g.IsAllMuted,
|
||||
Status: g.Status,
|
||||
CreatedAt: g.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user