style: add format

Signed-off-by: Xinwei Xiong(cubxxw-openim) <3293172751nss@gmail.com>
This commit is contained in:
Xinwei Xiong(cubxxw-openim) 2023-07-03 16:29:22 +08:00
parent 187ee9a375
commit 166ddb1e34
170 changed files with 4816 additions and 1279 deletions

View File

@ -52,8 +52,10 @@ func run(port int) error {
fmt.Println("api start init discov client") fmt.Println("api start init discov client")
var client discoveryregistry.SvcDiscoveryRegistry var client discoveryregistry.SvcDiscoveryRegistry
client, err = openKeeper.NewClient(config.Config.Zookeeper.ZkAddr, config.Config.Zookeeper.Schema, client, err = openKeeper.NewClient(config.Config.Zookeeper.ZkAddr, config.Config.Zookeeper.Schema,
openKeeper.WithFreq(time.Hour), openKeeper.WithUserNameAndPassword(config.Config.Zookeeper.Username, openKeeper.WithFreq(time.Hour), openKeeper.WithUserNameAndPassword(
config.Config.Zookeeper.Password), openKeeper.WithRoundRobin(), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger())) config.Config.Zookeeper.Username,
config.Config.Zookeeper.Password,
), openKeeper.WithRoundRobin(), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger()))
if err != nil { if err != nil {
return err return err
} }

View File

@ -1,11 +1,12 @@
package api package api
import ( import (
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/auth" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/auth"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
) )
type AuthApi rpcclient.Auth type AuthApi rpcclient.Auth

View File

@ -1,11 +1,12 @@
package api package api
import ( import (
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
) )
type ConversationApi rpcclient.Conversation type ConversationApi rpcclient.Conversation

View File

@ -1,8 +1,9 @@
package api package api
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
) )
func RequiredIf(fl validator.FieldLevel) bool { func RequiredIf(fl validator.FieldLevel) bool {

View File

@ -1,6 +1,11 @@
package api package api
import ( import (
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct" "github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct"
@ -12,10 +17,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"google.golang.org/protobuf/proto"
) )
type MessageApi struct { type MessageApi struct {

View File

@ -3,17 +3,18 @@ package api
import ( import (
"context" "context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
) )
func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.UniversalClient) *gin.Engine { func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.UniversalClient) *gin.Engine {

View File

@ -1,11 +1,12 @@
package api package api
import ( import (
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
) )
type StatisticsApi rpcclient.User type StatisticsApi rpcclient.User

View File

@ -5,6 +5,8 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
@ -12,7 +14,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
) )
type ThirdApi rpcclient.Third type ThirdApi rpcclient.Third
@ -65,7 +66,10 @@ func (o *ThirdApi) GetURL(c *gin.Context) {
} }
attachment, _ := strconv.ParseBool(c.Query("attachment")) attachment, _ := strconv.ParseBool(c.Query("attachment"))
c.Set(constant.OperationID, operationID) c.Set(constant.OperationID, operationID)
resp, err := o.Client.GetUrl(mcontext.SetOperationID(c, operationID), &third.GetUrlReq{Name: name, Expires: expires, Attachment: attachment}) resp, err := o.Client.GetUrl(
mcontext.SetOperationID(c, operationID),
&third.GetUrlReq{Name: name, Expires: expires, Attachment: attachment},
)
if err != nil { if err != nil {
if errs.ErrArgs.Is(err) { if errs.ErrArgs.Is(err) {
c.String(http.StatusBadRequest, err.Error()) c.String(http.StatusBadRequest, err.Error())

View File

@ -1,6 +1,8 @@
package api package api
import ( import (
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r" "github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct" "github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct"
@ -9,7 +11,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
) )
type UserApi rpcclient.User type UserApi rpcclient.User

View File

@ -78,7 +78,8 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
return http.CallBackPostReturn(ctx, url(), req, resp, config.Config.Callback.CallbackUserOffline) return http.CallBackPostReturn(ctx, url(), req, resp, config.Config.Callback.CallbackUserOffline)
} }
//func callbackUserOnline(operationID, userID string, platformID int, token string, isAppBackground bool, connID string) cbApi.CommonCallbackResp { // func callbackUserOnline(operationID, userID string, platformID int, token string, isAppBackground bool, connID
// string) cbApi.CommonCallbackResp {
// callbackResp := cbApi.CommonCallbackResp{OperationID: operationID} // callbackResp := cbApi.CommonCallbackResp{OperationID: operationID}
// if !config.Config.Callback.CallbackUserOnline.Enable { // if !config.Config.Callback.CallbackUserOnline.Enable {
// return callbackResp // return callbackResp
@ -99,7 +100,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// ConnID: connID, // ConnID: connID,
// } // }
// callbackUserOnlineResp := &cbApi.CallbackUserOnlineResp{CommonCallbackResp: &callbackResp} // callbackUserOnlineResp := &cbApi.CallbackUserOnlineResp{CommonCallbackResp: &callbackResp}
// if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserOnlineCommand, callbackUserOnlineReq, callbackUserOnlineResp, config.Config.Callback.CallbackUserOnline.CallbackTimeOut); err != nil { // if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserOnlineCommand,
// callbackUserOnlineReq, callbackUserOnlineResp, config.Config.Callback.CallbackUserOnline.CallbackTimeOut); err != nil
// {
// callbackResp.ErrCode = http2.StatusInternalServerError // callbackResp.ErrCode = http2.StatusInternalServerError
// callbackResp.ErrMsg = err.Error() // callbackResp.ErrMsg = err.Error()
// } // }
@ -124,7 +127,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// ConnID: connID, // ConnID: connID,
// } // }
// callbackUserOfflineResp := &cbApi.CallbackUserOfflineResp{CommonCallbackResp: &callbackResp} // callbackUserOfflineResp := &cbApi.CallbackUserOfflineResp{CommonCallbackResp: &callbackResp}
// if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserOfflineCommand, callbackOfflineReq, callbackUserOfflineResp, config.Config.Callback.CallbackUserOffline.CallbackTimeOut); err != nil { // if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserOfflineCommand,
// callbackOfflineReq, callbackUserOfflineResp, config.Config.Callback.CallbackUserOffline.CallbackTimeOut); err != nil
// {
// callbackResp.ErrCode = http2.StatusInternalServerError // callbackResp.ErrCode = http2.StatusInternalServerError
// callbackResp.ErrMsg = err.Error() // callbackResp.ErrMsg = err.Error()
// } // }
@ -148,7 +153,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// Seq: int(time.Now().UnixNano() / 1e6), // Seq: int(time.Now().UnixNano() / 1e6),
// } // }
// callbackUserKickOffResp := &cbApi.CallbackUserKickOffResp{CommonCallbackResp: &callbackResp} // callbackUserKickOffResp := &cbApi.CallbackUserKickOffResp{CommonCallbackResp: &callbackResp}
// if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserKickOffCommand, callbackUserKickOffReq, callbackUserKickOffResp, config.Config.Callback.CallbackUserOffline.CallbackTimeOut); err != nil { // if err := http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, constant.CallbackUserKickOffCommand,
// callbackUserKickOffReq, callbackUserKickOffResp, config.Config.Callback.CallbackUserOffline.CallbackTimeOut); err !=
// nil {
// callbackResp.ErrCode = http2.StatusInternalServerError // callbackResp.ErrCode = http2.StatusInternalServerError
// callbackResp.ErrMsg = err.Error() // callbackResp.ErrMsg = err.Error()
// } // }

View File

@ -7,13 +7,14 @@ import (
"runtime/debug" "runtime/debug"
"sync" "sync"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/protobuf/proto"
) )
var ErrConnClosed = errors.New("conn has closed") var ErrConnClosed = errors.New("conn has closed")
@ -65,7 +66,13 @@ func newClient(ctx *UserConnContext, conn LongConn, isCompress bool) *Client {
ctx: ctx, ctx: ctx,
} }
} }
func (c *Client) ResetClient(ctx *UserConnContext, conn LongConn, isBackground, isCompress bool, longConnServer LongConnServer) {
func (c *Client) ResetClient(
ctx *UserConnContext,
conn LongConn,
isBackground, isCompress bool,
longConnServer LongConnServer,
) {
c.w = new(sync.Mutex) c.w = new(sync.Mutex)
c.conn = conn c.conn = conn
c.PlatformID = utils.StringToInt(ctx.GetPlatformID()) c.PlatformID = utils.StringToInt(ctx.GetPlatformID())
@ -145,7 +152,9 @@ func (c *Client) handleMessage(message []byte) error {
if binaryReq.SendID != c.UserID { if binaryReq.SendID != c.UserID {
return utils.Wrap(errors.New("exception conn userID not same to req userID"), binaryReq.String()) return utils.Wrap(errors.New("exception conn userID not same to req userID"), binaryReq.String())
} }
ctx := mcontext.WithMustInfoCtx([]string{binaryReq.OperationID, binaryReq.SendID, constant.PlatformIDToName(c.PlatformID), c.ctx.GetConnID()}) ctx := mcontext.WithMustInfoCtx(
[]string{binaryReq.OperationID, binaryReq.SendID, constant.PlatformIDToName(c.PlatformID), c.ctx.GetConnID()},
)
log.ZDebug(ctx, "gateway req message", "req", binaryReq.String()) log.ZDebug(ctx, "gateway req message", "req", binaryReq.String())
var messageErr error var messageErr error
var resp []byte var resp []byte
@ -163,7 +172,12 @@ func (c *Client) handleMessage(message []byte) error {
case WsSetBackgroundStatus: case WsSetBackgroundStatus:
resp, messageErr = c.setAppBackgroundStatus(ctx, binaryReq) resp, messageErr = c.setAppBackgroundStatus(ctx, binaryReq)
default: default:
return fmt.Errorf("ReqIdentifier failed,sendID:%s,msgIncr:%s,reqIdentifier:%d", binaryReq.SendID, binaryReq.MsgIncr, binaryReq.ReqIdentifier) return fmt.Errorf(
"ReqIdentifier failed,sendID:%s,msgIncr:%s,reqIdentifier:%d",
binaryReq.SendID,
binaryReq.MsgIncr,
binaryReq.ReqIdentifier,
)
} }
c.replyMessage(ctx, &binaryReq, messageErr, resp) c.replyMessage(ctx, &binaryReq, messageErr, resp)
return nil return nil

View File

@ -5,6 +5,8 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
@ -15,7 +17,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msggateway" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msggateway"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc" "github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
) )
func (s *Server) InitServer(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { func (s *Server) InitServer(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error {
@ -31,7 +32,12 @@ func (s *Server) InitServer(client discoveryregistry.SvcDiscoveryRegistry, serve
} }
func (s *Server) Start() error { func (s *Server) Start() error {
return startrpc.Start(s.rpcPort, config.Config.RpcRegisterName.OpenImMessageGatewayName, s.prometheusPort, s.InitServer) return startrpc.Start(
s.rpcPort,
config.Config.RpcRegisterName.OpenImMessageGatewayName,
s.prometheusPort,
s.InitServer,
)
} }
type Server struct { type Server struct {
@ -46,14 +52,24 @@ func (s *Server) SetLongConnServer(LongConnServer LongConnServer) {
} }
func NewServer(rpcPort int, longConnServer LongConnServer) *Server { func NewServer(rpcPort int, longConnServer LongConnServer) *Server {
return &Server{rpcPort: rpcPort, LongConnServer: longConnServer, pushTerminal: []int{constant.IOSPlatformID, constant.AndroidPlatformID}} return &Server{
rpcPort: rpcPort,
LongConnServer: longConnServer,
pushTerminal: []int{constant.IOSPlatformID, constant.AndroidPlatformID},
}
} }
func (s *Server) OnlinePushMsg(context context.Context, req *msggateway.OnlinePushMsgReq) (*msggateway.OnlinePushMsgResp, error) { func (s *Server) OnlinePushMsg(
context context.Context,
req *msggateway.OnlinePushMsgReq,
) (*msggateway.OnlinePushMsgResp, error) {
panic("implement me") panic("implement me")
} }
func (s *Server) GetUsersOnlineStatus(ctx context.Context, req *msggateway.GetUsersOnlineStatusReq) (*msggateway.GetUsersOnlineStatusResp, error) { func (s *Server) GetUsersOnlineStatus(
ctx context.Context,
req *msggateway.GetUsersOnlineStatusReq,
) (*msggateway.GetUsersOnlineStatusResp, error) {
if !tokenverify.IsAppManagerUid(ctx) { if !tokenverify.IsAppManagerUid(ctx) {
return nil, errs.ErrNoPermission.Wrap("only app manager") return nil, errs.ErrNoPermission.Wrap("only app manager")
} }
@ -83,11 +99,17 @@ func (s *Server) GetUsersOnlineStatus(ctx context.Context, req *msggateway.GetUs
return &resp, nil return &resp, nil
} }
func (s *Server) OnlineBatchPushOneMsg(ctx context.Context, req *msggateway.OnlineBatchPushOneMsgReq) (*msggateway.OnlineBatchPushOneMsgResp, error) { func (s *Server) OnlineBatchPushOneMsg(
ctx context.Context,
req *msggateway.OnlineBatchPushOneMsgReq,
) (*msggateway.OnlineBatchPushOneMsgResp, error) {
panic("implement me") panic("implement me")
} }
func (s *Server) SuperGroupOnlineBatchPushOneMsg(ctx context.Context, req *msggateway.OnlineBatchPushOneMsgReq) (*msggateway.OnlineBatchPushOneMsgResp, error) { func (s *Server) SuperGroupOnlineBatchPushOneMsg(
ctx context.Context,
req *msggateway.OnlineBatchPushOneMsgReq,
) (*msggateway.OnlineBatchPushOneMsgResp, error) {
var singleUserResult []*msggateway.SingleMsgToUserResults var singleUserResult []*msggateway.SingleMsgToUserResults
for _, v := range req.PushToUserIDs { for _, v := range req.PushToUserIDs {
var resp []*msggateway.SingleMsgToUserPlatform var resp []*msggateway.SingleMsgToUserPlatform
@ -108,7 +130,8 @@ func (s *Server) SuperGroupOnlineBatchPushOneMsg(ctx context.Context, req *msgga
RecvID: v, RecvID: v,
RecvPlatFormID: int32(client.PlatformID), RecvPlatFormID: int32(client.PlatformID),
} }
if !client.IsBackground || (client.IsBackground == true && client.PlatformID != constant.IOSPlatformID) { if !client.IsBackground ||
(client.IsBackground == true && client.PlatformID != constant.IOSPlatformID) {
err := client.PushMessage(ctx, req.MsgData) err := client.PushMessage(ctx, req.MsgData)
if err != nil { if err != nil {
temp.ResultCode = -2 temp.ResultCode = -2
@ -135,7 +158,10 @@ func (s *Server) SuperGroupOnlineBatchPushOneMsg(ctx context.Context, req *msgga
}, nil }, nil
} }
func (s *Server) KickUserOffline(ctx context.Context, req *msggateway.KickUserOfflineReq) (*msggateway.KickUserOfflineResp, error) { func (s *Server) KickUserOffline(
ctx context.Context,
req *msggateway.KickUserOfflineReq,
) (*msggateway.KickUserOfflineResp, error) {
for _, v := range req.KickUserIDList { for _, v := range req.KickUserIDList {
if clients, _, ok := s.LongConnServer.GetUserPlatformCons(v, int(req.PlatformID)); ok { if clients, _, ok := s.LongConnServer.GetUserPlatformCons(v, int(req.PlatformID)); ok {
for _, client := range clients { for _, client := range clients {
@ -149,7 +175,10 @@ func (s *Server) KickUserOffline(ctx context.Context, req *msggateway.KickUserOf
return &msggateway.KickUserOfflineResp{}, nil return &msggateway.KickUserOfflineResp{}, nil
} }
func (s *Server) MultiTerminalLoginCheck(ctx context.Context, req *msggateway.MultiTerminalLoginCheckReq) (*msggateway.MultiTerminalLoginCheckResp, error) { func (s *Server) MultiTerminalLoginCheck(
ctx context.Context,
req *msggateway.MultiTerminalLoginCheckReq,
) (*msggateway.MultiTerminalLoginCheckResp, error) {
//TODO implement me //TODO implement me
panic("implement me") panic("implement me")
} }

View File

@ -8,7 +8,14 @@ import (
) )
func RunWsAndServer(rpcPort, wsPort, prometheusPort int) error { func RunWsAndServer(rpcPort, wsPort, prometheusPort int) error {
fmt.Println("start rpc/msg_gateway server, port: ", rpcPort, wsPort, prometheusPort, ", OpenIM version: ", config.Version) fmt.Println(
"start rpc/msg_gateway server, port: ",
rpcPort,
wsPort,
prometheusPort,
", OpenIM version: ",
config.Version,
)
longServer, err := NewWsServer( longServer, err := NewWsServer(
WithPort(wsPort), WithPort(wsPort),
WithMaxConnNum(int64(config.Config.LongConnSvr.WebsocketMaxConnNum)), WithMaxConnNum(int64(config.Config.LongConnSvr.WebsocketMaxConnNum)),

View File

@ -6,17 +6,18 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push"
"github.com/go-playground/validator/v10"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/go-playground/validator/v10"
"google.golang.org/protobuf/proto"
) )
type Req struct { type Req struct {
ReqIdentifier int32 `json:"reqIdentifier" validate:"required"` ReqIdentifier int32 `json:"reqIdentifier" validate:"required"`
Token string `json:"token" ` Token string `json:"token"`
SendID string `json:"sendID" validate:"required"` SendID string `json:"sendID" validate:"required"`
OperationID string `json:"operationID" validate:"required"` OperationID string `json:"operationID" validate:"required"`
MsgIncr string `json:"msgIncr" validate:"required"` MsgIncr string `json:"msgIncr" validate:"required"`
@ -160,7 +161,8 @@ func (g GrpcHandler) SetUserDeviceBackground(_ context.Context, data Req) ([]byt
return nil, req.IsBackground, nil return nil, req.IsBackground, nil
} }
//func (g GrpcHandler) call[T any](ctx context.Context, data Req, m proto.Message, rpc func(ctx context.Context, req proto.Message)) ([]byte, error) { // func (g GrpcHandler) call[T any](ctx context.Context, data Req, m proto.Message, rpc func(ctx context.Context, req
// proto.Message)) ([]byte, error) {
// if err := proto.Unmarshal(data.Data, m); err != nil { // if err := proto.Unmarshal(data.Data, m); err != nil {
// return nil, err // return nil, err
// } // }

View File

@ -13,14 +13,16 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/go-playground/validator/v10"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/go-playground/validator/v10"
) )
type LongConnServer interface { type LongConnServer interface {
@ -169,7 +171,14 @@ func (ws *WsServer) registerClient(client *Client) {
atomic.AddInt64(&ws.onlineUserConnNum, 1) atomic.AddInt64(&ws.onlineUserConnNum, 1)
} }
} }
log.ZInfo(client.ctx, "user online", "online user Num", ws.onlineUserNum, "online user conn Num", ws.onlineUserConnNum) log.ZInfo(
client.ctx,
"user online",
"online user Num",
ws.onlineUserNum,
"online user conn Num",
ws.onlineUserConnNum,
)
} }
func getRemoteAdders(client []*Client) string { func getRemoteAdders(client []*Client) string {
var ret string var ret string
@ -200,18 +209,47 @@ func (ws *WsServer) multiTerminalLoginChecker(info *kickHandler) {
log.ZWarn(c.ctx, "KickOnlineMessage", err) log.ZWarn(c.ctx, "KickOnlineMessage", err)
} }
} }
m, err := ws.cache.GetTokensWithoutError(info.newClient.ctx, info.newClient.UserID, info.newClient.PlatformID) m, err := ws.cache.GetTokensWithoutError(
info.newClient.ctx,
info.newClient.UserID,
info.newClient.PlatformID,
)
if err != nil && err != redis.Nil { if err != nil && err != redis.Nil {
log.ZWarn(info.newClient.ctx, "get token from redis err", err, "userID", info.newClient.UserID, "platformID", info.newClient.PlatformID) log.ZWarn(
info.newClient.ctx,
"get token from redis err",
err,
"userID",
info.newClient.UserID,
"platformID",
info.newClient.PlatformID,
)
return return
} }
if m == nil { if m == nil {
log.ZWarn(info.newClient.ctx, "m is nil", errors.New("m is nil"), "userID", info.newClient.UserID, "platformID", info.newClient.PlatformID) log.ZWarn(
info.newClient.ctx,
"m is nil",
errors.New("m is nil"),
"userID",
info.newClient.UserID,
"platformID",
info.newClient.PlatformID,
)
return return
} }
log.ZDebug(info.newClient.ctx, "get token from redis", "userID", info.newClient.UserID, "platformID", info.newClient.PlatformID, "tokenMap", m) log.ZDebug(
info.newClient.ctx,
"get token from redis",
"userID",
info.newClient.UserID,
"platformID",
info.newClient.PlatformID,
"tokenMap",
m,
)
for k, _ := range m { for k := range m {
if k != info.newClient.ctx.GetToken() { if k != info.newClient.ctx.GetToken() {
m[k] = constant.KickedToken m[k] = constant.KickedToken
} }
@ -219,7 +257,15 @@ func (ws *WsServer) multiTerminalLoginChecker(info *kickHandler) {
log.ZDebug(info.newClient.ctx, "set token map is ", "token map", m, "userID", info.newClient.UserID) log.ZDebug(info.newClient.ctx, "set token map is ", "token map", m, "userID", info.newClient.UserID)
err = ws.cache.SetTokenMapByUidPid(info.newClient.ctx, info.newClient.UserID, info.newClient.PlatformID, m) err = ws.cache.SetTokenMapByUidPid(info.newClient.ctx, info.newClient.UserID, info.newClient.PlatformID, m)
if err != nil { if err != nil {
log.ZWarn(info.newClient.ctx, "SetTokenMapByUidPid err", err, "userID", info.newClient.UserID, "platformID", info.newClient.PlatformID) log.ZWarn(
info.newClient.ctx,
"SetTokenMapByUidPid err",
err,
"userID",
info.newClient.UserID,
"platformID",
info.newClient.PlatformID,
)
return return
} }
} }
@ -233,7 +279,16 @@ func (ws *WsServer) unregisterClient(client *Client) {
atomic.AddInt64(&ws.onlineUserNum, -1) atomic.AddInt64(&ws.onlineUserNum, -1)
} }
atomic.AddInt64(&ws.onlineUserConnNum, -1) atomic.AddInt64(&ws.onlineUserConnNum, -1)
log.ZInfo(client.ctx, "user offline", "close reason", client.closedErr, "online user Num", ws.onlineUserNum, "online user conn Num", ws.onlineUserConnNum) log.ZInfo(
client.ctx,
"user offline",
"close reason",
client.closedErr,
"online user Num",
ws.onlineUserNum,
"online user conn Num",
ws.onlineUserConnNum,
)
} }
func (ws *WsServer) wsHandler(w http.ResponseWriter, r *http.Request) { func (ws *WsServer) wsHandler(w http.ResponseWriter, r *http.Request) {

View File

@ -5,6 +5,9 @@ import (
"sync" "sync"
"time" "time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -17,8 +20,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome"
openKeeper "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper" openKeeper "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
) )
type MsgTransfer struct { type MsgTransfer struct {
@ -47,9 +48,18 @@ func StartTransfer(prometheusPort int) error {
if err := mongo.CreateMsgIndex(); err != nil { if err := mongo.CreateMsgIndex(); err != nil {
return err return err
} }
client, err := openKeeper.NewClient(config.Config.Zookeeper.ZkAddr, config.Config.Zookeeper.Schema, client, err := openKeeper.NewClient(
openKeeper.WithFreq(time.Hour), openKeeper.WithRoundRobin(), openKeeper.WithUserNameAndPassword(config.Config.Zookeeper.Username, config.Config.Zookeeper.ZkAddr,
config.Config.Zookeeper.Password), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger())) config.Config.Zookeeper.Schema,
openKeeper.WithFreq(
time.Hour,
),
openKeeper.WithRoundRobin(),
openKeeper.WithUserNameAndPassword(config.Config.Zookeeper.Username,
config.Config.Zookeeper.Password),
openKeeper.WithTimeout(10),
openKeeper.WithLogger(log.NewZkLogger()),
)
if err != nil { if err != nil {
return err return err
} }
@ -66,7 +76,13 @@ func StartTransfer(prometheusPort int) error {
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, msgModel) msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, msgModel)
conversationRpcClient := rpcclient.NewConversationRpcClient(client) conversationRpcClient := rpcclient.NewConversationRpcClient(client)
groupRpcClient := rpcclient.NewGroupRpcClient(client) groupRpcClient := rpcclient.NewGroupRpcClient(client)
msgTransfer := NewMsgTransfer(chatLogDatabase, extendMsgDatabase, msgDatabase, &conversationRpcClient, &groupRpcClient) msgTransfer := NewMsgTransfer(
chatLogDatabase,
extendMsgDatabase,
msgDatabase,
&conversationRpcClient,
&groupRpcClient,
)
msgTransfer.initPrometheus() msgTransfer.initPrometheus()
return msgTransfer.Start(prometheusPort) return msgTransfer.Start(prometheusPort)
} }
@ -74,8 +90,14 @@ func StartTransfer(prometheusPort int) error {
func NewMsgTransfer(chatLogDatabase controller.ChatLogDatabase, func NewMsgTransfer(chatLogDatabase controller.ChatLogDatabase,
extendMsgDatabase controller.ExtendMsgDatabase, msgDatabase controller.CommonMsgDatabase, extendMsgDatabase controller.ExtendMsgDatabase, msgDatabase controller.CommonMsgDatabase,
conversationRpcClient *rpcclient.ConversationRpcClient, groupRpcClient *rpcclient.GroupRpcClient) *MsgTransfer { conversationRpcClient *rpcclient.ConversationRpcClient, groupRpcClient *rpcclient.GroupRpcClient) *MsgTransfer {
return &MsgTransfer{persistentCH: NewPersistentConsumerHandler(chatLogDatabase), historyCH: NewOnlineHistoryRedisConsumerHandler(msgDatabase, conversationRpcClient, groupRpcClient), return &MsgTransfer{
historyMongoCH: NewOnlineHistoryMongoConsumerHandler(msgDatabase), modifyCH: NewModifyMsgConsumerHandler(extendMsgDatabase)} persistentCH: NewPersistentConsumerHandler(chatLogDatabase),
historyCH: NewOnlineHistoryRedisConsumerHandler(msgDatabase, conversationRpcClient, groupRpcClient),
historyMongoCH: NewOnlineHistoryMongoConsumerHandler(
msgDatabase,
),
modifyCH: NewModifyMsgConsumerHandler(extendMsgDatabase),
}
} }
func (m *MsgTransfer) initPrometheus() { func (m *MsgTransfer) initPrometheus() {

View File

@ -4,6 +4,8 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/Shopify/sarama"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -14,7 +16,6 @@ import (
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
@ -41,7 +42,18 @@ func (mmc *ModifyMsgConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSessi
claim sarama.ConsumerGroupClaim) error { claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() { for msg := range claim.Messages() {
ctx := mmc.modifyMsgConsumerGroup.GetContextFromMsg(msg) ctx := mmc.modifyMsgConsumerGroup.GetContextFromMsg(msg)
log.ZDebug(ctx, "kafka get info to mysql", "ModifyMsgConsumerHandler", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value), "key", string(msg.Key)) log.ZDebug(
ctx,
"kafka get info to mysql",
"ModifyMsgConsumerHandler",
msg.Topic,
"msgPartition",
msg.Partition,
"msg",
string(msg.Value),
"key",
string(msg.Key),
)
if len(msg.Value) != 0 { if len(msg.Value) != 0 {
mmc.ModifyMsg(ctx, msg, string(msg.Key), sess) mmc.ModifyMsg(ctx, msg, string(msg.Key), sess)
} else { } else {
@ -52,7 +64,12 @@ func (mmc *ModifyMsgConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSessi
return nil return nil
} }
func (mmc *ModifyMsgConsumerHandler) ModifyMsg(ctx context.Context, cMsg *sarama.ConsumerMessage, msgKey string, _ sarama.ConsumerGroupSession) { func (mmc *ModifyMsgConsumerHandler) ModifyMsg(
ctx context.Context,
cMsg *sarama.ConsumerMessage,
msgKey string,
_ sarama.ConsumerGroupSession,
) {
msgFromMQ := pbMsg.MsgDataToModifyByMQ{} msgFromMQ := pbMsg.MsgDataToModifyByMQ{}
operationID := mcontext.GetOperationID(ctx) operationID := mcontext.GetOperationID(ctx)
err := proto.Unmarshal(cMsg.Value, &msgFromMQ) err := proto.Unmarshal(cMsg.Value, &msgFromMQ)
@ -92,7 +109,8 @@ func (mmc *ModifyMsgConsumerHandler) ModifyMsg(ctx context.Context, cMsg *sarama
} }
if err := mmc.extendMsgDatabase.InsertExtendMsg(ctx, notification.ConversationID, notification.SessionType, &extendMsg); err != nil { if err := mmc.extendMsgDatabase.InsertExtendMsg(ctx, notification.ConversationID, notification.SessionType, &extendMsg); err != nil {
// log.ZError(ctx, "MsgFirstModify InsertExtendMsg failed", notification.ConversationID, notification.SessionType, extendMsg, err.Error()) // log.ZError(ctx, "MsgFirstModify InsertExtendMsg failed", notification.ConversationID,
// notification.SessionType, extendMsg, err.Error())
continue continue
} }
} else { } else {

View File

@ -9,6 +9,10 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/Shopify/sarama"
"github.com/go-redis/redis"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -18,9 +22,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/Shopify/sarama"
"github.com/go-redis/redis"
"google.golang.org/protobuf/proto"
) )
const ConsumerMsgs = 3 const ConsumerMsgs = 3
@ -63,7 +64,11 @@ type OnlineHistoryRedisConsumerHandler struct {
groupRpcClient *rpcclient.GroupRpcClient groupRpcClient *rpcclient.GroupRpcClient
} }
func NewOnlineHistoryRedisConsumerHandler(database controller.CommonMsgDatabase, conversationRpcClient *rpcclient.ConversationRpcClient, groupRpcClient *rpcclient.GroupRpcClient) *OnlineHistoryRedisConsumerHandler { func NewOnlineHistoryRedisConsumerHandler(
database controller.CommonMsgDatabase,
conversationRpcClient *rpcclient.ConversationRpcClient,
groupRpcClient *rpcclient.GroupRpcClient,
) *OnlineHistoryRedisConsumerHandler {
var och OnlineHistoryRedisConsumerHandler var och OnlineHistoryRedisConsumerHandler
och.msgDatabase = database och.msgDatabase = database
och.msgDistributionCh = make(chan Cmd2Value) //no buffer channel och.msgDistributionCh = make(chan Cmd2Value) //no buffer channel
@ -77,7 +82,8 @@ func NewOnlineHistoryRedisConsumerHandler(database controller.CommonMsgDatabase,
och.historyConsumerGroup = kafka.NewMConsumerGroup(&kafka.MConsumerGroupConfig{KafkaVersion: sarama.V2_0_0_0, och.historyConsumerGroup = kafka.NewMConsumerGroup(&kafka.MConsumerGroupConfig{KafkaVersion: sarama.V2_0_0_0,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.LatestMsgToRedis.Topic}, OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.LatestMsgToRedis.Topic},
config.Config.Kafka.Addr, config.Config.Kafka.ConsumerGroupID.MsgToRedis) config.Config.Kafka.Addr, config.Config.Kafka.ConsumerGroupID.MsgToRedis)
//statistics.NewStatistics(&och.singleMsgSuccessCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d second singleMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval) // statistics.NewStatistics(&och.singleMsgSuccessCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d
// second singleMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
return &och return &och
} }
@ -90,16 +96,53 @@ func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
msgChannelValue := cmd.Value.(MsgChannelValue) msgChannelValue := cmd.Value.(MsgChannelValue)
ctxMsgList := msgChannelValue.ctxMsgList ctxMsgList := msgChannelValue.ctxMsgList
ctx := msgChannelValue.ctx ctx := msgChannelValue.ctx
log.ZDebug(ctx, "msg arrived channel", "channel id", channelID, "msgList length", len(ctxMsgList), "uniqueKey", msgChannelValue.uniqueKey) log.ZDebug(
storageMsgList, notStorageMsgList, storageNotificationList, notStorageNotificationList, modifyMsgList := och.getPushStorageMsgList(ctxMsgList) ctx,
log.ZDebug(ctx, "msg lens", "storageMsgList", len(storageMsgList), "notStorageMsgList", len(notStorageMsgList), "msg arrived channel",
"storageNotificationList", len(storageNotificationList), "notStorageNotificationList", len(notStorageNotificationList), "modifyMsgList", len(modifyMsgList)) "channel id",
channelID,
"msgList length",
len(ctxMsgList),
"uniqueKey",
msgChannelValue.uniqueKey,
)
storageMsgList, notStorageMsgList, storageNotificationList, notStorageNotificationList, modifyMsgList := och.getPushStorageMsgList(
ctxMsgList,
)
log.ZDebug(
ctx,
"msg lens",
"storageMsgList",
len(storageMsgList),
"notStorageMsgList",
len(notStorageMsgList),
"storageNotificationList",
len(storageNotificationList),
"notStorageNotificationList",
len(notStorageNotificationList),
"modifyMsgList",
len(modifyMsgList),
)
conversationIDMsg := utils.GetChatConversationIDByMsg(ctxMsgList[0].message) conversationIDMsg := utils.GetChatConversationIDByMsg(ctxMsgList[0].message)
conversationIDNotification := utils.GetNotificationConversationID(ctxMsgList[0].message) conversationIDNotification := utils.GetNotificationConversationID(ctxMsgList[0].message)
och.handleMsg(ctx, msgChannelValue.uniqueKey, conversationIDMsg, storageMsgList, notStorageMsgList) och.handleMsg(ctx, msgChannelValue.uniqueKey, conversationIDMsg, storageMsgList, notStorageMsgList)
och.handleNotification(ctx, msgChannelValue.uniqueKey, conversationIDNotification, storageNotificationList, notStorageNotificationList) och.handleNotification(
ctx,
msgChannelValue.uniqueKey,
conversationIDNotification,
storageNotificationList,
notStorageNotificationList,
)
if err := och.msgDatabase.MsgToModifyMQ(ctx, msgChannelValue.uniqueKey, conversationIDNotification, modifyMsgList); err != nil { if err := och.msgDatabase.MsgToModifyMQ(ctx, msgChannelValue.uniqueKey, conversationIDNotification, modifyMsgList); err != nil {
log.ZError(ctx, "msg to modify mq error", err, "uniqueKey", msgChannelValue.uniqueKey, "modifyMsgList", modifyMsgList) log.ZError(
ctx,
"msg to modify mq error",
err,
"uniqueKey",
msgChannelValue.uniqueKey,
"modifyMsgList",
modifyMsgList,
)
} }
} }
} }
@ -107,7 +150,9 @@ func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
} }
// 获取消息/通知 存储的消息列表, 不存储并且推送的消息列表, // 获取消息/通知 存储的消息列表, 不存储并且推送的消息列表,
func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []*ContextMsg) (storageMsgList, notStorageMsgList, storageNotificatoinList, notStorageNotificationList, modifyMsgList []*sdkws.MsgData) { func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(
totalMsgs []*ContextMsg,
) (storageMsgList, notStorageMsgList, storageNotificatoinList, notStorageNotificationList, modifyMsgList []*sdkws.MsgData) {
isStorage := func(msg *sdkws.MsgData) bool { isStorage := func(msg *sdkws.MsgData) bool {
options2 := utils.Options(msg.Options) options2 := utils.Options(msg.Options)
if options2.IsHistory() { if options2.IsHistory() {
@ -130,11 +175,17 @@ func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []
msg.Options = utils.NewMsgOptions() msg.Options = utils.NewMsgOptions()
} }
if options.IsOfflinePush() { if options.IsOfflinePush() {
v.message.Options = utils.WithOptions(utils.Options(v.message.Options), utils.WithOfflinePush(false)) v.message.Options = utils.WithOptions(
utils.Options(v.message.Options),
utils.WithOfflinePush(false),
)
msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithOfflinePush(true)) msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithOfflinePush(true))
} }
if options.IsUnreadCount() { if options.IsUnreadCount() {
v.message.Options = utils.WithOptions(utils.Options(v.message.Options), utils.WithUnreadCount(false)) v.message.Options = utils.WithOptions(
utils.Options(v.message.Options),
utils.WithUnreadCount(false),
)
msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithUnreadCount(true)) msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithUnreadCount(true))
} }
storageMsgList = append(storageMsgList, msg) storageMsgList = append(storageMsgList, msg)
@ -151,19 +202,32 @@ func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []
notStorageMsgList = append(notStorageMsgList, v.message) notStorageMsgList = append(notStorageMsgList, v.message)
} }
} }
if v.message.ContentType == constant.ReactionMessageModifier || v.message.ContentType == constant.ReactionMessageDeleter { if v.message.ContentType == constant.ReactionMessageModifier ||
v.message.ContentType == constant.ReactionMessageDeleter {
modifyMsgList = append(modifyMsgList, v.message) modifyMsgList = append(modifyMsgList, v.message)
} }
} }
return return
} }
func (och *OnlineHistoryRedisConsumerHandler) handleNotification(ctx context.Context, key, conversationID string, storageList, notStorageList []*sdkws.MsgData) { func (och *OnlineHistoryRedisConsumerHandler) handleNotification(
ctx context.Context,
key, conversationID string,
storageList, notStorageList []*sdkws.MsgData,
) {
och.toPushTopic(ctx, key, conversationID, notStorageList) och.toPushTopic(ctx, key, conversationID, notStorageList)
if len(storageList) > 0 { if len(storageList) > 0 {
lastSeq, _, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList) lastSeq, _, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
if err != nil { if err != nil {
log.ZError(ctx, "notification batch insert to redis error", err, "conversationID", conversationID, "storageList", storageList) log.ZError(
ctx,
"notification batch insert to redis error",
err,
"conversationID",
conversationID,
"storageList",
storageList,
)
return return
} }
log.ZDebug(ctx, "success to next topic", "conversationID", conversationID) log.ZDebug(ctx, "success to next topic", "conversationID", conversationID)
@ -172,13 +236,21 @@ func (och *OnlineHistoryRedisConsumerHandler) handleNotification(ctx context.Con
} }
} }
func (och *OnlineHistoryRedisConsumerHandler) toPushTopic(ctx context.Context, key, conversationID string, msgs []*sdkws.MsgData) { func (och *OnlineHistoryRedisConsumerHandler) toPushTopic(
ctx context.Context,
key, conversationID string,
msgs []*sdkws.MsgData,
) {
for _, v := range msgs { for _, v := range msgs {
och.msgDatabase.MsgToPushMQ(ctx, key, conversationID, v) och.msgDatabase.MsgToPushMQ(ctx, key, conversationID, v)
} }
} }
func (och *OnlineHistoryRedisConsumerHandler) handleMsg(ctx context.Context, key, conversationID string, storageList, notStorageList []*sdkws.MsgData) { func (och *OnlineHistoryRedisConsumerHandler) handleMsg(
ctx context.Context,
key, conversationID string,
storageList, notStorageList []*sdkws.MsgData,
) {
och.toPushTopic(ctx, key, conversationID, notStorageList) och.toPushTopic(ctx, key, conversationID, notStorageList)
if len(storageList) > 0 { if len(storageList) > 0 {
lastSeq, isNewConversation, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList) lastSeq, isNewConversation, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
@ -240,11 +312,26 @@ func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
for i, header := range consumerMessages[i].Headers { for i, header := range consumerMessages[i].Headers {
arr = append(arr, strconv.Itoa(i), string(header.Key), string(header.Value)) arr = append(arr, strconv.Itoa(i), string(header.Key), string(header.Value))
} }
log.ZInfo(ctx, "consumer.kafka.GetContextWithMQHeader", "len", len(consumerMessages[i].Headers), "header", strings.Join(arr, ", ")) log.ZInfo(
ctx,
"consumer.kafka.GetContextWithMQHeader",
"len",
len(consumerMessages[i].Headers),
"header",
strings.Join(arr, ", "),
)
ctxMsg.ctx = kafka.GetContextWithMQHeader(consumerMessages[i].Headers) ctxMsg.ctx = kafka.GetContextWithMQHeader(consumerMessages[i].Headers)
ctxMsg.message = msgFromMQ ctxMsg.message = msgFromMQ
log.ZDebug(ctx, "single msg come to distribution center", "message", msgFromMQ, "key", string(consumerMessages[i].Key)) log.ZDebug(
//aggregationMsgs[string(consumerMessages[i].Key)] = append(aggregationMsgs[string(consumerMessages[i].Key)], ctxMsg) ctx,
"single msg come to distribution center",
"message",
msgFromMQ,
"key",
string(consumerMessages[i].Key),
)
// aggregationMsgs[string(consumerMessages[i].Key)] =
// append(aggregationMsgs[string(consumerMessages[i].Key)], ctxMsg)
if oldM, ok := aggregationMsgs[string(consumerMessages[i].Key)]; ok { if oldM, ok := aggregationMsgs[string(consumerMessages[i].Key)]; ok {
oldM = append(oldM, ctxMsg) oldM = append(oldM, ctxMsg)
aggregationMsgs[string(consumerMessages[i].Key)] = oldM aggregationMsgs[string(consumerMessages[i].Key)] = oldM
@ -260,7 +347,16 @@ func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
hashCode := utils.GetHashCode(uniqueKey) hashCode := utils.GetHashCode(uniqueKey)
channelID := hashCode % ChannelNum channelID := hashCode % ChannelNum
newCtx := withAggregationCtx(ctx, v) newCtx := withAggregationCtx(ctx, v)
log.ZDebug(newCtx, "generate channelID", "hashCode", hashCode, "channelID", channelID, "uniqueKey", uniqueKey) log.ZDebug(
newCtx,
"generate channelID",
"hashCode",
hashCode,
"channelID",
channelID,
"uniqueKey",
uniqueKey,
)
och.chArrays[channelID] <- Cmd2Value{Cmd: SourceMessages, Value: MsgChannelValue{uniqueKey: uniqueKey, ctxMsgList: v, ctx: newCtx}} och.chArrays[channelID] <- Cmd2Value{Cmd: SourceMessages, Value: MsgChannelValue{uniqueKey: uniqueKey, ctxMsgList: v, ctx: newCtx}}
} }
} }
@ -288,7 +384,10 @@ func (och *OnlineHistoryRedisConsumerHandler) Cleanup(_ sarama.ConsumerGroupSess
return nil return nil
} }
func (och *OnlineHistoryRedisConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group func (och *OnlineHistoryRedisConsumerHandler) ConsumeClaim(
sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim,
) error { // a instance in the consumer group
for { for {
if sess == nil { if sess == nil {
log.ZWarn(context.Background(), "sess == nil, waiting", nil) log.ZWarn(context.Background(), "sess == nil, waiting", nil)

View File

@ -3,13 +3,14 @@ package msgtransfer
import ( import (
"context" "context"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka" kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
) )
type OnlineHistoryMongoConsumerHandler struct { type OnlineHistoryMongoConsumerHandler struct {
@ -27,7 +28,12 @@ func NewOnlineHistoryMongoConsumerHandler(database controller.CommonMsgDatabase)
return mc return mc
} }
func (mc *OnlineHistoryMongoConsumerHandler) handleChatWs2Mongo(ctx context.Context, cMsg *sarama.ConsumerMessage, key string, session sarama.ConsumerGroupSession) { func (mc *OnlineHistoryMongoConsumerHandler) handleChatWs2Mongo(
ctx context.Context,
cMsg *sarama.ConsumerMessage,
key string,
session sarama.ConsumerGroupSession,
) {
msg := cMsg.Value msg := cMsg.Value
msgFromMQ := pbMsg.MsgDataToMongoByMQ{} msgFromMQ := pbMsg.MsgDataToMongoByMQ{}
err := proto.Unmarshal(msg, &msgFromMQ) err := proto.Unmarshal(msg, &msgFromMQ)
@ -42,7 +48,15 @@ func (mc *OnlineHistoryMongoConsumerHandler) handleChatWs2Mongo(ctx context.Cont
log.ZInfo(ctx, "mongo consumer recv msg", "msgs", msgFromMQ.MsgData) log.ZInfo(ctx, "mongo consumer recv msg", "msgs", msgFromMQ.MsgData)
err = mc.msgDatabase.BatchInsertChat2DB(ctx, msgFromMQ.ConversationID, msgFromMQ.MsgData, msgFromMQ.LastSeq) err = mc.msgDatabase.BatchInsertChat2DB(ctx, msgFromMQ.ConversationID, msgFromMQ.MsgData, msgFromMQ.LastSeq)
if err != nil { if err != nil {
log.ZError(ctx, "single data insert to mongo err", err, "msg", msgFromMQ.MsgData, "conversationID", msgFromMQ.ConversationID) log.ZError(
ctx,
"single data insert to mongo err",
err,
"msg",
msgFromMQ.MsgData,
"conversationID",
msgFromMQ.ConversationID,
)
} }
var seqs []int64 var seqs []int64
for _, msg := range msgFromMQ.MsgData { for _, msg := range msgFromMQ.MsgData {
@ -50,14 +64,26 @@ func (mc *OnlineHistoryMongoConsumerHandler) handleChatWs2Mongo(ctx context.Cont
} }
err = mc.msgDatabase.DeleteMessagesFromCache(ctx, msgFromMQ.ConversationID, seqs) err = mc.msgDatabase.DeleteMessagesFromCache(ctx, msgFromMQ.ConversationID, seqs)
if err != nil { if err != nil {
log.ZError(ctx, "remove cache msg from redis err", err, "msg", msgFromMQ.MsgData, "conversationID", msgFromMQ.ConversationID) log.ZError(
ctx,
"remove cache msg from redis err",
err,
"msg",
msgFromMQ.MsgData,
"conversationID",
msgFromMQ.ConversationID,
)
} }
mc.msgDatabase.DelUserDeleteMsgsList(ctx, msgFromMQ.ConversationID, seqs) mc.msgDatabase.DelUserDeleteMsgsList(ctx, msgFromMQ.ConversationID, seqs)
} }
func (OnlineHistoryMongoConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (OnlineHistoryMongoConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (OnlineHistoryMongoConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (OnlineHistoryMongoConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (mc *OnlineHistoryMongoConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group
func (mc *OnlineHistoryMongoConsumerHandler) ConsumeClaim(
sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim,
) error { // a instance in the consumer group
log.ZDebug(context.Background(), "online new session msg come", "highWaterMarkOffset", log.ZDebug(context.Background(), "online new session msg come", "highWaterMarkOffset",
claim.HighWaterMarkOffset(), "topic", claim.Topic(), "partition", claim.Partition()) claim.HighWaterMarkOffset(), "topic", claim.Topic(), "partition", claim.Partition())
for msg := range claim.Messages() { for msg := range claim.Messages() {

View File

@ -3,8 +3,7 @@
** copyright('tuoyun,www.tuoyun.net'). ** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net"). ** author("fg,Gordon@tuoyun.net").
** time(2021/5/11 15:37). ** time(2021/5/11 15:37).
*/ */package msgtransfer
package msgtransfer
import ( import (
"context" "context"
@ -35,7 +34,12 @@ func NewPersistentConsumerHandler(database controller.ChatLogDatabase) *Persiste
} }
} }
func (pc *PersistentConsumerHandler) handleChatWs2Mysql(ctx context.Context, cMsg *sarama.ConsumerMessage, msgKey string, _ sarama.ConsumerGroupSession) { func (pc *PersistentConsumerHandler) handleChatWs2Mysql(
ctx context.Context,
cMsg *sarama.ConsumerMessage,
msgKey string,
_ sarama.ConsumerGroupSession,
) {
msg := cMsg.Value msg := cMsg.Value
var tag bool var tag bool
msgFromMQ := pbMsg.MsgDataToMQ{} msgFromMQ := pbMsg.MsgDataToMQ{}
@ -73,10 +77,25 @@ func (pc *PersistentConsumerHandler) handleChatWs2Mysql(ctx context.Context, cMs
} }
func (PersistentConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (PersistentConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (PersistentConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (PersistentConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (pc *PersistentConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
func (pc *PersistentConsumerHandler) ConsumeClaim(
sess sarama.ConsumerGroupSession,
claim sarama.ConsumerGroupClaim,
) error {
for msg := range claim.Messages() { for msg := range claim.Messages() {
ctx := pc.persistentConsumerGroup.GetContextFromMsg(msg) ctx := pc.persistentConsumerGroup.GetContextFromMsg(msg)
log.ZDebug(ctx, "kafka get info to mysql", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value), "key", string(msg.Key)) log.ZDebug(
ctx,
"kafka get info to mysql",
"msgTopic",
msg.Topic,
"msgPartition",
msg.Partition,
"msg",
string(msg.Value),
"key",
string(msg.Key),
)
if len(msg.Value) != 0 { if len(msg.Value) != 0 {
pc.handleChatWs2Mysql(ctx, msg, string(msg.Key), sess) pc.handleChatWs2Mysql(ctx, msg, string(msg.Key), sess)
} else { } else {

View File

@ -17,7 +17,12 @@ func url() string {
return config.Config.Callback.CallbackUrl return config.Config.Callback.CallbackUrl
} }
func callbackOfflinePush(ctx context.Context, userIDs []string, msg *sdkws.MsgData, offlinePushUserIDs *[]string) error { func callbackOfflinePush(
ctx context.Context,
userIDs []string,
msg *sdkws.MsgData,
offlinePushUserIDs *[]string,
) error {
if !config.Config.Callback.CallbackOfflinePush.Enable { if !config.Config.Callback.CallbackOfflinePush.Enable {
return nil return nil
} }
@ -82,7 +87,12 @@ func callbackOnlinePush(ctx context.Context, userIDs []string, msg *sdkws.MsgDat
return http.CallBackPostReturn(ctx, url(), req, resp, config.Config.Callback.CallbackOnlinePush) return http.CallBackPostReturn(ctx, url(), req, resp, config.Config.Callback.CallbackOnlinePush)
} }
func callbackBeforeSuperGroupOnlinePush(ctx context.Context, groupID string, msg *sdkws.MsgData, pushToUserIDs *[]string) error { func callbackBeforeSuperGroupOnlinePush(
ctx context.Context,
groupID string,
msg *sdkws.MsgData,
pushToUserIDs *[]string,
) error {
if !config.Config.Callback.CallbackBeforeSuperGroupOnlinePush.Enable { if !config.Config.Callback.CallbackBeforeSuperGroupOnlinePush.Enable {
return nil return nil
} }

View File

@ -21,6 +21,7 @@ func (c *Consumer) initPrometheus() {
} }
func (c *Consumer) Start() { func (c *Consumer) Start() {
//statistics.NewStatistics(&c.successCount, config.Config.ModuleName.PushName, fmt.Sprintf("%d second push to msg_gateway count", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval) // statistics.NewStatistics(&c.successCount, config.Config.ModuleName.PushName, fmt.Sprintf("%d second push to
// msg_gateway count", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
go c.pushCh.pushConsumerGroup.RegisterHandleAndConsumer(&c.pushCh) go c.pushCh.pushConsumerGroup.RegisterHandleAndConsumer(&c.pushCh)
} }

View File

@ -6,12 +6,13 @@ import (
firebase "firebase.google.com/go" firebase "firebase.google.com/go"
"firebase.google.com/go/messaging" "firebase.google.com/go/messaging"
"github.com/redis/go-redis/v9"
"google.golang.org/api/option"
"github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/redis/go-redis/v9"
"google.golang.org/api/option"
) )
const SinglePushCountLimit = 400 const SinglePushCountLimit = 400

View File

@ -4,9 +4,10 @@ import (
"context" "context"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/stretchr/testify/assert"
) )
func Test_Push(t *testing.T) { func Test_Push(t *testing.T) {

View File

@ -99,7 +99,9 @@ func (g *Client) Push(ctx context.Context, userIDs []string, title, content stri
func (g *Client) Auth(ctx context.Context, timeStamp int64) (token string, expireTime int64, err error) { func (g *Client) Auth(ctx context.Context, timeStamp int64) (token string, expireTime int64, err error) {
h := sha256.New() h := sha256.New()
h.Write([]byte(config.Config.Push.GeTui.AppKey + strconv.Itoa(int(timeStamp)) + config.Config.Push.GeTui.MasterSecret)) h.Write(
[]byte(config.Config.Push.GeTui.AppKey + strconv.Itoa(int(timeStamp)) + config.Config.Push.GeTui.MasterSecret),
)
sign := hex.EncodeToString(h.Sum(nil)) sign := hex.EncodeToString(h.Sum(nil))
reqAuth := AuthReq{ reqAuth := AuthReq{
Sign: sign, Sign: sign,
@ -150,7 +152,14 @@ func (g *Client) request(ctx context.Context, url string, input interface{}, tok
return g.postReturn(ctx, config.Config.Push.GeTui.PushUrl+url, header, input, resp, 3) return g.postReturn(ctx, config.Config.Push.GeTui.PushUrl+url, header, input, resp, 3)
} }
func (g *Client) postReturn(ctx context.Context, url string, header map[string]string, input interface{}, output RespI, timeout int) error { func (g *Client) postReturn(
ctx context.Context,
url string,
header map[string]string,
input interface{},
output RespI,
timeout int,
) error {
err := http2.PostReturn(ctx, url, header, input, output, timeout) err := http2.PostReturn(ctx, url, header, input, output, timeout)
if err != nil { if err != nil {
return err return err

View File

@ -60,5 +60,14 @@ func (j *JPush) Push(ctx context.Context, userIDs []string, title, content strin
} }
func (j *JPush) request(ctx context.Context, po body.PushObj, resp interface{}, timeout int) error { func (j *JPush) request(ctx context.Context, po body.PushObj, resp interface{}, timeout int) error {
return http2.PostReturn(ctx, config.Config.Push.Jpns.PushUrl, map[string]string{"Authorization": j.getAuthorization(config.Config.Push.Jpns.AppKey, config.Config.Push.Jpns.MasterSecret)}, po, resp, timeout) return http2.PostReturn(
ctx,
config.Config.Push.Jpns.PushUrl,
map[string]string{
"Authorization": j.getAuthorization(config.Config.Push.Jpns.AppKey, config.Config.Push.Jpns.MasterSecret),
},
po,
resp,
timeout,
)
} }

View File

@ -3,6 +3,9 @@ package push
import ( import (
"context" "context"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka" kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka"
@ -10,8 +13,6 @@ import (
pbChat "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbChat "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push" pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
) )
type ConsumerHandler struct { type ConsumerHandler struct {

View File

@ -4,6 +4,8 @@ import (
"context" "context"
"sync" "sync"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -12,7 +14,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push" pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
) )
type pushServer struct { type pushServer struct {
@ -30,7 +31,16 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
groupRpcClient := rpcclient.NewGroupRpcClient(client) groupRpcClient := rpcclient.NewGroupRpcClient(client)
conversationRpcClient := rpcclient.NewConversationRpcClient(client) conversationRpcClient := rpcclient.NewConversationRpcClient(client)
msgRpcClient := rpcclient.NewMessageRpcClient(client) msgRpcClient := rpcclient.NewMessageRpcClient(client)
pusher := NewPusher(client, offlinePusher, database, localcache.NewGroupLocalCache(&groupRpcClient), localcache.NewConversationLocalCache(&conversationRpcClient), &conversationRpcClient, &groupRpcClient, &msgRpcClient) pusher := NewPusher(
client,
offlinePusher,
database,
localcache.NewGroupLocalCache(&groupRpcClient),
localcache.NewConversationLocalCache(&conversationRpcClient),
&conversationRpcClient,
&groupRpcClient,
&msgRpcClient,
)
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) wg.Add(2)
go func() { go func() {
@ -66,7 +76,10 @@ func (r *pushServer) PushMsg(ctx context.Context, pbData *pbPush.PushMsgReq) (re
return &pbPush.PushMsgResp{}, nil return &pbPush.PushMsgResp{}, nil
} }
func (r *pushServer) DelUserPushToken(ctx context.Context, req *pbPush.DelUserPushTokenReq) (resp *pbPush.DelUserPushTokenResp, err error) { func (r *pushServer) DelUserPushToken(
ctx context.Context,
req *pbPush.DelUserPushTokenReq,
) (resp *pbPush.DelUserPushTokenResp, err error) {
if err = r.pusher.database.DelFcmToken(ctx, req.UserID, int(req.PlatformID)); err != nil { if err = r.pusher.database.DelFcmToken(ctx, req.UserID, int(req.PlatformID)); err != nil {
return nil, err return nil, err
} }

View File

@ -38,9 +38,16 @@ type Pusher struct {
var errNoOfflinePusher = errors.New("no offlinePusher is configured") var errNoOfflinePusher = errors.New("no offlinePusher is configured")
func NewPusher(discov discoveryregistry.SvcDiscoveryRegistry, offlinePusher offlinepush.OfflinePusher, database controller.PushDatabase, func NewPusher(
groupLocalCache *localcache.GroupLocalCache, conversationLocalCache *localcache.ConversationLocalCache, discov discoveryregistry.SvcDiscoveryRegistry,
conversationRpcClient *rpcclient.ConversationRpcClient, groupRpcClient *rpcclient.GroupRpcClient, msgRpcClient *rpcclient.MessageRpcClient) *Pusher { offlinePusher offlinepush.OfflinePusher,
database controller.PushDatabase,
groupLocalCache *localcache.GroupLocalCache,
conversationLocalCache *localcache.ConversationLocalCache,
conversationRpcClient *rpcclient.ConversationRpcClient,
groupRpcClient *rpcclient.GroupRpcClient,
msgRpcClient *rpcclient.MessageRpcClient,
) *Pusher {
return &Pusher{ return &Pusher{
discov: discov, discov: discov,
database: database, database: database,
@ -87,7 +94,18 @@ func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.Msg
return err return err
} }
isOfflinePush := utils.GetSwitchFromOptions(msg.Options, constant.IsOfflinePush) isOfflinePush := utils.GetSwitchFromOptions(msg.Options, constant.IsOfflinePush)
log.ZDebug(ctx, "push_result", "ws push result", wsResults, "sendData", msg, "isOfflinePush", isOfflinePush, "push_to_userID", userIDs) log.ZDebug(
ctx,
"push_result",
"ws push result",
wsResults,
"sendData",
msg,
"isOfflinePush",
isOfflinePush,
"push_to_userID",
userIDs,
)
p.successCount++ p.successCount++
for _, userID := range userIDs { for _, userID := range userIDs {
if isOfflinePush && userID != msg.SendID { if isOfflinePush && userID != msg.SendID {
@ -138,7 +156,15 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
} }
defer func(groupID string, userIDs []string) { defer func(groupID string, userIDs []string) {
if err := p.DeleteMemberAndSetConversationSeq(ctx, groupID, userIDs); err != nil { if err := p.DeleteMemberAndSetConversationSeq(ctx, groupID, userIDs); err != nil {
log.ZError(ctx, "MemberQuitNotification DeleteMemberAndSetConversationSeq", err, "groupID", groupID, "userIDs", userIDs) log.ZError(
ctx,
"MemberQuitNotification DeleteMemberAndSetConversationSeq",
err,
"groupID",
groupID,
"userIDs",
userIDs,
)
} }
}(groupID, []string{tips.QuitUser.UserID}) }(groupID, []string{tips.QuitUser.UserID})
pushToUserIDs = append(pushToUserIDs, tips.QuitUser.UserID) pushToUserIDs = append(pushToUserIDs, tips.QuitUser.UserID)
@ -147,10 +173,21 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
if p.UnmarshalNotificationElem(msg.Content, &tips) != nil { if p.UnmarshalNotificationElem(msg.Content, &tips) != nil {
return err return err
} }
kickedUsers := utils.Slice(tips.KickedUserList, func(e *sdkws.GroupMemberFullInfo) string { return e.UserID }) kickedUsers := utils.Slice(
tips.KickedUserList,
func(e *sdkws.GroupMemberFullInfo) string { return e.UserID },
)
defer func(groupID string, userIDs []string) { defer func(groupID string, userIDs []string) {
if err := p.DeleteMemberAndSetConversationSeq(ctx, groupID, userIDs); err != nil { if err := p.DeleteMemberAndSetConversationSeq(ctx, groupID, userIDs); err != nil {
log.ZError(ctx, "MemberKickedNotification DeleteMemberAndSetConversationSeq", err, "groupID", groupID, "userIDs", userIDs) log.ZError(
ctx,
"MemberKickedNotification DeleteMemberAndSetConversationSeq",
err,
"groupID",
groupID,
"userIDs",
userIDs,
)
} }
}(groupID, kickedUsers) }(groupID, kickedUsers)
pushToUserIDs = append(pushToUserIDs, kickedUsers...) pushToUserIDs = append(pushToUserIDs, kickedUsers...)
@ -160,7 +197,16 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
if p.UnmarshalNotificationElem(msg.Content, &tips) != nil { if p.UnmarshalNotificationElem(msg.Content, &tips) != nil {
return err return err
} }
log.ZInfo(ctx, "GroupDismissedNotificationInfo****", "groupID", groupID, "num", len(pushToUserIDs), "list", pushToUserIDs) log.ZInfo(
ctx,
"GroupDismissedNotificationInfo****",
"groupID",
groupID,
"num",
len(pushToUserIDs),
"list",
pushToUserIDs,
)
if len(config.Config.Manager.UserID) > 0 { if len(config.Config.Manager.UserID) > 0 {
ctx = mcontext.WithOpUserIDContext(ctx, config.Config.Manager.UserID[0]) ctx = mcontext.WithOpUserIDContext(ctx, config.Config.Manager.UserID[0])
} }
@ -224,9 +270,23 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
log.ZError(ctx, "offlinePushMsg failed", err, "groupID", groupID, "msg", msg) log.ZError(ctx, "offlinePushMsg failed", err, "groupID", groupID, "msg", msg)
return err return err
} }
_, err := p.GetConnsAndOnlinePush(ctx, msg, utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs)) _, err := p.GetConnsAndOnlinePush(
ctx,
msg,
utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs),
)
if err != nil { if err != nil {
log.ZError(ctx, "offlinePushMsg failed", err, "groupID", groupID, "msg", msg, "userIDs", utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs)) log.ZError(
ctx,
"offlinePushMsg failed",
err,
"groupID",
groupID,
"msg",
msg,
"userIDs",
utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs),
)
return err return err
} }
} }
@ -234,7 +294,11 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
return nil return nil
} }
func (p *Pusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData, pushToUserIDs []string) (wsResults []*msggateway.SingleMsgToUserResults, err error) { func (p *Pusher) GetConnsAndOnlinePush(
ctx context.Context,
msg *sdkws.MsgData,
pushToUserIDs []string,
) (wsResults []*msggateway.SingleMsgToUserResults, err error) {
conns, err := p.discov.GetConns(ctx, config.Config.RpcRegisterName.OpenImMessageGatewayName) conns, err := p.discov.GetConns(ctx, config.Config.RpcRegisterName.OpenImMessageGatewayName)
log.ZDebug(ctx, "get gateway conn", "conn length", len(conns)) log.ZDebug(ctx, "get gateway conn", "conn length", len(conns))
if err != nil { if err != nil {
@ -243,7 +307,10 @@ func (p *Pusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
//Online push message //Online push message
for _, v := range conns { for _, v := range conns {
msgClient := msggateway.NewMsgGatewayClient(v) msgClient := msggateway.NewMsgGatewayClient(v)
reply, err := msgClient.SuperGroupOnlineBatchPushOneMsg(ctx, &msggateway.OnlineBatchPushOneMsgReq{MsgData: msg, PushToUserIDs: pushToUserIDs}) reply, err := msgClient.SuperGroupOnlineBatchPushOneMsg(
ctx,
&msggateway.OnlineBatchPushOneMsgReq{MsgData: msg, PushToUserIDs: pushToUserIDs},
)
p.discov.CloseConn(v) p.discov.CloseConn(v)
if err != nil { if err != nil {
continue continue
@ -257,7 +324,12 @@ func (p *Pusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
return wsResults, nil return wsResults, nil
} }
func (p *Pusher) offlinePushMsg(ctx context.Context, conversationID string, msg *sdkws.MsgData, offlinePushUserIDs []string) error { func (p *Pusher) offlinePushMsg(
ctx context.Context,
conversationID string,
msg *sdkws.MsgData,
offlinePushUserIDs []string,
) error {
title, content, opts, err := p.getOfflinePushInfos(conversationID, msg) title, content, opts, err := p.getOfflinePushInfos(conversationID, msg)
if err != nil { if err != nil {
return err return err
@ -291,7 +363,10 @@ func (p *Pusher) GetOfflinePushOpts(msg *sdkws.MsgData) (opts *offlinepush.Opts,
return opts, nil return opts, nil
} }
func (p *Pusher) getOfflinePushInfos(conversationID string, msg *sdkws.MsgData) (title, content string, opts *offlinepush.Opts, err error) { func (p *Pusher) getOfflinePushInfos(
conversationID string,
msg *sdkws.MsgData,
) (title, content string, opts *offlinepush.Opts, err error) {
if p.offlinePusher == nil { if p.offlinePusher == nil {
err = errNoOfflinePusher err = errNoOfflinePusher
return return

View File

@ -3,6 +3,8 @@ package auth
import ( import (
"context" "context"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
@ -15,7 +17,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msggateway" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msggateway"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
) )
type authServer struct { type authServer struct {
@ -33,7 +34,11 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
pbAuth.RegisterAuthServer(server, &authServer{ pbAuth.RegisterAuthServer(server, &authServer{
userRpcClient: &userRpcClient, userRpcClient: &userRpcClient,
RegisterCenter: client, RegisterCenter: client,
authDatabase: controller.NewAuthDatabase(cache.NewMsgCacheModel(rdb), config.Config.Secret, config.Config.TokenPolicy.Expire), authDatabase: controller.NewAuthDatabase(
cache.NewMsgCacheModel(rdb),
config.Config.Secret,
config.Config.TokenPolicy.Expire,
),
}) })
return nil return nil
} }
@ -80,7 +85,10 @@ func (s *authServer) parseToken(ctx context.Context, tokensString string) (claim
return nil, errs.ErrTokenNotExist.Wrap() return nil, errs.ErrTokenNotExist.Wrap()
} }
func (s *authServer) ParseToken(ctx context.Context, req *pbAuth.ParseTokenReq) (resp *pbAuth.ParseTokenResp, err error) { func (s *authServer) ParseToken(
ctx context.Context,
req *pbAuth.ParseTokenReq,
) (resp *pbAuth.ParseTokenResp, err error) {
resp = &pbAuth.ParseTokenResp{} resp = &pbAuth.ParseTokenResp{}
claims, err := s.parseToken(ctx, req.Token) claims, err := s.parseToken(ctx, req.Token)
if err != nil { if err != nil {

View File

@ -3,6 +3,8 @@ package conversation
import ( import (
"context" "context"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
@ -17,7 +19,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
) )
type conversationServer struct { type conversationServer struct {
@ -44,12 +45,19 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
pbConversation.RegisterConversationServer(server, &conversationServer{ pbConversation.RegisterConversationServer(server, &conversationServer{
conversationNotificationSender: notification.NewConversationNotificationSender(&msgRpcClient), conversationNotificationSender: notification.NewConversationNotificationSender(&msgRpcClient),
groupRpcClient: &groupRpcClient, groupRpcClient: &groupRpcClient,
conversationDatabase: controller.NewConversationDatabase(conversationDB, cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), conversationDB), tx.NewGorm(db)), conversationDatabase: controller.NewConversationDatabase(
conversationDB,
cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), conversationDB),
tx.NewGorm(db),
),
}) })
return nil return nil
} }
func (c *conversationServer) GetConversation(ctx context.Context, req *pbConversation.GetConversationReq) (*pbConversation.GetConversationResp, error) { func (c *conversationServer) GetConversation(
ctx context.Context,
req *pbConversation.GetConversationReq,
) (*pbConversation.GetConversationResp, error) {
conversations, err := c.conversationDatabase.FindConversations(ctx, req.OwnerUserID, []string{req.ConversationID}) conversations, err := c.conversationDatabase.FindConversations(ctx, req.OwnerUserID, []string{req.ConversationID})
if err != nil { if err != nil {
return nil, err return nil, err
@ -62,7 +70,10 @@ func (c *conversationServer) GetConversation(ctx context.Context, req *pbConvers
return resp, nil return resp, nil
} }
func (c *conversationServer) GetAllConversations(ctx context.Context, req *pbConversation.GetAllConversationsReq) (*pbConversation.GetAllConversationsResp, error) { func (c *conversationServer) GetAllConversations(
ctx context.Context,
req *pbConversation.GetAllConversationsReq,
) (*pbConversation.GetAllConversationsResp, error) {
conversations, err := c.conversationDatabase.GetUserAllConversation(ctx, req.OwnerUserID) conversations, err := c.conversationDatabase.GetUserAllConversation(ctx, req.OwnerUserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -72,7 +83,10 @@ func (c *conversationServer) GetAllConversations(ctx context.Context, req *pbCon
return resp, nil return resp, nil
} }
func (c *conversationServer) GetConversations(ctx context.Context, req *pbConversation.GetConversationsReq) (*pbConversation.GetConversationsResp, error) { func (c *conversationServer) GetConversations(
ctx context.Context,
req *pbConversation.GetConversationsReq,
) (*pbConversation.GetConversationsResp, error) {
conversations, err := c.conversationDatabase.FindConversations(ctx, req.OwnerUserID, req.ConversationIDs) conversations, err := c.conversationDatabase.FindConversations(ctx, req.OwnerUserID, req.ConversationIDs)
if err != nil { if err != nil {
return nil, err return nil, err
@ -82,7 +96,10 @@ func (c *conversationServer) GetConversations(ctx context.Context, req *pbConver
return resp, nil return resp, nil
} }
func (c *conversationServer) BatchSetConversations(ctx context.Context, req *pbConversation.BatchSetConversationsReq) (*pbConversation.BatchSetConversationsResp, error) { func (c *conversationServer) BatchSetConversations(
ctx context.Context,
req *pbConversation.BatchSetConversationsReq,
) (*pbConversation.BatchSetConversationsResp, error) {
conversations := convert.ConversationsPb2DB(req.Conversations) conversations := convert.ConversationsPb2DB(req.Conversations)
err := c.conversationDatabase.SetUserConversations(ctx, req.OwnerUserID, conversations) err := c.conversationDatabase.SetUserConversations(ctx, req.OwnerUserID, conversations)
if err != nil { if err != nil {
@ -92,12 +109,19 @@ func (c *conversationServer) BatchSetConversations(ctx context.Context, req *pbC
return &pbConversation.BatchSetConversationsResp{}, nil return &pbConversation.BatchSetConversationsResp{}, nil
} }
func (c *conversationServer) SetConversation(ctx context.Context, req *pbConversation.SetConversationReq) (*pbConversation.SetConversationResp, error) { func (c *conversationServer) SetConversation(
ctx context.Context,
req *pbConversation.SetConversationReq,
) (*pbConversation.SetConversationResp, error) {
var conversation tableRelation.ConversationModel var conversation tableRelation.ConversationModel
if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil { if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil {
return nil, err return nil, err
} }
err := c.conversationDatabase.SetUserConversations(ctx, req.Conversation.OwnerUserID, []*tableRelation.ConversationModel{&conversation}) err := c.conversationDatabase.SetUserConversations(
ctx,
req.Conversation.OwnerUserID,
[]*tableRelation.ConversationModel{&conversation},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -106,7 +130,10 @@ func (c *conversationServer) SetConversation(ctx context.Context, req *pbConvers
return resp, nil return resp, nil
} }
func (c *conversationServer) SetRecvMsgOpt(ctx context.Context, req *pbConversation.SetRecvMsgOptReq) (*pbConversation.SetRecvMsgOptResp, error) { func (c *conversationServer) SetRecvMsgOpt(
ctx context.Context,
req *pbConversation.SetRecvMsgOptReq,
) (*pbConversation.SetRecvMsgOptResp, error) {
if err := c.conversationDatabase.SetUsersConversationFiledTx(ctx, []string{req.OwnerUserID}, &tableRelation.ConversationModel{OwnerUserID: req.OwnerUserID, ConversationID: req.ConversationID, RecvMsgOpt: req.RecvMsgOpt}, map[string]interface{}{"recv_msg_opt": req.RecvMsgOpt}); err != nil { if err := c.conversationDatabase.SetUsersConversationFiledTx(ctx, []string{req.OwnerUserID}, &tableRelation.ConversationModel{OwnerUserID: req.OwnerUserID, ConversationID: req.ConversationID, RecvMsgOpt: req.RecvMsgOpt}, map[string]interface{}{"recv_msg_opt": req.RecvMsgOpt}); err != nil {
return nil, err return nil, err
} }
@ -115,7 +142,10 @@ func (c *conversationServer) SetRecvMsgOpt(ctx context.Context, req *pbConversat
} }
// deprecated // deprecated
func (c *conversationServer) ModifyConversationField(ctx context.Context, req *pbConversation.ModifyConversationFieldReq) (*pbConversation.ModifyConversationFieldResp, error) { func (c *conversationServer) ModifyConversationField(
ctx context.Context,
req *pbConversation.ModifyConversationFieldReq,
) (*pbConversation.ModifyConversationFieldResp, error) {
resp := &pbConversation.ModifyConversationFieldResp{} resp := &pbConversation.ModifyConversationFieldResp{}
var err error var err error
if req.Conversation.ConversationType == constant.GroupChatType { if req.Conversation.ConversationType == constant.GroupChatType {
@ -129,11 +159,19 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
} }
conversation := convert.ConversationPb2DB(req.Conversation) conversation := convert.ConversationPb2DB(req.Conversation)
if req.FieldType == constant.FieldIsPrivateChat { if req.FieldType == constant.FieldIsPrivateChat {
err := c.conversationDatabase.SyncPeerUserPrivateConversationTx(ctx, []*tableRelation.ConversationModel{conversation}) err := c.conversationDatabase.SyncPeerUserPrivateConversationTx(
ctx,
[]*tableRelation.ConversationModel{conversation},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
c.conversationNotificationSender.ConversationSetPrivateNotification(ctx, req.Conversation.OwnerUserID, req.Conversation.UserID, req.Conversation.IsPrivateChat) c.conversationNotificationSender.ConversationSetPrivateNotification(
ctx,
req.Conversation.OwnerUserID,
req.Conversation.UserID,
req.Conversation.IsPrivateChat,
)
return resp, nil return resp, nil
} }
filedMap := make(map[string]interface{}) filedMap := make(map[string]interface{})
@ -161,7 +199,10 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
return resp, nil return resp, nil
} }
func (c *conversationServer) SetConversations(ctx context.Context, req *pbConversation.SetConversationsReq) (*pbConversation.SetConversationsResp, error) { func (c *conversationServer) SetConversations(
ctx context.Context,
req *pbConversation.SetConversationsReq,
) (*pbConversation.SetConversationsResp, error) {
if req.Conversation == nil { if req.Conversation == nil {
return nil, errs.ErrArgs.Wrap("conversation must not be nil") return nil, errs.ErrArgs.Wrap("conversation must not be nil")
} }
@ -207,7 +248,12 @@ func (c *conversationServer) SetConversations(ctx context.Context, req *pbConver
return nil, err return nil, err
} }
for _, ownerUserID := range req.UserIDs { for _, ownerUserID := range req.UserIDs {
c.conversationNotificationSender.ConversationSetPrivateNotification(ctx, ownerUserID, req.Conversation.UserID, req.Conversation.IsPrivateChat.Value) c.conversationNotificationSender.ConversationSetPrivateNotification(
ctx,
ownerUserID,
req.Conversation.UserID,
req.Conversation.IsPrivateChat.Value,
)
} }
} }
if req.Conversation.BurnDuration != nil { if req.Conversation.BurnDuration != nil {
@ -224,7 +270,10 @@ func (c *conversationServer) SetConversations(ctx context.Context, req *pbConver
} }
// 获取超级大群开启免打扰的用户ID // 获取超级大群开启免打扰的用户ID
func (c *conversationServer) GetRecvMsgNotNotifyUserIDs(ctx context.Context, req *pbConversation.GetRecvMsgNotNotifyUserIDsReq) (*pbConversation.GetRecvMsgNotNotifyUserIDsResp, error) { func (c *conversationServer) GetRecvMsgNotNotifyUserIDs(
ctx context.Context,
req *pbConversation.GetRecvMsgNotNotifyUserIDsReq,
) (*pbConversation.GetRecvMsgNotNotifyUserIDsResp, error) {
userIDs, err := c.conversationDatabase.FindRecvMsgNotNotifyUserIDs(ctx, req.GroupID) userIDs, err := c.conversationDatabase.FindRecvMsgNotNotifyUserIDs(ctx, req.GroupID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -233,7 +282,10 @@ func (c *conversationServer) GetRecvMsgNotNotifyUserIDs(ctx context.Context, req
} }
// create conversation without notification for msg redis transfer // create conversation without notification for msg redis transfer
func (c *conversationServer) CreateSingleChatConversations(ctx context.Context, req *pbConversation.CreateSingleChatConversationsReq) (*pbConversation.CreateSingleChatConversationsResp, error) { func (c *conversationServer) CreateSingleChatConversations(
ctx context.Context,
req *pbConversation.CreateSingleChatConversationsReq,
) (*pbConversation.CreateSingleChatConversationsResp, error) {
var conversation tableRelation.ConversationModel var conversation tableRelation.ConversationModel
conversation.ConversationID = utils.GetConversationIDBySessionType(constant.SingleChatType, req.RecvID, req.SendID) conversation.ConversationID = utils.GetConversationIDBySessionType(constant.SingleChatType, req.RecvID, req.SendID)
conversation.ConversationType = constant.SingleChatType conversation.ConversationType = constant.SingleChatType
@ -254,7 +306,10 @@ func (c *conversationServer) CreateSingleChatConversations(ctx context.Context,
return &pbConversation.CreateSingleChatConversationsResp{}, nil return &pbConversation.CreateSingleChatConversationsResp{}, nil
} }
func (c *conversationServer) CreateGroupChatConversations(ctx context.Context, req *pbConversation.CreateGroupChatConversationsReq) (*pbConversation.CreateGroupChatConversationsResp, error) { func (c *conversationServer) CreateGroupChatConversations(
ctx context.Context,
req *pbConversation.CreateGroupChatConversationsReq,
) (*pbConversation.CreateGroupChatConversationsResp, error) {
err := c.conversationDatabase.CreateGroupChatConversation(ctx, req.GroupID, req.UserIDs) err := c.conversationDatabase.CreateGroupChatConversation(ctx, req.GroupID, req.UserIDs)
if err != nil { if err != nil {
return nil, err return nil, err
@ -262,7 +317,10 @@ func (c *conversationServer) CreateGroupChatConversations(ctx context.Context, r
return &pbConversation.CreateGroupChatConversationsResp{}, nil return &pbConversation.CreateGroupChatConversationsResp{}, nil
} }
func (c *conversationServer) SetConversationMaxSeq(ctx context.Context, req *pbConversation.SetConversationMaxSeqReq) (*pbConversation.SetConversationMaxSeqResp, error) { func (c *conversationServer) SetConversationMaxSeq(
ctx context.Context,
req *pbConversation.SetConversationMaxSeqReq,
) (*pbConversation.SetConversationMaxSeqResp, error) {
if err := c.conversationDatabase.UpdateUsersConversationFiled(ctx, req.OwnerUserID, req.ConversationID, if err := c.conversationDatabase.UpdateUsersConversationFiled(ctx, req.OwnerUserID, req.ConversationID,
map[string]interface{}{"max_seq": req.MaxSeq}); err != nil { map[string]interface{}{"max_seq": req.MaxSeq}); err != nil {
return nil, err return nil, err
@ -270,7 +328,10 @@ func (c *conversationServer) SetConversationMaxSeq(ctx context.Context, req *pbC
return &pbConversation.SetConversationMaxSeqResp{}, nil return &pbConversation.SetConversationMaxSeqResp{}, nil
} }
func (c *conversationServer) GetConversationIDs(ctx context.Context, req *pbConversation.GetConversationIDsReq) (*pbConversation.GetConversationIDsResp, error) { func (c *conversationServer) GetConversationIDs(
ctx context.Context,
req *pbConversation.GetConversationIDsReq,
) (*pbConversation.GetConversationIDsResp, error) {
conversationIDs, err := c.conversationDatabase.GetConversationIDs(ctx, req.UserID) conversationIDs, err := c.conversationDatabase.GetConversationIDs(ctx, req.UserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -278,7 +339,10 @@ func (c *conversationServer) GetConversationIDs(ctx context.Context, req *pbConv
return &pbConversation.GetConversationIDsResp{ConversationIDs: conversationIDs}, nil return &pbConversation.GetConversationIDsResp{ConversationIDs: conversationIDs}, nil
} }
func (c *conversationServer) GetUserConversationIDsHash(ctx context.Context, req *pbConversation.GetUserConversationIDsHashReq) (*pbConversation.GetUserConversationIDsHashResp, error) { func (c *conversationServer) GetUserConversationIDsHash(
ctx context.Context,
req *pbConversation.GetUserConversationIDsHashReq,
) (*pbConversation.GetUserConversationIDsHashResp, error) {
hash, err := c.conversationDatabase.GetUserConversationIDsHash(ctx, req.OwnerUserID) hash, err := c.conversationDatabase.GetUserConversationIDsHash(ctx, req.OwnerUserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -286,10 +350,15 @@ func (c *conversationServer) GetUserConversationIDsHash(ctx context.Context, req
return &pbConversation.GetUserConversationIDsHashResp{Hash: hash}, nil return &pbConversation.GetUserConversationIDsHashResp{Hash: hash}, nil
} }
func (c *conversationServer) GetConversationsByConversationID(ctx context.Context, req *pbConversation.GetConversationsByConversationIDReq) (*pbConversation.GetConversationsByConversationIDResp, error) { func (c *conversationServer) GetConversationsByConversationID(
ctx context.Context,
req *pbConversation.GetConversationsByConversationIDReq,
) (*pbConversation.GetConversationsByConversationIDResp, error) {
conversations, err := c.conversationDatabase.GetConversationsByConversationID(ctx, req.ConversationIDs) conversations, err := c.conversationDatabase.GetConversationsByConversationID(ctx, req.ConversationIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &pbConversation.GetConversationsByConversationIDResp{Conversations: convert.ConversationsDB2Pb(conversations)}, nil return &pbConversation.GetConversationsByConversationIDResp{
Conversations: convert.ConversationsDB2Pb(conversations),
}, nil
} }

View File

@ -11,7 +11,10 @@ import (
pbFriend "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/friend" pbFriend "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/friend"
) )
func (s *friendServer) GetPaginationBlacks(ctx context.Context, req *pbFriend.GetPaginationBlacksReq) (resp *pbFriend.GetPaginationBlacksResp, err error) { func (s *friendServer) GetPaginationBlacks(
ctx context.Context,
req *pbFriend.GetPaginationBlacksReq,
) (resp *pbFriend.GetPaginationBlacksResp, err error) {
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err return nil, err
} }
@ -44,7 +47,10 @@ func (s *friendServer) IsBlack(ctx context.Context, req *pbFriend.IsBlackReq) (*
return resp, nil return resp, nil
} }
func (s *friendServer) RemoveBlack(ctx context.Context, req *pbFriend.RemoveBlackReq) (*pbFriend.RemoveBlackResp, error) { func (s *friendServer) RemoveBlack(
ctx context.Context,
req *pbFriend.RemoveBlackReq,
) (*pbFriend.RemoveBlackResp, error) {
if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil { if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil {
return nil, err return nil, err
} }
@ -63,7 +69,12 @@ func (s *friendServer) AddBlack(ctx context.Context, req *pbFriend.AddBlackReq)
if err != nil { if err != nil {
return nil, err return nil, err
} }
black := relation.BlackModel{OwnerUserID: req.OwnerUserID, BlockUserID: req.BlackUserID, OperatorUserID: mcontext.GetOpUserID(ctx), CreateTime: time.Now()} black := relation.BlackModel{
OwnerUserID: req.OwnerUserID,
BlockUserID: req.BlackUserID,
OperatorUserID: mcontext.GetOpUserID(ctx),
CreateTime: time.Now(),
}
if err := s.blackDatabase.Create(ctx, []*relation.BlackModel{&black}); err != nil { if err := s.blackDatabase.Create(ctx, []*relation.BlackModel{&black}); err != nil {
return nil, err return nil, err
} }

View File

@ -7,6 +7,8 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -19,7 +21,6 @@ import (
pbfriend "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/friend" pbfriend "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/friend"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
) )
type friendServer struct { type friendServer struct {
@ -46,10 +47,21 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
friendDB := relation.NewFriendGorm(db) friendDB := relation.NewFriendGorm(db)
userRpcClient := rpcclient.NewUserRpcClient(client) userRpcClient := rpcclient.NewUserRpcClient(client)
msgRpcClient := rpcclient.NewMessageRpcClient(client) msgRpcClient := rpcclient.NewMessageRpcClient(client)
notificationSender := notification.NewFriendNotificationSender(&msgRpcClient, notification.WithRpcFunc(userRpcClient.GetUsersInfo)) notificationSender := notification.NewFriendNotificationSender(
&msgRpcClient,
notification.WithRpcFunc(userRpcClient.GetUsersInfo),
)
pbfriend.RegisterFriendServer(server, &friendServer{ pbfriend.RegisterFriendServer(server, &friendServer{
friendDatabase: controller.NewFriendDatabase(friendDB, relation.NewFriendRequestGorm(db), cache.NewFriendCacheRedis(rdb, friendDB, cache.GetDefaultOpt()), tx.NewGorm(db)), friendDatabase: controller.NewFriendDatabase(
blackDatabase: controller.NewBlackDatabase(blackDB, cache.NewBlackCacheRedis(rdb, blackDB, cache.GetDefaultOpt())), friendDB,
relation.NewFriendRequestGorm(db),
cache.NewFriendCacheRedis(rdb, friendDB, cache.GetDefaultOpt()),
tx.NewGorm(db),
),
blackDatabase: controller.NewBlackDatabase(
blackDB,
cache.NewBlackCacheRedis(rdb, blackDB, cache.GetDefaultOpt()),
),
userRpcClient: &userRpcClient, userRpcClient: &userRpcClient,
notificationSender: notificationSender, notificationSender: notificationSender,
RegisterCenter: client, RegisterCenter: client,
@ -58,7 +70,10 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
} }
// ok // ok
func (s *friendServer) ApplyToAddFriend(ctx context.Context, req *pbfriend.ApplyToAddFriendReq) (resp *pbfriend.ApplyToAddFriendResp, err error) { func (s *friendServer) ApplyToAddFriend(
ctx context.Context,
req *pbfriend.ApplyToAddFriendReq,
) (resp *pbfriend.ApplyToAddFriendResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.ApplyToAddFriendResp{} resp = &pbfriend.ApplyToAddFriendResp{}
if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil { if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil {
@ -88,7 +103,10 @@ func (s *friendServer) ApplyToAddFriend(ctx context.Context, req *pbfriend.Apply
} }
// ok // ok
func (s *friendServer) ImportFriends(ctx context.Context, req *pbfriend.ImportFriendReq) (resp *pbfriend.ImportFriendResp, err error) { func (s *friendServer) ImportFriends(
ctx context.Context,
req *pbfriend.ImportFriendReq,
) (resp *pbfriend.ImportFriendResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
if err := tokenverify.CheckAdmin(ctx); err != nil { if err := tokenverify.CheckAdmin(ctx); err != nil {
return nil, err return nil, err
@ -111,14 +129,22 @@ func (s *friendServer) ImportFriends(ctx context.Context, req *pbfriend.ImportFr
} }
// ok // ok
func (s *friendServer) RespondFriendApply(ctx context.Context, req *pbfriend.RespondFriendApplyReq) (resp *pbfriend.RespondFriendApplyResp, err error) { func (s *friendServer) RespondFriendApply(
ctx context.Context,
req *pbfriend.RespondFriendApplyReq,
) (resp *pbfriend.RespondFriendApplyResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.RespondFriendApplyResp{} resp = &pbfriend.RespondFriendApplyResp{}
if err := tokenverify.CheckAccessV3(ctx, req.ToUserID); err != nil { if err := tokenverify.CheckAccessV3(ctx, req.ToUserID); err != nil {
return nil, err return nil, err
} }
friendRequest := tablerelation.FriendRequestModel{FromUserID: req.FromUserID, ToUserID: req.ToUserID, HandleMsg: req.HandleMsg, HandleResult: req.HandleResult} friendRequest := tablerelation.FriendRequestModel{
FromUserID: req.FromUserID,
ToUserID: req.ToUserID,
HandleMsg: req.HandleMsg,
HandleResult: req.HandleResult,
}
if req.HandleResult == constant.FriendResponseAgree { if req.HandleResult == constant.FriendResponseAgree {
err := s.friendDatabase.AgreeFriendRequest(ctx, &friendRequest) err := s.friendDatabase.AgreeFriendRequest(ctx, &friendRequest)
if err != nil { if err != nil {
@ -139,7 +165,10 @@ func (s *friendServer) RespondFriendApply(ctx context.Context, req *pbfriend.Res
} }
// ok // ok
func (s *friendServer) DeleteFriend(ctx context.Context, req *pbfriend.DeleteFriendReq) (resp *pbfriend.DeleteFriendResp, err error) { func (s *friendServer) DeleteFriend(
ctx context.Context,
req *pbfriend.DeleteFriendReq,
) (resp *pbfriend.DeleteFriendResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.DeleteFriendResp{} resp = &pbfriend.DeleteFriendResp{}
if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil { if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil {
@ -157,7 +186,10 @@ func (s *friendServer) DeleteFriend(ctx context.Context, req *pbfriend.DeleteFri
} }
// ok // ok
func (s *friendServer) SetFriendRemark(ctx context.Context, req *pbfriend.SetFriendRemarkReq) (resp *pbfriend.SetFriendRemarkResp, err error) { func (s *friendServer) SetFriendRemark(
ctx context.Context,
req *pbfriend.SetFriendRemarkReq,
) (resp *pbfriend.SetFriendRemarkResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.SetFriendRemarkResp{} resp = &pbfriend.SetFriendRemarkResp{}
if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil { if err := s.userRpcClient.Access(ctx, req.OwnerUserID); err != nil {
@ -175,7 +207,10 @@ func (s *friendServer) SetFriendRemark(ctx context.Context, req *pbfriend.SetFri
} }
// ok // ok
func (s *friendServer) GetDesignatedFriends(ctx context.Context, req *pbfriend.GetDesignatedFriendsReq) (resp *pbfriend.GetDesignatedFriendsResp, err error) { func (s *friendServer) GetDesignatedFriends(
ctx context.Context,
req *pbfriend.GetDesignatedFriendsReq,
) (resp *pbfriend.GetDesignatedFriendsResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.GetDesignatedFriendsResp{} resp = &pbfriend.GetDesignatedFriendsResp{}
if utils.Duplicate(req.FriendUserIDs) { if utils.Duplicate(req.FriendUserIDs) {
@ -192,7 +227,10 @@ func (s *friendServer) GetDesignatedFriends(ctx context.Context, req *pbfriend.G
} }
// ok 获取接收到的好友申请(即别人主动申请的) // ok 获取接收到的好友申请(即别人主动申请的)
func (s *friendServer) GetPaginationFriendsApplyTo(ctx context.Context, req *pbfriend.GetPaginationFriendsApplyToReq) (resp *pbfriend.GetPaginationFriendsApplyToResp, err error) { func (s *friendServer) GetPaginationFriendsApplyTo(
ctx context.Context,
req *pbfriend.GetPaginationFriendsApplyToReq,
) (resp *pbfriend.GetPaginationFriendsApplyToResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.GetPaginationFriendsApplyToResp{} resp = &pbfriend.GetPaginationFriendsApplyToResp{}
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
@ -212,7 +250,10 @@ func (s *friendServer) GetPaginationFriendsApplyTo(ctx context.Context, req *pbf
} }
// ok 获取主动发出去的好友申请列表 // ok 获取主动发出去的好友申请列表
func (s *friendServer) GetPaginationFriendsApplyFrom(ctx context.Context, req *pbfriend.GetPaginationFriendsApplyFromReq) (resp *pbfriend.GetPaginationFriendsApplyFromResp, err error) { func (s *friendServer) GetPaginationFriendsApplyFrom(
ctx context.Context,
req *pbfriend.GetPaginationFriendsApplyFromReq,
) (resp *pbfriend.GetPaginationFriendsApplyFromResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.GetPaginationFriendsApplyFromResp{} resp = &pbfriend.GetPaginationFriendsApplyFromResp{}
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
@ -232,7 +273,10 @@ func (s *friendServer) GetPaginationFriendsApplyFrom(ctx context.Context, req *p
} }
// ok // ok
func (s *friendServer) IsFriend(ctx context.Context, req *pbfriend.IsFriendReq) (resp *pbfriend.IsFriendResp, err error) { func (s *friendServer) IsFriend(
ctx context.Context,
req *pbfriend.IsFriendReq,
) (resp *pbfriend.IsFriendResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
resp = &pbfriend.IsFriendResp{} resp = &pbfriend.IsFriendResp{}
resp.InUser1Friends, resp.InUser2Friends, err = s.friendDatabase.CheckIn(ctx, req.UserID1, req.UserID2) resp.InUser1Friends, resp.InUser2Friends, err = s.friendDatabase.CheckIn(ctx, req.UserID1, req.UserID2)
@ -243,7 +287,10 @@ func (s *friendServer) IsFriend(ctx context.Context, req *pbfriend.IsFriendReq)
} }
// ok // ok
func (s *friendServer) GetPaginationFriends(ctx context.Context, req *pbfriend.GetPaginationFriendsReq) (resp *pbfriend.GetPaginationFriendsResp, err error) { func (s *friendServer) GetPaginationFriends(
ctx context.Context,
req *pbfriend.GetPaginationFriendsReq,
) (resp *pbfriend.GetPaginationFriendsResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err return nil, err
@ -262,7 +309,10 @@ func (s *friendServer) GetPaginationFriends(ctx context.Context, req *pbfriend.G
return resp, nil return resp, nil
} }
func (s *friendServer) GetFriendIDs(ctx context.Context, req *pbfriend.GetFriendIDsReq) (resp *pbfriend.GetFriendIDsResp, err error) { func (s *friendServer) GetFriendIDs(
ctx context.Context,
req *pbfriend.GetFriendIDsReq,
) (resp *pbfriend.GetFriendIDsResp, err error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil { if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err return nil, err

View File

@ -7,7 +7,10 @@ import (
pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group" pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group"
) )
func (s *groupServer) GetGroupInfoCache(ctx context.Context, req *pbGroup.GetGroupInfoCacheReq) (resp *pbGroup.GetGroupInfoCacheResp, err error) { func (s *groupServer) GetGroupInfoCache(
ctx context.Context,
req *pbGroup.GetGroupInfoCacheReq,
) (resp *pbGroup.GetGroupInfoCacheResp, err error) {
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID) group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -16,7 +19,10 @@ func (s *groupServer) GetGroupInfoCache(ctx context.Context, req *pbGroup.GetGro
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMemberCache(ctx context.Context, req *pbGroup.GetGroupMemberCacheReq) (resp *pbGroup.GetGroupMemberCacheResp, err error) { func (s *groupServer) GetGroupMemberCache(
ctx context.Context,
req *pbGroup.GetGroupMemberCacheReq,
) (resp *pbGroup.GetGroupMemberCacheResp, err error) {
members, err := s.GroupDatabase.TakeGroupMember(ctx, req.GroupID, req.GroupMemberID) members, err := s.GroupDatabase.TakeGroupMember(ctx, req.GroupID, req.GroupMemberID)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -43,7 +43,13 @@ func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (
}) })
} }
resp := &callbackstruct.CallbackBeforeCreateGroupResp{} resp := &callbackstruct.CallbackBeforeCreateGroupResp{}
err = http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, cbReq, resp, config.Config.Callback.CallbackBeforeCreateGroup) err = http.CallBackPostReturn(
ctx,
config.Config.Callback.CallbackUrl,
cbReq,
resp,
config.Config.Callback.CallbackBeforeCreateGroup,
)
if err != nil { if err != nil {
if err == errs.ErrCallbackContinue { if err == errs.ErrCallbackContinue {
return nil return nil
@ -65,7 +71,11 @@ func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (
return nil return nil
} }
func CallbackBeforeMemberJoinGroup(ctx context.Context, groupMember *relation.GroupMemberModel, groupEx string) (err error) { func CallbackBeforeMemberJoinGroup(
ctx context.Context,
groupMember *relation.GroupMemberModel,
groupEx string,
) (err error) {
if !config.Config.Callback.CallbackBeforeMemberJoinGroup.Enable { if !config.Config.Callback.CallbackBeforeMemberJoinGroup.Enable {
return nil return nil
} }
@ -78,7 +88,13 @@ func CallbackBeforeMemberJoinGroup(ctx context.Context, groupMember *relation.Gr
GroupEx: groupEx, GroupEx: groupEx,
} }
resp := &callbackstruct.CallbackBeforeMemberJoinGroupResp{} resp := &callbackstruct.CallbackBeforeMemberJoinGroupResp{}
err = http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, callbackReq, resp, config.Config.Callback.CallbackBeforeMemberJoinGroup) err = http.CallBackPostReturn(
ctx,
config.Config.Callback.CallbackUrl,
callbackReq,
resp,
config.Config.Callback.CallbackBeforeMemberJoinGroup,
)
if err != nil { if err != nil {
if err == errs.ErrCallbackContinue { if err == errs.ErrCallbackContinue {
return nil return nil
@ -118,7 +134,13 @@ func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *group.SetGroupMe
callbackReq.Ex = &req.Ex.Value callbackReq.Ex = &req.Ex.Value
} }
resp := &callbackstruct.CallbackBeforeSetGroupMemberInfoResp{} resp := &callbackstruct.CallbackBeforeSetGroupMemberInfoResp{}
err = http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, callbackReq, resp, config.Config.Callback.CallbackBeforeSetGroupMemberInfo) err = http.CallBackPostReturn(
ctx,
config.Config.Callback.CallbackUrl,
callbackReq,
resp,
config.Config.Callback.CallbackBeforeSetGroupMemberInfo,
)
if err != nil { if err != nil {
if err == errs.ErrCallbackContinue { if err == errs.ErrCallbackContinue {
return nil return nil

View File

@ -27,7 +27,10 @@ func (s *groupServer) groupDB2PB(group *relation.GroupModel, ownerUserID string,
} }
} }
func (s *groupServer) groupMemberDB2PB(member *relation.GroupMemberModel, appMangerLevel int32) *sdkws.GroupMemberFullInfo { func (s *groupServer) groupMemberDB2PB(
member *relation.GroupMemberModel,
appMangerLevel int32,
) *sdkws.GroupMemberFullInfo {
return &sdkws.GroupMemberFullInfo{ return &sdkws.GroupMemberFullInfo{
GroupID: member.GroupID, GroupID: member.GroupID,
UserID: member.UserID, UserID: member.UserID,

View File

@ -7,7 +7,12 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
func (s *groupServer) FindGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) ([]*relationTb.GroupMemberModel, error) { func (s *groupServer) FindGroupMember(
ctx context.Context,
groupIDs []string,
userIDs []string,
roleLevels []int32,
) ([]*relationTb.GroupMemberModel, error) {
members, err := s.GroupDatabase.FindGroupMember(ctx, groupIDs, userIDs, roleLevels) members, err := s.GroupDatabase.FindGroupMember(ctx, groupIDs, userIDs, roleLevels)
if err != nil { if err != nil {
return nil, err return nil, err
@ -39,7 +44,11 @@ func (s *groupServer) FindGroupMember(ctx context.Context, groupIDs []string, us
return members, nil return members, nil
} }
func (s *groupServer) TakeGroupMember(ctx context.Context, groupID string, userID string) (*relationTb.GroupMemberModel, error) { func (s *groupServer) TakeGroupMember(
ctx context.Context,
groupID string,
userID string,
) (*relationTb.GroupMemberModel, error) {
member, err := s.GroupDatabase.TakeGroupMember(ctx, groupID, userID) member, err := s.GroupDatabase.TakeGroupMember(ctx, groupID, userID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -79,7 +88,11 @@ func (s *groupServer) TakeGroupOwner(ctx context.Context, groupID string) (*rela
return owner, nil return owner, nil
} }
func (s *groupServer) PageGetGroupMember(ctx context.Context, groupID string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupMemberModel, error) { func (s *groupServer) PageGetGroupMember(
ctx context.Context,
groupID string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupMemberModel, error) {
total, members, err := s.GroupDatabase.PageGetGroupMember(ctx, groupID, pageNumber, showNumber) total, members, err := s.GroupDatabase.PageGetGroupMember(ctx, groupID, pageNumber, showNumber)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err

View File

@ -15,6 +15,8 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -29,7 +31,6 @@ import (
pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group" pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
) )
func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error {
@ -55,13 +56,17 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
pbGroup.RegisterGroupServer(server, &groupServer{ pbGroup.RegisterGroupServer(server, &groupServer{
GroupDatabase: database, GroupDatabase: database,
User: userRpcClient, User: userRpcClient,
Notification: notification.NewGroupNotificationSender(database, &msgRpcClient, func(ctx context.Context, userIDs []string) ([]notification.CommonUser, error) { Notification: notification.NewGroupNotificationSender(
database,
&msgRpcClient,
func(ctx context.Context, userIDs []string) ([]notification.CommonUser, error) {
users, err := userRpcClient.GetUsersInfo(ctx, userIDs) users, err := userRpcClient.GetUsersInfo(ctx, userIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return utils.Slice(users, func(e *sdkws.UserInfo) notification.CommonUser { return e }), nil return utils.Slice(users, func(e *sdkws.UserInfo) notification.CommonUser { return e }), nil
}), },
),
conversationRpcClient: conversationRpcClient, conversationRpcClient: conversationRpcClient,
msgRpcClient: msgRpcClient, msgRpcClient: msgRpcClient,
}) })
@ -118,7 +123,16 @@ func (s *groupServer) GenGroupID(ctx context.Context, groupID *string) error {
} }
} }
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
id := utils.Md5(strings.Join([]string{mcontext.GetOperationID(ctx), strconv.FormatInt(time.Now().UnixNano(), 10), strconv.Itoa(rand.Int())}, ",;,")) id := utils.Md5(
strings.Join(
[]string{
mcontext.GetOperationID(ctx),
strconv.FormatInt(time.Now().UnixNano(), 10),
strconv.Itoa(rand.Int()),
},
",;,",
),
)
bi := big.NewInt(0) bi := big.NewInt(0)
bi.SetString(id[0:8], 16) bi.SetString(id[0:8], 16)
id = bi.String() id = bi.String()
@ -232,7 +246,10 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
return resp, nil return resp, nil
} }
func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJoinedGroupListReq) (*pbGroup.GetJoinedGroupListResp, error) { func (s *groupServer) GetJoinedGroupList(
ctx context.Context,
req *pbGroup.GetJoinedGroupListReq,
) (*pbGroup.GetJoinedGroupListResp, error) {
resp := &pbGroup.GetJoinedGroupListResp{} resp := &pbGroup.GetJoinedGroupListResp{}
if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil { if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil {
return nil, err return nil, err
@ -242,7 +259,8 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
pageNumber = req.Pagination.PageNumber pageNumber = req.Pagination.PageNumber
showNumber = req.Pagination.ShowNumber showNumber = req.Pagination.ShowNumber
} }
//total, members, err := s.GroupDatabase.PageGroupMember(ctx, nil, []string{req.FromUserID}, nil, pageNumber, showNumber) // total, members, err := s.GroupDatabase.PageGroupMember(ctx, nil, []string{req.FromUserID}, nil, pageNumber,
// showNumber)
total, members, err := s.GroupDatabase.PageGetJoinGroup(ctx, req.FromUserID, pageNumber, showNumber) total, members, err := s.GroupDatabase.PageGetJoinGroup(ctx, req.FromUserID, pageNumber, showNumber)
if err != nil { if err != nil {
return nil, err return nil, err
@ -281,7 +299,10 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
return resp, nil return resp, nil
} }
func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.InviteUserToGroupReq) (*pbGroup.InviteUserToGroupResp, error) { func (s *groupServer) InviteUserToGroup(
ctx context.Context,
req *pbGroup.InviteUserToGroupReq,
) (*pbGroup.InviteUserToGroupResp, error) {
resp := &pbGroup.InviteUserToGroupResp{} resp := &pbGroup.InviteUserToGroupResp{}
if len(req.InvitedUserIDs) == 0 { if len(req.InvitedUserIDs) == 0 {
return nil, errs.ErrArgs.Wrap("user empty") return nil, errs.ErrArgs.Wrap("user empty")
@ -382,7 +403,10 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGroupAllMemberReq) (*pbGroup.GetGroupAllMemberResp, error) { func (s *groupServer) GetGroupAllMember(
ctx context.Context,
req *pbGroup.GetGroupAllMemberReq,
) (*pbGroup.GetGroupAllMemberResp, error) {
resp := &pbGroup.GetGroupAllMemberResp{} resp := &pbGroup.GetGroupAllMemberResp{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID) group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil { if err != nil {
@ -410,7 +434,10 @@ func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGro
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGroupMemberListReq) (*pbGroup.GetGroupMemberListResp, error) { func (s *groupServer) GetGroupMemberList(
ctx context.Context,
req *pbGroup.GetGroupMemberListReq,
) (*pbGroup.GetGroupMemberListResp, error) {
resp := &pbGroup.GetGroupMemberListResp{} resp := &pbGroup.GetGroupMemberListResp{}
total, members, err := s.PageGetGroupMember(ctx, req.GroupID, req.Pagination.PageNumber, req.Pagination.ShowNumber) total, members, err := s.PageGetGroupMember(ctx, req.GroupID, req.Pagination.PageNumber, req.Pagination.ShowNumber)
log.ZDebug(ctx, "GetGroupMemberList", "total", total, "members", members, "length", len(members)) log.ZDebug(ctx, "GetGroupMemberList", "total", total, "members", members, "length", len(members))
@ -423,7 +450,10 @@ func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGr
return resp, nil return resp, nil
} }
func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGroupMemberReq) (*pbGroup.KickGroupMemberResp, error) { func (s *groupServer) KickGroupMember(
ctx context.Context,
req *pbGroup.KickGroupMemberReq,
) (*pbGroup.KickGroupMemberResp, error) {
resp := &pbGroup.KickGroupMemberResp{} resp := &pbGroup.KickGroupMemberResp{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID) group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil { if err != nil {
@ -531,7 +561,10 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetGroupMembersInfoReq) (*pbGroup.GetGroupMembersInfoResp, error) { func (s *groupServer) GetGroupMembersInfo(
ctx context.Context,
req *pbGroup.GetGroupMembersInfoReq,
) (*pbGroup.GetGroupMembersInfoResp, error) {
resp := &pbGroup.GetGroupMembersInfoResp{} resp := &pbGroup.GetGroupMembersInfoResp{}
if len(req.UserIDs) == 0 { if len(req.UserIDs) == 0 {
return nil, errs.ErrArgs.Wrap("userIDs empty") return nil, errs.ErrArgs.Wrap("userIDs empty")
@ -558,7 +591,10 @@ func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetG
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.GetGroupApplicationListReq) (*pbGroup.GetGroupApplicationListResp, error) { func (s *groupServer) GetGroupApplicationList(
ctx context.Context,
req *pbGroup.GetGroupApplicationListReq,
) (*pbGroup.GetGroupApplicationListResp, error) {
pageNumber, showNumber := utils.GetPage(req.Pagination) pageNumber, showNumber := utils.GetPage(req.Pagination)
groupIDs, err := s.GroupDatabase.FindUserManagedGroupID(ctx, req.FromUserID) groupIDs, err := s.GroupDatabase.FindUserManagedGroupID(ctx, req.FromUserID)
@ -609,12 +645,19 @@ func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.
return e.GroupID return e.GroupID
}) })
resp.GroupRequests = utils.Slice(groupRequests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest { resp.GroupRequests = utils.Slice(groupRequests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest {
return convert.Db2PbGroupRequest(e, userMap[e.UserID], convert.Db2PbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, groupMemberNumMap[e.GroupID])) return convert.Db2PbGroupRequest(
e,
userMap[e.UserID],
convert.Db2PbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, groupMemberNumMap[e.GroupID]),
)
}) })
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsInfoReq) (*pbGroup.GetGroupsInfoResp, error) { func (s *groupServer) GetGroupsInfo(
ctx context.Context,
req *pbGroup.GetGroupsInfoReq,
) (*pbGroup.GetGroupsInfoResp, error) {
resp := &pbGroup.GetGroupsInfoResp{} resp := &pbGroup.GetGroupsInfoResp{}
if len(req.GroupIDs) == 0 { if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupID is empty") return nil, errs.ErrArgs.Wrap("groupID is empty")
@ -644,7 +687,10 @@ func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsI
return resp, nil return resp, nil
} }
func (s *groupServer) GroupApplicationResponse(ctx context.Context, req *pbGroup.GroupApplicationResponseReq) (*pbGroup.GroupApplicationResponseResp, error) { func (s *groupServer) GroupApplicationResponse(
ctx context.Context,
req *pbGroup.GroupApplicationResponseReq,
) (*pbGroup.GroupApplicationResponseResp, error) {
defer log.ZInfo(ctx, utils.GetFuncName()+" Return") defer log.ZInfo(ctx, utils.GetFuncName()+" Return")
if !utils.Contain(req.HandleResult, constant.GroupResponseAgree, constant.GroupResponseRefuse) { if !utils.Contain(req.HandleResult, constant.GroupResponseAgree, constant.GroupResponseRefuse) {
return nil, errs.ErrArgs.Wrap("HandleResult unknown") return nil, errs.ErrArgs.Wrap("HandleResult unknown")
@ -716,7 +762,10 @@ func (s *groupServer) GroupApplicationResponse(ctx context.Context, req *pbGroup
return &pbGroup.GroupApplicationResponseResp{}, nil return &pbGroup.GroupApplicationResponseResp{}, nil
} }
func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq) (resp *pbGroup.JoinGroupResp, err error) { func (s *groupServer) JoinGroup(
ctx context.Context,
req *pbGroup.JoinGroupReq,
) (resp *pbGroup.JoinGroupResp, err error) {
defer log.ZInfo(ctx, "JoinGroup.Return") defer log.ZInfo(ctx, "JoinGroup.Return")
user, err := s.User.GetUserInfo(ctx, req.InviterUserID) user, err := s.User.GetUserInfo(ctx, req.InviterUserID)
if err != nil { if err != nil {
@ -816,7 +865,10 @@ func (s *groupServer) deleteMemberAndSetConversationSeq(ctx context.Context, gro
return s.conversationRpcClient.SetConversationMaxSeq(ctx, userIDs, conevrsationID, maxSeq) return s.conversationRpcClient.SetConversationMaxSeq(ctx, userIDs, conevrsationID, maxSeq)
} }
func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInfoReq) (*pbGroup.SetGroupInfoResp, error) { func (s *groupServer) SetGroupInfo(
ctx context.Context,
req *pbGroup.SetGroupInfoReq,
) (*pbGroup.SetGroupInfoResp, error) {
var opMember *relationTb.GroupMemberModel var opMember *relationTb.GroupMemberModel
if !tokenverify.IsAppManagerUid(ctx) { if !tokenverify.IsAppManagerUid(ctx) {
var err error var err error
@ -866,7 +918,10 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
var num int var num int
if req.GroupInfoForSet.Notification != "" { if req.GroupInfoForSet.Notification != "" {
num++ num++
s.Notification.GroupInfoSetAnnouncementNotification(ctx, &sdkws.GroupInfoSetAnnouncementTips{Group: tips.Group, OpUser: tips.OpUser}) s.Notification.GroupInfoSetAnnouncementNotification(
ctx,
&sdkws.GroupInfoSetAnnouncementTips{Group: tips.Group, OpUser: tips.OpUser},
)
} }
switch len(data) - num { switch len(data) - num {
@ -883,7 +938,10 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
return resp, nil return resp, nil
} }
func (s *groupServer) TransferGroupOwner(ctx context.Context, req *pbGroup.TransferGroupOwnerReq) (*pbGroup.TransferGroupOwnerResp, error) { func (s *groupServer) TransferGroupOwner(
ctx context.Context,
req *pbGroup.TransferGroupOwnerReq,
) (*pbGroup.TransferGroupOwnerResp, error) {
resp := &pbGroup.TransferGroupOwnerResp{} resp := &pbGroup.TransferGroupOwnerResp{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID) group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil { if err != nil {
@ -962,9 +1020,20 @@ func (s *groupServer) GetGroups(ctx context.Context, req *pbGroup.GetGroupsReq)
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMembersCMS(ctx context.Context, req *pbGroup.GetGroupMembersCMSReq) (*pbGroup.GetGroupMembersCMSResp, error) { func (s *groupServer) GetGroupMembersCMS(
ctx context.Context,
req *pbGroup.GetGroupMembersCMSReq,
) (*pbGroup.GetGroupMembersCMSResp, error) {
resp := &pbGroup.GetGroupMembersCMSResp{} resp := &pbGroup.GetGroupMembersCMSResp{}
total, members, err := s.GroupDatabase.SearchGroupMember(ctx, req.UserName, []string{req.GroupID}, nil, nil, req.Pagination.PageNumber, req.Pagination.ShowNumber) total, members, err := s.GroupDatabase.SearchGroupMember(
ctx,
req.UserName,
[]string{req.GroupID},
nil,
nil,
req.Pagination.PageNumber,
req.Pagination.ShowNumber,
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -984,7 +1053,10 @@ func (s *groupServer) GetGroupMembersCMS(ctx context.Context, req *pbGroup.GetGr
return resp, nil return resp, nil
} }
func (s *groupServer) GetUserReqApplicationList(ctx context.Context, req *pbGroup.GetUserReqApplicationListReq) (*pbGroup.GetUserReqApplicationListResp, error) { func (s *groupServer) GetUserReqApplicationList(
ctx context.Context,
req *pbGroup.GetUserReqApplicationListReq,
) (*pbGroup.GetUserReqApplicationListResp, error) {
resp := &pbGroup.GetUserReqApplicationListResp{} resp := &pbGroup.GetUserReqApplicationListResp{}
user, err := s.User.GetPublicUserInfo(ctx, req.UserID) user, err := s.User.GetPublicUserInfo(ctx, req.UserID)
if err != nil { if err != nil {
@ -1031,12 +1103,19 @@ func (s *groupServer) GetUserReqApplicationList(ctx context.Context, req *pbGrou
return nil, err return nil, err
} }
resp.GroupRequests = utils.Slice(requests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest { resp.GroupRequests = utils.Slice(requests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest {
return convert.Db2PbGroupRequest(e, user, convert.Db2PbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, uint32(groupMemberNum[e.GroupID]))) return convert.Db2PbGroupRequest(
e,
user,
convert.Db2PbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, uint32(groupMemberNum[e.GroupID])),
)
}) })
return resp, nil return resp, nil
} }
func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGroupReq) (*pbGroup.DismissGroupResp, error) { func (s *groupServer) DismissGroup(
ctx context.Context,
req *pbGroup.DismissGroupReq,
) (*pbGroup.DismissGroupResp, error) {
defer log.ZInfo(ctx, "DismissGroup.return") defer log.ZInfo(ctx, "DismissGroup.return")
resp := &pbGroup.DismissGroupResp{} resp := &pbGroup.DismissGroupResp{}
owner, err := s.TakeGroupOwner(ctx, req.GroupID) owner, err := s.TakeGroupOwner(ctx, req.GroupID)
@ -1085,7 +1164,10 @@ func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGrou
return resp, nil return resp, nil
} }
func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGroupMemberReq) (*pbGroup.MuteGroupMemberResp, error) { func (s *groupServer) MuteGroupMember(
ctx context.Context,
req *pbGroup.MuteGroupMemberReq,
) (*pbGroup.MuteGroupMemberResp, error) {
resp := &pbGroup.MuteGroupMemberResp{} resp := &pbGroup.MuteGroupMemberResp{}
//if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil { //if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil {
// return nil, err // return nil, err
@ -1120,7 +1202,10 @@ func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGrou
return resp, nil return resp, nil
} }
func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.CancelMuteGroupMemberReq) (*pbGroup.CancelMuteGroupMemberResp, error) { func (s *groupServer) CancelMuteGroupMember(
ctx context.Context,
req *pbGroup.CancelMuteGroupMemberReq,
) (*pbGroup.CancelMuteGroupMemberResp, error) {
resp := &pbGroup.CancelMuteGroupMemberResp{} resp := &pbGroup.CancelMuteGroupMemberResp{}
//member, err := s.GroupDatabase.TakeGroupMember(ctx, req.GroupID, req.UserID) //member, err := s.GroupDatabase.TakeGroupMember(ctx, req.GroupID, req.UserID)
//if err != nil { //if err != nil {
@ -1132,7 +1217,8 @@ func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.Ca
// return nil, err // return nil, err
// } // }
// if opMember.RoleLevel <= member.RoleLevel { // if opMember.RoleLevel <= member.RoleLevel {
// return nil, errs.ErrNoPermission.Wrap(fmt.Sprintf("self RoleLevel %d target %d", opMember.RoleLevel, member.RoleLevel)) // return nil, errs.ErrNoPermission.Wrap(fmt.Sprintf("self RoleLevel %d target %d", opMember.RoleLevel,
// member.RoleLevel))
// } // }
//} //}
//if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil { //if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil {
@ -1180,7 +1266,10 @@ func (s *groupServer) MuteGroup(ctx context.Context, req *pbGroup.MuteGroupReq)
return resp, nil return resp, nil
} }
func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMuteGroupReq) (*pbGroup.CancelMuteGroupResp, error) { func (s *groupServer) CancelMuteGroup(
ctx context.Context,
req *pbGroup.CancelMuteGroupReq,
) (*pbGroup.CancelMuteGroupResp, error) {
resp := &pbGroup.CancelMuteGroupResp{} resp := &pbGroup.CancelMuteGroupResp{}
if err := s.CheckGroupAdmin(ctx, req.GroupID); err != nil { if err := s.CheckGroupAdmin(ctx, req.GroupID); err != nil {
return nil, err return nil, err
@ -1192,7 +1281,10 @@ func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMu
return resp, nil return resp, nil
} }
func (s *groupServer) SetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGroupMemberInfoReq) (*pbGroup.SetGroupMemberInfoResp, error) { func (s *groupServer) SetGroupMemberInfo(
ctx context.Context,
req *pbGroup.SetGroupMemberInfoReq,
) (*pbGroup.SetGroupMemberInfoResp, error) {
resp := &pbGroup.SetGroupMemberInfoResp{} resp := &pbGroup.SetGroupMemberInfoResp{}
if len(req.Members) == 0 { if len(req.Members) == 0 {
return nil, errs.ErrArgs.Wrap("members empty") return nil, errs.ErrArgs.Wrap("members empty")
@ -1219,9 +1311,11 @@ func (s *groupServer) SetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGr
delete(duplicateMap, [...]string{member.GroupID, member.UserID}) delete(duplicateMap, [...]string{member.GroupID, member.UserID})
} }
if len(duplicateMap) > 0 { if len(duplicateMap) > 0 {
return nil, errs.ErrArgs.Wrap("user not found" + strings.Join(utils.Slice(utils.Keys(duplicateMap), func(e [2]string) string { return nil, errs.ErrArgs.Wrap(
"user not found" + strings.Join(utils.Slice(utils.Keys(duplicateMap), func(e [2]string) string {
return fmt.Sprintf("[group: %s user: %s]", e[0], e[1]) return fmt.Sprintf("[group: %s user: %s]", e[0], e[1])
}), ",")) }), ","),
)
} }
memberMap := utils.SliceToMap(members, func(e *relationTb.GroupMemberModel) [2]string { memberMap := utils.SliceToMap(members, func(e *relationTb.GroupMemberModel) [2]string {
return [...]string{e.GroupID, e.UserID} return [...]string{e.GroupID, e.UserID}
@ -1251,7 +1345,9 @@ func (s *groupServer) SetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGr
} }
dbMember, ok := memberMap[[...]string{member.GroupID, member.UserID}] dbMember, ok := memberMap[[...]string{member.GroupID, member.UserID}]
if !ok { if !ok {
return nil, errs.ErrRecordNotFound.Wrap(fmt.Sprintf("user %s not in group %s", member.UserID, member.GroupID)) return nil, errs.ErrRecordNotFound.Wrap(
fmt.Sprintf("user %s not in group %s", member.UserID, member.GroupID),
)
} }
//if opMember.RoleLevel == constant.GroupOwner { //if opMember.RoleLevel == constant.GroupOwner {
// continue // continue
@ -1313,14 +1409,25 @@ func (s *groupServer) SetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGr
if member.Nickname != nil || member.FaceURL != nil || member.Ex != nil { if member.Nickname != nil || member.FaceURL != nil || member.Ex != nil {
log.ZDebug(ctx, "setGroupMemberInfo notification", "member", member.UserID) log.ZDebug(ctx, "setGroupMemberInfo notification", "member", member.UserID)
if err := s.Notification.GroupMemberInfoSetNotification(ctx, member.GroupID, member.UserID); err != nil { if err := s.Notification.GroupMemberInfoSetNotification(ctx, member.GroupID, member.UserID); err != nil {
log.ZError(ctx, "setGroupMemberInfo notification failed", err, "member", member.UserID, "groupID", member.GroupID) log.ZError(
ctx,
"setGroupMemberInfo notification failed",
err,
"member",
member.UserID,
"groupID",
member.GroupID,
)
} }
} }
} }
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupAbstractInfo(ctx context.Context, req *pbGroup.GetGroupAbstractInfoReq) (*pbGroup.GetGroupAbstractInfoResp, error) { func (s *groupServer) GetGroupAbstractInfo(
ctx context.Context,
req *pbGroup.GetGroupAbstractInfoReq,
) (*pbGroup.GetGroupAbstractInfoResp, error) {
resp := &pbGroup.GetGroupAbstractInfoResp{} resp := &pbGroup.GetGroupAbstractInfoResp{}
if len(req.GroupIDs) == 0 { if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupIDs empty") return nil, errs.ErrArgs.Wrap("groupIDs empty")
@ -1351,7 +1458,10 @@ func (s *groupServer) GetGroupAbstractInfo(ctx context.Context, req *pbGroup.Get
return resp, nil return resp, nil
} }
func (s *groupServer) GetUserInGroupMembers(ctx context.Context, req *pbGroup.GetUserInGroupMembersReq) (*pbGroup.GetUserInGroupMembersResp, error) { func (s *groupServer) GetUserInGroupMembers(
ctx context.Context,
req *pbGroup.GetUserInGroupMembersReq,
) (*pbGroup.GetUserInGroupMembersResp, error) {
resp := &pbGroup.GetUserInGroupMembersResp{} resp := &pbGroup.GetUserInGroupMembersResp{}
if len(req.GroupIDs) == 0 { if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupIDs empty") return nil, errs.ErrArgs.Wrap("groupIDs empty")
@ -1375,7 +1485,10 @@ func (s *groupServer) GetUserInGroupMembers(ctx context.Context, req *pbGroup.Ge
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMemberUserIDs(ctx context.Context, req *pbGroup.GetGroupMemberUserIDsReq) (resp *pbGroup.GetGroupMemberUserIDsResp, err error) { func (s *groupServer) GetGroupMemberUserIDs(
ctx context.Context,
req *pbGroup.GetGroupMemberUserIDsReq,
) (resp *pbGroup.GetGroupMemberUserIDsResp, err error) {
resp = &pbGroup.GetGroupMemberUserIDsResp{} resp = &pbGroup.GetGroupMemberUserIDsResp{}
resp.UserIDs, err = s.GroupDatabase.FindGroupMemberUserID(ctx, req.GroupID) resp.UserIDs, err = s.GroupDatabase.FindGroupMemberUserID(ctx, req.GroupID)
if err != nil { if err != nil {
@ -1384,7 +1497,10 @@ func (s *groupServer) GetGroupMemberUserIDs(ctx context.Context, req *pbGroup.Ge
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMemberRoleLevel(ctx context.Context, req *pbGroup.GetGroupMemberRoleLevelReq) (*pbGroup.GetGroupMemberRoleLevelResp, error) { func (s *groupServer) GetGroupMemberRoleLevel(
ctx context.Context,
req *pbGroup.GetGroupMemberRoleLevelReq,
) (*pbGroup.GetGroupMemberRoleLevelResp, error) {
resp := &pbGroup.GetGroupMemberRoleLevelResp{} resp := &pbGroup.GetGroupMemberRoleLevelResp{}
if len(req.RoleLevels) == 0 { if len(req.RoleLevels) == 0 {
return nil, errs.ErrArgs.Wrap("RoleLevels empty") return nil, errs.ErrArgs.Wrap("RoleLevels empty")

View File

@ -15,7 +15,10 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
func (s *groupServer) GetJoinedSuperGroupList(ctx context.Context, req *pbGroup.GetJoinedSuperGroupListReq) (*pbGroup.GetJoinedSuperGroupListResp, error) { func (s *groupServer) GetJoinedSuperGroupList(
ctx context.Context,
req *pbGroup.GetJoinedSuperGroupListReq,
) (*pbGroup.GetJoinedSuperGroupListResp, error) {
resp := &pbGroup.GetJoinedSuperGroupListResp{} resp := &pbGroup.GetJoinedSuperGroupListResp{}
groupIDs, err := s.GroupDatabase.FindJoinSuperGroup(ctx, req.UserID) groupIDs, err := s.GroupDatabase.FindJoinSuperGroup(ctx, req.UserID)
if err != nil { if err != nil {
@ -48,16 +51,22 @@ func (s *groupServer) GetJoinedSuperGroupList(ctx context.Context, req *pbGroup.
if err != nil { if err != nil {
return nil, err return nil, err
} }
superGroupMemberMap := utils.SliceToMapAny(superGroupMembers, func(e *unrelation.SuperGroupModel) (string, []string) { superGroupMemberMap := utils.SliceToMapAny(
superGroupMembers,
func(e *unrelation.SuperGroupModel) (string, []string) {
return e.GroupID, e.MemberIDs return e.GroupID, e.MemberIDs
}) },
)
resp.Groups = utils.Slice(groupIDs, func(groupID string) *sdkws.GroupInfo { resp.Groups = utils.Slice(groupIDs, func(groupID string) *sdkws.GroupInfo {
return convert.Db2PbGroupInfo(groupMap[groupID], ownerMap[groupID].UserID, uint32(len(superGroupMemberMap))) return convert.Db2PbGroupInfo(groupMap[groupID], ownerMap[groupID].UserID, uint32(len(superGroupMemberMap)))
}) })
return resp, nil return resp, nil
} }
func (s *groupServer) GetSuperGroupsInfo(ctx context.Context, req *pbGroup.GetSuperGroupsInfoReq) (resp *pbGroup.GetSuperGroupsInfoResp, err error) { func (s *groupServer) GetSuperGroupsInfo(
ctx context.Context,
req *pbGroup.GetSuperGroupsInfoReq,
) (resp *pbGroup.GetSuperGroupsInfoResp, err error) {
resp = &pbGroup.GetSuperGroupsInfoResp{} resp = &pbGroup.GetSuperGroupsInfoResp{}
if len(req.GroupIDs) == 0 { if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupIDs empty") return nil, errs.ErrArgs.Wrap("groupIDs empty")
@ -70,9 +79,12 @@ func (s *groupServer) GetSuperGroupsInfo(ctx context.Context, req *pbGroup.GetSu
if err != nil { if err != nil {
return nil, err return nil, err
} }
superGroupMemberMap := utils.SliceToMapAny(superGroupMembers, func(e *unrelation.SuperGroupModel) (string, []string) { superGroupMemberMap := utils.SliceToMapAny(
superGroupMembers,
func(e *unrelation.SuperGroupModel) (string, []string) {
return e.GroupID, e.MemberIDs return e.GroupID, e.MemberIDs
}) },
)
owners, err := s.FindGroupMember(ctx, req.GroupIDs, nil, []int32{constant.GroupOwner}) owners, err := s.FindGroupMember(ctx, req.GroupIDs, nil, []int32{constant.GroupOwner})
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -3,15 +3,19 @@ package msg
import ( import (
"context" "context"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/redis/go-redis/v9"
) )
func (m *msgServer) GetConversationsHasReadAndMaxSeq(ctx context.Context, req *msg.GetConversationsHasReadAndMaxSeqReq) (*msg.GetConversationsHasReadAndMaxSeqResp, error) { func (m *msgServer) GetConversationsHasReadAndMaxSeq(
ctx context.Context,
req *msg.GetConversationsHasReadAndMaxSeqReq,
) (*msg.GetConversationsHasReadAndMaxSeqResp, error) {
conversationIDs, err := m.ConversationLocalCache.GetConversationIDs(ctx, req.UserID) conversationIDs, err := m.ConversationLocalCache.GetConversationIDs(ctx, req.UserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -47,7 +51,10 @@ func (m *msgServer) GetConversationsHasReadAndMaxSeq(ctx context.Context, req *m
return resp, nil return resp, nil
} }
func (m *msgServer) SetConversationHasReadSeq(ctx context.Context, req *msg.SetConversationHasReadSeqReq) (resp *msg.SetConversationHasReadSeqResp, err error) { func (m *msgServer) SetConversationHasReadSeq(
ctx context.Context,
req *msg.SetConversationHasReadSeqReq,
) (resp *msg.SetConversationHasReadSeqResp, err error) {
maxSeq, err := m.MsgDatabase.GetMaxSeq(ctx, req.ConversationID) maxSeq, err := m.MsgDatabase.GetMaxSeq(ctx, req.ConversationID)
if err != nil { if err != nil {
return return
@ -64,7 +71,10 @@ func (m *msgServer) SetConversationHasReadSeq(ctx context.Context, req *msg.SetC
return &msg.SetConversationHasReadSeqResp{}, nil return &msg.SetConversationHasReadSeqResp{}, nil
} }
func (m *msgServer) MarkMsgsAsRead(ctx context.Context, req *msg.MarkMsgsAsReadReq) (resp *msg.MarkMsgsAsReadResp, err error) { func (m *msgServer) MarkMsgsAsRead(
ctx context.Context,
req *msg.MarkMsgsAsReadReq,
) (resp *msg.MarkMsgsAsReadResp, err error) {
if len(req.Seqs) < 1 { if len(req.Seqs) < 1 {
return nil, errs.ErrArgs.Wrap("seqs must not be empty") return nil, errs.ErrArgs.Wrap("seqs must not be empty")
} }
@ -99,7 +109,10 @@ func (m *msgServer) MarkMsgsAsRead(ctx context.Context, req *msg.MarkMsgsAsReadR
return &msg.MarkMsgsAsReadResp{}, nil return &msg.MarkMsgsAsReadResp{}, nil
} }
func (m *msgServer) MarkConversationAsRead(ctx context.Context, req *msg.MarkConversationAsReadReq) (resp *msg.MarkConversationAsReadResp, err error) { func (m *msgServer) MarkConversationAsRead(
ctx context.Context,
req *msg.MarkConversationAsReadReq,
) (resp *msg.MarkConversationAsReadResp, err error) {
conversation, err := m.Conversation.GetConversation(ctx, req.UserID, req.ConversationID) conversation, err := m.Conversation.GetConversation(ctx, req.UserID, req.ConversationID)
if err != nil { if err != nil {
return return
@ -136,7 +149,14 @@ func (m *msgServer) MarkConversationAsRead(ctx context.Context, req *msg.MarkCon
return &msg.MarkConversationAsReadResp{}, nil return &msg.MarkConversationAsReadResp{}, nil
} }
func (m *msgServer) sendMarkAsReadNotification(ctx context.Context, conversationID string, sesstionType int32, sendID, recvID string, seqs []int64, hasReadSeq int64) error { func (m *msgServer) sendMarkAsReadNotification(
ctx context.Context,
conversationID string,
sesstionType int32,
sendID, recvID string,
seqs []int64,
hasReadSeq int64,
) error {
tips := &sdkws.MarkAsReadTips{ tips := &sdkws.MarkAsReadTips{
MarkAsReadUserID: sendID, MarkAsReadUserID: sendID,
ConversationID: conversationID, ConversationID: conversationID,

View File

@ -27,7 +27,10 @@ func (m *msgServer) validateDeleteSyncOpt(opt *msg.DeleteSyncOpt) (isSyncSelf, i
return opt.IsSyncSelf, opt.IsSyncOther return opt.IsSyncSelf, opt.IsSyncOther
} }
func (m *msgServer) ClearConversationsMsg(ctx context.Context, req *msg.ClearConversationsMsgReq) (*msg.ClearConversationsMsgResp, error) { func (m *msgServer) ClearConversationsMsg(
ctx context.Context,
req *msg.ClearConversationsMsgReq,
) (*msg.ClearConversationsMsgResp, error) {
if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil { if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil {
return nil, err return nil, err
} }
@ -37,7 +40,10 @@ func (m *msgServer) ClearConversationsMsg(ctx context.Context, req *msg.ClearCon
return &msg.ClearConversationsMsgResp{}, nil return &msg.ClearConversationsMsgResp{}, nil
} }
func (m *msgServer) UserClearAllMsg(ctx context.Context, req *msg.UserClearAllMsgReq) (*msg.UserClearAllMsgResp, error) { func (m *msgServer) UserClearAllMsg(
ctx context.Context,
req *msg.UserClearAllMsgReq,
) (*msg.UserClearAllMsgResp, error) {
if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil { if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil {
return nil, err return nil, err
} }
@ -66,7 +72,14 @@ func (m *msgServer) DeleteMsgs(ctx context.Context, req *msg.DeleteMsgsReq) (*ms
return nil, err return nil, err
} }
tips := &sdkws.DeleteMsgsTips{UserID: req.UserID, ConversationID: req.ConversationID, Seqs: req.Seqs} tips := &sdkws.DeleteMsgsTips{UserID: req.UserID, ConversationID: req.ConversationID, Seqs: req.Seqs}
m.notificationSender.NotificationWithSesstionType(ctx, req.UserID, m.conversationAndGetRecvID(conversations[0], req.UserID), constant.DeleteMsgsNotification, conversations[0].ConversationType, tips) m.notificationSender.NotificationWithSesstionType(
ctx,
req.UserID,
m.conversationAndGetRecvID(conversations[0], req.UserID),
constant.DeleteMsgsNotification,
conversations[0].ConversationType,
tips,
)
} else { } else {
if err := m.MsgDatabase.DeleteUserMsgsBySeqs(ctx, req.UserID, req.ConversationID, req.Seqs); err != nil { if err := m.MsgDatabase.DeleteUserMsgsBySeqs(ctx, req.UserID, req.ConversationID, req.Seqs); err != nil {
return nil, err return nil, err
@ -79,7 +92,10 @@ func (m *msgServer) DeleteMsgs(ctx context.Context, req *msg.DeleteMsgsReq) (*ms
return &msg.DeleteMsgsResp{}, nil return &msg.DeleteMsgsResp{}, nil
} }
func (m *msgServer) DeleteMsgPhysicalBySeq(ctx context.Context, req *msg.DeleteMsgPhysicalBySeqReq) (*msg.DeleteMsgPhysicalBySeqResp, error) { func (m *msgServer) DeleteMsgPhysicalBySeq(
ctx context.Context,
req *msg.DeleteMsgPhysicalBySeqReq,
) (*msg.DeleteMsgPhysicalBySeqResp, error) {
err := m.MsgDatabase.DeleteMsgsPhysicalBySeqs(ctx, req.ConversationID, req.Seqs) err := m.MsgDatabase.DeleteMsgsPhysicalBySeqs(ctx, req.ConversationID, req.Seqs)
if err != nil { if err != nil {
return nil, err return nil, err
@ -87,20 +103,36 @@ func (m *msgServer) DeleteMsgPhysicalBySeq(ctx context.Context, req *msg.DeleteM
return &msg.DeleteMsgPhysicalBySeqResp{}, nil return &msg.DeleteMsgPhysicalBySeqResp{}, nil
} }
func (m *msgServer) DeleteMsgPhysical(ctx context.Context, req *msg.DeleteMsgPhysicalReq) (*msg.DeleteMsgPhysicalResp, error) { func (m *msgServer) DeleteMsgPhysical(
ctx context.Context,
req *msg.DeleteMsgPhysicalReq,
) (*msg.DeleteMsgPhysicalResp, error) {
if err := tokenverify.CheckAdmin(ctx); err != nil { if err := tokenverify.CheckAdmin(ctx); err != nil {
return nil, err return nil, err
} }
remainTime := utils.GetCurrentTimestampBySecond() - req.Timestamp remainTime := utils.GetCurrentTimestampBySecond() - req.Timestamp
for _, conversationID := range req.ConversationIDs { for _, conversationID := range req.ConversationIDs {
if err := m.MsgDatabase.DeleteConversationMsgsAndSetMinSeq(ctx, conversationID, remainTime); err != nil { if err := m.MsgDatabase.DeleteConversationMsgsAndSetMinSeq(ctx, conversationID, remainTime); err != nil {
log.ZWarn(ctx, "DeleteConversationMsgsAndSetMinSeq error", err, "conversationID", conversationID, "err", err) log.ZWarn(
ctx,
"DeleteConversationMsgsAndSetMinSeq error",
err,
"conversationID",
conversationID,
"err",
err,
)
} }
} }
return &msg.DeleteMsgPhysicalResp{}, nil return &msg.DeleteMsgPhysicalResp{}, nil
} }
func (m *msgServer) clearConversation(ctx context.Context, conversationIDs []string, userID string, deleteSyncOpt *msg.DeleteSyncOpt) error { func (m *msgServer) clearConversation(
ctx context.Context,
conversationIDs []string,
userID string,
deleteSyncOpt *msg.DeleteSyncOpt,
) error {
defer log.ZDebug(ctx, "clearConversation return line") defer log.ZDebug(ctx, "clearConversation return line")
conversations, err := m.Conversation.GetConversationsByConversationID(ctx, conversationIDs) conversations, err := m.Conversation.GetConversationsByConversationID(ctx, conversationIDs)
if err != nil { if err != nil {
@ -125,7 +157,14 @@ func (m *msgServer) clearConversation(ctx context.Context, conversationIDs []str
// notification 2 self // notification 2 self
if isSyncSelf { if isSyncSelf {
tips := &sdkws.ClearConversationTips{UserID: userID, ConversationIDs: existConversationIDs} tips := &sdkws.ClearConversationTips{UserID: userID, ConversationIDs: existConversationIDs}
m.notificationSender.NotificationWithSesstionType(ctx, userID, userID, constant.ClearConversationNotification, constant.SingleChatType, tips) m.notificationSender.NotificationWithSesstionType(
ctx,
userID,
userID,
constant.ClearConversationNotification,
constant.SingleChatType,
tips,
)
} }
} else { } else {
if err := m.MsgDatabase.SetMinSeqs(ctx, m.getMinSeqs(maxSeqs)); err != nil { if err := m.MsgDatabase.SetMinSeqs(ctx, m.getMinSeqs(maxSeqs)); err != nil {

View File

@ -7,7 +7,10 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
) )
func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.SetMessageReactionExtensionsReq) (resp *msg.SetMessageReactionExtensionsResp, err error) { func (m *msgServer) SetMessageReactionExtensions(
ctx context.Context,
req *msg.SetMessageReactionExtensionsReq,
) (resp *msg.SetMessageReactionExtensionsResp, err error) {
//resp = &msg.SetMessageReactionExtensionsResp{} //resp = &msg.SetMessageReactionExtensionsResp{}
////resp.ClientMsgID = req.ClientMsgID ////resp.ClientMsgID = req.ClientMsgID
////resp.MsgFirstModifyTime = req.MsgFirstModifyTime ////resp.MsgFirstModifyTime = req.MsgFirstModifyTime
@ -18,7 +21,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
////if ExternalExtension ////if ExternalExtension
//if req.IsExternalExtensions { //if req.IsExternalExtensions {
// resp.MsgFirstModifyTime = req.MsgFirstModifyTime // resp.MsgFirstModifyTime = req.MsgFirstModifyTime
// notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &resp, !req.IsReact, false) // notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID,
// req.SessionType, req, &resp, !req.IsReact, false)
// return resp, nil // return resp, nil
//} //}
//isExists, err := m.MsgDatabase.JudgeMessageReactionExist(ctx, req.ClientMsgID, req.SessionType) //isExists, err := m.MsgDatabase.JudgeMessageReactionExist(ctx, req.ClientMsgID, req.SessionType)
@ -35,12 +39,14 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// return nil, err // return nil, err
// } // }
// v.LatestUpdateTime = utils.GetCurrentTimestampByMill() // v.LatestUpdateTime = utils.GetCurrentTimestampByMill()
// if err := m.MsgDatabase.SetMessageTypeKeyValue(ctx, req.ClientMsgID, req.SessionType, k, utils.StructToJsonString(v)); err != nil { // if err := m.MsgDatabase.SetMessageTypeKeyValue(ctx, req.ClientMsgID, req.SessionType, k,
// utils.StructToJsonString(v)); err != nil {
// return nil, err // return nil, err
// } // }
// } // }
// resp.IsReact = true // resp.IsReact = true
// _, err := m.MsgDatabase.SetMessageReactionExpire(ctx, req.ClientMsgID, req.SessionType, time.Duration(24*3)*time.Hour) // _, err := m.MsgDatabase.SetMessageReactionExpire(ctx, req.ClientMsgID, req.SessionType,
// time.Duration(24*3)*time.Hour)
// if err != nil { // if err != nil {
// return nil, err // return nil, err
// } // }
@ -49,7 +55,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// if err != nil { // if err != nil {
// return nil, err // return nil, err
// } // }
// mongoValue, err := m.MsgDatabase.GetExtendMsg(ctx, req.conversationID, req.SessionType, req.ClientMsgID, req.MsgFirstModifyTime) // mongoValue, err := m.MsgDatabase.GetExtendMsg(ctx, req.conversationID, req.SessionType, req.ClientMsgID,
// req.MsgFirstModifyTime)
// if err != nil { // if err != nil {
// return nil, err // return nil, err
// } // }
@ -69,7 +76,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// temp.LatestUpdateTime = utils.GetCurrentTimestampByMill() // temp.LatestUpdateTime = utils.GetCurrentTimestampByMill()
// setValue[k] = temp // setValue[k] = temp
// } // }
// err = db.DB.InsertOrUpdateReactionExtendMsgSet(req.conversationID, req.SessionType, req.ClientMsgID, req.MsgFirstModifyTime, setValue) // err = db.DB.InsertOrUpdateReactionExtendMsgSet(req.conversationID, req.SessionType, req.ClientMsgID,
// req.MsgFirstModifyTime, setValue)
// if err != nil { // if err != nil {
// for _, value := range setValue { // for _, value := range setValue {
// temp := new(msg.KeyValueResp) // temp := new(msg.KeyValueResp)
@ -124,26 +132,28 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
//} //}
//if !isExists { //if !isExists {
// if !req.IsReact { // if !req.IsReact {
// notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &resp, true, true) // notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID,
// req.SessionType, req, &resp, true, true)
// } else { // } else {
// notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &resp, false, false) // notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID,
// req.SessionType, req, &resp, false, false)
// } // }
//} else { //} else {
// notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &resp, false, true) // notification.ExtendMessageUpdatedNotification(req.OperationID, req.OpUserID, req.conversationID,
// req.SessionType, req, &resp, false, true)
//} //}
//log.Debug(req.OperationID, utils.GetSelfFuncName(), "m return is:", resp.String()) //log.Debug(req.OperationID, utils.GetSelfFuncName(), "m return is:", resp.String())
return resp, nil return resp, nil
} }
func (m *msgServer) setKeyResultInfo(ctx context.Context, r *msg.SetMessageReactionExtensionsResp, errCode int32, errMsg, clientMsgID, typeKey string, keyValue *sdkws.KeyValue) {
temp := new(msg.KeyValueResp) func (m *msgServer) setKeyResultInfo(
temp.KeyValue = keyValue ctx context.Context,
temp.ErrCode = errCode r *msg.SetMessageReactionExtensionsResp,
temp.ErrMsg = errMsg errCode int32,
r.Result = append(r.Result, temp) errMsg, clientMsgID, typeKey string,
_ = m.MessageLocker.UnLockMessageTypeKey(ctx, clientMsgID, typeKey) keyValue *sdkws.KeyValue,
} ) {
func (m *msgServer) setDeleteKeyResultInfo(ctx context.Context, r *msg.DeleteMessagesReactionExtensionsResp, errCode int32, errMsg, clientMsgID, typeKey string, keyValue *sdkws.KeyValue) {
temp := new(msg.KeyValueResp) temp := new(msg.KeyValueResp)
temp.KeyValue = keyValue temp.KeyValue = keyValue
temp.ErrCode = errCode temp.ErrCode = errCode
@ -152,7 +162,25 @@ func (m *msgServer) setDeleteKeyResultInfo(ctx context.Context, r *msg.DeleteMes
_ = m.MessageLocker.UnLockMessageTypeKey(ctx, clientMsgID, typeKey) _ = m.MessageLocker.UnLockMessageTypeKey(ctx, clientMsgID, typeKey)
} }
func (m *msgServer) GetMessagesReactionExtensions(ctx context.Context, req *msg.GetMessagesReactionExtensionsReq) (resp *msg.GetMessagesReactionExtensionsResp, err error) { func (m *msgServer) setDeleteKeyResultInfo(
ctx context.Context,
r *msg.DeleteMessagesReactionExtensionsResp,
errCode int32,
errMsg, clientMsgID, typeKey string,
keyValue *sdkws.KeyValue,
) {
temp := new(msg.KeyValueResp)
temp.KeyValue = keyValue
temp.ErrCode = errCode
temp.ErrMsg = errMsg
r.Result = append(r.Result, temp)
_ = m.MessageLocker.UnLockMessageTypeKey(ctx, clientMsgID, typeKey)
}
func (m *msgServer) GetMessagesReactionExtensions(
ctx context.Context,
req *msg.GetMessagesReactionExtensionsReq,
) (resp *msg.GetMessagesReactionExtensionsResp, err error) {
//log.Debug(req.OperationID, utils.GetSelfFuncName(), "m args is:", req.String()) //log.Debug(req.OperationID, utils.GetSelfFuncName(), "m args is:", req.String())
//var rResp msg.GetMessageListReactionExtensionsResp //var rResp msg.GetMessageListReactionExtensionsResp
//for _, messageValue := range req.MessageReactionKeyList { //for _, messageValue := range req.MessageReactionKeyList {
@ -183,7 +211,8 @@ func (m *msgServer) GetMessagesReactionExtensions(ctx context.Context, req *msg.
// oneMessage.Pb2Model = keyMap // oneMessage.Pb2Model = keyMap
// //
// } else { // } else {
// mongoValue, err := db.DB.GetExtendMsg(req.conversationID, req.SessionType, messageValue.ClientMsgID, messageValue.MsgFirstModifyTime) // mongoValue, err := db.DB.GetExtendMsg(req.conversationID, req.SessionType, messageValue.ClientMsgID,
// messageValue.MsgFirstModifyTime)
// if err != nil { // if err != nil {
// oneMessage.ErrCode = 100 // oneMessage.ErrCode = 100
// oneMessage.ErrMsg = err.Error() // oneMessage.ErrMsg = err.Error()
@ -208,11 +237,17 @@ func (m *msgServer) GetMessagesReactionExtensions(ctx context.Context, req *msg.
} }
func (m *msgServer) AddMessageReactionExtensions(ctx context.Context, req *msg.ModifyMessageReactionExtensionsReq) (resp *msg.ModifyMessageReactionExtensionsResp, err error) { func (m *msgServer) AddMessageReactionExtensions(
ctx context.Context,
req *msg.ModifyMessageReactionExtensionsReq,
) (resp *msg.ModifyMessageReactionExtensionsResp, err error) {
return return
} }
func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *msg.DeleteMessagesReactionExtensionsReq) (resp *msg.DeleteMessagesReactionExtensionsResp, err error) { func (m *msgServer) DeleteMessageReactionExtensions(
ctx context.Context,
req *msg.DeleteMessagesReactionExtensionsReq,
) (resp *msg.DeleteMessagesReactionExtensionsResp, err error) {
//log.Debug(req.OperationID, utils.GetSelfFuncName(), "m args is:", req.String()) //log.Debug(req.OperationID, utils.GetSelfFuncName(), "m args is:", req.String())
//var rResp msg.DeleteMessagesReactionExtensionsResp //var rResp msg.DeleteMessagesReactionExtensionsResp
//callbackResp := notification.callbackDeleteMessageReactionExtensions(req) //callbackResp := notification.callbackDeleteMessageReactionExtensions(req)
@ -231,7 +266,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
////if ExternalExtension ////if ExternalExtension
//if req.IsExternalExtensions { //if req.IsExternalExtensions {
// rResp.Result = callbackResp.ResultReactionExtensionList // rResp.Result = callbackResp.ResultReactionExtensionList
// notification.ExtendMessageDeleteNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &rResp, false, false) // notification.ExtendMessageDeleteNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType,
// req, &rResp, false, false)
// return &rResp, nil // return &rResp, nil
// //
//} //}
@ -303,7 +339,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
// } // }
// return &rResp, nil // return &rResp, nil
// } // }
// mongoValue, err := db.DB.GetExtendMsg(req.conversationID, req.SessionType, req.ClientMsgID, req.MsgFirstModifyTime) // mongoValue, err := db.DB.GetExtendMsg(req.conversationID, req.SessionType, req.ClientMsgID,
// req.MsgFirstModifyTime)
// if err != nil { // if err != nil {
// rResp.ErrCode = 200 // rResp.ErrCode = 200
// rResp.ErrMsg = err.Error() // rResp.ErrMsg = err.Error()
@ -333,7 +370,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
// temp.TypeKey = v.TypeKey // temp.TypeKey = v.TypeKey
// setValue[v.TypeKey] = temp // setValue[v.TypeKey] = temp
// } // }
// err = db.DB.DeleteReactionExtendMsgSet(req.conversationID, req.SessionType, req.ClientMsgID, req.MsgFirstModifyTime, setValue) // err = db.DB.DeleteReactionExtendMsgSet(req.conversationID, req.SessionType, req.ClientMsgID,
// req.MsgFirstModifyTime, setValue)
// if err != nil { // if err != nil {
// for _, value := range setValue { // for _, value := range setValue {
// temp := new(msg.KeyValueResp) // temp := new(msg.KeyValueResp)
@ -355,7 +393,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
// } // }
// //
//} //}
//notification.ExtendMessageDeleteNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType, req, &rResp, false, isExists) // notification.ExtendMessageDeleteNotification(req.OperationID, req.OpUserID, req.conversationID, req.SessionType,
// req, &rResp, false, isExists)
//log.Debug(req.OperationID, utils.GetSelfFuncName(), "m return is:", rResp.String()) //log.Debug(req.OperationID, utils.GetSelfFuncName(), "m return is:", rResp.String())
return resp, nil return resp, nil
} }

View File

@ -35,7 +35,10 @@ func callbackSetMessageReactionExtensions(ctx context.Context, setReq *msg.SetMe
return nil return nil
} }
func callbackDeleteMessageReactionExtensions(ctx context.Context, setReq *msg.DeleteMessagesReactionExtensionsReq) error { func callbackDeleteMessageReactionExtensions(
ctx context.Context,
setReq *msg.DeleteMessagesReactionExtensionsReq,
) error {
if !config.Config.Callback.CallbackAfterSendGroupMsg.Enable { if !config.Config.Callback.CallbackAfterSendGroupMsg.Enable {
return nil return nil
} }

View File

@ -8,7 +8,10 @@ import (
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
) )
func (m *msgServer) SetSendMsgStatus(ctx context.Context, req *pbMsg.SetSendMsgStatusReq) (*pbMsg.SetSendMsgStatusResp, error) { func (m *msgServer) SetSendMsgStatus(
ctx context.Context,
req *pbMsg.SetSendMsgStatusReq,
) (*pbMsg.SetSendMsgStatusResp, error) {
resp := &pbMsg.SetSendMsgStatusResp{} resp := &pbMsg.SetSendMsgStatusResp{}
if err := m.MsgDatabase.SetSendMsgStatus(ctx, mcontext.GetOperationID(ctx), req.Status); err != nil { if err := m.MsgDatabase.SetSendMsgStatus(ctx, mcontext.GetOperationID(ctx), req.Status); err != nil {
return nil, err return nil, err
@ -16,7 +19,10 @@ func (m *msgServer) SetSendMsgStatus(ctx context.Context, req *pbMsg.SetSendMsgS
return resp, nil return resp, nil
} }
func (m *msgServer) GetSendMsgStatus(ctx context.Context, req *pbMsg.GetSendMsgStatusReq) (*pbMsg.GetSendMsgStatusResp, error) { func (m *msgServer) GetSendMsgStatus(
ctx context.Context,
req *pbMsg.GetSendMsgStatusReq,
) (*pbMsg.GetSendMsgStatusResp, error) {
resp := &pbMsg.GetSendMsgStatusResp{} resp := &pbMsg.GetSendMsgStatusResp{}
status, err := m.MsgDatabase.GetSendMsgStatus(ctx, mcontext.GetOperationID(ctx)) status, err := m.MsgDatabase.GetSendMsgStatus(ctx, mcontext.GetOperationID(ctx))
if IsNotFound(err) { if IsNotFound(err) {

View File

@ -56,7 +56,12 @@ func (m *msgServer) RevokeMsg(ctx context.Context, req *msg.RevokeMsgReq) (*msg.
} }
role = user.AppMangerLevel role = user.AppMangerLevel
case constant.SuperGroupChatType: case constant.SuperGroupChatType:
members, err := m.Group.GetGroupMemberInfoMap(ctx, msgs[0].GroupID, utils.Distinct([]string{req.UserID, msgs[0].SendID}), true) members, err := m.Group.GetGroupMemberInfoMap(
ctx,
msgs[0].GroupID,
utils.Distinct([]string{req.UserID, msgs[0].SendID}),
true,
)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -34,7 +34,10 @@ func (m *msgServer) SendMsg(ctx context.Context, req *pbMsg.SendMsgReq) (resp *p
} }
} }
func (m *msgServer) sendMsgSuperGroupChat(ctx context.Context, req *pbMsg.SendMsgReq) (resp *pbMsg.SendMsgResp, err error) { func (m *msgServer) sendMsgSuperGroupChat(
ctx context.Context,
req *pbMsg.SendMsgReq,
) (resp *pbMsg.SendMsgResp, err error) {
promePkg.Inc(promePkg.WorkSuperGroupChatMsgRecvSuccessCounter) promePkg.Inc(promePkg.WorkSuperGroupChatMsgRecvSuccessCounter)
if err = m.messageVerification(ctx, req); err != nil { if err = m.messageVerification(ctx, req); err != nil {
promePkg.Inc(promePkg.WorkSuperGroupChatMsgProcessFailedCounter) promePkg.Inc(promePkg.WorkSuperGroupChatMsgProcessFailedCounter)
@ -105,7 +108,10 @@ func (m *msgServer) setConversationAtInfo(nctx context.Context, msg *sdkws.MsgDa
} }
func (m *msgServer) sendMsgNotification(ctx context.Context, req *pbMsg.SendMsgReq) (resp *pbMsg.SendMsgResp, err error) { func (m *msgServer) sendMsgNotification(
ctx context.Context,
req *pbMsg.SendMsgReq,
) (resp *pbMsg.SendMsgResp, err error) {
promePkg.Inc(promePkg.SingleChatMsgRecvSuccessCounter) promePkg.Inc(promePkg.SingleChatMsgRecvSuccessCounter)
if err := m.MsgDatabase.MsgToMQ(ctx, utils.GenConversationUniqueKeyForSingle(req.MsgData.SendID, req.MsgData.RecvID), req.MsgData); err != nil { if err := m.MsgDatabase.MsgToMQ(ctx, utils.GenConversationUniqueKeyForSingle(req.MsgData.SendID, req.MsgData.RecvID), req.MsgData); err != nil {
promePkg.Inc(promePkg.SingleChatMsgProcessFailedCounter) promePkg.Inc(promePkg.SingleChatMsgProcessFailedCounter)
@ -127,7 +133,13 @@ func (m *msgServer) sendMsgSingleChat(ctx context.Context, req *pbMsg.SendMsgReq
var isSend bool = true var isSend bool = true
isNotification := utils.IsNotificationByMsg(req.MsgData) isNotification := utils.IsNotificationByMsg(req.MsgData)
if !isNotification { if !isNotification {
isSend, err = m.modifyMessageByUserMessageReceiveOpt(ctx, req.MsgData.RecvID, utils.GenConversationIDForSingle(req.MsgData.SendID, req.MsgData.RecvID), constant.SingleChatType, req) isSend, err = m.modifyMessageByUserMessageReceiveOpt(
ctx,
req.MsgData.RecvID,
utils.GenConversationIDForSingle(req.MsgData.SendID, req.MsgData.RecvID),
constant.SingleChatType,
req,
)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -6,7 +6,10 @@ import (
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
) )
func (m *msgServer) GetConversationMaxSeq(ctx context.Context, req *pbMsg.GetConversationMaxSeqReq) (resp *pbMsg.GetConversationMaxSeqResp, err error) { func (m *msgServer) GetConversationMaxSeq(
ctx context.Context,
req *pbMsg.GetConversationMaxSeqReq,
) (resp *pbMsg.GetConversationMaxSeqResp, err error) {
maxSeq, err := m.MsgDatabase.GetMaxSeq(ctx, req.ConversationID) maxSeq, err := m.MsgDatabase.GetMaxSeq(ctx, req.ConversationID)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -3,6 +3,8 @@ package msg
import ( import (
"context" "context"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -14,7 +16,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
) )
type MessageInterceptorChain []MessageInterceptorFunc type MessageInterceptorChain []MessageInterceptorFunc
@ -64,7 +65,11 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase()) msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase())
extendMsgModel := unrelation.NewExtendMsgSetMongoDriver(mongo.GetDatabase()) extendMsgModel := unrelation.NewExtendMsgSetMongoDriver(mongo.GetDatabase())
extendMsgCacheModel := cache.NewExtendMsgSetCacheRedis(rdb, extendMsgModel, cache.GetDefaultOpt()) extendMsgCacheModel := cache.NewExtendMsgSetCacheRedis(rdb, extendMsgModel, cache.GetDefaultOpt())
extendMsgDatabase := controller.NewExtendMsgDatabase(extendMsgModel, extendMsgCacheModel, tx.NewMongo(mongo.GetClient())) extendMsgDatabase := controller.NewExtendMsgDatabase(
extendMsgModel,
extendMsgCacheModel,
tx.NewMongo(mongo.GetClient()),
)
msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, cacheModel) msgDatabase := controller.NewCommonMsgDatabase(msgDocModel, cacheModel)
conversationClient := rpcclient.NewConversationRpcClient(client) conversationClient := rpcclient.NewConversationRpcClient(client)
userRpcClient := rpcclient.NewUserRpcClient(client) userRpcClient := rpcclient.NewUserRpcClient(client)
@ -106,7 +111,8 @@ func (m *msgServer) initPrometheus() {
} }
func (m *msgServer) conversationAndGetRecvID(conversation *conversation.Conversation, userID string) (recvID string) { func (m *msgServer) conversationAndGetRecvID(conversation *conversation.Conversation, userID string) (recvID string) {
if conversation.ConversationType == constant.SingleChatType || conversation.ConversationType == constant.NotificationChatType { if conversation.ConversationType == constant.SingleChatType ||
conversation.ConversationType == constant.NotificationChatType {
if userID == conversation.OwnerUserID { if userID == conversation.OwnerUserID {
recvID = conversation.UserID recvID = conversation.UserID
} else { } else {

View File

@ -9,7 +9,10 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
func (m *msgServer) PullMessageBySeqs(ctx context.Context, req *sdkws.PullMessageBySeqsReq) (*sdkws.PullMessageBySeqsResp, error) { func (m *msgServer) PullMessageBySeqs(
ctx context.Context,
req *sdkws.PullMessageBySeqsReq,
) (*sdkws.PullMessageBySeqsResp, error) {
resp := &sdkws.PullMessageBySeqsResp{} resp := &sdkws.PullMessageBySeqsResp{}
resp.Msgs = make(map[string]*sdkws.PullMsgs) resp.Msgs = make(map[string]*sdkws.PullMsgs)
resp.NotificationMsgs = make(map[string]*sdkws.PullMsgs) resp.NotificationMsgs = make(map[string]*sdkws.PullMsgs)
@ -20,7 +23,15 @@ func (m *msgServer) PullMessageBySeqs(ctx context.Context, req *sdkws.PullMessag
log.ZError(ctx, "GetConversation error", err, "conversationID", seq.ConversationID) log.ZError(ctx, "GetConversation error", err, "conversationID", seq.ConversationID)
continue continue
} }
minSeq, maxSeq, msgs, err := m.MsgDatabase.GetMsgBySeqsRange(ctx, req.UserID, seq.ConversationID, seq.Begin, seq.End, seq.Num, conversation.MaxSeq) minSeq, maxSeq, msgs, err := m.MsgDatabase.GetMsgBySeqsRange(
ctx,
req.UserID,
seq.ConversationID,
seq.Begin,
seq.End,
seq.Num,
conversation.MaxSeq,
)
if err != nil { if err != nil {
log.ZWarn(ctx, "GetMsgBySeqsRange error", err, "conversationID", seq.ConversationID, "seq", seq) log.ZWarn(ctx, "GetMsgBySeqsRange error", err, "conversationID", seq.ConversationID, "seq", seq)
continue continue

View File

@ -1,12 +1,13 @@
package msg package msg
import ( import (
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
) )
func isMessageHasReadEnabled(msgData *sdkws.MsgData) bool { func isMessageHasReadEnabled(msgData *sdkws.MsgData) bool {

View File

@ -41,7 +41,8 @@ func (m *msgServer) messageVerification(ctx context.Context, data *msg.SendMsgRe
if utils.IsContain(data.MsgData.SendID, config.Config.Manager.UserID) { if utils.IsContain(data.MsgData.SendID, config.Config.Manager.UserID) {
return nil return nil
} }
if data.MsgData.ContentType <= constant.NotificationEnd && data.MsgData.ContentType >= constant.NotificationBegin { if data.MsgData.ContentType <= constant.NotificationEnd &&
data.MsgData.ContentType >= constant.NotificationBegin {
return nil return nil
} }
black, err := m.friend.IsBlocked(ctx, data.MsgData.SendID, data.MsgData.RecvID) black, err := m.friend.IsBlocked(ctx, data.MsgData.SendID, data.MsgData.RecvID)
@ -67,7 +68,8 @@ func (m *msgServer) messageVerification(ctx context.Context, data *msg.SendMsgRe
if err != nil { if err != nil {
return err return err
} }
if groupInfo.Status == constant.GroupStatusDismissed && data.MsgData.ContentType != constant.GroupDismissedNotification { if groupInfo.Status == constant.GroupStatusDismissed &&
data.MsgData.ContentType != constant.GroupDismissedNotification {
return errs.ErrDismissedAlready.Wrap() return errs.ErrDismissedAlready.Wrap()
} }
if groupInfo.GroupType == constant.SuperGroup { if groupInfo.GroupType == constant.SuperGroup {
@ -76,7 +78,8 @@ func (m *msgServer) messageVerification(ctx context.Context, data *msg.SendMsgRe
if utils.IsContain(data.MsgData.SendID, config.Config.Manager.UserID) { if utils.IsContain(data.MsgData.SendID, config.Config.Manager.UserID) {
return nil return nil
} }
if data.MsgData.ContentType <= constant.NotificationEnd && data.MsgData.ContentType >= constant.NotificationBegin { if data.MsgData.ContentType <= constant.NotificationEnd &&
data.MsgData.ContentType >= constant.NotificationBegin {
return nil return nil
} }
// memberIDs, err := m.GroupLocalCache.GetGroupMemberIDs(ctx, data.MsgData.GroupID) // memberIDs, err := m.GroupLocalCache.GetGroupMemberIDs(ctx, data.MsgData.GroupID)
@ -161,7 +164,12 @@ func GetMsgID(sendID string) string {
return utils.Md5(t + "-" + sendID + "-" + strconv.Itoa(rand.Int())) return utils.Md5(t + "-" + sendID + "-" + strconv.Itoa(rand.Int()))
} }
func (m *msgServer) modifyMessageByUserMessageReceiveOpt(ctx context.Context, userID, conversationID string, sessionType int, pb *msg.SendMsgReq) (bool, error) { func (m *msgServer) modifyMessageByUserMessageReceiveOpt(
ctx context.Context,
userID, conversationID string,
sessionType int,
pb *msg.SendMsgReq,
) (bool, error) {
opt, err := m.User.GetUserGlobalMsgRecvOpt(ctx, userID) opt, err := m.User.GetUserGlobalMsgRecvOpt(ctx, userID)
if err != nil { if err != nil {
return false, err return false, err

View File

@ -4,6 +4,8 @@ import (
"context" "context"
"net/url" "net/url"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
@ -13,7 +15,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
) )
func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error {
@ -39,7 +40,13 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
third.RegisterThirdServer(server, &thirdServer{ third.RegisterThirdServer(server, &thirdServer{
thirdDatabase: controller.NewThirdDatabase(cache.NewMsgCacheModel(rdb)), thirdDatabase: controller.NewThirdDatabase(cache.NewMsgCacheModel(rdb)),
userRpcClient: rpcclient.NewUserRpcClient(client), userRpcClient: rpcclient.NewUserRpcClient(client),
s3dataBase: controller.NewS3Database(o, relation.NewObjectHash(db), relation.NewObjectInfo(db), relation.NewObjectPut(db), u), s3dataBase: controller.NewS3Database(
o,
relation.NewObjectHash(db),
relation.NewObjectInfo(db),
relation.NewObjectPut(db),
u,
),
}) })
return nil return nil
} }
@ -50,7 +57,10 @@ type thirdServer struct {
userRpcClient rpcclient.UserRpcClient userRpcClient rpcclient.UserRpcClient
} }
func (t *thirdServer) FcmUpdateToken(ctx context.Context, req *third.FcmUpdateTokenReq) (resp *third.FcmUpdateTokenResp, err error) { func (t *thirdServer) FcmUpdateToken(
ctx context.Context,
req *third.FcmUpdateTokenReq,
) (resp *third.FcmUpdateTokenResp, err error) {
err = t.thirdDatabase.FcmUpdateToken(ctx, req.Account, int(req.PlatformID), req.FcmToken, req.ExpireTime) err = t.thirdDatabase.FcmUpdateToken(ctx, req.Account, int(req.PlatformID), req.FcmToken, req.ExpireTime)
if err != nil { if err != nil {
return nil, err return nil, err
@ -58,7 +68,10 @@ func (t *thirdServer) FcmUpdateToken(ctx context.Context, req *third.FcmUpdateTo
return &third.FcmUpdateTokenResp{}, nil return &third.FcmUpdateTokenResp{}, nil
} }
func (t *thirdServer) SetAppBadge(ctx context.Context, req *third.SetAppBadgeReq) (resp *third.SetAppBadgeResp, err error) { func (t *thirdServer) SetAppBadge(
ctx context.Context,
req *third.SetAppBadgeReq,
) (resp *third.SetAppBadgeResp, err error) {
err = t.thirdDatabase.SetAppBadge(ctx, req.UserID, int(req.AppUnreadCount)) err = t.thirdDatabase.SetAppBadge(ctx, req.UserID, int(req.AppUnreadCount))
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -8,7 +8,10 @@ import (
pbuser "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user" pbuser "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/user"
) )
func (s *userServer) UserRegisterCount(ctx context.Context, req *pbuser.UserRegisterCountReq) (*pbuser.UserRegisterCountResp, error) { func (s *userServer) UserRegisterCount(
ctx context.Context,
req *pbuser.UserRegisterCountReq,
) (*pbuser.UserRegisterCountResp, error) {
if req.Start > req.End { if req.Start > req.End {
return nil, errs.ErrArgs.Wrap("start > end") return nil, errs.ErrArgs.Wrap("start > end")
} }

View File

@ -23,8 +23,9 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
type userServer struct { type userServer struct {
@ -62,13 +63,19 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
UserDatabase: database, UserDatabase: database,
RegisterCenter: client, RegisterCenter: client,
friendRpcClient: &friendRpcClient, friendRpcClient: &friendRpcClient,
notificationSender: notification.NewFriendNotificationSender(&msgRpcClient, notification.WithDBFunc(database.FindWithError)), notificationSender: notification.NewFriendNotificationSender(
&msgRpcClient,
notification.WithDBFunc(database.FindWithError),
),
} }
pbuser.RegisterUserServer(server, u) pbuser.RegisterUserServer(server, u)
return u.UserDatabase.InitOnce(context.Background(), users) return u.UserDatabase.InitOnce(context.Background(), users)
} }
func (s *userServer) GetDesignateUsers(ctx context.Context, req *pbuser.GetDesignateUsersReq) (resp *pbuser.GetDesignateUsersResp, err error) { func (s *userServer) GetDesignateUsers(
ctx context.Context,
req *pbuser.GetDesignateUsersReq,
) (resp *pbuser.GetDesignateUsersResp, err error) {
resp = &pbuser.GetDesignateUsersResp{} resp = &pbuser.GetDesignateUsersResp{}
users, err := s.FindWithError(ctx, req.UserIDs) users, err := s.FindWithError(ctx, req.UserIDs)
if err != nil { if err != nil {
@ -81,7 +88,10 @@ func (s *userServer) GetDesignateUsers(ctx context.Context, req *pbuser.GetDesig
return resp, nil return resp, nil
} }
func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbuser.UpdateUserInfoReq) (resp *pbuser.UpdateUserInfoResp, err error) { func (s *userServer) UpdateUserInfo(
ctx context.Context,
req *pbuser.UpdateUserInfoReq,
) (resp *pbuser.UpdateUserInfoResp, err error) {
resp = &pbuser.UpdateUserInfoResp{} resp = &pbuser.UpdateUserInfoResp{}
err = tokenverify.CheckAccessV3(ctx, req.UserInfo.UserID) err = tokenverify.CheckAccessV3(ctx, req.UserInfo.UserID)
if err != nil { if err != nil {
@ -106,7 +116,10 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbuser.UpdateUserI
return resp, nil return resp, nil
} }
func (s *userServer) SetGlobalRecvMessageOpt(ctx context.Context, req *pbuser.SetGlobalRecvMessageOptReq) (resp *pbuser.SetGlobalRecvMessageOptResp, err error) { func (s *userServer) SetGlobalRecvMessageOpt(
ctx context.Context,
req *pbuser.SetGlobalRecvMessageOptReq,
) (resp *pbuser.SetGlobalRecvMessageOptResp, err error) {
resp = &pbuser.SetGlobalRecvMessageOptResp{} resp = &pbuser.SetGlobalRecvMessageOptResp{}
if _, err := s.FindWithError(ctx, []string{req.UserID}); err != nil { if _, err := s.FindWithError(ctx, []string{req.UserID}); err != nil {
return nil, err return nil, err
@ -120,7 +133,10 @@ func (s *userServer) SetGlobalRecvMessageOpt(ctx context.Context, req *pbuser.Se
return resp, nil return resp, nil
} }
func (s *userServer) AccountCheck(ctx context.Context, req *pbuser.AccountCheckReq) (resp *pbuser.AccountCheckResp, err error) { func (s *userServer) AccountCheck(
ctx context.Context,
req *pbuser.AccountCheckReq,
) (resp *pbuser.AccountCheckResp, err error) {
resp = &pbuser.AccountCheckResp{} resp = &pbuser.AccountCheckResp{}
if utils.Duplicate(req.CheckUserIDs) { if utils.Duplicate(req.CheckUserIDs) {
return nil, errs.ErrArgs.Wrap("userID repeated") return nil, errs.ErrArgs.Wrap("userID repeated")
@ -149,7 +165,10 @@ func (s *userServer) AccountCheck(ctx context.Context, req *pbuser.AccountCheckR
return resp, nil return resp, nil
} }
func (s *userServer) GetPaginationUsers(ctx context.Context, req *pbuser.GetPaginationUsersReq) (resp *pbuser.GetPaginationUsersResp, err error) { func (s *userServer) GetPaginationUsers(
ctx context.Context,
req *pbuser.GetPaginationUsersReq,
) (resp *pbuser.GetPaginationUsersResp, err error) {
var pageNumber, showNumber int32 var pageNumber, showNumber int32
if req.Pagination != nil { if req.Pagination != nil {
pageNumber = req.Pagination.PageNumber pageNumber = req.Pagination.PageNumber
@ -162,7 +181,10 @@ func (s *userServer) GetPaginationUsers(ctx context.Context, req *pbuser.GetPagi
return &pbuser.GetPaginationUsersResp{Total: int32(total), Users: convert.UsersDB2Pb(users)}, err return &pbuser.GetPaginationUsersResp{Total: int32(total), Users: convert.UsersDB2Pb(users)}, err
} }
func (s *userServer) UserRegister(ctx context.Context, req *pbuser.UserRegisterReq) (resp *pbuser.UserRegisterResp, err error) { func (s *userServer) UserRegister(
ctx context.Context,
req *pbuser.UserRegisterReq,
) (resp *pbuser.UserRegisterResp, err error) {
resp = &pbuser.UserRegisterResp{} resp = &pbuser.UserRegisterResp{}
if len(req.Users) == 0 { if len(req.Users) == 0 {
return nil, errs.ErrArgs.Wrap("users is empty") return nil, errs.ErrArgs.Wrap("users is empty")
@ -210,7 +232,10 @@ func (s *userServer) UserRegister(ctx context.Context, req *pbuser.UserRegisterR
return resp, nil return resp, nil
} }
func (s *userServer) GetGlobalRecvMessageOpt(ctx context.Context, req *pbuser.GetGlobalRecvMessageOptReq) (resp *pbuser.GetGlobalRecvMessageOptResp, err error) { func (s *userServer) GetGlobalRecvMessageOpt(
ctx context.Context,
req *pbuser.GetGlobalRecvMessageOptReq,
) (resp *pbuser.GetGlobalRecvMessageOptResp, err error) {
user, err := s.FindWithError(ctx, []string{req.UserID}) user, err := s.FindWithError(ctx, []string{req.UserID})
if err != nil { if err != nil {
return nil, err return nil, err
@ -218,7 +243,10 @@ func (s *userServer) GetGlobalRecvMessageOpt(ctx context.Context, req *pbuser.Ge
return &pbuser.GetGlobalRecvMessageOptResp{GlobalRecvMsgOpt: user[0].GlobalRecvMsgOpt}, nil return &pbuser.GetGlobalRecvMessageOptResp{GlobalRecvMsgOpt: user[0].GlobalRecvMsgOpt}, nil
} }
func (s *userServer) GetAllUserID(ctx context.Context, req *pbuser.GetAllUserIDReq) (resp *pbuser.GetAllUserIDResp, err error) { func (s *userServer) GetAllUserID(
ctx context.Context,
req *pbuser.GetAllUserIDReq,
) (resp *pbuser.GetAllUserIDResp, err error) {
userIDs, err := s.UserDatabase.GetAllUserID(ctx) userIDs, err := s.UserDatabase.GetAllUserID(ctx)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -5,9 +5,10 @@ import (
"fmt" "fmt"
"sync" "sync"
"github.com/robfig/cron/v3"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/robfig/cron/v3"
) )
func StartCronTask() error { func StartCronTask() error {

View File

@ -26,7 +26,12 @@ type MsgTool struct {
var errSeq = errors.New("cache max seq and mongo max seq is diff > 10") var errSeq = errors.New("cache max seq and mongo max seq is diff > 10")
func NewMsgTool(msgDatabase controller.CommonMsgDatabase, userDatabase controller.UserDatabase, groupDatabase controller.GroupDatabase, conversationDatabase controller.ConversationDatabase) *MsgTool { func NewMsgTool(
msgDatabase controller.CommonMsgDatabase,
userDatabase controller.UserDatabase,
groupDatabase controller.GroupDatabase,
conversationDatabase controller.ConversationDatabase,
) *MsgTool {
return &MsgTool{ return &MsgTool{
msgDatabase: msgDatabase, msgDatabase: msgDatabase,
userDatabase: userDatabase, userDatabase: userDatabase,
@ -50,9 +55,17 @@ func InitMsgTool() (*MsgTool, error) {
} }
userDB := relation.NewUserGorm(db) userDB := relation.NewUserGorm(db)
msgDatabase := controller.InitCommonMsgDatabase(rdb, mongo.GetDatabase()) msgDatabase := controller.InitCommonMsgDatabase(rdb, mongo.GetDatabase())
userDatabase := controller.NewUserDatabase(userDB, cache.NewUserCacheRedis(rdb, relation.NewUserGorm(db), cache.GetDefaultOpt()), tx.NewGorm(db)) userDatabase := controller.NewUserDatabase(
userDB,
cache.NewUserCacheRedis(rdb, relation.NewUserGorm(db), cache.GetDefaultOpt()),
tx.NewGorm(db),
)
groupDatabase := controller.InitGroupDatabase(db, rdb, mongo.GetDatabase()) groupDatabase := controller.InitGroupDatabase(db, rdb, mongo.GetDatabase())
conversationDatabase := controller.NewConversationDatabase(relation.NewConversationGorm(db), cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), relation.NewConversationGorm(db)), tx.NewGorm(db)) conversationDatabase := controller.NewConversationDatabase(
relation.NewConversationGorm(db),
cache.NewConversationRedis(rdb, cache.GetDefaultOpt(), relation.NewConversationGorm(db)),
tx.NewGorm(db),
)
msgTool := NewMsgTool(msgDatabase, userDatabase, groupDatabase, conversationDatabase) msgTool := NewMsgTool(msgDatabase, userDatabase, groupDatabase, conversationDatabase)
return msgTool, nil return msgTool, nil
} }
@ -75,7 +88,15 @@ func (c *MsgTool) AllConversationClearMsgAndFixSeq() {
func (c *MsgTool) ClearConversationsMsg(ctx context.Context, conversationIDs []string) { func (c *MsgTool) ClearConversationsMsg(ctx context.Context, conversationIDs []string) {
for _, conversationID := range conversationIDs { for _, conversationID := range conversationIDs {
if err := c.msgDatabase.DeleteConversationMsgsAndSetMinSeq(ctx, conversationID, int64(config.Config.RetainChatRecords*24*60*60)); err != nil { if err := c.msgDatabase.DeleteConversationMsgsAndSetMinSeq(ctx, conversationID, int64(config.Config.RetainChatRecords*24*60*60)); err != nil {
log.ZError(ctx, "DeleteUserSuperGroupMsgsAndSetMinSeq failed", err, "conversationID", conversationID, "DBRetainChatRecords", config.Config.RetainChatRecords) log.ZError(
ctx,
"DeleteUserSuperGroupMsgsAndSetMinSeq failed",
err,
"conversationID",
conversationID,
"DBRetainChatRecords",
config.Config.RetainChatRecords,
)
} }
if err := c.checkMaxSeq(ctx, conversationID); err != nil { if err := c.checkMaxSeq(ctx, conversationID); err != nil {
log.ZError(ctx, "fixSeq failed", err, "conversationID", conversationID) log.ZError(ctx, "fixSeq failed", err, "conversationID", conversationID)

View File

@ -4,11 +4,12 @@ import (
"context" "context"
"strconv" "strconv"
"go.mongodb.org/mongo-driver/bson"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"go.mongodb.org/mongo-driver/bson"
unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
@ -89,7 +90,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
return return
} }
msgTools.ClearConversationsMsg(ctx, []string{conversationID}) msgTools.ClearConversationsMsg(ctx, []string{conversationID})
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err := msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err := msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
@ -132,7 +136,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
} }
msgTools.ClearConversationsMsg(ctx, []string{conversationID}) msgTools.ClearConversationsMsg(ctx, []string{conversationID})
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
@ -164,7 +171,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
} }
msgTools.ClearConversationsMsg(ctx, []string{conversationID}) msgTools.ClearConversationsMsg(ctx, []string{conversationID})
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
@ -214,7 +224,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
} }
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
@ -255,7 +268,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
} }
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return
@ -305,7 +321,10 @@ func TestDeleteMongoMsgAndResetRedisSeq(t *testing.T) {
if _, err := mongoClient.InsertOne(ctx, msgDoc4); err != nil { if _, err := mongoClient.InsertOne(ctx, msgDoc4); err != nil {
t.Error("InsertOne failed", testUID4) t.Error("InsertOne failed", testUID4)
} }
minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(ctx, conversationID) minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache, err = msgTools.msgDatabase.GetConversationMinMaxSeqInMongoAndCache(
ctx,
conversationID,
)
if err != nil { if err != nil {
t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed") t.Error("GetSuperGroupMinMaxSeqInMongoAndCache failed")
return return

View File

@ -5,11 +5,12 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/checker" "github.com/OpenIMSDK/Open-IM-Server/pkg/checker"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
) )
func Call[A, B, C any]( func Call[A, B, C any](

View File

@ -46,7 +46,7 @@ type ParseTokenReq struct {
//} //}
type ExpireTime struct { type ExpireTime struct {
ExpireTimeSeconds uint32 `json:"expireTimeSeconds" ` ExpireTimeSeconds uint32 `json:"expireTimeSeconds"`
} }
type ParseTokenResp struct { type ParseTokenResp struct {

View File

@ -35,8 +35,8 @@ type AccountCheckResp struct {
type ManagementSendMsg struct { type ManagementSendMsg struct {
SendID string `json:"sendID" binding:"required"` SendID string `json:"sendID" binding:"required"`
GroupID string `json:"groupID" binding:"required_if=SessionType 2|required_if=SessionType 3"` GroupID string `json:"groupID" binding:"required_if=SessionType 2|required_if=SessionType 3"`
SenderNickname string `json:"senderNickname" ` SenderNickname string `json:"senderNickname"`
SenderFaceURL string `json:"senderFaceURL" ` SenderFaceURL string `json:"senderFaceURL"`
SenderPlatformID int32 `json:"senderPlatformID"` SenderPlatformID int32 `json:"senderPlatformID"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"` Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"` ContentType int32 `json:"contentType" binding:"required"`
@ -50,8 +50,8 @@ type ManagementSendMsgReq struct {
SendID string `json:"sendID" binding:"required"` SendID string `json:"sendID" binding:"required"`
RecvID string `json:"recvID" binding:"required_if" message:"recvID is required if sessionType is SingleChatType or NotificationChatType"` RecvID string `json:"recvID" binding:"required_if" message:"recvID is required if sessionType is SingleChatType or NotificationChatType"`
GroupID string `json:"groupID" binding:"required_if" message:"groupID is required if sessionType is GroupChatType or SuperGroupChatType"` GroupID string `json:"groupID" binding:"required_if" message:"groupID is required if sessionType is GroupChatType or SuperGroupChatType"`
SenderNickname string `json:"senderNickname" ` SenderNickname string `json:"senderNickname"`
SenderFaceURL string `json:"senderFaceURL" ` SenderFaceURL string `json:"senderFaceURL"`
SenderPlatformID int32 `json:"senderPlatformID"` SenderPlatformID int32 `json:"senderPlatformID"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"` Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"` ContentType int32 `json:"contentType" binding:"required"`
@ -81,7 +81,7 @@ type SingleReturnResult struct {
ServerMsgID string `json:"serverMsgID"` ServerMsgID string `json:"serverMsgID"`
ClientMsgID string `json:"clientMsgID"` ClientMsgID string `json:"clientMsgID"`
SendTime int64 `json:"sendTime"` SendTime int64 `json:"sendTime"`
RecvID string `json:"recvID" ` RecvID string `json:"recvID"`
} }
type CheckMsgIsSendSuccessReq struct { type CheckMsgIsSendSuccessReq struct {

View File

@ -71,10 +71,11 @@ type ModifyMessageReactionExtensionsResp struct {
} }
//type OperateMessageListReactionExtensionsReq struct { //type OperateMessageListReactionExtensionsReq struct {
// OperationID string `json:"operationID" binding:"required"` // OperationID string `json:"operationID"
// conversationID string `json:"conversationID" binding:"required"` // binding:"required"` conversationID string
// SessionType string `json:"sessionType" binding:"required"` // `json:"conversationID" binding:"required"` SessionType string
// MessageReactionKeyList []*msg.GetMessageListReactionExtensionsReq_MessageReactionKey `json:"messageReactionKeyList" binding:"required"` // `json:"sessionType" binding:"required"` MessageReactionKeyList
// []*msg.GetMessageListReactionExtensionsReq_MessageReactionKey `json:"messageReactionKeyList" binding:"required"`
//} //}
type OperateMessageListReactionExtensionsResp struct { type OperateMessageListReactionExtensionsResp struct {
@ -114,17 +115,17 @@ type DeleteMessageReactionExtensionsResp struct {
type PictureBaseInfo struct { type PictureBaseInfo struct {
UUID string `mapstructure:"uuid"` UUID string `mapstructure:"uuid"`
Type string `mapstructure:"type" ` Type string `mapstructure:"type"`
Size int64 `mapstructure:"size" ` Size int64 `mapstructure:"size"`
Width int32 `mapstructure:"width" ` Width int32 `mapstructure:"width"`
Height int32 `mapstructure:"height"` Height int32 `mapstructure:"height"`
Url string `mapstructure:"url" ` Url string `mapstructure:"url"`
} }
type PictureElem struct { type PictureElem struct {
SourcePath string `mapstructure:"sourcePath"` SourcePath string `mapstructure:"sourcePath"`
SourcePicture PictureBaseInfo `mapstructure:"sourcePicture"` SourcePicture PictureBaseInfo `mapstructure:"sourcePicture"`
BigPicture PictureBaseInfo `mapstructure:"bigPicture" ` BigPicture PictureBaseInfo `mapstructure:"bigPicture"`
SnapshotPicture PictureBaseInfo `mapstructure:"snapshotPicture"` SnapshotPicture PictureBaseInfo `mapstructure:"snapshotPicture"`
} }
type SoundElem struct { type SoundElem struct {

View File

@ -3,8 +3,9 @@ package cmd
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/internal/msggateway" "github.com/OpenIMSDK/Open-IM-Server/internal/msggateway"
//"github.com/OpenIMSDK/Open-IM-Server/internal/msggateway" //"github.com/OpenIMSDK/Open-IM-Server/internal/msggateway"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
) )
type MsgGatewayCmd struct { type MsgGatewayCmd struct {

View File

@ -1,8 +1,9 @@
package cmd package cmd
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/internal/msgtransfer"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/OpenIMSDK/Open-IM-Server/internal/msgtransfer"
) )
type MsgTransferCmd struct { type MsgTransferCmd struct {

View File

@ -1,8 +1,9 @@
package cmd package cmd
import ( import (
"github.com/OpenIMSDK/Open-IM-Server/internal/tools"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/OpenIMSDK/Open-IM-Server/internal/tools"
) )
type MsgUtilsCmd struct { type MsgUtilsCmd struct {

View File

@ -3,10 +3,11 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/spf13/cobra"
) )
type RootCmd struct { type RootCmd struct {

View File

@ -3,10 +3,11 @@ package cmd
import ( import (
"errors" "errors"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
) )
type RpcCmd struct { type RpcCmd struct {
@ -26,7 +27,10 @@ func (a *RpcCmd) Exec() error {
return a.Execute() return a.Execute()
} }
func (a *RpcCmd) StartSvr(name string, rpcFn func(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error) error { func (a *RpcCmd) StartSvr(
name string,
rpcFn func(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error,
) error {
if a.GetPortFlag() == 0 { if a.GetPortFlag() == 0 {
return errors.New("port is required") return errors.New("port is required")
} }

View File

@ -303,6 +303,15 @@ type notification struct {
} }
func GetServiceNames() []string { func GetServiceNames() []string {
return []string{Config.RpcRegisterName.OpenImUserName, Config.RpcRegisterName.OpenImFriendName, Config.RpcRegisterName.OpenImMsgName, Config.RpcRegisterName.OpenImPushName, Config.RpcRegisterName.OpenImMessageGatewayName, return []string{
Config.RpcRegisterName.OpenImGroupName, Config.RpcRegisterName.OpenImAuthName, Config.RpcRegisterName.OpenImConversationName, Config.RpcRegisterName.OpenImThirdName} Config.RpcRegisterName.OpenImUserName,
Config.RpcRegisterName.OpenImFriendName,
Config.RpcRegisterName.OpenImMsgName,
Config.RpcRegisterName.OpenImPushName,
Config.RpcRegisterName.OpenImMessageGatewayName,
Config.RpcRegisterName.OpenImGroupName,
Config.RpcRegisterName.OpenImAuthName,
Config.RpcRegisterName.OpenImConversationName,
Config.RpcRegisterName.OpenImThirdName,
}
} }

View File

@ -7,10 +7,11 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"gopkg.in/yaml.v3"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gopkg.in/yaml.v3"
) )
var ( var (

View File

@ -125,7 +125,8 @@ const (
SingleTerminalLogin = 2 SingleTerminalLogin = 2
//The web side can be online at the same time, and the other side can only log in at one end //The web side can be online at the same time, and the other side can only log in at one end
WebAndOther = 3 WebAndOther = 3
//The PC side is mutually exclusive, and the mobile side is mutually exclusive, but the web side can be online at the same time // The PC side is mutually exclusive, and the mobile side is mutually exclusive, but the web side can be online at
// the same time
PcMobileAndWeb = 4 PcMobileAndWeb = 4
//The PC terminal can be online at the same time,but other terminal only one of the endpoints can login //The PC terminal can be online at the same time,but other terminal only one of the endpoints can login
PCAndOther = 5 PCAndOther = 5

View File

@ -8,7 +8,11 @@ import (
sdk "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sdk "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
) )
func BlackDB2Pb(ctx context.Context, blackDBs []*relation.BlackModel, f func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error)) (blackPbs []*sdk.BlackInfo, err error) { func BlackDB2Pb(
ctx context.Context,
blackDBs []*relation.BlackModel,
f func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) (blackPbs []*sdk.BlackInfo, err error) {
var userIDs []string var userIDs []string
for _, blackDB := range blackDBs { for _, blackDB := range blackDBs {
userIDs = append(userIDs, blackDB.BlockUserID) userIDs = append(userIDs, blackDB.BlockUserID)

View File

@ -16,7 +16,11 @@ func FriendPb2DB(friend *sdkws.FriendInfo) *relation.FriendModel {
return dbFriend return dbFriend
} }
func FriendDB2Pb(ctx context.Context, friendDB *relation.FriendModel, getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error)) (*sdkws.FriendInfo, error) { func FriendDB2Pb(
ctx context.Context,
friendDB *relation.FriendModel,
getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) (*sdkws.FriendInfo, error) {
pbfriend := &sdkws.FriendInfo{FriendUser: &sdkws.UserInfo{}} pbfriend := &sdkws.FriendInfo{FriendUser: &sdkws.UserInfo{}}
utils.CopyStructFields(pbfriend, friendDB) utils.CopyStructFields(pbfriend, friendDB)
users, err := getUsers(ctx, []string{friendDB.FriendUserID}) users, err := getUsers(ctx, []string{friendDB.FriendUserID})
@ -31,7 +35,11 @@ func FriendDB2Pb(ctx context.Context, friendDB *relation.FriendModel, getUsers f
return pbfriend, nil return pbfriend, nil
} }
func FriendsDB2Pb(ctx context.Context, friendsDB []*relation.FriendModel, getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error)) (friendsPb []*sdkws.FriendInfo, err error) { func FriendsDB2Pb(
ctx context.Context,
friendsDB []*relation.FriendModel,
getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) (friendsPb []*sdkws.FriendInfo, err error) {
var userID []string var userID []string
for _, friendDB := range friendsDB { for _, friendDB := range friendsDB {
userID = append(userID, friendDB.FriendUserID) userID = append(userID, friendDB.FriendUserID)
@ -53,7 +61,11 @@ func FriendsDB2Pb(ctx context.Context, friendsDB []*relation.FriendModel, getUse
return friendsPb, nil return friendsPb, nil
} }
func FriendRequestDB2Pb(ctx context.Context, friendRequests []*relation.FriendRequestModel, getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error)) ([]*sdkws.FriendRequest, error) { func FriendRequestDB2Pb(
ctx context.Context,
friendRequests []*relation.FriendRequestModel,
getUsers func(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error),
) ([]*sdkws.FriendRequest, error) {
userIDMap := make(map[string]struct{}) userIDMap := make(map[string]struct{})
for _, friendRequest := range friendRequests { for _, friendRequest := range friendRequests {
userIDMap[friendRequest.ToUserID] = struct{}{} userIDMap[friendRequest.ToUserID] = struct{}{}

View File

@ -41,7 +41,12 @@ func Pb2DbGroupRequest(req *pbGroup.GroupApplicationResponseReq, handleUserID st
} }
} }
func Db2PbCMSGroup(m *relation.GroupModel, ownerUserID string, ownerUserName string, memberCount uint32) *pbGroup.CMSGroup { func Db2PbCMSGroup(
m *relation.GroupModel,
ownerUserID string,
ownerUserName string,
memberCount uint32,
) *pbGroup.CMSGroup {
return &pbGroup.CMSGroup{ return &pbGroup.CMSGroup{
GroupInfo: Db2PbGroupInfo(m, ownerUserID, memberCount), GroupInfo: Db2PbGroupInfo(m, ownerUserID, memberCount),
GroupOwnerUserID: ownerUserID, GroupOwnerUserID: ownerUserID,
@ -66,7 +71,11 @@ func Db2PbGroupMember(m *relation.GroupMemberModel) *sdkws.GroupMemberFullInfo {
} }
} }
func Db2PbGroupRequest(m *relation.GroupRequestModel, user *sdkws.PublicUserInfo, group *sdkws.GroupInfo) *sdkws.GroupRequest { func Db2PbGroupRequest(
m *relation.GroupRequestModel,
user *sdkws.PublicUserInfo,
group *sdkws.GroupInfo,
) *sdkws.GroupRequest {
return &sdkws.GroupRequest{ return &sdkws.GroupRequest{
UserInfo: user, UserInfo: user,
GroupInfo: group, GroupInfo: group,
@ -82,7 +91,11 @@ func Db2PbGroupRequest(m *relation.GroupRequestModel, user *sdkws.PublicUserInfo
} }
} }
func Db2PbGroupAbstractInfo(groupID string, groupMemberNumber uint32, groupMemberListHash uint64) *pbGroup.GroupAbstractInfo { func Db2PbGroupAbstractInfo(
groupID string,
groupMemberNumber uint32,
groupMemberListHash uint64,
) *pbGroup.GroupAbstractInfo {
return &pbGroup.GroupAbstractInfo{ return &pbGroup.GroupAbstractInfo{
GroupID: groupID, GroupID: groupID,
GroupMemberNumber: groupMemberNumber, GroupMemberNumber: groupMemberNumber,

View File

@ -4,9 +4,10 @@ import (
"context" "context"
"time" "time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
) )
const ( const (
@ -31,7 +32,11 @@ type BlackCacheRedis struct {
blackDB relationTb.BlackModelInterface blackDB relationTb.BlackModelInterface
} }
func NewBlackCacheRedis(rdb redis.UniversalClient, blackDB relationTb.BlackModelInterface, options rockscache.Options) BlackCache { func NewBlackCacheRedis(
rdb redis.UniversalClient,
blackDB relationTb.BlackModelInterface,
options rockscache.Options,
) BlackCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &BlackCacheRedis{ return &BlackCacheRedis{
expireTime: blackExpireTime, expireTime: blackExpireTime,
@ -55,9 +60,15 @@ func (b *BlackCacheRedis) getBlackIDsKey(ownerUserID string) string {
} }
func (b *BlackCacheRedis) GetBlackIDs(ctx context.Context, userID string) (blackIDs []string, err error) { func (b *BlackCacheRedis) GetBlackIDs(ctx context.Context, userID string) (blackIDs []string, err error) {
return getCache(ctx, b.rcClient, b.getBlackIDsKey(userID), b.expireTime, func(ctx context.Context) ([]string, error) { return getCache(
ctx,
b.rcClient,
b.getBlackIDsKey(userID),
b.expireTime,
func(ctx context.Context) ([]string, error) {
return b.blackDB.FindBlackUserIDs(ctx, userID) return b.blackDB.FindBlackUserIDs(ctx, userID)
}) },
)
} }
func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) BlackCache { func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) BlackCache {

View File

@ -7,11 +7,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
) )
const ( const (
@ -42,7 +43,11 @@ type ConversationCache interface {
DelConvsersations(ownerUserID string, conversationIDs ...string) ConversationCache DelConvsersations(ownerUserID string, conversationIDs ...string) ConversationCache
DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache
// get one conversation from msgCache // get one conversation from msgCache
GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) GetConversations(
ctx context.Context,
ownerUserID string,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error)
// get one user's all conversations from msgCache // get one user's all conversations from msgCache
GetUserAllConversations(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error) GetUserAllConversations(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error)
// get user conversation recv msg from msgCache // get user conversation recv msg from msgCache
@ -58,13 +63,25 @@ type ConversationCache interface {
GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error)
DelUserAllHasReadSeqs(ownerUserID string, conversationIDs ...string) ConversationCache DelUserAllHasReadSeqs(ownerUserID string, conversationIDs ...string) ConversationCache
GetConversationsByConversationID(ctx context.Context, conversationIDs []string) ([]*relationTb.ConversationModel, error) GetConversationsByConversationID(
ctx context.Context,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error)
DelConversationByConversationID(conversationIDs ...string) ConversationCache DelConversationByConversationID(conversationIDs ...string) ConversationCache
} }
func NewConversationRedis(rdb redis.UniversalClient, opts rockscache.Options, db relationTb.ConversationModelInterface) ConversationCache { func NewConversationRedis(
rdb redis.UniversalClient,
opts rockscache.Options,
db relationTb.ConversationModelInterface,
) ConversationCache {
rcClient := rockscache.NewClient(rdb, opts) rcClient := rockscache.NewClient(rdb, opts)
return &ConversationRedisCache{rcClient: rcClient, metaCache: NewMetaCacheRedis(rcClient), conversationDB: db, expireTime: conversationExpireTime} return &ConversationRedisCache{
rcClient: rcClient,
metaCache: NewMetaCacheRedis(rcClient),
conversationDB: db,
expireTime: conversationExpireTime,
}
} }
type ConversationRedisCache struct { type ConversationRedisCache struct {
@ -74,13 +91,27 @@ type ConversationRedisCache struct {
expireTime time.Duration expireTime time.Duration
} }
func NewNewConversationRedis(rdb redis.UniversalClient, conversationDB *relation.ConversationGorm, options rockscache.Options) ConversationCache { func NewNewConversationRedis(
rdb redis.UniversalClient,
conversationDB *relation.ConversationGorm,
options rockscache.Options,
) ConversationCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &ConversationRedisCache{rcClient: rcClient, metaCache: NewMetaCacheRedis(rcClient), conversationDB: conversationDB, expireTime: conversationExpireTime} return &ConversationRedisCache{
rcClient: rcClient,
metaCache: NewMetaCacheRedis(rcClient),
conversationDB: conversationDB,
expireTime: conversationExpireTime,
}
} }
func (c *ConversationRedisCache) NewCache() ConversationCache { func (c *ConversationRedisCache) NewCache() ConversationCache {
return &ConversationRedisCache{rcClient: c.rcClient, metaCache: NewMetaCacheRedis(c.rcClient, c.metaCache.GetPreDelKeys()...), conversationDB: c.conversationDB, expireTime: c.expireTime} return &ConversationRedisCache{
rcClient: c.rcClient,
metaCache: NewMetaCacheRedis(c.rcClient, c.metaCache.GetPreDelKeys()...),
conversationDB: c.conversationDB,
expireTime: c.expireTime,
}
} }
func (c *ConversationRedisCache) getConversationKey(ownerUserID, conversationID string) string { func (c *ConversationRedisCache) getConversationKey(ownerUserID, conversationID string) string {
@ -108,9 +139,15 @@ func (c *ConversationRedisCache) getConversationHasReadSeqKey(ownerUserID, conve
} }
func (c *ConversationRedisCache) GetUserConversationIDs(ctx context.Context, ownerUserID string) ([]string, error) { func (c *ConversationRedisCache) GetUserConversationIDs(ctx context.Context, ownerUserID string) ([]string, error) {
return getCache(ctx, c.rcClient, c.getConversationIDsKey(ownerUserID), c.expireTime, func(ctx context.Context) ([]string, error) { return getCache(
ctx,
c.rcClient,
c.getConversationIDsKey(ownerUserID),
c.expireTime,
func(ctx context.Context) ([]string, error) {
return c.conversationDB.FindUserIDAllConversationID(ctx, ownerUserID) return c.conversationDB.FindUserIDAllConversationID(ctx, ownerUserID)
}) },
)
} }
func (c *ConversationRedisCache) DelConversationIDs(userIDs ...string) ConversationCache { func (c *ConversationRedisCache) DelConversationIDs(userIDs ...string) ConversationCache {
@ -127,8 +164,16 @@ func (c *ConversationRedisCache) getUserConversationIDsHashKey(ownerUserID strin
return conversationIDsHashKey + ownerUserID return conversationIDsHashKey + ownerUserID
} }
func (c *ConversationRedisCache) GetUserConversationIDsHash(ctx context.Context, ownerUserID string) (hash uint64, err error) { func (c *ConversationRedisCache) GetUserConversationIDsHash(
return getCache(ctx, c.rcClient, c.getUserConversationIDsHashKey(ownerUserID), c.expireTime, func(ctx context.Context) (uint64, error) { ctx context.Context,
ownerUserID string,
) (hash uint64, err error) {
return getCache(
ctx,
c.rcClient,
c.getUserConversationIDsHashKey(ownerUserID),
c.expireTime,
func(ctx context.Context) (uint64, error) {
conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID) conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID)
if err != nil { if err != nil {
return 0, err return 0, err
@ -137,7 +182,8 @@ func (c *ConversationRedisCache) GetUserConversationIDsHash(ctx context.Context,
bi := big.NewInt(0) bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(conversationIDs, ";"))[0:8], 16) bi.SetString(utils.Md5(strings.Join(conversationIDs, ";"))[0:8], 16)
return bi.Uint64(), nil return bi.Uint64(), nil
}) },
)
} }
func (c *ConversationRedisCache) DelUserConversationIDsHash(ownerUserIDs ...string) ConversationCache { func (c *ConversationRedisCache) DelUserConversationIDsHash(ownerUserIDs ...string) ConversationCache {
@ -150,10 +196,19 @@ func (c *ConversationRedisCache) DelUserConversationIDsHash(ownerUserIDs ...stri
return cache return cache
} }
func (c *ConversationRedisCache) GetConversation(ctx context.Context, ownerUserID, conversationID string) (*relationTb.ConversationModel, error) { func (c *ConversationRedisCache) GetConversation(
return getCache(ctx, c.rcClient, c.getConversationKey(ownerUserID, conversationID), c.expireTime, func(ctx context.Context) (*relationTb.ConversationModel, error) { ctx context.Context,
ownerUserID, conversationID string,
) (*relationTb.ConversationModel, error) {
return getCache(
ctx,
c.rcClient,
c.getConversationKey(ownerUserID, conversationID),
c.expireTime,
func(ctx context.Context) (*relationTb.ConversationModel, error) {
return c.conversationDB.Take(ctx, ownerUserID, conversationID) return c.conversationDB.Take(ctx, ownerUserID, conversationID)
}) },
)
} }
func (c *ConversationRedisCache) DelConvsersations(ownerUserID string, convsersationIDs ...string) ConversationCache { func (c *ConversationRedisCache) DelConvsersations(ownerUserID string, convsersationIDs ...string) ConversationCache {
@ -166,7 +221,10 @@ func (c *ConversationRedisCache) DelConvsersations(ownerUserID string, convsersa
return cache return cache
} }
func (c *ConversationRedisCache) getConversationIndex(convsation *relationTb.ConversationModel, keys []string) (int, error) { func (c *ConversationRedisCache) getConversationIndex(
convsation *relationTb.ConversationModel,
keys []string,
) (int, error) {
key := c.getConversationKey(convsation.OwnerUserID, convsation.ConversationID) key := c.getConversationKey(convsation.OwnerUserID, convsation.ConversationID)
for _i, _key := range keys { for _i, _key := range keys {
if _key == key { if _key == key {
@ -176,17 +234,31 @@ func (c *ConversationRedisCache) getConversationIndex(convsation *relationTb.Con
return 0, errors.New("not found key:" + key + " in keys") return 0, errors.New("not found key:" + key + " in keys")
} }
func (c *ConversationRedisCache) GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) { func (c *ConversationRedisCache) GetConversations(
ctx context.Context,
ownerUserID string,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error) {
var keys []string var keys []string
for _, conversarionID := range conversationIDs { for _, conversarionID := range conversationIDs {
keys = append(keys, c.getConversationKey(ownerUserID, conversarionID)) keys = append(keys, c.getConversationKey(ownerUserID, conversarionID))
} }
return batchGetCache(ctx, c.rcClient, keys, c.expireTime, c.getConversationIndex, func(ctx context.Context) ([]*relationTb.ConversationModel, error) { return batchGetCache(
ctx,
c.rcClient,
keys,
c.expireTime,
c.getConversationIndex,
func(ctx context.Context) ([]*relationTb.ConversationModel, error) {
return c.conversationDB.Find(ctx, ownerUserID, conversationIDs) return c.conversationDB.Find(ctx, ownerUserID, conversationIDs)
}) },
)
} }
func (c *ConversationRedisCache) GetUserAllConversations(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error) { func (c *ConversationRedisCache) GetUserAllConversations(
ctx context.Context,
ownerUserID string,
) ([]*relationTb.ConversationModel, error) {
conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID) conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -195,21 +267,46 @@ func (c *ConversationRedisCache) GetUserAllConversations(ctx context.Context, ow
for _, conversarionID := range conversationIDs { for _, conversarionID := range conversationIDs {
keys = append(keys, c.getConversationKey(ownerUserID, conversarionID)) keys = append(keys, c.getConversationKey(ownerUserID, conversarionID))
} }
return batchGetCache(ctx, c.rcClient, keys, c.expireTime, c.getConversationIndex, func(ctx context.Context) ([]*relationTb.ConversationModel, error) { return batchGetCache(
ctx,
c.rcClient,
keys,
c.expireTime,
c.getConversationIndex,
func(ctx context.Context) ([]*relationTb.ConversationModel, error) {
return c.conversationDB.FindUserIDAllConversations(ctx, ownerUserID) return c.conversationDB.FindUserIDAllConversations(ctx, ownerUserID)
}) },
)
} }
func (c *ConversationRedisCache) GetUserRecvMsgOpt(ctx context.Context, ownerUserID, conversationID string) (opt int, err error) { func (c *ConversationRedisCache) GetUserRecvMsgOpt(
return getCache(ctx, c.rcClient, c.getRecvMsgOptKey(ownerUserID, conversationID), c.expireTime, func(ctx context.Context) (opt int, err error) { ctx context.Context,
ownerUserID, conversationID string,
) (opt int, err error) {
return getCache(
ctx,
c.rcClient,
c.getRecvMsgOptKey(ownerUserID, conversationID),
c.expireTime,
func(ctx context.Context) (opt int, err error) {
return c.conversationDB.GetUserRecvMsgOpt(ctx, ownerUserID, conversationID) return c.conversationDB.GetUserRecvMsgOpt(ctx, ownerUserID, conversationID)
}) },
)
} }
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDs(
return getCache(ctx, c.rcClient, c.getSuperGroupRecvNotNotifyUserIDsKey(groupID), c.expireTime, func(ctx context.Context) (userIDs []string, err error) { ctx context.Context,
groupID string,
) (userIDs []string, err error) {
return getCache(
ctx,
c.rcClient,
c.getSuperGroupRecvNotNotifyUserIDsKey(groupID),
c.expireTime,
func(ctx context.Context) (userIDs []string, err error) {
return c.conversationDB.FindSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID) return c.conversationDB.FindSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID)
}) },
)
} }
func (c *ConversationRedisCache) DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache { func (c *ConversationRedisCache) DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache {
@ -234,8 +331,16 @@ func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDs(groupID st
return cache return cache
} }
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDsHash(ctx context.Context, groupID string) (hash uint64, err error) { func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDsHash(
return getCache(ctx, c.rcClient, c.getSuperGroupRecvNotNotifyUserIDsHashKey(groupID), c.expireTime, func(ctx context.Context) (hash uint64, err error) { ctx context.Context,
groupID string,
) (hash uint64, err error) {
return getCache(
ctx,
c.rcClient,
c.getSuperGroupRecvNotNotifyUserIDsHashKey(groupID),
c.expireTime,
func(ctx context.Context) (hash uint64, err error) {
userIDs, err := c.GetSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID) userIDs, err := c.GetSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
@ -244,7 +349,8 @@ func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDsHash(ctx co
bi := big.NewInt(0) bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16) bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
return bi.Uint64(), nil return bi.Uint64(), nil
}) },
)
} }
func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDsHash(groupID string) ConversationCache { func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDsHash(groupID string) ConversationCache {
@ -253,7 +359,10 @@ func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDsHash(groupI
return cache return cache
} }
func (c *ConversationRedisCache) getUserAllHasReadSeqsIndex(conversationID string, conversationIDs []string) (int, error) { func (c *ConversationRedisCache) getUserAllHasReadSeqsIndex(
conversationID string,
conversationIDs []string,
) (int, error) {
for _i, _conversationID := range conversationIDs { for _i, _conversationID := range conversationIDs {
if _conversationID == conversationID { if _conversationID == conversationID {
return _i, nil return _i, nil
@ -262,7 +371,10 @@ func (c *ConversationRedisCache) getUserAllHasReadSeqsIndex(conversationID strin
return 0, errors.New("not found key:" + conversationID + " in keys") return 0, errors.New("not found key:" + conversationID + " in keys")
} }
func (c *ConversationRedisCache) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error) { func (c *ConversationRedisCache) GetUserAllHasReadSeqs(
ctx context.Context,
ownerUserID string,
) (map[string]int64, error) {
conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID) conversationIDs, err := c.GetUserConversationIDs(ctx, ownerUserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -271,12 +383,23 @@ func (c *ConversationRedisCache) GetUserAllHasReadSeqs(ctx context.Context, owne
for _, conversarionID := range conversationIDs { for _, conversarionID := range conversationIDs {
keys = append(keys, c.getConversationHasReadSeqKey(ownerUserID, conversarionID)) keys = append(keys, c.getConversationHasReadSeqKey(ownerUserID, conversarionID))
} }
return batchGetCacheMap(ctx, c.rcClient, keys, conversationIDs, c.expireTime, c.getUserAllHasReadSeqsIndex, func(ctx context.Context) (map[string]int64, error) { return batchGetCacheMap(
ctx,
c.rcClient,
keys,
conversationIDs,
c.expireTime,
c.getUserAllHasReadSeqsIndex,
func(ctx context.Context) (map[string]int64, error) {
return c.conversationDB.GetUserAllHasReadSeqs(ctx, ownerUserID) return c.conversationDB.GetUserAllHasReadSeqs(ctx, ownerUserID)
}) },
)
} }
func (c *ConversationRedisCache) DelUserAllHasReadSeqs(ownerUserID string, conversationIDs ...string) ConversationCache { func (c *ConversationRedisCache) DelUserAllHasReadSeqs(
ownerUserID string,
conversationIDs ...string,
) ConversationCache {
cache := c.NewCache() cache := c.NewCache()
for _, conversationID := range conversationIDs { for _, conversationID := range conversationIDs {
cache.AddKeys(c.getConversationHasReadSeqKey(ownerUserID, conversationID)) cache.AddKeys(c.getConversationHasReadSeqKey(ownerUserID, conversationID))
@ -284,7 +407,10 @@ func (c *ConversationRedisCache) DelUserAllHasReadSeqs(ownerUserID string, conve
return cache return cache
} }
func (c *ConversationRedisCache) GetConversationsByConversationID(ctx context.Context, conversationIDs []string) ([]*relationTb.ConversationModel, error) { func (c *ConversationRedisCache) GetConversationsByConversationID(
ctx context.Context,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error) {
panic("implement me") panic("implement me")
} }

View File

@ -4,9 +4,10 @@ import (
"context" "context"
"time" "time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
) )
const ( const (
@ -17,7 +18,13 @@ const (
type ExtendMsgSetCache interface { type ExtendMsgSetCache interface {
metaCache metaCache
NewCache() ExtendMsgSetCache NewCache() ExtendMsgSetCache
GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, firstModifyTime int64) (extendMsg *unrelation.ExtendMsgModel, err error) GetExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
firstModifyTime int64,
) (extendMsg *unrelation.ExtendMsgModel, err error)
DelExtendMsg(clientMsgID string) ExtendMsgSetCache DelExtendMsg(clientMsgID string) ExtendMsgSetCache
} }
@ -28,7 +35,11 @@ type ExtendMsgSetCacheRedis struct {
extendMsgSetDB unrelation.ExtendMsgSetModelInterface extendMsgSetDB unrelation.ExtendMsgSetModelInterface
} }
func NewExtendMsgSetCacheRedis(rdb redis.UniversalClient, extendMsgSetDB unrelation.ExtendMsgSetModelInterface, options rockscache.Options) ExtendMsgSetCache { func NewExtendMsgSetCacheRedis(
rdb redis.UniversalClient,
extendMsgSetDB unrelation.ExtendMsgSetModelInterface,
options rockscache.Options,
) ExtendMsgSetCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &ExtendMsgSetCacheRedis{ return &ExtendMsgSetCacheRedis{
metaCache: NewMetaCacheRedis(rcClient), metaCache: NewMetaCacheRedis(rcClient),
@ -51,10 +62,22 @@ func (e *ExtendMsgSetCacheRedis) getKey(clientMsgID string) string {
return extendMsgCache + clientMsgID return extendMsgCache + clientMsgID
} }
func (e *ExtendMsgSetCacheRedis) GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, firstModifyTime int64) (extendMsg *unrelation.ExtendMsgModel, err error) { func (e *ExtendMsgSetCacheRedis) GetExtendMsg(
return getCache(ctx, e.rcClient, e.getKey(clientMsgID), e.expireTime, func(ctx context.Context) (*unrelation.ExtendMsgModel, error) { ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
firstModifyTime int64,
) (extendMsg *unrelation.ExtendMsgModel, err error) {
return getCache(
ctx,
e.rcClient,
e.getKey(clientMsgID),
e.expireTime,
func(ctx context.Context) (*unrelation.ExtendMsgModel, error) {
return e.extendMsgSetDB.TakeExtendMsg(ctx, conversationID, sessionType, clientMsgID, firstModifyTime) return e.extendMsgSetDB.TakeExtendMsg(ctx, conversationID, sessionType, clientMsgID, firstModifyTime)
}) },
)
} }
func (e *ExtendMsgSetCacheRedis) DelExtendMsg(clientMsgID string) ExtendMsgSetCache { func (e *ExtendMsgSetCacheRedis) DelExtendMsg(clientMsgID string) ExtendMsgSetCache {

View File

@ -4,10 +4,11 @@ import (
"context" "context"
"time" "time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
const ( const (
@ -37,7 +38,11 @@ type FriendCacheRedis struct {
rcClient *rockscache.Client rcClient *rockscache.Client
} }
func NewFriendCacheRedis(rdb redis.UniversalClient, friendDB relationTb.FriendModelInterface, options rockscache.Options) FriendCache { func NewFriendCacheRedis(
rdb redis.UniversalClient,
friendDB relationTb.FriendModelInterface,
options rockscache.Options,
) FriendCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &FriendCacheRedis{ return &FriendCacheRedis{
metaCache: NewMetaCacheRedis(rcClient), metaCache: NewMetaCacheRedis(rcClient),
@ -48,7 +53,12 @@ func NewFriendCacheRedis(rdb redis.UniversalClient, friendDB relationTb.FriendMo
} }
func (c *FriendCacheRedis) NewCache() FriendCache { func (c *FriendCacheRedis) NewCache() FriendCache {
return &FriendCacheRedis{rcClient: c.rcClient, metaCache: NewMetaCacheRedis(c.rcClient, c.metaCache.GetPreDelKeys()...), friendDB: c.friendDB, expireTime: c.expireTime} return &FriendCacheRedis{
rcClient: c.rcClient,
metaCache: NewMetaCacheRedis(c.rcClient, c.metaCache.GetPreDelKeys()...),
friendDB: c.friendDB,
expireTime: c.expireTime,
}
} }
func (f *FriendCacheRedis) getFriendIDsKey(ownerUserID string) string { func (f *FriendCacheRedis) getFriendIDsKey(ownerUserID string) string {
@ -64,9 +74,15 @@ func (f *FriendCacheRedis) getFriendKey(ownerUserID, friendUserID string) string
} }
func (f *FriendCacheRedis) GetFriendIDs(ctx context.Context, ownerUserID string) (friendIDs []string, err error) { func (f *FriendCacheRedis) GetFriendIDs(ctx context.Context, ownerUserID string) (friendIDs []string, err error) {
return getCache(ctx, f.rcClient, f.getFriendIDsKey(ownerUserID), f.expireTime, func(ctx context.Context) ([]string, error) { return getCache(
ctx,
f.rcClient,
f.getFriendIDsKey(ownerUserID),
f.expireTime,
func(ctx context.Context) ([]string, error) {
return f.friendDB.FindFriendUserIDs(ctx, ownerUserID) return f.friendDB.FindFriendUserIDs(ctx, ownerUserID)
}) },
)
} }
func (f *FriendCacheRedis) DelFriendIDs(ownerUserID ...string) FriendCache { func (f *FriendCacheRedis) DelFriendIDs(ownerUserID ...string) FriendCache {
@ -80,7 +96,10 @@ func (f *FriendCacheRedis) DelFriendIDs(ownerUserID ...string) FriendCache {
} }
// todo // todo
func (f *FriendCacheRedis) GetTwoWayFriendIDs(ctx context.Context, ownerUserID string) (twoWayFriendIDs []string, err error) { func (f *FriendCacheRedis) GetTwoWayFriendIDs(
ctx context.Context,
ownerUserID string,
) (twoWayFriendIDs []string, err error) {
friendIDs, err := f.GetFriendIDs(ctx, ownerUserID) friendIDs, err := f.GetFriendIDs(ctx, ownerUserID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -103,10 +122,19 @@ func (f *FriendCacheRedis) DelTwoWayFriendIDs(ctx context.Context, ownerUserID s
return new return new
} }
func (f *FriendCacheRedis) GetFriend(ctx context.Context, ownerUserID, friendUserID string) (friend *relationTb.FriendModel, err error) { func (f *FriendCacheRedis) GetFriend(
return getCache(ctx, f.rcClient, f.getFriendKey(ownerUserID, friendUserID), f.expireTime, func(ctx context.Context) (*relationTb.FriendModel, error) { ctx context.Context,
ownerUserID, friendUserID string,
) (friend *relationTb.FriendModel, err error) {
return getCache(
ctx,
f.rcClient,
f.getFriendKey(ownerUserID, friendUserID),
f.expireTime,
func(ctx context.Context) (*relationTb.FriendModel, error) {
return f.friendDB.Take(ctx, ownerUserID, friendUserID) return f.friendDB.Take(ctx, ownerUserID, friendUserID)
}) },
)
} }
func (f *FriendCacheRedis) DelFriend(ownerUserID, friendUserID string) FriendCache { func (f *FriendCacheRedis) DelFriend(ownerUserID, friendUserID string) FriendCache {

View File

@ -6,11 +6,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
unrelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" unrelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
) )
const ( const (
@ -49,10 +50,22 @@ type GroupCache interface {
GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error) GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error)
DelJoinedGroupID(userID ...string) GroupCache DelJoinedGroupID(userID ...string) GroupCache
GetGroupMemberInfo(ctx context.Context, groupID, userID string) (groupMember *relationTb.GroupMemberModel, err error) GetGroupMemberInfo(
GetGroupMembersInfo(ctx context.Context, groupID string, userID []string) (groupMembers []*relationTb.GroupMemberModel, err error) ctx context.Context,
groupID, userID string,
) (groupMember *relationTb.GroupMemberModel, err error)
GetGroupMembersInfo(
ctx context.Context,
groupID string,
userID []string,
) (groupMembers []*relationTb.GroupMemberModel, err error)
GetAllGroupMembersInfo(ctx context.Context, groupID string) (groupMembers []*relationTb.GroupMemberModel, err error) GetAllGroupMembersInfo(ctx context.Context, groupID string) (groupMembers []*relationTb.GroupMemberModel, err error)
GetGroupMembersPage(ctx context.Context, groupID string, userID []string, showNumber, pageNumber int32) (total uint32, groupMembers []*relationTb.GroupMemberModel, err error) GetGroupMembersPage(
ctx context.Context,
groupID string,
userID []string,
showNumber, pageNumber int32,
) (total uint32, groupMembers []*relationTb.GroupMemberModel, err error)
DelGroupMembersInfo(groupID string, userID ...string) GroupCache DelGroupMembersInfo(groupID string, userID ...string) GroupCache
@ -70,7 +83,14 @@ type GroupCacheRedis struct {
rcClient *rockscache.Client rcClient *rockscache.Client
} }
func NewGroupCacheRedis(rdb redis.UniversalClient, groupDB relationTb.GroupModelInterface, groupMemberDB relationTb.GroupMemberModelInterface, groupRequestDB relationTb.GroupRequestModelInterface, mongoClient unrelationTb.SuperGroupModelInterface, opts rockscache.Options) GroupCache { func NewGroupCacheRedis(
rdb redis.UniversalClient,
groupDB relationTb.GroupModelInterface,
groupMemberDB relationTb.GroupMemberModelInterface,
groupRequestDB relationTb.GroupRequestModelInterface,
mongoClient unrelationTb.SuperGroupModelInterface,
opts rockscache.Options,
) GroupCache {
rcClient := rockscache.NewClient(rdb, opts) rcClient := rockscache.NewClient(rdb, opts)
return &GroupCacheRedis{rcClient: rcClient, expireTime: groupExpireTime, return &GroupCacheRedis{rcClient: rcClient, expireTime: groupExpireTime,
groupDB: groupDB, groupMemberDB: groupMemberDB, groupRequestDB: groupRequestDB, groupDB: groupDB, groupMemberDB: groupMemberDB, groupRequestDB: groupRequestDB,
@ -79,7 +99,15 @@ func NewGroupCacheRedis(rdb redis.UniversalClient, groupDB relationTb.GroupModel
} }
func (g *GroupCacheRedis) NewCache() GroupCache { func (g *GroupCacheRedis) NewCache() GroupCache {
return &GroupCacheRedis{rcClient: g.rcClient, expireTime: g.expireTime, groupDB: g.groupDB, groupMemberDB: g.groupMemberDB, groupRequestDB: g.groupRequestDB, mongoDB: g.mongoDB, metaCache: NewMetaCacheRedis(g.rcClient, g.metaCache.GetPreDelKeys()...)} return &GroupCacheRedis{
rcClient: g.rcClient,
expireTime: g.expireTime,
groupDB: g.groupDB,
groupMemberDB: g.groupMemberDB,
groupRequestDB: g.groupRequestDB,
mongoDB: g.mongoDB,
metaCache: NewMetaCacheRedis(g.rcClient, g.metaCache.GetPreDelKeys()...),
}
} }
func (g *GroupCacheRedis) getGroupInfoKey(groupID string) string { func (g *GroupCacheRedis) getGroupInfoKey(groupID string) string {
@ -135,20 +163,36 @@ func (g *GroupCacheRedis) GetGroupMemberIndex(groupMember *relationTb.GroupMembe
} }
// / groupInfo // / groupInfo
func (g *GroupCacheRedis) GetGroupsInfo(ctx context.Context, groupIDs []string) (groups []*relationTb.GroupModel, err error) { func (g *GroupCacheRedis) GetGroupsInfo(
ctx context.Context,
groupIDs []string,
) (groups []*relationTb.GroupModel, err error) {
var keys []string var keys []string
for _, group := range groupIDs { for _, group := range groupIDs {
keys = append(keys, g.getGroupInfoKey(group)) keys = append(keys, g.getGroupInfoKey(group))
} }
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, g.GetGroupIndex, func(ctx context.Context) ([]*relationTb.GroupModel, error) { return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
g.GetGroupIndex,
func(ctx context.Context) ([]*relationTb.GroupModel, error) {
return g.groupDB.Find(ctx, groupIDs) return g.groupDB.Find(ctx, groupIDs)
}) },
)
} }
func (g *GroupCacheRedis) GetGroupInfo(ctx context.Context, groupID string) (group *relationTb.GroupModel, err error) { func (g *GroupCacheRedis) GetGroupInfo(ctx context.Context, groupID string) (group *relationTb.GroupModel, err error) {
return getCache(ctx, g.rcClient, g.getGroupInfoKey(groupID), g.expireTime, func(ctx context.Context) (*relationTb.GroupModel, error) { return getCache(
ctx,
g.rcClient,
g.getGroupInfoKey(groupID),
g.expireTime,
func(ctx context.Context) (*relationTb.GroupModel, error) {
return g.groupDB.Take(ctx, groupID) return g.groupDB.Take(ctx, groupID)
}) },
)
} }
func (g *GroupCacheRedis) DelGroupsInfo(groupIDs ...string) GroupCache { func (g *GroupCacheRedis) DelGroupsInfo(groupIDs ...string) GroupCache {
@ -161,31 +205,50 @@ func (g *GroupCacheRedis) DelGroupsInfo(groupIDs ...string) GroupCache {
return new return new
} }
func (g *GroupCacheRedis) GetJoinedSuperGroupIDs(ctx context.Context, userID string) (joinedSuperGroupIDs []string, err error) { func (g *GroupCacheRedis) GetJoinedSuperGroupIDs(
return getCache(ctx, g.rcClient, g.getJoinedSuperGroupsIDKey(userID), g.expireTime, func(ctx context.Context) ([]string, error) { ctx context.Context,
userID string,
) (joinedSuperGroupIDs []string, err error) {
return getCache(
ctx,
g.rcClient,
g.getJoinedSuperGroupsIDKey(userID),
g.expireTime,
func(ctx context.Context) ([]string, error) {
userGroup, err := g.mongoDB.GetSuperGroupByUserID(ctx, userID) userGroup, err := g.mongoDB.GetSuperGroupByUserID(ctx, userID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return userGroup.GroupIDs, nil return userGroup.GroupIDs, nil
}) },
)
} }
func (g *GroupCacheRedis) GetSuperGroupMemberIDs(ctx context.Context, groupIDs ...string) (models []*unrelationTb.SuperGroupModel, err error) { func (g *GroupCacheRedis) GetSuperGroupMemberIDs(
ctx context.Context,
groupIDs ...string,
) (models []*unrelationTb.SuperGroupModel, err error) {
var keys []string var keys []string
for _, group := range groupIDs { for _, group := range groupIDs {
keys = append(keys, g.getSuperGroupMemberIDsKey(group)) keys = append(keys, g.getSuperGroupMemberIDsKey(group))
} }
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, func(model *unrelationTb.SuperGroupModel, keys []string) (int, error) { return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
func(model *unrelationTb.SuperGroupModel, keys []string) (int, error) {
for i, key := range keys { for i, key := range keys {
if g.getSuperGroupMemberIDsKey(model.GroupID) == key { if g.getSuperGroupMemberIDsKey(model.GroupID) == key {
return i, nil return i, nil
} }
} }
return 0, errIndex return 0, errIndex
}, func(ctx context.Context) ([]*unrelationTb.SuperGroupModel, error) { },
func(ctx context.Context) ([]*unrelationTb.SuperGroupModel, error) {
return g.mongoDB.FindSuperGroup(ctx, groupIDs) return g.mongoDB.FindSuperGroup(ctx, groupIDs)
}) },
)
} }
// userJoinSuperGroup // userJoinSuperGroup
@ -211,7 +274,12 @@ func (g *GroupCacheRedis) DelSuperGroupMemberIDs(groupIDs ...string) GroupCache
// groupMembersHash // groupMembersHash
func (g *GroupCacheRedis) GetGroupMembersHash(ctx context.Context, groupID string) (hashCode uint64, err error) { func (g *GroupCacheRedis) GetGroupMembersHash(ctx context.Context, groupID string) (hashCode uint64, err error) {
return getCache(ctx, g.rcClient, g.getGroupMembersHashKey(groupID), g.expireTime, func(ctx context.Context) (uint64, error) { return getCache(
ctx,
g.rcClient,
g.getGroupMembersHashKey(groupID),
g.expireTime,
func(ctx context.Context) (uint64, error) {
userIDs, err := g.GetGroupMemberIDs(ctx, groupID) userIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
@ -220,10 +288,14 @@ func (g *GroupCacheRedis) GetGroupMembersHash(ctx context.Context, groupID strin
bi := big.NewInt(0) bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16) bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
return bi.Uint64(), nil return bi.Uint64(), nil
}) },
)
} }
func (g *GroupCacheRedis) GetGroupMemberHashMap(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error) { func (g *GroupCacheRedis) GetGroupMemberHashMap(
ctx context.Context,
groupIDs []string,
) (map[string]*relationTb.GroupSimpleUserID, error) {
res := make(map[string]*relationTb.GroupSimpleUserID) res := make(map[string]*relationTb.GroupSimpleUserID)
for _, groupID := range groupIDs { for _, groupID := range groupIDs {
hash, err := g.GetGroupMembersHash(ctx, groupID) hash, err := g.GetGroupMembersHash(ctx, groupID)
@ -247,9 +319,15 @@ func (g *GroupCacheRedis) DelGroupMembersHash(groupID string) GroupCache {
// groupMemberIDs // groupMemberIDs
func (g *GroupCacheRedis) GetGroupMemberIDs(ctx context.Context, groupID string) (groupMemberIDs []string, err error) { func (g *GroupCacheRedis) GetGroupMemberIDs(ctx context.Context, groupID string) (groupMemberIDs []string, err error) {
return getCache(ctx, g.rcClient, g.getGroupMemberIDsKey(groupID), g.expireTime, func(ctx context.Context) ([]string, error) { return getCache(
ctx,
g.rcClient,
g.getGroupMemberIDsKey(groupID),
g.expireTime,
func(ctx context.Context) ([]string, error) {
return g.groupMemberDB.FindMemberUserID(ctx, groupID) return g.groupMemberDB.FindMemberUserID(ctx, groupID)
}) },
)
} }
func (g *GroupCacheRedis) GetGroupsMemberIDs(ctx context.Context, groupIDs []string) (map[string][]string, error) { func (g *GroupCacheRedis) GetGroupsMemberIDs(ctx context.Context, groupIDs []string) (map[string][]string, error) {
@ -271,9 +349,15 @@ func (g *GroupCacheRedis) DelGroupMemberIDs(groupID string) GroupCache {
} }
func (g *GroupCacheRedis) GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error) { func (g *GroupCacheRedis) GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error) {
return getCache(ctx, g.rcClient, g.getJoinedGroupsKey(userID), g.expireTime, func(ctx context.Context) ([]string, error) { return getCache(
ctx,
g.rcClient,
g.getJoinedGroupsKey(userID),
g.expireTime,
func(ctx context.Context) ([]string, error) {
return g.groupMemberDB.FindUserJoinedGroupID(ctx, userID) return g.groupMemberDB.FindUserJoinedGroupID(ctx, userID)
}) },
)
} }
func (g *GroupCacheRedis) DelJoinedGroupID(userIDs ...string) GroupCache { func (g *GroupCacheRedis) DelJoinedGroupID(userIDs ...string) GroupCache {
@ -286,23 +370,48 @@ func (g *GroupCacheRedis) DelJoinedGroupID(userIDs ...string) GroupCache {
return cache return cache
} }
func (g *GroupCacheRedis) GetGroupMemberInfo(ctx context.Context, groupID, userID string) (groupMember *relationTb.GroupMemberModel, err error) { func (g *GroupCacheRedis) GetGroupMemberInfo(
return getCache(ctx, g.rcClient, g.getGroupMemberInfoKey(groupID, userID), g.expireTime, func(ctx context.Context) (*relationTb.GroupMemberModel, error) { ctx context.Context,
groupID, userID string,
) (groupMember *relationTb.GroupMemberModel, err error) {
return getCache(
ctx,
g.rcClient,
g.getGroupMemberInfoKey(groupID, userID),
g.expireTime,
func(ctx context.Context) (*relationTb.GroupMemberModel, error) {
return g.groupMemberDB.Take(ctx, groupID, userID) return g.groupMemberDB.Take(ctx, groupID, userID)
}) },
)
} }
func (g *GroupCacheRedis) GetGroupMembersInfo(ctx context.Context, groupID string, userIDs []string) ([]*relationTb.GroupMemberModel, error) { func (g *GroupCacheRedis) GetGroupMembersInfo(
ctx context.Context,
groupID string,
userIDs []string,
) ([]*relationTb.GroupMemberModel, error) {
var keys []string var keys []string
for _, userID := range userIDs { for _, userID := range userIDs {
keys = append(keys, g.getGroupMemberInfoKey(groupID, userID)) keys = append(keys, g.getGroupMemberInfoKey(groupID, userID))
} }
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, g.GetGroupMemberIndex, func(ctx context.Context) ([]*relationTb.GroupMemberModel, error) { return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
g.GetGroupMemberIndex,
func(ctx context.Context) ([]*relationTb.GroupMemberModel, error) {
return g.groupMemberDB.Find(ctx, []string{groupID}, userIDs, nil) return g.groupMemberDB.Find(ctx, []string{groupID}, userIDs, nil)
}) },
)
} }
func (g *GroupCacheRedis) GetGroupMembersPage(ctx context.Context, groupID string, userIDs []string, showNumber, pageNumber int32) (total uint32, groupMembers []*relationTb.GroupMemberModel, err error) { func (g *GroupCacheRedis) GetGroupMembersPage(
ctx context.Context,
groupID string,
userIDs []string,
showNumber, pageNumber int32,
) (total uint32, groupMembers []*relationTb.GroupMemberModel, err error) {
groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID) groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
@ -316,7 +425,10 @@ func (g *GroupCacheRedis) GetGroupMembersPage(ctx context.Context, groupID strin
return uint32(len(userIDs)), groupMembers, err return uint32(len(userIDs)), groupMembers, err
} }
func (g *GroupCacheRedis) GetAllGroupMembersInfo(ctx context.Context, groupID string) (groupMembers []*relationTb.GroupMemberModel, err error) { func (g *GroupCacheRedis) GetAllGroupMembersInfo(
ctx context.Context,
groupID string,
) (groupMembers []*relationTb.GroupMemberModel, err error) {
groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID) groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -324,7 +436,10 @@ func (g *GroupCacheRedis) GetAllGroupMembersInfo(ctx context.Context, groupID st
return g.GetGroupMembersInfo(ctx, groupID, groupMemberIDs) return g.GetGroupMembersInfo(ctx, groupID, groupMemberIDs)
} }
func (g *GroupCacheRedis) GetAllGroupMemberInfo(ctx context.Context, groupID string) ([]*relationTb.GroupMemberModel, error) { func (g *GroupCacheRedis) GetAllGroupMemberInfo(
ctx context.Context,
groupID string,
) ([]*relationTb.GroupMemberModel, error) {
groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID) groupMemberIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -333,9 +448,16 @@ func (g *GroupCacheRedis) GetAllGroupMemberInfo(ctx context.Context, groupID str
for _, groupMemberID := range groupMemberIDs { for _, groupMemberID := range groupMemberIDs {
keys = append(keys, g.getGroupMemberInfoKey(groupID, groupMemberID)) keys = append(keys, g.getGroupMemberInfoKey(groupID, groupMemberID))
} }
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, g.GetGroupMemberIndex, func(ctx context.Context) ([]*relationTb.GroupMemberModel, error) { return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
g.GetGroupMemberIndex,
func(ctx context.Context) ([]*relationTb.GroupMemberModel, error) {
return g.groupMemberDB.Find(ctx, []string{groupID}, groupMemberIDs, nil) return g.groupMemberDB.Find(ctx, []string{groupID}, groupMemberIDs, nil)
}) },
)
} }
func (g *GroupCacheRedis) DelGroupMembersInfo(groupID string, userIDs ...string) GroupCache { func (g *GroupCacheRedis) DelGroupMembersInfo(groupID string, userIDs ...string) GroupCache {
@ -349,9 +471,15 @@ func (g *GroupCacheRedis) DelGroupMembersInfo(groupID string, userIDs ...string)
} }
func (g *GroupCacheRedis) GetGroupMemberNum(ctx context.Context, groupID string) (memberNum int64, err error) { func (g *GroupCacheRedis) GetGroupMemberNum(ctx context.Context, groupID string) (memberNum int64, err error) {
return getCache(ctx, g.rcClient, g.getGroupMemberNumKey(groupID), g.expireTime, func(ctx context.Context) (int64, error) { return getCache(
ctx,
g.rcClient,
g.getGroupMemberNumKey(groupID),
g.expireTime,
func(ctx context.Context) (int64, error) {
return g.groupMemberDB.TakeGroupMemberNum(ctx, groupID) return g.groupMemberDB.TakeGroupMemberNum(ctx, groupID)
}) },
)
} }
func (g *GroupCacheRedis) DelGroupsMemberNum(groupID ...string) GroupCache { func (g *GroupCacheRedis) DelGroupsMemberNum(groupID ...string) GroupCache {

View File

@ -6,10 +6,11 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/redis/go-redis/v9"
) )
func NewRedis() (redis.UniversalClient, error) { func NewRedis() (redis.UniversalClient, error) {

View File

@ -7,10 +7,11 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/dtm-labs/rockscache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
) )
const ( const (
@ -48,7 +49,14 @@ func (m *metaCacheRedis) ExecDel(ctx context.Context) error {
for { for {
if err := m.rcClient.TagAsDeletedBatch2(ctx, m.keys); err != nil { if err := m.rcClient.TagAsDeletedBatch2(ctx, m.keys); err != nil {
if retryTimes >= m.maxRetryTimes { if retryTimes >= m.maxRetryTimes {
err = errs.ErrInternalServer.Wrap(fmt.Sprintf("delete cache error: %v, keys: %v, retry times %d, please check redis server", err, m.keys, retryTimes)) err = errs.ErrInternalServer.Wrap(
fmt.Sprintf(
"delete cache error: %v, keys: %v, retry times %d, please check redis server",
err,
m.keys,
retryTimes,
),
)
log.ZWarn(ctx, "delete cache failed, please handle keys", err, "keys", m.keys) log.ZWarn(ctx, "delete cache failed, please handle keys", err, "keys", m.keys)
return err return err
} }
@ -84,7 +92,13 @@ func GetDefaultOpt() rockscache.Options {
return opts return opts
} }
func getCache[T any](ctx context.Context, rcClient *rockscache.Client, key string, expire time.Duration, fn func(ctx context.Context) (T, error)) (T, error) { func getCache[T any](
ctx context.Context,
rcClient *rockscache.Client,
key string,
expire time.Duration,
fn func(ctx context.Context) (T, error),
) (T, error) {
var t T var t T
var write bool var write bool
v, err := rcClient.Fetch2(ctx, key, expire, func() (s string, err error) { v, err := rcClient.Fetch2(ctx, key, expire, func() (s string, err error) {
@ -116,7 +130,14 @@ func getCache[T any](ctx context.Context, rcClient *rockscache.Client, key strin
return t, nil return t, nil
} }
func batchGetCache[T any](ctx context.Context, rcClient *rockscache.Client, keys []string, expire time.Duration, keyIndexFn func(t T, keys []string) (int, error), fn func(ctx context.Context) ([]T, error)) ([]T, error) { func batchGetCache[T any](
ctx context.Context,
rcClient *rockscache.Client,
keys []string,
expire time.Duration,
keyIndexFn func(t T, keys []string) (int, error),
fn func(ctx context.Context) ([]T, error),
) ([]T, error) {
batchMap, err := rcClient.FetchBatch2(ctx, keys, expire, func(idxs []int) (m map[int]string, err error) { batchMap, err := rcClient.FetchBatch2(ctx, keys, expire, func(idxs []int) (m map[int]string, err error) {
values := make(map[int]string) values := make(map[int]string)
tArrays, err := fn(ctx) tArrays, err := fn(ctx)
@ -153,7 +174,14 @@ func batchGetCache[T any](ctx context.Context, rcClient *rockscache.Client, keys
return tArrays, nil return tArrays, nil
} }
func batchGetCacheMap[T any](ctx context.Context, rcClient *rockscache.Client, keys, originKeys []string, expire time.Duration, keyIndexFn func(s string, keys []string) (int, error), fn func(ctx context.Context) (map[string]T, error)) (map[string]T, error) { func batchGetCacheMap[T any](
ctx context.Context,
rcClient *rockscache.Client,
keys, originKeys []string,
expire time.Duration,
keyIndexFn func(s string, keys []string) (int, error),
fn func(ctx context.Context) (map[string]T, error),
) (map[string]T, error) {
batchMap, err := rcClient.FetchBatch2(ctx, keys, expire, func(idxs []int) (m map[int]string, err error) { batchMap, err := rcClient.FetchBatch2(ctx, keys, expire, func(idxs []int) (m map[int]string, err error) {
tArrays, err := fn(ctx) tArrays, err := fn(ctx)
if err != nil { if err != nil {

View File

@ -5,16 +5,18 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/gogo/protobuf/jsonpb"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/gogo/protobuf/jsonpb"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@ -86,7 +88,11 @@ type MsgModel interface {
GetTokensWithoutError(ctx context.Context, userID string, platformID int) (map[string]int, error) GetTokensWithoutError(ctx context.Context, userID string, platformID int) (map[string]int, error)
SetTokenMapByUidPid(ctx context.Context, userID string, platformID int, m map[string]int) error SetTokenMapByUidPid(ctx context.Context, userID string, platformID int, m map[string]int) error
DeleteTokenByUidPid(ctx context.Context, userID string, platformID int, fields []string) error DeleteTokenByUidPid(ctx context.Context, userID string, platformID int, fields []string) error
GetMessagesBySeq(ctx context.Context, conversationID string, seqs []int64) (seqMsg []*sdkws.MsgData, failedSeqList []int64, err error) GetMessagesBySeq(
ctx context.Context,
conversationID string,
seqs []int64,
) (seqMsg []*sdkws.MsgData, failedSeqList []int64, err error)
SetMessageToCache(ctx context.Context, conversationID string, msgs []*sdkws.MsgData) (int, error) SetMessageToCache(ctx context.Context, conversationID string, msgs []*sdkws.MsgData) (int, error)
UserDeleteMsgs(ctx context.Context, conversationID string, seqs []int64, userID string) error UserDeleteMsgs(ctx context.Context, conversationID string, seqs []int64, userID string) error
DelUserDeleteMsgsList(ctx context.Context, conversationID string, seqs []int64) DelUserDeleteMsgsList(ctx context.Context, conversationID string, seqs []int64)
@ -99,7 +105,12 @@ type MsgModel interface {
JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, error) JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, error)
GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error) GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error)
DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error
SetMessageReactionExpire(ctx context.Context, clientMsgID string, sessionType int32, expiration time.Duration) (bool, error) SetMessageReactionExpire(
ctx context.Context,
clientMsgID string,
sessionType int32,
expiration time.Duration,
) (bool, error)
GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error) GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error)
SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error
LockMessageTypeKey(ctx context.Context, clientMsgID string, TypeKey string) error LockMessageTypeKey(ctx context.Context, clientMsgID string, TypeKey string) error
@ -130,15 +141,28 @@ func (c *msgCache) getHasReadSeqKey(conversationID string, userID string) string
return hasReadSeq + userID + ":" + conversationID return hasReadSeq + userID + ":" + conversationID
} }
func (c *msgCache) setSeq(ctx context.Context, conversationID string, seq int64, getkey func(conversationID string) string) error { func (c *msgCache) setSeq(
ctx context.Context,
conversationID string,
seq int64,
getkey func(conversationID string) string,
) error {
return utils.Wrap1(c.rdb.Set(ctx, getkey(conversationID), seq, 0).Err()) return utils.Wrap1(c.rdb.Set(ctx, getkey(conversationID), seq, 0).Err())
} }
func (c *msgCache) getSeq(ctx context.Context, conversationID string, getkey func(conversationID string) string) (int64, error) { func (c *msgCache) getSeq(
ctx context.Context,
conversationID string,
getkey func(conversationID string) string,
) (int64, error) {
return utils.Wrap2(c.rdb.Get(ctx, getkey(conversationID)).Int64()) return utils.Wrap2(c.rdb.Get(ctx, getkey(conversationID)).Int64())
} }
func (c *msgCache) getSeqs(ctx context.Context, items []string, getkey func(s string) string) (m map[string]int64, err error) { func (c *msgCache) getSeqs(
ctx context.Context,
items []string,
getkey func(s string) string,
) (m map[string]int64, err error) {
pipe := c.rdb.Pipeline() pipe := c.rdb.Pipeline()
for _, v := range items { for _, v := range items {
if err := pipe.Get(ctx, getkey(v)).Err(); err != nil && err != redis.Nil { if err := pipe.Get(ctx, getkey(v)).Err(); err != nil && err != redis.Nil {
@ -209,16 +233,30 @@ func (c *msgCache) GetConversationUserMinSeq(ctx context.Context, conversationID
return utils.Wrap2(c.rdb.Get(ctx, c.getConversationUserMinSeqKey(conversationID, userID)).Int64()) return utils.Wrap2(c.rdb.Get(ctx, c.getConversationUserMinSeqKey(conversationID, userID)).Int64())
} }
func (c *msgCache) GetConversationUserMinSeqs(ctx context.Context, conversationID string, userIDs []string) (m map[string]int64, err error) { func (c *msgCache) GetConversationUserMinSeqs(
ctx context.Context,
conversationID string,
userIDs []string,
) (m map[string]int64, err error) {
return c.getSeqs(ctx, userIDs, func(userID string) string { return c.getSeqs(ctx, userIDs, func(userID string) string {
return c.getConversationUserMinSeqKey(conversationID, userID) return c.getConversationUserMinSeqKey(conversationID, userID)
}) })
} }
func (c *msgCache) SetConversationUserMinSeq(ctx context.Context, conversationID string, userID string, minSeq int64) error {
func (c *msgCache) SetConversationUserMinSeq(
ctx context.Context,
conversationID string,
userID string,
minSeq int64,
) error {
return utils.Wrap1(c.rdb.Set(ctx, c.getConversationUserMinSeqKey(conversationID, userID), minSeq, 0).Err()) return utils.Wrap1(c.rdb.Set(ctx, c.getConversationUserMinSeqKey(conversationID, userID), minSeq, 0).Err())
} }
func (c *msgCache) SetConversationUserMinSeqs(ctx context.Context, conversationID string, seqs map[string]int64) (err error) { func (c *msgCache) SetConversationUserMinSeqs(
ctx context.Context,
conversationID string,
seqs map[string]int64,
) (err error) {
return c.setSeqs(ctx, seqs, func(userID string) string { return c.setSeqs(ctx, seqs, func(userID string) string {
return c.getConversationUserMinSeqKey(conversationID, userID) return c.getConversationUserMinSeqKey(conversationID, userID)
}) })
@ -246,7 +284,11 @@ func (c *msgCache) UserSetHasReadSeqs(ctx context.Context, userID string, hasRea
}) })
} }
func (c *msgCache) GetHasReadSeqs(ctx context.Context, userID string, conversationIDs []string) (map[string]int64, error) { func (c *msgCache) GetHasReadSeqs(
ctx context.Context,
userID string,
conversationIDs []string,
) (map[string]int64, error) {
return c.getSeqs(ctx, conversationIDs, func(conversationID string) string { return c.getSeqs(ctx, conversationIDs, func(conversationID string) string {
return c.getHasReadSeqKey(conversationID, userID) return c.getHasReadSeqKey(conversationID, userID)
}) })
@ -296,7 +338,11 @@ func (c *msgCache) allMessageCacheKey(conversationID string) string {
return messageCache + conversationID + "_*" return messageCache + conversationID + "_*"
} }
func (c *msgCache) GetMessagesBySeq(ctx context.Context, conversationID string, seqs []int64) (seqMsgs []*sdkws.MsgData, failedSeqs []int64, err error) { func (c *msgCache) GetMessagesBySeq(
ctx context.Context,
conversationID string,
seqs []int64,
) (seqMsgs []*sdkws.MsgData, failedSeqs []int64, err error) {
pipe := c.rdb.Pipeline() pipe := c.rdb.Pipeline()
for _, v := range seqs { for _, v := range seqs {
//MESSAGE_CACHE:169.254.225.224_reliability1653387820_0_1 //MESSAGE_CACHE:169.254.225.224_reliability1653387820_0_1
@ -404,7 +450,17 @@ func (c *msgCache) DelUserDeleteMsgsList(ctx context.Context, conversationID str
err = pipe.SRem(ctx, c.getUserDelList(conversationID, userID), seq).Err() err = pipe.SRem(ctx, c.getUserDelList(conversationID, userID), seq).Err()
if err != nil { if err != nil {
failedFlag = true failedFlag = true
log.ZWarn(ctx, "DelUserDeleteMsgsList failed", err, "conversationID", conversationID, "seq", seq, "userID", userID) log.ZWarn(
ctx,
"DelUserDeleteMsgsList failed",
err,
"conversationID",
conversationID,
"seq",
seq,
"userID",
userID,
)
} }
} }
if !failedFlag { if !failedFlag {
@ -499,8 +555,17 @@ func (c *msgCache) GetSendMsgStatus(ctx context.Context, id string) (int32, erro
return int32(result), errs.Wrap(err) return int32(result), errs.Wrap(err)
} }
func (c *msgCache) SetFcmToken(ctx context.Context, account string, platformID int, fcmToken string, expireTime int64) (err error) { func (c *msgCache) SetFcmToken(
return errs.Wrap(c.rdb.Set(ctx, fcmToken+account+":"+strconv.Itoa(platformID), fcmToken, time.Duration(expireTime)*time.Second).Err()) ctx context.Context,
account string,
platformID int,
fcmToken string,
expireTime int64,
) (err error) {
return errs.Wrap(
c.rdb.Set(ctx, fcmToken+account+":"+strconv.Itoa(platformID), fcmToken, time.Duration(expireTime)*time.Second).
Err(),
)
} }
func (c *msgCache) GetFcmToken(ctx context.Context, account string, platformID int) (string, error) { func (c *msgCache) GetFcmToken(ctx context.Context, account string, platformID int) (string, error) {
@ -556,22 +621,46 @@ func (c *msgCache) JudgeMessageReactionExist(ctx context.Context, clientMsgID st
return n > 0, nil return n > 0, nil
} }
func (c *msgCache) SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error { func (c *msgCache) SetMessageTypeKeyValue(
ctx context.Context,
clientMsgID string,
sessionType int32,
typeKey, value string,
) error {
return errs.Wrap(c.rdb.HSet(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), typeKey, value).Err()) return errs.Wrap(c.rdb.HSet(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), typeKey, value).Err())
} }
func (c *msgCache) SetMessageReactionExpire(ctx context.Context, clientMsgID string, sessionType int32, expiration time.Duration) (bool, error) { func (c *msgCache) SetMessageReactionExpire(
ctx context.Context,
clientMsgID string,
sessionType int32,
expiration time.Duration,
) (bool, error) {
return utils.Wrap2(c.rdb.Expire(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), expiration).Result()) return utils.Wrap2(c.rdb.Expire(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), expiration).Result())
} }
func (c *msgCache) GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error) { func (c *msgCache) GetMessageTypeKeyValue(
ctx context.Context,
clientMsgID string,
sessionType int32,
typeKey string,
) (string, error) {
return utils.Wrap2(c.rdb.HGet(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), typeKey).Result()) return utils.Wrap2(c.rdb.HGet(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), typeKey).Result())
} }
func (c *msgCache) GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error) { func (c *msgCache) GetOneMessageAllReactionList(
ctx context.Context,
clientMsgID string,
sessionType int32,
) (map[string]string, error) {
return utils.Wrap2(c.rdb.HGetAll(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType)).Result()) return utils.Wrap2(c.rdb.HGetAll(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType)).Result())
} }
func (c *msgCache) DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error { func (c *msgCache) DeleteOneMessageKey(
ctx context.Context,
clientMsgID string,
sessionType int32,
subKey string,
) error {
return errs.Wrap(c.rdb.HDel(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), subKey).Err()) return errs.Wrap(c.rdb.HDel(ctx, c.getMessageReactionExPrefix(clientMsgID, sessionType), subKey).Err())
} }

View File

@ -4,9 +4,10 @@ import (
"context" "context"
"time" "time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
) )
const ( const (
@ -32,7 +33,11 @@ type UserCacheRedis struct {
rcClient *rockscache.Client rcClient *rockscache.Client
} }
func NewUserCacheRedis(rdb redis.UniversalClient, userDB relationTb.UserModelInterface, options rockscache.Options) UserCache { func NewUserCacheRedis(
rdb redis.UniversalClient,
userDB relationTb.UserModelInterface,
options rockscache.Options,
) UserCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &UserCacheRedis{ return &UserCacheRedis{
metaCache: NewMetaCacheRedis(rcClient), metaCache: NewMetaCacheRedis(rcClient),
@ -60,9 +65,15 @@ func (u *UserCacheRedis) getUserGlobalRecvMsgOptKey(userID string) string {
} }
func (u *UserCacheRedis) GetUserInfo(ctx context.Context, userID string) (userInfo *relationTb.UserModel, err error) { func (u *UserCacheRedis) GetUserInfo(ctx context.Context, userID string) (userInfo *relationTb.UserModel, err error) {
return getCache(ctx, u.rcClient, u.getUserInfoKey(userID), u.expireTime, func(ctx context.Context) (*relationTb.UserModel, error) { return getCache(
ctx,
u.rcClient,
u.getUserInfoKey(userID),
u.expireTime,
func(ctx context.Context) (*relationTb.UserModel, error) {
return u.userDB.Take(ctx, userID) return u.userDB.Take(ctx, userID)
}) },
)
} }
func (u *UserCacheRedis) GetUsersInfo(ctx context.Context, userIDs []string) ([]*relationTb.UserModel, error) { func (u *UserCacheRedis) GetUsersInfo(ctx context.Context, userIDs []string) ([]*relationTb.UserModel, error) {
@ -70,16 +81,23 @@ func (u *UserCacheRedis) GetUsersInfo(ctx context.Context, userIDs []string) ([]
for _, userID := range userIDs { for _, userID := range userIDs {
keys = append(keys, u.getUserInfoKey(userID)) keys = append(keys, u.getUserInfoKey(userID))
} }
return batchGetCache(ctx, u.rcClient, keys, u.expireTime, func(user *relationTb.UserModel, keys []string) (int, error) { return batchGetCache(
ctx,
u.rcClient,
keys,
u.expireTime,
func(user *relationTb.UserModel, keys []string) (int, error) {
for i, key := range keys { for i, key := range keys {
if key == u.getUserInfoKey(user.UserID) { if key == u.getUserInfoKey(user.UserID) {
return i, nil return i, nil
} }
} }
return 0, errIndex return 0, errIndex
}, func(ctx context.Context) ([]*relationTb.UserModel, error) { },
func(ctx context.Context) ([]*relationTb.UserModel, error) {
return u.userDB.Find(ctx, userIDs) return u.userDB.Find(ctx, userIDs)
}) },
)
} }
func (u *UserCacheRedis) DelUsersInfo(userIDs ...string) UserCache { func (u *UserCacheRedis) DelUsersInfo(userIDs ...string) UserCache {
@ -93,9 +111,15 @@ func (u *UserCacheRedis) DelUsersInfo(userIDs ...string) UserCache {
} }
func (u *UserCacheRedis) GetUserGlobalRecvMsgOpt(ctx context.Context, userID string) (opt int, err error) { func (u *UserCacheRedis) GetUserGlobalRecvMsgOpt(ctx context.Context, userID string) (opt int, err error) {
return getCache(ctx, u.rcClient, u.getUserGlobalRecvMsgOptKey(userID), u.expireTime, func(ctx context.Context) (int, error) { return getCache(
ctx,
u.rcClient,
u.getUserGlobalRecvMsgOptKey(userID),
u.expireTime,
func(ctx context.Context) (int, error) {
return u.userDB.GetUserGlobalRecvMsgOpt(ctx, userID) return u.userDB.GetUserGlobalRecvMsgOpt(ctx, userID)
}) },
)
} }
func (u *UserCacheRedis) DelUsersGlobalRecvMsgOpt(userIDs ...string) UserCache { func (u *UserCacheRedis) DelUsersGlobalRecvMsgOpt(userIDs ...string) UserCache {

View File

@ -3,11 +3,12 @@ package controller
import ( import (
"context" "context"
"github.com/golang-jwt/jwt/v4"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/golang-jwt/jwt/v4"
) )
type AuthDatabase interface { type AuthDatabase interface {
@ -29,7 +30,11 @@ func NewAuthDatabase(cache cache.MsgModel, accessSecret string, accessExpire int
} }
// 结果为空 不返回错误 // 结果为空 不返回错误
func (a *authDatabase) GetTokensWithoutError(ctx context.Context, userID string, platformID int) (map[string]int, error) { func (a *authDatabase) GetTokensWithoutError(
ctx context.Context,
userID string,
platformID int,
) (map[string]int, error) {
return a.cache.GetTokensWithoutError(ctx, userID, platformID) return a.cache.GetTokensWithoutError(ctx, userID, platformID)
} }

View File

@ -15,7 +15,11 @@ type BlackDatabase interface {
// Delete 删除黑名单 // Delete 删除黑名单
Delete(ctx context.Context, blacks []*relation.BlackModel) (err error) Delete(ctx context.Context, blacks []*relation.BlackModel) (err error)
// FindOwnerBlacks 获取黑名单列表 // FindOwnerBlacks 获取黑名单列表
FindOwnerBlacks(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (blacks []*relation.BlackModel, total int64, err error) FindOwnerBlacks(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (blacks []*relation.BlackModel, total int64, err error)
FindBlackIDs(ctx context.Context, ownerUserID string) (blackIDs []string, err error) FindBlackIDs(ctx context.Context, ownerUserID string) (blackIDs []string, err error)
// CheckIn 检查user2是否在user1的黑名单列表中(inUser1Blacks==true) 检查user1是否在user2的黑名单列表中(inUser2Blacks==true) // CheckIn 检查user2是否在user1的黑名单列表中(inUser1Blacks==true) 检查user1是否在user2的黑名单列表中(inUser2Blacks==true)
CheckIn(ctx context.Context, userID1, userID2 string) (inUser1Blacks bool, inUser2Blacks bool, err error) CheckIn(ctx context.Context, userID1, userID2 string) (inUser1Blacks bool, inUser2Blacks bool, err error)
@ -55,12 +59,19 @@ func (b *blackDatabase) deleteBlackIDsCache(ctx context.Context, blacks []*relat
} }
// FindOwnerBlacks 获取黑名单列表 // FindOwnerBlacks 获取黑名单列表
func (b *blackDatabase) FindOwnerBlacks(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (blacks []*relation.BlackModel, total int64, err error) { func (b *blackDatabase) FindOwnerBlacks(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (blacks []*relation.BlackModel, total int64, err error) {
return b.black.FindOwnerBlacks(ctx, ownerUserID, pageNumber, showNumber) return b.black.FindOwnerBlacks(ctx, ownerUserID, pageNumber, showNumber)
} }
// CheckIn 检查user2是否在user1的黑名单列表中(inUser1Blacks==true) 检查user1是否在user2的黑名单列表中(inUser2Blacks==true) // CheckIn 检查user2是否在user1的黑名单列表中(inUser1Blacks==true) 检查user1是否在user2的黑名单列表中(inUser2Blacks==true)
func (b *blackDatabase) CheckIn(ctx context.Context, userID1, userID2 string) (inUser1Blacks bool, inUser2Blacks bool, err error) { func (b *blackDatabase) CheckIn(
ctx context.Context,
userID1, userID2 string,
) (inUser1Blacks bool, inUser2Blacks bool, err error) {
userID1BlackIDs, err := b.cache.GetBlackIDs(ctx, userID1) userID1BlackIDs, err := b.cache.GetBlackIDs(ctx, userID1)
if err != nil { if err != nil {
return return

View File

@ -7,7 +7,11 @@ import (
type ChatLogDatabase interface { type ChatLogDatabase interface {
CreateChatLog(msg *pbMsg.MsgDataToMQ) error CreateChatLog(msg *pbMsg.MsgDataToMQ) error
GetChatLog(chatLog *relationTb.ChatLogModel, pageNumber, showNumber int32, contentTypes []int32) (int64, []relationTb.ChatLogModel, error) GetChatLog(
chatLog *relationTb.ChatLogModel,
pageNumber, showNumber int32,
contentTypes []int32,
) (int64, []relationTb.ChatLogModel, error)
} }
func NewChatLogDatabase(chatLogModelInterface relationTb.ChatLogModelInterface) ChatLogDatabase { func NewChatLogDatabase(chatLogModelInterface relationTb.ChatLogModelInterface) ChatLogDatabase {
@ -22,6 +26,10 @@ func (c *chatLogDatabase) CreateChatLog(msg *pbMsg.MsgDataToMQ) error {
return c.chatLogModel.Create(msg) return c.chatLogModel.Create(msg)
} }
func (c *chatLogDatabase) GetChatLog(chatLog *relationTb.ChatLogModel, pageNumber, showNumber int32, contentTypes []int32) (int64, []relationTb.ChatLogModel, error) { func (c *chatLogDatabase) GetChatLog(
chatLog *relationTb.ChatLogModel,
pageNumber, showNumber int32,
contentTypes []int32,
) (int64, []relationTb.ChatLogModel, error) {
return c.chatLogModel.GetChatLog(chatLog, pageNumber, showNumber, contentTypes) return c.chatLogModel.GetChatLog(chatLog, pageNumber, showNumber, contentTypes)
} }

View File

@ -13,13 +13,22 @@ import (
type ConversationDatabase interface { type ConversationDatabase interface {
//UpdateUserConversationFiled 更新用户该会话的属性信息 //UpdateUserConversationFiled 更新用户该会话的属性信息
UpdateUsersConversationFiled(ctx context.Context, userIDs []string, conversationID string, args map[string]interface{}) error UpdateUsersConversationFiled(
ctx context.Context,
userIDs []string,
conversationID string,
args map[string]interface{},
) error
//CreateConversation 创建一批新的会话 //CreateConversation 创建一批新的会话
CreateConversation(ctx context.Context, conversations []*relationTb.ConversationModel) error CreateConversation(ctx context.Context, conversations []*relationTb.ConversationModel) error
//SyncPeerUserPrivateConversation 同步对端私聊会话内部保证事务操作 //SyncPeerUserPrivateConversation 同步对端私聊会话内部保证事务操作
SyncPeerUserPrivateConversationTx(ctx context.Context, conversation []*relationTb.ConversationModel) error SyncPeerUserPrivateConversationTx(ctx context.Context, conversation []*relationTb.ConversationModel) error
//FindConversations 根据会话ID获取某个用户的多个会话 //FindConversations 根据会话ID获取某个用户的多个会话
FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) FindConversations(
ctx context.Context,
ownerUserID string,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error)
//FindRecvMsgNotNotifyUserIDs 获取超级大群开启免打扰的用户ID //FindRecvMsgNotNotifyUserIDs 获取超级大群开启免打扰的用户ID
FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) ([]string, error) FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) ([]string, error)
//GetUserAllConversation 获取一个用户在服务器上所有的会话 //GetUserAllConversation 获取一个用户在服务器上所有的会话
@ -27,16 +36,28 @@ type ConversationDatabase interface {
//SetUserConversations 设置用户多个会话属性,如果会话不存在则创建,否则更新,内部保证原子性 //SetUserConversations 设置用户多个会话属性,如果会话不存在则创建,否则更新,内部保证原子性
SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error
//SetUsersConversationFiledTx 设置多个用户会话关于某个字段的更新操作,如果会话不存在则创建,否则更新,内部保证事务操作 //SetUsersConversationFiledTx 设置多个用户会话关于某个字段的更新操作,如果会话不存在则创建,否则更新,内部保证事务操作
SetUsersConversationFiledTx(ctx context.Context, userIDs []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) error SetUsersConversationFiledTx(
ctx context.Context,
userIDs []string,
conversation *relationTb.ConversationModel,
filedMap map[string]interface{},
) error
CreateGroupChatConversation(ctx context.Context, groupID string, userIDs []string) error CreateGroupChatConversation(ctx context.Context, groupID string, userIDs []string) error
GetConversationIDs(ctx context.Context, userID string) ([]string, error) GetConversationIDs(ctx context.Context, userID string) ([]string, error)
GetUserConversationIDsHash(ctx context.Context, ownerUserID string) (hash uint64, err error) GetUserConversationIDsHash(ctx context.Context, ownerUserID string) (hash uint64, err error)
GetAllConversationIDs(ctx context.Context) ([]string, error) GetAllConversationIDs(ctx context.Context) ([]string, error)
GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error)
GetConversationsByConversationID(ctx context.Context, conversationIDs []string) ([]*relationTb.ConversationModel, error) GetConversationsByConversationID(
ctx context.Context,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error)
} }
func NewConversationDatabase(conversation relationTb.ConversationModelInterface, cache cache.ConversationCache, tx tx.Tx) ConversationDatabase { func NewConversationDatabase(
conversation relationTb.ConversationModelInterface,
cache cache.ConversationCache,
tx tx.Tx,
) ConversationDatabase {
return &conversationDatabase{ return &conversationDatabase{
conversationDB: conversation, conversationDB: conversation,
cache: cache, cache: cache,
@ -50,7 +71,12 @@ type conversationDatabase struct {
tx tx.Tx tx tx.Tx
} }
func (c *conversationDatabase) SetUsersConversationFiledTx(ctx context.Context, userIDs []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) (err error) { func (c *conversationDatabase) SetUsersConversationFiledTx(
ctx context.Context,
userIDs []string,
conversation *relationTb.ConversationModel,
filedMap map[string]interface{},
) (err error) {
cache := c.cache.NewCache() cache := c.cache.NewCache()
if err := c.tx.Transaction(func(tx any) error { if err := c.tx.Transaction(func(tx any) error {
conversationTx := c.conversationDB.NewTx(tx) conversationTx := c.conversationDB.NewTx(tx)
@ -96,7 +122,12 @@ func (c *conversationDatabase) SetUsersConversationFiledTx(ctx context.Context,
return cache.ExecDel(ctx) return cache.ExecDel(ctx)
} }
func (c *conversationDatabase) UpdateUsersConversationFiled(ctx context.Context, userIDs []string, conversationID string, args map[string]interface{}) error { func (c *conversationDatabase) UpdateUsersConversationFiled(
ctx context.Context,
userIDs []string,
conversationID string,
args map[string]interface{},
) error {
_, err := c.conversationDB.UpdateByMap(ctx, userIDs, conversationID, args) _, err := c.conversationDB.UpdateByMap(ctx, userIDs, conversationID, args)
if err != nil { if err != nil {
return err return err
@ -104,7 +135,10 @@ func (c *conversationDatabase) UpdateUsersConversationFiled(ctx context.Context,
return c.cache.DelUsersConversation(conversationID, userIDs...).ExecDel(ctx) return c.cache.DelUsersConversation(conversationID, userIDs...).ExecDel(ctx)
} }
func (c *conversationDatabase) CreateConversation(ctx context.Context, conversations []*relationTb.ConversationModel) error { func (c *conversationDatabase) CreateConversation(
ctx context.Context,
conversations []*relationTb.ConversationModel,
) error {
if err := c.conversationDB.Create(ctx, conversations); err != nil { if err := c.conversationDB.Create(ctx, conversations); err != nil {
return err return err
} }
@ -117,7 +151,10 @@ func (c *conversationDatabase) CreateConversation(ctx context.Context, conversat
return cache.DelConversationIDs(userIDs...).DelUserConversationIDsHash(userIDs...).ExecDel(ctx) return cache.DelConversationIDs(userIDs...).DelUserConversationIDsHash(userIDs...).ExecDel(ctx)
} }
func (c *conversationDatabase) SyncPeerUserPrivateConversationTx(ctx context.Context, conversations []*relationTb.ConversationModel) error { func (c *conversationDatabase) SyncPeerUserPrivateConversationTx(
ctx context.Context,
conversations []*relationTb.ConversationModel,
) error {
cache := c.cache.NewCache() cache := c.cache.NewCache()
if err := c.tx.Transaction(func(tx any) error { if err := c.tx.Transaction(func(tx any) error {
conversationTx := c.conversationDB.NewTx(tx) conversationTx := c.conversationDB.NewTx(tx)
@ -153,19 +190,34 @@ func (c *conversationDatabase) SyncPeerUserPrivateConversationTx(ctx context.Con
return c.cache.ExecDel(ctx) return c.cache.ExecDel(ctx)
} }
func (c *conversationDatabase) FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) { func (c *conversationDatabase) FindConversations(
ctx context.Context,
ownerUserID string,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error) {
return c.cache.GetConversations(ctx, ownerUserID, conversationIDs) return c.cache.GetConversations(ctx, ownerUserID, conversationIDs)
} }
func (c *conversationDatabase) GetConversation(ctx context.Context, ownerUserID string, conversationID string) (*relationTb.ConversationModel, error) { func (c *conversationDatabase) GetConversation(
ctx context.Context,
ownerUserID string,
conversationID string,
) (*relationTb.ConversationModel, error) {
return c.cache.GetConversation(ctx, ownerUserID, conversationID) return c.cache.GetConversation(ctx, ownerUserID, conversationID)
} }
func (c *conversationDatabase) GetUserAllConversation(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error) { func (c *conversationDatabase) GetUserAllConversation(
ctx context.Context,
ownerUserID string,
) ([]*relationTb.ConversationModel, error) {
return c.cache.GetUserAllConversations(ctx, ownerUserID) return c.cache.GetUserAllConversations(ctx, ownerUserID)
} }
func (c *conversationDatabase) SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error { func (c *conversationDatabase) SetUserConversations(
ctx context.Context,
ownerUserID string,
conversations []*relationTb.ConversationModel,
) error {
cache := c.cache.NewCache() cache := c.cache.NewCache()
if err := c.tx.Transaction(func(tx any) error { if err := c.tx.Transaction(func(tx any) error {
var conversationIDs []string var conversationIDs []string
@ -215,7 +267,11 @@ func (c *conversationDatabase) FindRecvMsgNotNotifyUserIDs(ctx context.Context,
return c.cache.GetSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID) return c.cache.GetSuperGroupRecvMsgNotNotifyUserIDs(ctx, groupID)
} }
func (c *conversationDatabase) CreateGroupChatConversation(ctx context.Context, groupID string, userIDs []string) error { func (c *conversationDatabase) CreateGroupChatConversation(
ctx context.Context,
groupID string,
userIDs []string,
) error {
cache := c.cache.NewCache() cache := c.cache.NewCache()
conversationID := utils.GetConversationIDBySessionType(constant.SuperGroupChatType, groupID) conversationID := utils.GetConversationIDBySessionType(constant.SuperGroupChatType, groupID)
if err := c.tx.Transaction(func(tx any) error { if err := c.tx.Transaction(func(tx any) error {
@ -255,7 +311,10 @@ func (c *conversationDatabase) GetConversationIDs(ctx context.Context, userID st
return c.cache.GetUserConversationIDs(ctx, userID) return c.cache.GetUserConversationIDs(ctx, userID)
} }
func (c *conversationDatabase) GetUserConversationIDsHash(ctx context.Context, ownerUserID string) (hash uint64, err error) { func (c *conversationDatabase) GetUserConversationIDsHash(
ctx context.Context,
ownerUserID string,
) (hash uint64, err error) {
return c.cache.GetUserConversationIDsHash(ctx, ownerUserID) return c.cache.GetUserConversationIDsHash(ctx, ownerUserID)
} }
@ -263,10 +322,16 @@ func (c *conversationDatabase) GetAllConversationIDs(ctx context.Context) ([]str
return c.conversationDB.GetAllConversationIDs(ctx) return c.conversationDB.GetAllConversationIDs(ctx)
} }
func (c *conversationDatabase) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error) { func (c *conversationDatabase) GetUserAllHasReadSeqs(
ctx context.Context,
ownerUserID string,
) (map[string]int64, error) {
return c.cache.GetUserAllHasReadSeqs(ctx, ownerUserID) return c.cache.GetUserAllHasReadSeqs(ctx, ownerUserID)
} }
func (c *conversationDatabase) GetConversationsByConversationID(ctx context.Context, conversationIDs []string) ([]*relationTb.ConversationModel, error) { func (c *conversationDatabase) GetConversationsByConversationID(
ctx context.Context,
conversationIDs []string,
) ([]*relationTb.ConversationModel, error) {
return c.conversationDB.GetConversationsByConversationID(ctx, conversationIDs) return c.conversationDB.GetConversationsByConversationID(ctx, conversationIDs)
} }

View File

@ -11,12 +11,46 @@ import (
// for mongoDB // for mongoDB
type ExtendMsgDatabase interface { type ExtendMsgDatabase interface {
CreateExtendMsgSet(ctx context.Context, set *unRelationTb.ExtendMsgSetModel) error CreateExtendMsgSet(ctx context.Context, set *unRelationTb.ExtendMsgSetModel) error
GetAllExtendMsgSet(ctx context.Context, ID string, opts *unRelationTb.GetAllExtendMsgSetOpts) (sets []*unRelationTb.ExtendMsgSetModel, err error) GetAllExtendMsgSet(
GetExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, maxMsgUpdateTime int64) (*unRelationTb.ExtendMsgSetModel, error) ctx context.Context,
InsertExtendMsg(ctx context.Context, conversationID string, sessionType int32, msg *unRelationTb.ExtendMsgModel) error ID string,
InsertOrUpdateReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*unRelationTb.KeyValueModel) error opts *unRelationTb.GetAllExtendMsgSetOpts,
DeleteReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*unRelationTb.KeyValueModel) error ) (sets []*unRelationTb.ExtendMsgSetModel, err error)
GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, maxMsgUpdateTime int64) (extendMsg *unRelationTb.ExtendMsgModel, err error) GetExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
maxMsgUpdateTime int64,
) (*unRelationTb.ExtendMsgSetModel, error)
InsertExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
msg *unRelationTb.ExtendMsgModel,
) error
InsertOrUpdateReactionExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*unRelationTb.KeyValueModel,
) error
DeleteReactionExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*unRelationTb.KeyValueModel,
) error
GetExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
maxMsgUpdateTime int64,
) (extendMsg *unRelationTb.ExtendMsgModel, err error)
} }
type extendMsgDatabase struct { type extendMsgDatabase struct {
@ -25,7 +59,11 @@ type extendMsgDatabase struct {
ctxTx tx.CtxTx ctxTx tx.CtxTx
} }
func NewExtendMsgDatabase(extendMsgModel unRelationTb.ExtendMsgSetModelInterface, cache cache.ExtendMsgSetCache, ctxTx tx.CtxTx) ExtendMsgDatabase { func NewExtendMsgDatabase(
extendMsgModel unRelationTb.ExtendMsgSetModelInterface,
cache cache.ExtendMsgSetCache,
ctxTx tx.CtxTx,
) ExtendMsgDatabase {
return &extendMsgDatabase{database: extendMsgModel, cache: cache, ctxTx: ctxTx} return &extendMsgDatabase{database: extendMsgModel, cache: cache, ctxTx: ctxTx}
} }
@ -33,26 +71,74 @@ func (e *extendMsgDatabase) CreateExtendMsgSet(ctx context.Context, set *unRelat
return e.database.CreateExtendMsgSet(ctx, set) return e.database.CreateExtendMsgSet(ctx, set)
} }
func (e *extendMsgDatabase) GetAllExtendMsgSet(ctx context.Context, conversationID string, opts *unRelationTb.GetAllExtendMsgSetOpts) (sets []*unRelationTb.ExtendMsgSetModel, err error) { func (e *extendMsgDatabase) GetAllExtendMsgSet(
ctx context.Context,
conversationID string,
opts *unRelationTb.GetAllExtendMsgSetOpts,
) (sets []*unRelationTb.ExtendMsgSetModel, err error) {
return e.database.GetAllExtendMsgSet(ctx, conversationID, opts) return e.database.GetAllExtendMsgSet(ctx, conversationID, opts)
} }
func (e *extendMsgDatabase) GetExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, maxMsgUpdateTime int64) (*unRelationTb.ExtendMsgSetModel, error) { func (e *extendMsgDatabase) GetExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
maxMsgUpdateTime int64,
) (*unRelationTb.ExtendMsgSetModel, error) {
return e.database.GetExtendMsgSet(ctx, conversationID, sessionType, maxMsgUpdateTime) return e.database.GetExtendMsgSet(ctx, conversationID, sessionType, maxMsgUpdateTime)
} }
func (e *extendMsgDatabase) InsertExtendMsg(ctx context.Context, conversationID string, sessionType int32, msg *unRelationTb.ExtendMsgModel) error { func (e *extendMsgDatabase) InsertExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
msg *unRelationTb.ExtendMsgModel,
) error {
return e.database.InsertExtendMsg(ctx, conversationID, sessionType, msg) return e.database.InsertExtendMsg(ctx, conversationID, sessionType, msg)
} }
func (e *extendMsgDatabase) InsertOrUpdateReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*unRelationTb.KeyValueModel) error { func (e *extendMsgDatabase) InsertOrUpdateReactionExtendMsgSet(
return e.database.InsertOrUpdateReactionExtendMsgSet(ctx, conversationID, sessionType, clientMsgID, msgFirstModifyTime, reactionExtensionList) ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*unRelationTb.KeyValueModel,
) error {
return e.database.InsertOrUpdateReactionExtendMsgSet(
ctx,
conversationID,
sessionType,
clientMsgID,
msgFirstModifyTime,
reactionExtensionList,
)
} }
func (e *extendMsgDatabase) DeleteReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*unRelationTb.KeyValueModel) error { func (e *extendMsgDatabase) DeleteReactionExtendMsgSet(
return e.database.DeleteReactionExtendMsgSet(ctx, conversationID, sessionType, clientMsgID, msgFirstModifyTime, reactionExtensionList) ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*unRelationTb.KeyValueModel,
) error {
return e.database.DeleteReactionExtendMsgSet(
ctx,
conversationID,
sessionType,
clientMsgID,
msgFirstModifyTime,
reactionExtensionList,
)
} }
func (e *extendMsgDatabase) GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, maxMsgUpdateTime int64) (extendMsg *unRelationTb.ExtendMsgModel, err error) { func (e *extendMsgDatabase) GetExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
maxMsgUpdateTime int64,
) (extendMsg *unRelationTb.ExtendMsgModel, err error) {
return e.cache.GetExtendMsg(ctx, conversationID, sessionType, clientMsgID, maxMsgUpdateTime) return e.cache.GetExtendMsg(ctx, conversationID, sessionType, clientMsgID, maxMsgUpdateTime)
} }

View File

@ -4,6 +4,8 @@ import (
"context" "context"
"time" "time"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
@ -11,7 +13,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
) )
type FriendDatabase interface { type FriendDatabase interface {
@ -30,15 +31,35 @@ type FriendDatabase interface {
// 更新好友备注 // 更新好友备注
UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error) UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error)
// 获取ownerUserID的好友列表 // 获取ownerUserID的好友列表
PageOwnerFriends(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) PageOwnerFriends(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error)
// friendUserID在哪些人的好友列表中 // friendUserID在哪些人的好友列表中
PageInWhoseFriends(ctx context.Context, friendUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) PageInWhoseFriends(
ctx context.Context,
friendUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error)
// 获取我发出去的好友申请 // 获取我发出去的好友申请
PageFriendRequestFromMe(ctx context.Context, userID string, pageNumber, showNumber int32) (friends []*relation.FriendRequestModel, total int64, err error) PageFriendRequestFromMe(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendRequestModel, total int64, err error)
// 获取我收到的的好友申请 // 获取我收到的的好友申请
PageFriendRequestToMe(ctx context.Context, userID string, pageNumber, showNumber int32) (friends []*relation.FriendRequestModel, total int64, err error) PageFriendRequestToMe(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendRequestModel, total int64, err error)
// 获取某人指定好友的信息 // 获取某人指定好友的信息
FindFriendsWithError(ctx context.Context, ownerUserID string, friendUserIDs []string) (friends []*relation.FriendModel, err error) FindFriendsWithError(
ctx context.Context,
ownerUserID string,
friendUserIDs []string,
) (friends []*relation.FriendModel, err error)
FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error)
} }
@ -49,12 +70,20 @@ type friendDatabase struct {
cache cache.FriendCache cache cache.FriendCache
} }
func NewFriendDatabase(friend relation.FriendModelInterface, friendRequest relation.FriendRequestModelInterface, cache cache.FriendCache, tx tx.Tx) FriendDatabase { func NewFriendDatabase(
friend relation.FriendModelInterface,
friendRequest relation.FriendRequestModelInterface,
cache cache.FriendCache,
tx tx.Tx,
) FriendDatabase {
return &friendDatabase{friend: friend, friendRequest: friendRequest, cache: cache, tx: tx} return &friendDatabase{friend: friend, friendRequest: friendRequest, cache: cache, tx: tx}
} }
// ok 检查user2是否在user1的好友列表中(inUser1Friends==true) 检查user1是否在user2的好友列表中(inUser2Friends==true) // ok 检查user2是否在user1的好友列表中(inUser1Friends==true) 检查user1是否在user2的好友列表中(inUser2Friends==true)
func (f *friendDatabase) CheckIn(ctx context.Context, userID1, userID2 string) (inUser1Friends bool, inUser2Friends bool, err error) { func (f *friendDatabase) CheckIn(
ctx context.Context,
userID1, userID2 string,
) (inUser1Friends bool, inUser2Friends bool, err error) {
userID1FriendIDs, err := f.cache.GetFriendIDs(ctx, userID1) userID1FriendIDs, err := f.cache.GetFriendIDs(ctx, userID1)
if err != nil { if err != nil {
return return
@ -67,7 +96,12 @@ func (f *friendDatabase) CheckIn(ctx context.Context, userID1, userID2 string) (
} }
// 增加或者更新好友申请 如果之前有记录则更新,没有记录则新增 // 增加或者更新好友申请 如果之前有记录则更新,没有记录则新增
func (f *friendDatabase) AddFriendRequest(ctx context.Context, fromUserID, toUserID string, reqMsg string, ex string) (err error) { func (f *friendDatabase) AddFriendRequest(
ctx context.Context,
fromUserID, toUserID string,
reqMsg string,
ex string,
) (err error) {
return f.tx.Transaction(func(tx any) error { return f.tx.Transaction(func(tx any) error {
_, err := f.friendRequest.NewTx(tx).Take(ctx, fromUserID, toUserID) _, err := f.friendRequest.NewTx(tx).Take(ctx, fromUserID, toUserID)
//有db错误 //有db错误
@ -96,7 +130,12 @@ func (f *friendDatabase) AddFriendRequest(ctx context.Context, fromUserID, toUse
} }
// (1)先判断是否在好友表 (在不在都不返回错误) (2)对于不在好友列表的 插入即可 // (1)先判断是否在好友表 (在不在都不返回错误) (2)对于不在好友列表的 插入即可
func (f *friendDatabase) BecomeFriends(ctx context.Context, ownerUserID string, friendUserIDs []string, addSource int32) (err error) { func (f *friendDatabase) BecomeFriends(
ctx context.Context,
ownerUserID string,
friendUserIDs []string,
addSource int32,
) (err error) {
cache := f.cache.NewCache() cache := f.cache.NewCache()
if err := f.tx.Transaction(func(tx any) error { if err := f.tx.Transaction(func(tx any) error {
//先find 找出重复的 去掉重复的 //先find 找出重复的 去掉重复的
@ -142,7 +181,10 @@ func (f *friendDatabase) BecomeFriends(ctx context.Context, ownerUserID string,
} }
// 拒绝好友申请 (1)检查是否有申请记录且为未处理状态 (没有记录返回错误) (2)修改申请记录 已拒绝 // 拒绝好友申请 (1)检查是否有申请记录且为未处理状态 (没有记录返回错误) (2)修改申请记录 已拒绝
func (f *friendDatabase) RefuseFriendRequest(ctx context.Context, friendRequest *relation.FriendRequestModel) (err error) { func (f *friendDatabase) RefuseFriendRequest(
ctx context.Context,
friendRequest *relation.FriendRequestModel,
) (err error) {
fr, err := f.friendRequest.Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID) fr, err := f.friendRequest.Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID)
if err != nil { if err != nil {
return err return err
@ -160,7 +202,10 @@ func (f *friendDatabase) RefuseFriendRequest(ctx context.Context, friendRequest
} }
// AgreeFriendRequest 同意好友申请 (1)检查是否有申请记录且为未处理状态 (没有记录返回错误) (2)检查是否好友(不返回错误) (3) 建立双向好友关系(存在的忽略) // AgreeFriendRequest 同意好友申请 (1)检查是否有申请记录且为未处理状态 (没有记录返回错误) (2)检查是否好友(不返回错误) (3) 建立双向好友关系(存在的忽略)
func (f *friendDatabase) AgreeFriendRequest(ctx context.Context, friendRequest *relation.FriendRequestModel) (err error) { func (f *friendDatabase) AgreeFriendRequest(
ctx context.Context,
friendRequest *relation.FriendRequestModel,
) (err error) {
return f.tx.Transaction(func(tx any) error { return f.tx.Transaction(func(tx any) error {
fr, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID) fr, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID)
if err != nil { if err != nil {
@ -185,10 +230,26 @@ func (f *friendDatabase) AgreeFriendRequest(ctx context.Context, friendRequest *
})) }))
var adds []*relation.FriendModel var adds []*relation.FriendModel
if _, ok := existsMap[[...]string{friendRequest.ToUserID, friendRequest.FromUserID}]; !ok { // 自己 - 好友 if _, ok := existsMap[[...]string{friendRequest.ToUserID, friendRequest.FromUserID}]; !ok { // 自己 - 好友
adds = append(adds, &relation.FriendModel{OwnerUserID: friendRequest.ToUserID, FriendUserID: friendRequest.FromUserID, AddSource: int32(constant.BecomeFriendByApply), OperatorUserID: friendRequest.FromUserID}) adds = append(
adds,
&relation.FriendModel{
OwnerUserID: friendRequest.ToUserID,
FriendUserID: friendRequest.FromUserID,
AddSource: int32(constant.BecomeFriendByApply),
OperatorUserID: friendRequest.FromUserID,
},
)
} }
if _, ok := existsMap[[...]string{friendRequest.FromUserID, friendRequest.ToUserID}]; !ok { // 好友 - 自己 if _, ok := existsMap[[...]string{friendRequest.FromUserID, friendRequest.ToUserID}]; !ok { // 好友 - 自己
adds = append(adds, &relation.FriendModel{OwnerUserID: friendRequest.FromUserID, FriendUserID: friendRequest.ToUserID, AddSource: int32(constant.BecomeFriendByApply), OperatorUserID: friendRequest.FromUserID}) adds = append(
adds,
&relation.FriendModel{
OwnerUserID: friendRequest.FromUserID,
FriendUserID: friendRequest.ToUserID,
AddSource: int32(constant.BecomeFriendByApply),
OperatorUserID: friendRequest.FromUserID,
},
)
} }
if len(adds) > 0 { if len(adds) > 0 {
if err := f.friend.NewTx(tx).Create(ctx, adds); err != nil { if err := f.friend.NewTx(tx).Create(ctx, adds); err != nil {
@ -216,27 +277,47 @@ func (f *friendDatabase) UpdateRemark(ctx context.Context, ownerUserID, friendUs
} }
// 获取ownerUserID的好友列表 无结果不返回错误 // 获取ownerUserID的好友列表 无结果不返回错误
func (f *friendDatabase) PageOwnerFriends(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *friendDatabase) PageOwnerFriends(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error) {
return f.friend.FindOwnerFriends(ctx, ownerUserID, pageNumber, showNumber) return f.friend.FindOwnerFriends(ctx, ownerUserID, pageNumber, showNumber)
} }
// friendUserID在哪些人的好友列表中 // friendUserID在哪些人的好友列表中
func (f *friendDatabase) PageInWhoseFriends(ctx context.Context, friendUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *friendDatabase) PageInWhoseFriends(
ctx context.Context,
friendUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error) {
return f.friend.FindInWhoseFriends(ctx, friendUserID, pageNumber, showNumber) return f.friend.FindInWhoseFriends(ctx, friendUserID, pageNumber, showNumber)
} }
// 获取我发出去的好友申请 无结果不返回错误 // 获取我发出去的好友申请 无结果不返回错误
func (f *friendDatabase) PageFriendRequestFromMe(ctx context.Context, userID string, pageNumber, showNumber int32) (friends []*relation.FriendRequestModel, total int64, err error) { func (f *friendDatabase) PageFriendRequestFromMe(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendRequestModel, total int64, err error) {
return f.friendRequest.FindFromUserID(ctx, userID, pageNumber, showNumber) return f.friendRequest.FindFromUserID(ctx, userID, pageNumber, showNumber)
} }
// 获取我收到的的好友申请 无结果不返回错误 // 获取我收到的的好友申请 无结果不返回错误
func (f *friendDatabase) PageFriendRequestToMe(ctx context.Context, userID string, pageNumber, showNumber int32) (friends []*relation.FriendRequestModel, total int64, err error) { func (f *friendDatabase) PageFriendRequestToMe(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendRequestModel, total int64, err error) {
return f.friendRequest.FindToUserID(ctx, userID, pageNumber, showNumber) return f.friendRequest.FindToUserID(ctx, userID, pageNumber, showNumber)
} }
// 获取某人指定好友的信息 如果有好友不存在,也返回错误 // 获取某人指定好友的信息 如果有好友不存在,也返回错误
func (f *friendDatabase) FindFriendsWithError(ctx context.Context, ownerUserID string, friendUserIDs []string) (friends []*relation.FriendModel, err error) { func (f *friendDatabase) FindFriendsWithError(
ctx context.Context,
ownerUserID string,
friendUserIDs []string,
) (friends []*relation.FriendModel, err error) {
friends, err = f.friend.FindFriends(ctx, ownerUserID, friendUserIDs) friends, err = f.friend.FindFriends(ctx, ownerUserID, friendUserIDs)
if err != nil { if err != nil {
return return
@ -247,6 +328,9 @@ func (f *friendDatabase) FindFriendsWithError(ctx context.Context, ownerUserID s
return return
} }
func (f *friendDatabase) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) { func (f *friendDatabase) FindFriendUserIDs(
ctx context.Context,
ownerUserID string,
) (friendUserIDs []string, err error) {
return f.cache.GetFriendIDs(ctx, ownerUserID) return f.cache.GetFriendIDs(ctx, ownerUserID)
} }

View File

@ -4,6 +4,11 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
"go.mongodb.org/mongo-driver/mongo"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation"
@ -12,10 +17,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
"go.mongodb.org/mongo-driver/mongo"
"gorm.io/gorm"
) )
type GroupDatabase interface { type GroupDatabase interface {
@ -23,33 +24,82 @@ type GroupDatabase interface {
CreateGroup(ctx context.Context, groups []*relationTb.GroupModel, groupMembers []*relationTb.GroupMemberModel) error CreateGroup(ctx context.Context, groups []*relationTb.GroupModel, groupMembers []*relationTb.GroupMemberModel) error
TakeGroup(ctx context.Context, groupID string) (group *relationTb.GroupModel, err error) TakeGroup(ctx context.Context, groupID string) (group *relationTb.GroupModel, err error)
FindGroup(ctx context.Context, groupIDs []string) (groups []*relationTb.GroupModel, err error) FindGroup(ctx context.Context, groupIDs []string) (groups []*relationTb.GroupModel, err error)
SearchGroup(ctx context.Context, keyword string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupModel, error) SearchGroup(
ctx context.Context,
keyword string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupModel, error)
UpdateGroup(ctx context.Context, groupID string, data map[string]any) error UpdateGroup(ctx context.Context, groupID string, data map[string]any) error
DismissGroup(ctx context.Context, groupID string, deleteMember bool) error // 解散群,并删除群成员 DismissGroup(ctx context.Context, groupID string, deleteMember bool) error // 解散群,并删除群成员
GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error) GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error)
// GroupMember // GroupMember
TakeGroupMember(ctx context.Context, groupID string, userID string) (groupMember *relationTb.GroupMemberModel, err error) TakeGroupMember(
ctx context.Context,
groupID string,
userID string,
) (groupMember *relationTb.GroupMemberModel, err error)
TakeGroupOwner(ctx context.Context, groupID string) (*relationTb.GroupMemberModel, error) TakeGroupOwner(ctx context.Context, groupID string) (*relationTb.GroupMemberModel, error)
FindGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) ([]*relationTb.GroupMemberModel, error) FindGroupMember(
ctx context.Context,
groupIDs []string,
userIDs []string,
roleLevels []int32,
) ([]*relationTb.GroupMemberModel, error)
FindGroupMemberUserID(ctx context.Context, groupID string) ([]string, error) FindGroupMemberUserID(ctx context.Context, groupID string) ([]string, error)
FindGroupMemberNum(ctx context.Context, groupID string) (uint32, error) FindGroupMemberNum(ctx context.Context, groupID string) (uint32, error)
FindUserManagedGroupID(ctx context.Context, userID string) (groupIDs []string, err error) FindUserManagedGroupID(ctx context.Context, userID string) (groupIDs []string, err error)
PageGroupRequest(ctx context.Context, groupIDs []string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupRequestModel, error) PageGroupRequest(
//PageGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (uint32, []*relationTb.GroupMemberModel, error) ctx context.Context,
PageGetJoinGroup(ctx context.Context, userID string, pageNumber, showNumber int32) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) groupIDs []string,
PageGetGroupMember(ctx context.Context, groupID string, pageNumber, showNumber int32) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) pageNumber, showNumber int32,
SearchGroupMember(ctx context.Context, keyword string, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (uint32, []*relationTb.GroupMemberModel, error) ) (uint32, []*relationTb.GroupRequestModel, error)
HandlerGroupRequest(ctx context.Context, groupID string, userID string, handledMsg string, handleResult int32, member *relationTb.GroupMemberModel) error // PageGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber,
// showNumber int32) (uint32, []*relationTb.GroupMemberModel, error)
PageGetJoinGroup(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error)
PageGetGroupMember(
ctx context.Context,
groupID string,
pageNumber, showNumber int32,
) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error)
SearchGroupMember(
ctx context.Context,
keyword string,
groupIDs []string,
userIDs []string,
roleLevels []int32,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupMemberModel, error)
HandlerGroupRequest(
ctx context.Context,
groupID string,
userID string,
handledMsg string,
handleResult int32,
member *relationTb.GroupMemberModel,
) error
DeleteGroupMember(ctx context.Context, groupID string, userIDs []string) error DeleteGroupMember(ctx context.Context, groupID string, userIDs []string) error
MapGroupMemberUserID(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error) MapGroupMemberUserID(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error)
MapGroupMemberNum(ctx context.Context, groupIDs []string) (map[string]uint32, error) MapGroupMemberNum(ctx context.Context, groupIDs []string) (map[string]uint32, error)
TransferGroupOwner(ctx context.Context, groupID string, oldOwnerUserID, newOwnerUserID string, roleLevel int32) error // 转让群 TransferGroupOwner(
ctx context.Context,
groupID string,
oldOwnerUserID, newOwnerUserID string,
roleLevel int32,
) error // 转让群
UpdateGroupMember(ctx context.Context, groupID string, userID string, data map[string]any) error UpdateGroupMember(ctx context.Context, groupID string, userID string, data map[string]any) error
UpdateGroupMembers(ctx context.Context, data []*relationTb.BatchUpdateGroupMember) error UpdateGroupMembers(ctx context.Context, data []*relationTb.BatchUpdateGroupMember) error
// GroupRequest // GroupRequest
CreateGroupRequest(ctx context.Context, requests []*relationTb.GroupRequestModel) error CreateGroupRequest(ctx context.Context, requests []*relationTb.GroupRequestModel) error
TakeGroupRequest(ctx context.Context, groupID string, userID string) (*relationTb.GroupRequestModel, error) TakeGroupRequest(ctx context.Context, groupID string, userID string) (*relationTb.GroupRequestModel, error)
PageGroupRequestUser(ctx context.Context, userID string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupRequestModel, error) PageGroupRequestUser(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupRequestModel, error)
// SuperGroupModelInterface // SuperGroupModelInterface
FindSuperGroup(ctx context.Context, groupIDs []string) ([]*unRelationTb.SuperGroupModel, error) FindSuperGroup(ctx context.Context, groupIDs []string) ([]*unRelationTb.SuperGroupModel, error)
FindJoinSuperGroup(ctx context.Context, userID string) ([]string, error) FindJoinSuperGroup(ctx context.Context, userID string) ([]string, error)
@ -91,7 +141,14 @@ func InitGroupDatabase(db *gorm.DB, rdb redis.UniversalClient, database *mongo.D
tx.NewGorm(db), tx.NewGorm(db),
tx.NewMongo(database.Client()), tx.NewMongo(database.Client()),
unrelation.NewSuperGroupMongoDriver(database), unrelation.NewSuperGroupMongoDriver(database),
cache.NewGroupCacheRedis(rdb, relation.NewGroupDB(db), relation.NewGroupMemberDB(db), relation.NewGroupRequest(db), unrelation.NewSuperGroupMongoDriver(database), rcOptions), cache.NewGroupCacheRedis(
rdb,
relation.NewGroupDB(db),
relation.NewGroupMemberDB(db),
relation.NewGroupRequest(db),
unrelation.NewSuperGroupMongoDriver(database),
rcOptions,
),
) )
} }
@ -121,7 +178,11 @@ func (g *groupDatabase) FindGroupMemberNum(ctx context.Context, groupID string)
return uint32(num), nil return uint32(num), nil
} }
func (g *groupDatabase) CreateGroup(ctx context.Context, groups []*relationTb.GroupModel, groupMembers []*relationTb.GroupMemberModel) error { func (g *groupDatabase) CreateGroup(
ctx context.Context,
groups []*relationTb.GroupModel,
groupMembers []*relationTb.GroupMemberModel,
) error {
var cache = g.cache.NewCache() var cache = g.cache.NewCache()
if err := g.tx.Transaction(func(tx any) error { if err := g.tx.Transaction(func(tx any) error {
if len(groups) > 0 { if len(groups) > 0 {
@ -162,7 +223,11 @@ func (g *groupDatabase) FindGroup(ctx context.Context, groupIDs []string) (group
return g.cache.GetGroupsInfo(ctx, groupIDs) return g.cache.GetGroupsInfo(ctx, groupIDs)
} }
func (g *groupDatabase) SearchGroup(ctx context.Context, keyword string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupModel, error) { func (g *groupDatabase) SearchGroup(
ctx context.Context,
keyword string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupModel, error) {
return g.groupDB.Search(ctx, keyword, pageNumber, showNumber) return g.groupDB.Search(ctx, keyword, pageNumber, showNumber)
} }
@ -197,7 +262,11 @@ func (g *groupDatabase) DismissGroup(ctx context.Context, groupID string, delete
return cache.ExecDel(ctx) return cache.ExecDel(ctx)
} }
func (g *groupDatabase) TakeGroupMember(ctx context.Context, groupID string, userID string) (groupMember *relationTb.GroupMemberModel, err error) { func (g *groupDatabase) TakeGroupMember(
ctx context.Context,
groupID string,
userID string,
) (groupMember *relationTb.GroupMemberModel, err error) {
return g.cache.GetGroupMemberInfo(ctx, groupID, userID) return g.cache.GetGroupMemberInfo(ctx, groupID, userID)
} }
@ -209,11 +278,20 @@ func (g *groupDatabase) FindUserManagedGroupID(ctx context.Context, userID strin
return g.groupMemberDB.FindUserManagedGroupID(ctx, userID) return g.groupMemberDB.FindUserManagedGroupID(ctx, userID)
} }
func (g *groupDatabase) PageGroupRequest(ctx context.Context, groupIDs []string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupRequestModel, error) { func (g *groupDatabase) PageGroupRequest(
ctx context.Context,
groupIDs []string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupRequestModel, error) {
return g.groupRequestDB.PageGroup(ctx, groupIDs, pageNumber, showNumber) return g.groupRequestDB.PageGroup(ctx, groupIDs, pageNumber, showNumber)
} }
func (g *groupDatabase) FindGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) (totalGroupMembers []*relationTb.GroupMemberModel, err error) { func (g *groupDatabase) FindGroupMember(
ctx context.Context,
groupIDs []string,
userIDs []string,
roleLevels []int32,
) (totalGroupMembers []*relationTb.GroupMemberModel, err error) {
if roleLevels == nil { if roleLevels == nil {
for _, groupID := range groupIDs { for _, groupID := range groupIDs {
groupMembers, err := g.cache.GetGroupMembersInfo(ctx, groupID, userIDs) groupMembers, err := g.cache.GetGroupMembersInfo(ctx, groupID, userIDs)
@ -227,7 +305,11 @@ func (g *groupDatabase) FindGroupMember(ctx context.Context, groupIDs []string,
return g.groupMemberDB.Find(ctx, groupIDs, userIDs, roleLevels) return g.groupMemberDB.Find(ctx, groupIDs, userIDs, roleLevels)
} }
func (g *groupDatabase) PageGetJoinGroup(ctx context.Context, userID string, pageNumber, showNumber int32) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) { func (g *groupDatabase) PageGetJoinGroup(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) {
groupIDs, err := g.cache.GetJoinedGroupIDs(ctx, userID) groupIDs, err := g.cache.GetJoinedGroupIDs(ctx, userID)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
@ -242,7 +324,11 @@ func (g *groupDatabase) PageGetJoinGroup(ctx context.Context, userID string, pag
return uint32(len(groupIDs)), totalGroupMembers, nil return uint32(len(groupIDs)), totalGroupMembers, nil
} }
func (g *groupDatabase) PageGetGroupMember(ctx context.Context, groupID string, pageNumber, showNumber int32) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) { func (g *groupDatabase) PageGetGroupMember(
ctx context.Context,
groupID string,
pageNumber, showNumber int32,
) (total uint32, totalGroupMembers []*relationTb.GroupMemberModel, err error) {
groupMemberIDs, err := g.cache.GetGroupMemberIDs(ctx, groupID) groupMemberIDs, err := g.cache.GetGroupMemberIDs(ctx, groupID)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
@ -258,11 +344,25 @@ func (g *groupDatabase) PageGetGroupMember(ctx context.Context, groupID string,
return uint32(len(groupMemberIDs)), members, nil return uint32(len(groupMemberIDs)), members, nil
} }
func (g *groupDatabase) SearchGroupMember(ctx context.Context, keyword string, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (uint32, []*relationTb.GroupMemberModel, error) { func (g *groupDatabase) SearchGroupMember(
ctx context.Context,
keyword string,
groupIDs []string,
userIDs []string,
roleLevels []int32,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupMemberModel, error) {
return g.groupMemberDB.SearchMember(ctx, keyword, groupIDs, userIDs, roleLevels, pageNumber, showNumber) return g.groupMemberDB.SearchMember(ctx, keyword, groupIDs, userIDs, roleLevels, pageNumber, showNumber)
} }
func (g *groupDatabase) HandlerGroupRequest(ctx context.Context, groupID string, userID string, handledMsg string, handleResult int32, member *relationTb.GroupMemberModel) error { func (g *groupDatabase) HandlerGroupRequest(
ctx context.Context,
groupID string,
userID string,
handledMsg string,
handleResult int32,
member *relationTb.GroupMemberModel,
) error {
cache := g.cache.NewCache() cache := g.cache.NewCache()
if err := g.tx.Transaction(func(tx any) error { if err := g.tx.Transaction(func(tx any) error {
if err := g.groupRequestDB.NewTx(tx).UpdateHandler(ctx, groupID, userID, handledMsg, handleResult); err != nil { if err := g.groupRequestDB.NewTx(tx).UpdateHandler(ctx, groupID, userID, handledMsg, handleResult); err != nil {
@ -285,10 +385,18 @@ func (g *groupDatabase) DeleteGroupMember(ctx context.Context, groupID string, u
if err := g.groupMemberDB.Delete(ctx, groupID, userIDs); err != nil { if err := g.groupMemberDB.Delete(ctx, groupID, userIDs); err != nil {
return err return err
} }
return g.cache.DelGroupMembersHash(groupID).DelGroupMemberIDs(groupID).DelGroupsMemberNum(groupID).DelJoinedGroupID(userIDs...).DelGroupMembersInfo(groupID, userIDs...).ExecDel(ctx) return g.cache.DelGroupMembersHash(groupID).
DelGroupMemberIDs(groupID).
DelGroupsMemberNum(groupID).
DelJoinedGroupID(userIDs...).
DelGroupMembersInfo(groupID, userIDs...).
ExecDel(ctx)
} }
func (g *groupDatabase) MapGroupMemberUserID(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error) { func (g *groupDatabase) MapGroupMemberUserID(
ctx context.Context,
groupIDs []string,
) (map[string]*relationTb.GroupSimpleUserID, error) {
return g.cache.GetGroupMemberHashMap(ctx, groupIDs) return g.cache.GetGroupMemberHashMap(ctx, groupIDs)
} }
@ -304,7 +412,12 @@ func (g *groupDatabase) MapGroupMemberNum(ctx context.Context, groupIDs []string
return m, nil return m, nil
} }
func (g *groupDatabase) TransferGroupOwner(ctx context.Context, groupID string, oldOwnerUserID, newOwnerUserID string, roleLevel int32) error { func (g *groupDatabase) TransferGroupOwner(
ctx context.Context,
groupID string,
oldOwnerUserID, newOwnerUserID string,
roleLevel int32,
) error {
if err := g.tx.Transaction(func(tx any) error { if err := g.tx.Transaction(func(tx any) error {
rowsAffected, err := g.groupMemberDB.NewTx(tx).UpdateRoleLevel(ctx, groupID, oldOwnerUserID, roleLevel) rowsAffected, err := g.groupMemberDB.NewTx(tx).UpdateRoleLevel(ctx, groupID, oldOwnerUserID, roleLevel)
if err != nil { if err != nil {
@ -327,7 +440,12 @@ func (g *groupDatabase) TransferGroupOwner(ctx context.Context, groupID string,
return g.cache.DelGroupMembersInfo(groupID, oldOwnerUserID, newOwnerUserID).ExecDel(ctx) return g.cache.DelGroupMembersInfo(groupID, oldOwnerUserID, newOwnerUserID).ExecDel(ctx)
} }
func (g *groupDatabase) UpdateGroupMember(ctx context.Context, groupID string, userID string, data map[string]any) error { func (g *groupDatabase) UpdateGroupMember(
ctx context.Context,
groupID string,
userID string,
data map[string]any,
) error {
if err := g.groupMemberDB.Update(ctx, groupID, userID, data); err != nil { if err := g.groupMemberDB.Update(ctx, groupID, userID, data); err != nil {
return err return err
} }
@ -362,15 +480,26 @@ func (g *groupDatabase) CreateGroupRequest(ctx context.Context, requests []*rela
}) })
} }
func (g *groupDatabase) TakeGroupRequest(ctx context.Context, groupID string, userID string) (*relationTb.GroupRequestModel, error) { func (g *groupDatabase) TakeGroupRequest(
ctx context.Context,
groupID string,
userID string,
) (*relationTb.GroupRequestModel, error) {
return g.groupRequestDB.Take(ctx, groupID, userID) return g.groupRequestDB.Take(ctx, groupID, userID)
} }
func (g *groupDatabase) PageGroupRequestUser(ctx context.Context, userID string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupRequestModel, error) { func (g *groupDatabase) PageGroupRequestUser(
ctx context.Context,
userID string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupRequestModel, error) {
return g.groupRequestDB.Page(ctx, userID, pageNumber, showNumber) return g.groupRequestDB.Page(ctx, userID, pageNumber, showNumber)
} }
func (g *groupDatabase) FindSuperGroup(ctx context.Context, groupIDs []string) (models []*unRelationTb.SuperGroupModel, err error) { func (g *groupDatabase) FindSuperGroup(
ctx context.Context,
groupIDs []string,
) (models []*unRelationTb.SuperGroupModel, err error) {
return g.cache.GetSuperGroupMemberIDs(ctx, groupIDs...) return g.cache.GetSuperGroupMemberIDs(ctx, groupIDs...)
} }

View File

@ -19,10 +19,11 @@ import (
"context" "context"
"errors" "errors"
"go.mongodb.org/mongo-driver/mongo"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"go.mongodb.org/mongo-driver/mongo"
) )
const ( const (
@ -41,12 +42,26 @@ type CommonMsgDatabase interface {
DeleteMessagesFromCache(ctx context.Context, conversationID string, seqs []int64) error DeleteMessagesFromCache(ctx context.Context, conversationID string, seqs []int64) error
DelUserDeleteMsgsList(ctx context.Context, conversationID string, seqs []int64) DelUserDeleteMsgsList(ctx context.Context, conversationID string, seqs []int64)
// incrSeq然后批量插入缓存 // incrSeq然后批量插入缓存
BatchInsertChat2Cache(ctx context.Context, conversationID string, msgs []*sdkws.MsgData) (seq int64, isNewConversation bool, err error) BatchInsertChat2Cache(
ctx context.Context,
conversationID string,
msgs []*sdkws.MsgData,
) (seq int64, isNewConversation bool, err error)
// 通过seqList获取mongo中写扩散消息 // 通过seqList获取mongo中写扩散消息
GetMsgBySeqsRange(ctx context.Context, userID string, conversationID string, begin, end, num, userMaxSeq int64) (minSeq int64, maxSeq int64, seqMsg []*sdkws.MsgData, err error) GetMsgBySeqsRange(
ctx context.Context,
userID string,
conversationID string,
begin, end, num, userMaxSeq int64,
) (minSeq int64, maxSeq int64, seqMsg []*sdkws.MsgData, err error)
// 通过seqList获取大群在 mongo里面的消息 // 通过seqList获取大群在 mongo里面的消息
GetMsgBySeqs(ctx context.Context, userID string, conversationID string, seqs []int64) (minSeq int64, maxSeq int64, seqMsg []*sdkws.MsgData, err error) GetMsgBySeqs(
ctx context.Context,
userID string,
conversationID string,
seqs []int64,
) (minSeq int64, maxSeq int64, seqMsg []*sdkws.MsgData, err error)
// 删除会话消息重置最小seq remainTime为消息保留的时间单位秒,超时消息删除, 传0删除所有消息(此方法不删除redis cache) // 删除会话消息重置最小seq remainTime为消息保留的时间单位秒,超时消息删除, 传0删除所有消息(此方法不删除redis cache)
DeleteConversationMsgsAndSetMinSeq(ctx context.Context, conversationID string, remainTime int64) error DeleteConversationMsgsAndSetMinSeq(ctx context.Context, conversationID string, remainTime int64) error
// 用户根据seq删除消息 // 用户根据seq删除消息
@ -73,7 +88,10 @@ type CommonMsgDatabase interface {
UserSetHasReadSeqs(ctx context.Context, userID string, hasReadSeqs map[string]int64) error UserSetHasReadSeqs(ctx context.Context, userID string, hasReadSeqs map[string]int64) error
GetMongoMaxAndMinSeq(ctx context.Context, conversationID string) (maxSeq, minSeq int64, err error) GetMongoMaxAndMinSeq(ctx context.Context, conversationID string) (maxSeq, minSeq int64, err error)
GetConversationMinMaxSeqInMongoAndCache(ctx context.Context, conversationID string) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error) GetConversationMinMaxSeqInMongoAndCache(
ctx context.Context,
conversationID string,
) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error)
SetSendMsgStatus(ctx context.Context, id string, status int32) error SetSendMsgStatus(ctx context.Context, id string, status int32) error
GetSendMsgStatus(ctx context.Context, id string) (int32, error) GetSendMsgStatus(ctx context.Context, id string) (int32, error)
@ -86,13 +104,38 @@ type CommonMsgDatabase interface {
// modify // modify
JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, error) JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, error)
SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error
SetMessageReactionExpire(ctx context.Context, clientMsgID string, sessionType int32, expiration time.Duration) (bool, error) SetMessageReactionExpire(
GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, maxMsgUpdateTime int64) (*pbMsg.ExtendMsg, error) ctx context.Context,
InsertOrUpdateReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*sdkws.KeyValue) error clientMsgID string,
sessionType int32,
expiration time.Duration,
) (bool, error)
GetExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
maxMsgUpdateTime int64,
) (*pbMsg.ExtendMsg, error)
InsertOrUpdateReactionExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*sdkws.KeyValue,
) error
GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error) GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error)
GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error) GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error)
DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error
DeleteReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensionList map[string]*sdkws.KeyValue) error DeleteReactionExtendMsgSet(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensionList map[string]*sdkws.KeyValue,
) error
} }
func NewCommonMsgDatabase(msgDocModel unRelationTb.MsgDocModelInterface, cacheModel cache.MsgModel) CommonMsgDatabase { func NewCommonMsgDatabase(msgDocModel unRelationTb.MsgDocModelInterface, cacheModel cache.MsgModel) CommonMsgDatabase {
@ -130,16 +173,32 @@ func (db *commonMsgDatabase) MsgToMQ(ctx context.Context, key string, msg2mq *sd
return err return err
} }
func (db *commonMsgDatabase) MsgToModifyMQ(ctx context.Context, key, conversationID string, messages []*sdkws.MsgData) error { func (db *commonMsgDatabase) MsgToModifyMQ(
ctx context.Context,
key, conversationID string,
messages []*sdkws.MsgData,
) error {
if len(messages) > 0 { if len(messages) > 0 {
_, _, err := db.producerToModify.SendMessage(ctx, key, &pbMsg.MsgDataToModifyByMQ{ConversationID: conversationID, Messages: messages}) _, _, err := db.producerToModify.SendMessage(
ctx,
key,
&pbMsg.MsgDataToModifyByMQ{ConversationID: conversationID, Messages: messages},
)
return err return err
} }
return nil return nil
} }
func (db *commonMsgDatabase) MsgToPushMQ(ctx context.Context, key, conversationID string, msg2mq *sdkws.MsgData) (int32, int64, error) { func (db *commonMsgDatabase) MsgToPushMQ(
partition, offset, err := db.producerToPush.SendMessage(ctx, key, &pbMsg.PushMsgDataToMQ{MsgData: msg2mq, ConversationID: conversationID}) ctx context.Context,
key, conversationID string,
msg2mq *sdkws.MsgData,
) (int32, int64, error) {
partition, offset, err := db.producerToPush.SendMessage(
ctx,
key,
&pbMsg.PushMsgDataToMQ{MsgData: msg2mq, ConversationID: conversationID},
)
if err != nil { if err != nil {
log.ZError(ctx, "MsgToPushMQ", err, "key", key, "msg2mq", msg2mq) log.ZError(ctx, "MsgToPushMQ", err, "key", key, "msg2mq", msg2mq)
return 0, 0, err return 0, 0, err
@ -147,15 +206,30 @@ func (db *commonMsgDatabase) MsgToPushMQ(ctx context.Context, key, conversationI
return partition, offset, nil return partition, offset, nil
} }
func (db *commonMsgDatabase) MsgToMongoMQ(ctx context.Context, key, conversationID string, messages []*sdkws.MsgData, lastSeq int64) error { func (db *commonMsgDatabase) MsgToMongoMQ(
ctx context.Context,
key, conversationID string,
messages []*sdkws.MsgData,
lastSeq int64,
) error {
if len(messages) > 0 { if len(messages) > 0 {
_, _, err := db.producerToMongo.SendMessage(ctx, key, &pbMsg.MsgDataToMongoByMQ{LastSeq: lastSeq, ConversationID: conversationID, MsgData: messages}) _, _, err := db.producerToMongo.SendMessage(
ctx,
key,
&pbMsg.MsgDataToMongoByMQ{LastSeq: lastSeq, ConversationID: conversationID, MsgData: messages},
)
return err return err
} }
return nil return nil
} }
func (db *commonMsgDatabase) BatchInsertBlock(ctx context.Context, conversationID string, fields []any, key int8, firstSeq int64) error { func (db *commonMsgDatabase) BatchInsertBlock(
ctx context.Context,
conversationID string,
fields []any,
key int8,
firstSeq int64,
) error {
if len(fields) == 0 { if len(fields) == 0 {
return nil return nil
} }
@ -256,7 +330,12 @@ func (db *commonMsgDatabase) BatchInsertBlock(ctx context.Context, conversationI
return nil return nil
} }
func (db *commonMsgDatabase) BatchInsertChat2DB(ctx context.Context, conversationID string, msgList []*sdkws.MsgData, currentMaxSeq int64) error { func (db *commonMsgDatabase) BatchInsertChat2DB(
ctx context.Context,
conversationID string,
msgList []*sdkws.MsgData,
currentMaxSeq int64,
) error {
if len(msgList) == 0 { if len(msgList) == 0 {
return errs.ErrArgs.Wrap("msgList is empty") return errs.ErrArgs.Wrap("msgList is empty")
} }
@ -302,11 +381,21 @@ func (db *commonMsgDatabase) BatchInsertChat2DB(ctx context.Context, conversatio
return db.BatchInsertBlock(ctx, conversationID, msgs, updateKeyMsg, msgList[0].Seq) return db.BatchInsertBlock(ctx, conversationID, msgs, updateKeyMsg, msgList[0].Seq)
} }
func (db *commonMsgDatabase) RevokeMsg(ctx context.Context, conversationID string, seq int64, revoke *unRelationTb.RevokeModel) error { func (db *commonMsgDatabase) RevokeMsg(
ctx context.Context,
conversationID string,
seq int64,
revoke *unRelationTb.RevokeModel,
) error {
return db.BatchInsertBlock(ctx, conversationID, []any{revoke}, updateKeyRevoke, seq) return db.BatchInsertBlock(ctx, conversationID, []any{revoke}, updateKeyRevoke, seq)
} }
func (db *commonMsgDatabase) MarkSingleChatMsgsAsRead(ctx context.Context, userID string, conversationID string, totalSeqs []int64) error { func (db *commonMsgDatabase) MarkSingleChatMsgsAsRead(
ctx context.Context,
userID string,
conversationID string,
totalSeqs []int64,
) error {
for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, totalSeqs) { for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, totalSeqs) {
var indexes []int64 var indexes []int64
for _, seq := range seqs { for _, seq := range seqs {
@ -329,7 +418,11 @@ func (db *commonMsgDatabase) DelUserDeleteMsgsList(ctx context.Context, conversa
db.cache.DelUserDeleteMsgsList(ctx, conversationID, seqs) db.cache.DelUserDeleteMsgsList(ctx, conversationID, seqs)
} }
func (db *commonMsgDatabase) BatchInsertChat2Cache(ctx context.Context, conversationID string, msgs []*sdkws.MsgData) (seq int64, isNew bool, err error) { func (db *commonMsgDatabase) BatchInsertChat2Cache(
ctx context.Context,
conversationID string,
msgs []*sdkws.MsgData,
) (seq int64, isNew bool, err error) {
currentMaxSeq, err := db.cache.GetMaxSeq(ctx, conversationID) currentMaxSeq, err := db.cache.GetMaxSeq(ctx, conversationID)
if err != nil && errs.Unwrap(err) != redis.Nil { if err != nil && errs.Unwrap(err) != redis.Nil {
prome.Inc(prome.SeqGetFailedCounter) prome.Inc(prome.SeqGetFailedCounter)
@ -376,7 +469,11 @@ func (db *commonMsgDatabase) BatchInsertChat2Cache(ctx context.Context, conversa
return lastMaxSeq, isNew, utils.Wrap(err, "") return lastMaxSeq, isNew, utils.Wrap(err, "")
} }
func (db *commonMsgDatabase) getMsgBySeqs(ctx context.Context, userID, conversationID string, seqs []int64) (totalMsgs []*sdkws.MsgData, err error) { func (db *commonMsgDatabase) getMsgBySeqs(
ctx context.Context,
userID, conversationID string,
seqs []int64,
) (totalMsgs []*sdkws.MsgData, err error) {
for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, seqs) { for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, seqs) {
//log.ZDebug(ctx, "getMsgBySeqs", "docID", docID, "seqs", seqs) //log.ZDebug(ctx, "getMsgBySeqs", "docID", docID, "seqs", seqs)
msgs, err := db.findMsgInfoBySeq(ctx, userID, docID, seqs) msgs, err := db.findMsgInfoBySeq(ctx, userID, docID, seqs)
@ -390,7 +487,8 @@ func (db *commonMsgDatabase) getMsgBySeqs(ctx context.Context, userID, conversat
return totalMsgs, nil return totalMsgs, nil
} }
// func (db *commonMsgDatabase) refetchDelSeqsMsgs(ctx context.Context, conversationID string, delNums, rangeBegin, begin int64) (seqMsgs []*unRelationTb.MsgDataModel, err error) { // func (db *commonMsgDatabase) refetchDelSeqsMsgs(ctx context.Context, conversationID string, delNums, rangeBegin,
// begin int64) (seqMsgs []*unRelationTb.MsgDataModel, err error) {
// var reFetchSeqs []int64 // var reFetchSeqs []int64
// if delNums > 0 { // if delNums > 0 {
// newBeginSeq := rangeBegin - delNums // newBeginSeq := rangeBegin - delNums
@ -428,7 +526,11 @@ func (db *commonMsgDatabase) getMsgBySeqs(ctx context.Context, userID, conversat
// return seqMsgs, nil // return seqMsgs, nil
// } // }
func (db *commonMsgDatabase) findMsgInfoBySeq(ctx context.Context, userID, docID string, seqs []int64) (totalMsgs []*unRelationTb.MsgInfoModel, err error) { func (db *commonMsgDatabase) findMsgInfoBySeq(
ctx context.Context,
userID, docID string,
seqs []int64,
) (totalMsgs []*unRelationTb.MsgInfoModel, err error) {
msgs, err := db.msgDocDatabase.GetMsgBySeqIndexIn1Doc(ctx, userID, docID, seqs) msgs, err := db.msgDocDatabase.GetMsgBySeqIndexIn1Doc(ctx, userID, docID, seqs)
for _, msg := range msgs { for _, msg := range msgs {
if msg.IsRead { if msg.IsRead {
@ -438,8 +540,25 @@ func (db *commonMsgDatabase) findMsgInfoBySeq(ctx context.Context, userID, docID
return msgs, err return msgs, err
} }
func (db *commonMsgDatabase) getMsgBySeqsRange(ctx context.Context, userID string, conversationID string, allSeqs []int64, begin, end int64) (seqMsgs []*sdkws.MsgData, err error) { func (db *commonMsgDatabase) getMsgBySeqsRange(
log.ZDebug(ctx, "getMsgBySeqsRange", "conversationID", conversationID, "allSeqs", allSeqs, "begin", begin, "end", end) ctx context.Context,
userID string,
conversationID string,
allSeqs []int64,
begin, end int64,
) (seqMsgs []*sdkws.MsgData, err error) {
log.ZDebug(
ctx,
"getMsgBySeqsRange",
"conversationID",
conversationID,
"allSeqs",
allSeqs,
"begin",
begin,
"end",
end,
)
for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, allSeqs) { for docID, seqs := range db.msg.GetDocIDSeqsMap(conversationID, allSeqs) {
log.ZDebug(ctx, "getMsgBySeqsRange", "docID", docID, "seqs", seqs) log.ZDebug(ctx, "getMsgBySeqsRange", "docID", docID, "seqs", seqs)
msgs, err := db.findMsgInfoBySeq(ctx, userID, docID, seqs) msgs, err := db.findMsgInfoBySeq(ctx, userID, docID, seqs)
@ -456,7 +575,12 @@ func (db *commonMsgDatabase) getMsgBySeqsRange(ctx context.Context, userID strin
return seqMsgs, nil return seqMsgs, nil
} }
func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID string, conversationID string, begin, end, num, userMaxSeq int64) (int64, int64, []*sdkws.MsgData, error) { func (db *commonMsgDatabase) GetMsgBySeqsRange(
ctx context.Context,
userID string,
conversationID string,
begin, end, num, userMaxSeq int64,
) (int64, int64, []*sdkws.MsgData, error) {
userMinSeq, err := db.cache.GetConversationUserMinSeq(ctx, conversationID, userID) userMinSeq, err := db.cache.GetConversationUserMinSeq(ctx, conversationID, userID)
if err != nil && errs.Unwrap(err) != redis.Nil { if err != nil && errs.Unwrap(err) != redis.Nil {
return 0, 0, nil, err return 0, 0, nil, err
@ -476,7 +600,18 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
if err != nil && errs.Unwrap(err) != redis.Nil { if err != nil && errs.Unwrap(err) != redis.Nil {
return 0, 0, nil, err return 0, 0, nil, err
} }
log.ZDebug(ctx, "GetMsgBySeqsRange", "userMinSeq", userMinSeq, "conMinSeq", minSeq, "conMaxSeq", maxSeq, "userMaxSeq", userMaxSeq) log.ZDebug(
ctx,
"GetMsgBySeqsRange",
"userMinSeq",
userMinSeq,
"conMinSeq",
minSeq,
"conMaxSeq",
maxSeq,
"userMaxSeq",
userMaxSeq,
)
if userMaxSeq != 0 { if userMaxSeq != 0 {
if userMaxSeq < maxSeq { if userMaxSeq < maxSeq {
maxSeq = userMaxSeq maxSeq = userMaxSeq
@ -526,7 +661,18 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
cacheDelNum += 1 cacheDelNum += 1
} }
} }
log.ZDebug(ctx, "get delSeqs from redis", "delSeqs", delSeqs, "userID", userID, "conversationID", conversationID, "cacheDelNum", cacheDelNum) log.ZDebug(
ctx,
"get delSeqs from redis",
"delSeqs",
delSeqs,
"userID",
userID,
"conversationID",
conversationID,
"cacheDelNum",
cacheDelNum,
)
var reGetSeqsCache []int64 var reGetSeqsCache []int64
for i := 1; i <= cacheDelNum; { for i := 1; i <= cacheDelNum; {
newSeq := newBegin - int64(i) newSeq := newBegin - int64(i)
@ -546,7 +692,15 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
if err != nil { if err != nil {
if err != redis.Nil { if err != redis.Nil {
prome.Add(prome.MsgPullFromRedisFailedCounter, len(failedSeqs2)) prome.Add(prome.MsgPullFromRedisFailedCounter, len(failedSeqs2))
log.ZError(ctx, "get message from redis exception", err, "conversationID", conversationID, "seqs", reGetSeqsCache) log.ZError(
ctx,
"get message from redis exception",
err,
"conversationID",
conversationID,
"seqs",
reGetSeqsCache,
)
} }
} }
failedSeqs = append(failedSeqs, failedSeqs2...) failedSeqs = append(failedSeqs, failedSeqs2...)
@ -572,7 +726,12 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
return minSeq, maxSeq, successMsgs, nil return minSeq, maxSeq, successMsgs, nil
} }
func (db *commonMsgDatabase) GetMsgBySeqs(ctx context.Context, userID string, conversationID string, seqs []int64) (int64, int64, []*sdkws.MsgData, error) { func (db *commonMsgDatabase) GetMsgBySeqs(
ctx context.Context,
userID string,
conversationID string,
seqs []int64,
) (int64, int64, []*sdkws.MsgData, error) {
userMinSeq, err := db.cache.GetConversationUserMinSeq(ctx, conversationID, userID) userMinSeq, err := db.cache.GetConversationUserMinSeq(ctx, conversationID, userID)
if err != nil && errs.Unwrap(err) != redis.Nil { if err != nil && errs.Unwrap(err) != redis.Nil {
return 0, 0, nil, err return 0, 0, nil, err
@ -598,10 +757,33 @@ func (db *commonMsgDatabase) GetMsgBySeqs(ctx context.Context, userID string, co
if err != nil { if err != nil {
if err != redis.Nil { if err != redis.Nil {
prome.Add(prome.MsgPullFromRedisFailedCounter, len(failedSeqs)) prome.Add(prome.MsgPullFromRedisFailedCounter, len(failedSeqs))
log.ZError(ctx, "get message from redis exception", err, "failedSeqs", failedSeqs, "conversationID", conversationID) log.ZError(
ctx,
"get message from redis exception",
err,
"failedSeqs",
failedSeqs,
"conversationID",
conversationID,
)
} }
} }
log.ZInfo(ctx, "db.cache.GetMessagesBySeq", "userID", userID, "conversationID", conversationID, "seqs", seqs, "successMsgs", len(successMsgs), "failedSeqs", failedSeqs, "conversationID", conversationID) log.ZInfo(
ctx,
"db.cache.GetMessagesBySeq",
"userID",
userID,
"conversationID",
conversationID,
"seqs",
seqs,
"successMsgs",
len(successMsgs),
"failedSeqs",
failedSeqs,
"conversationID",
conversationID,
)
prome.Add(prome.MsgPullFromRedisSuccessCounter, len(successMsgs)) prome.Add(prome.MsgPullFromRedisSuccessCounter, len(successMsgs))
if len(failedSeqs) > 0 { if len(failedSeqs) > 0 {
mongoMsgs, err := db.getMsgBySeqs(ctx, userID, conversationID, failedSeqs) mongoMsgs, err := db.getMsgBySeqs(ctx, userID, conversationID, failedSeqs)
@ -615,7 +797,11 @@ func (db *commonMsgDatabase) GetMsgBySeqs(ctx context.Context, userID string, co
return minSeq, maxSeq, successMsgs, nil return minSeq, maxSeq, successMsgs, nil
} }
func (db *commonMsgDatabase) DeleteConversationMsgsAndSetMinSeq(ctx context.Context, conversationID string, remainTime int64) error { func (db *commonMsgDatabase) DeleteConversationMsgsAndSetMinSeq(
ctx context.Context,
conversationID string,
remainTime int64,
) error {
var delStruct delMsgRecursionStruct var delStruct delMsgRecursionStruct
var skip int64 var skip int64
minSeq, err := db.deleteMsgRecursion(ctx, conversationID, skip, &delStruct, remainTime) minSeq, err := db.deleteMsgRecursion(ctx, conversationID, skip, &delStruct, remainTime)
@ -649,13 +835,26 @@ func (d *delMsgRecursionStruct) getSetMinSeq() int64 {
// seq 70 // seq 70
// set minSeq 21 // set minSeq 21
// recursion 删除list并且返回设置的最小seq // recursion 删除list并且返回设置的最小seq
func (db *commonMsgDatabase) deleteMsgRecursion(ctx context.Context, conversationID string, index int64, delStruct *delMsgRecursionStruct, remainTime int64) (int64, error) { func (db *commonMsgDatabase) deleteMsgRecursion(
ctx context.Context,
conversationID string,
index int64,
delStruct *delMsgRecursionStruct,
remainTime int64,
) (int64, error) {
// find from oldest list // find from oldest list
msgDocModel, err := db.msgDocDatabase.GetMsgDocModelByIndex(ctx, conversationID, index, 1) msgDocModel, err := db.msgDocDatabase.GetMsgDocModelByIndex(ctx, conversationID, index, 1)
if err != nil || msgDocModel.DocID == "" { if err != nil || msgDocModel.DocID == "" {
if err != nil { if err != nil {
if err == unrelation.ErrMsgListNotExist { if err == unrelation.ErrMsgListNotExist {
log.ZDebug(ctx, "deleteMsgRecursion ErrMsgListNotExist", "conversationID", conversationID, "index:", index) log.ZDebug(
ctx,
"deleteMsgRecursion ErrMsgListNotExist",
"conversationID",
conversationID,
"index:",
index,
)
} else { } else {
log.ZError(ctx, "deleteMsgRecursion GetUserMsgListByIndex failed", err, "conversationID", conversationID, "index", index) log.ZError(ctx, "deleteMsgRecursion GetUserMsgListByIndex failed", err, "conversationID", conversationID, "index", index)
} }
@ -667,11 +866,23 @@ func (db *commonMsgDatabase) deleteMsgRecursion(ctx context.Context, conversatio
} }
return delStruct.getSetMinSeq() + 1, nil return delStruct.getSetMinSeq() + 1, nil
} }
log.ZDebug(ctx, "doc info", "conversationID", conversationID, "index", index, "docID", msgDocModel.DocID, "len", len(msgDocModel.Msg)) log.ZDebug(
ctx,
"doc info",
"conversationID",
conversationID,
"index",
index,
"docID",
msgDocModel.DocID,
"len",
len(msgDocModel.Msg),
)
if int64(len(msgDocModel.Msg)) > db.msg.GetSingleGocMsgNum() { if int64(len(msgDocModel.Msg)) > db.msg.GetSingleGocMsgNum() {
log.ZWarn(ctx, "msgs too large", nil, "lenth", len(msgDocModel.Msg), "docID:", msgDocModel.DocID) log.ZWarn(ctx, "msgs too large", nil, "lenth", len(msgDocModel.Msg), "docID:", msgDocModel.DocID)
} }
if msgDocModel.IsFull() && msgDocModel.Msg[len(msgDocModel.Msg)-1].Msg.SendTime+(remainTime*1000) < utils.GetCurrentTimestampByMill() { if msgDocModel.IsFull() &&
msgDocModel.Msg[len(msgDocModel.Msg)-1].Msg.SendTime+(remainTime*1000) < utils.GetCurrentTimestampByMill() {
log.ZDebug(ctx, "doc is full and all msg is expired", "docID", msgDocModel.DocID) log.ZDebug(ctx, "doc is full and all msg is expired", "docID", msgDocModel.DocID)
delStruct.delDocIDs = append(delStruct.delDocIDs, msgDocModel.DocID) delStruct.delDocIDs = append(delStruct.delDocIDs, msgDocModel.DocID)
delStruct.minSeq = msgDocModel.Msg[len(msgDocModel.Msg)-1].Msg.Seq delStruct.minSeq = msgDocModel.Msg[len(msgDocModel.Msg)-1].Msg.Seq
@ -708,7 +919,11 @@ func (db *commonMsgDatabase) deleteMsgRecursion(ctx context.Context, conversatio
return seq, err return seq, err
} }
func (db *commonMsgDatabase) DeleteMsgsPhysicalBySeqs(ctx context.Context, conversationID string, allSeqs []int64) error { func (db *commonMsgDatabase) DeleteMsgsPhysicalBySeqs(
ctx context.Context,
conversationID string,
allSeqs []int64,
) error {
if err := db.cache.DeleteMessages(ctx, conversationID, allSeqs); err != nil { if err := db.cache.DeleteMessages(ctx, conversationID, allSeqs); err != nil {
return err return err
} }
@ -724,7 +939,12 @@ func (db *commonMsgDatabase) DeleteMsgsPhysicalBySeqs(ctx context.Context, conve
return nil return nil
} }
func (db *commonMsgDatabase) DeleteUserMsgsBySeqs(ctx context.Context, userID string, conversationID string, seqs []int64) error { func (db *commonMsgDatabase) DeleteUserMsgsBySeqs(
ctx context.Context,
userID string,
conversationID string,
seqs []int64,
) error {
cachedMsgs, _, err := db.cache.GetMessagesBySeq(ctx, conversationID, seqs) cachedMsgs, _, err := db.cache.GetMessagesBySeq(ctx, conversationID, seqs)
if err != nil && errs.Unwrap(err) != redis.Nil { if err != nil && errs.Unwrap(err) != redis.Nil {
log.ZWarn(ctx, "DeleteUserMsgsBySeqs", err, "conversationID", conversationID, "seqs", seqs) log.ZWarn(ctx, "DeleteUserMsgsBySeqs", err, "conversationID", conversationID, "seqs", seqs)
@ -793,31 +1013,70 @@ func (db *commonMsgDatabase) GetMinSeqs(ctx context.Context, conversationIDs []s
func (db *commonMsgDatabase) GetMinSeq(ctx context.Context, conversationID string) (int64, error) { func (db *commonMsgDatabase) GetMinSeq(ctx context.Context, conversationID string) (int64, error) {
return db.cache.GetMinSeq(ctx, conversationID) return db.cache.GetMinSeq(ctx, conversationID)
} }
func (db *commonMsgDatabase) GetConversationUserMinSeq(ctx context.Context, conversationID string, userID string) (int64, error) {
func (db *commonMsgDatabase) GetConversationUserMinSeq(
ctx context.Context,
conversationID string,
userID string,
) (int64, error) {
return db.cache.GetConversationUserMinSeq(ctx, conversationID, userID) return db.cache.GetConversationUserMinSeq(ctx, conversationID, userID)
} }
func (db *commonMsgDatabase) GetConversationUserMinSeqs(ctx context.Context, conversationID string, userIDs []string) (map[string]int64, error) {
func (db *commonMsgDatabase) GetConversationUserMinSeqs(
ctx context.Context,
conversationID string,
userIDs []string,
) (map[string]int64, error) {
return db.cache.GetConversationUserMinSeqs(ctx, conversationID, userIDs) return db.cache.GetConversationUserMinSeqs(ctx, conversationID, userIDs)
} }
func (db *commonMsgDatabase) SetConversationUserMinSeq(ctx context.Context, conversationID string, userID string, minSeq int64) error {
func (db *commonMsgDatabase) SetConversationUserMinSeq(
ctx context.Context,
conversationID string,
userID string,
minSeq int64,
) error {
return db.cache.SetConversationUserMinSeq(ctx, conversationID, userID, minSeq) return db.cache.SetConversationUserMinSeq(ctx, conversationID, userID, minSeq)
} }
func (db *commonMsgDatabase) SetConversationUserMinSeqs(ctx context.Context, conversationID string, seqs map[string]int64) (err error) {
func (db *commonMsgDatabase) SetConversationUserMinSeqs(
ctx context.Context,
conversationID string,
seqs map[string]int64,
) (err error) {
return db.cache.SetConversationUserMinSeqs(ctx, conversationID, seqs) return db.cache.SetConversationUserMinSeqs(ctx, conversationID, seqs)
} }
func (db *commonMsgDatabase) SetUserConversationsMinSeqs(ctx context.Context, userID string, seqs map[string]int64) error { func (db *commonMsgDatabase) SetUserConversationsMinSeqs(
ctx context.Context,
userID string,
seqs map[string]int64,
) error {
return db.cache.SetUserConversationsMinSeqs(ctx, userID, seqs) return db.cache.SetUserConversationsMinSeqs(ctx, userID, seqs)
} }
func (db *commonMsgDatabase) UserSetHasReadSeqs(ctx context.Context, userID string, hasReadSeqs map[string]int64) error { func (db *commonMsgDatabase) UserSetHasReadSeqs(
ctx context.Context,
userID string,
hasReadSeqs map[string]int64,
) error {
return db.cache.UserSetHasReadSeqs(ctx, userID, hasReadSeqs) return db.cache.UserSetHasReadSeqs(ctx, userID, hasReadSeqs)
} }
func (db *commonMsgDatabase) SetHasReadSeq(ctx context.Context, userID string, conversationID string, hasReadSeq int64) error { func (db *commonMsgDatabase) SetHasReadSeq(
ctx context.Context,
userID string,
conversationID string,
hasReadSeq int64,
) error {
return db.cache.SetHasReadSeq(ctx, userID, conversationID, hasReadSeq) return db.cache.SetHasReadSeq(ctx, userID, conversationID, hasReadSeq)
} }
func (db *commonMsgDatabase) GetHasReadSeqs(ctx context.Context, userID string, conversationIDs []string) (map[string]int64, error) {
func (db *commonMsgDatabase) GetHasReadSeqs(
ctx context.Context,
userID string,
conversationIDs []string,
) (map[string]int64, error) {
return db.cache.GetHasReadSeqs(ctx, userID, conversationIDs) return db.cache.GetHasReadSeqs(ctx, userID, conversationIDs)
} }
@ -833,7 +1092,10 @@ func (db *commonMsgDatabase) GetSendMsgStatus(ctx context.Context, id string) (i
return db.cache.GetSendMsgStatus(ctx, id) return db.cache.GetSendMsgStatus(ctx, id)
} }
func (db *commonMsgDatabase) GetConversationMinMaxSeqInMongoAndCache(ctx context.Context, conversationID string) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error) { func (db *commonMsgDatabase) GetConversationMinMaxSeqInMongoAndCache(
ctx context.Context,
conversationID string,
) (minSeqMongo, maxSeqMongo, minSeqCache, maxSeqCache int64, err error) {
minSeqMongo, maxSeqMongo, err = db.GetMinMaxSeqMongo(ctx, conversationID) minSeqMongo, maxSeqMongo, err = db.GetMinMaxSeqMongo(ctx, conversationID)
if err != nil { if err != nil {
return return
@ -849,11 +1111,17 @@ func (db *commonMsgDatabase) GetConversationMinMaxSeqInMongoAndCache(ctx context
return return
} }
func (db *commonMsgDatabase) GetMongoMaxAndMinSeq(ctx context.Context, conversationID string) (maxSeq, minSeq int64, err error) { func (db *commonMsgDatabase) GetMongoMaxAndMinSeq(
ctx context.Context,
conversationID string,
) (maxSeq, minSeq int64, err error) {
return db.GetMinMaxSeqMongo(ctx, conversationID) return db.GetMinMaxSeqMongo(ctx, conversationID)
} }
func (db *commonMsgDatabase) GetMinMaxSeqMongo(ctx context.Context, conversationID string) (minSeqMongo, maxSeqMongo int64, err error) { func (db *commonMsgDatabase) GetMinMaxSeqMongo(
ctx context.Context,
conversationID string,
) (minSeqMongo, maxSeqMongo int64, err error) {
oldestMsgMongo, err := db.msgDocDatabase.GetOldestMsg(ctx, conversationID) oldestMsgMongo, err := db.msgDocDatabase.GetOldestMsg(ctx, conversationID)
if err != nil { if err != nil {
return return
@ -867,35 +1135,83 @@ func (db *commonMsgDatabase) GetMinMaxSeqMongo(ctx context.Context, conversation
return return
} }
func (db *commonMsgDatabase) JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, error) { func (db *commonMsgDatabase) JudgeMessageReactionExist(
ctx context.Context,
clientMsgID string,
sessionType int32,
) (bool, error) {
return db.cache.JudgeMessageReactionExist(ctx, clientMsgID, sessionType) return db.cache.JudgeMessageReactionExist(ctx, clientMsgID, sessionType)
} }
func (db *commonMsgDatabase) SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value string) error { func (db *commonMsgDatabase) SetMessageTypeKeyValue(
ctx context.Context,
clientMsgID string,
sessionType int32,
typeKey, value string,
) error {
return db.cache.SetMessageTypeKeyValue(ctx, clientMsgID, sessionType, typeKey, value) return db.cache.SetMessageTypeKeyValue(ctx, clientMsgID, sessionType, typeKey, value)
} }
func (db *commonMsgDatabase) SetMessageReactionExpire(ctx context.Context, clientMsgID string, sessionType int32, expiration time.Duration) (bool, error) { func (db *commonMsgDatabase) SetMessageReactionExpire(
ctx context.Context,
clientMsgID string,
sessionType int32,
expiration time.Duration,
) (bool, error) {
return db.cache.SetMessageReactionExpire(ctx, clientMsgID, sessionType, expiration) return db.cache.SetMessageReactionExpire(ctx, clientMsgID, sessionType, expiration)
} }
func (db *commonMsgDatabase) GetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey string) (string, error) { func (db *commonMsgDatabase) GetMessageTypeKeyValue(
ctx context.Context,
clientMsgID string,
sessionType int32,
typeKey string,
) (string, error) {
return db.cache.GetMessageTypeKeyValue(ctx, clientMsgID, sessionType, typeKey) return db.cache.GetMessageTypeKeyValue(ctx, clientMsgID, sessionType, typeKey)
} }
func (db *commonMsgDatabase) GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]string, error) { func (db *commonMsgDatabase) GetOneMessageAllReactionList(
ctx context.Context,
clientMsgID string,
sessionType int32,
) (map[string]string, error) {
return db.cache.GetOneMessageAllReactionList(ctx, clientMsgID, sessionType) return db.cache.GetOneMessageAllReactionList(ctx, clientMsgID, sessionType)
} }
func (db *commonMsgDatabase) DeleteOneMessageKey(ctx context.Context, clientMsgID string, sessionType int32, subKey string) error { func (db *commonMsgDatabase) DeleteOneMessageKey(
ctx context.Context,
clientMsgID string,
sessionType int32,
subKey string,
) error {
return db.cache.DeleteOneMessageKey(ctx, clientMsgID, sessionType, subKey) return db.cache.DeleteOneMessageKey(ctx, clientMsgID, sessionType, subKey)
} }
func (db *commonMsgDatabase) InsertOrUpdateReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensions map[string]*sdkws.KeyValue) error { func (db *commonMsgDatabase) InsertOrUpdateReactionExtendMsgSet(
return db.extendMsgDatabase.InsertOrUpdateReactionExtendMsgSet(ctx, conversationID, sessionType, clientMsgID, msgFirstModifyTime, db.extendMsgSetModel.Pb2Model(reactionExtensions)) ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensions map[string]*sdkws.KeyValue,
) error {
return db.extendMsgDatabase.InsertOrUpdateReactionExtendMsgSet(
ctx,
conversationID,
sessionType,
clientMsgID,
msgFirstModifyTime,
db.extendMsgSetModel.Pb2Model(reactionExtensions),
)
} }
func (db *commonMsgDatabase) GetExtendMsg(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, maxMsgUpdateTime int64) (*pbMsg.ExtendMsg, error) { func (db *commonMsgDatabase) GetExtendMsg(
ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
maxMsgUpdateTime int64,
) (*pbMsg.ExtendMsg, error) {
extendMsgSet, err := db.extendMsgDatabase.GetExtendMsgSet(ctx, conversationID, sessionType, maxMsgUpdateTime) extendMsgSet, err := db.extendMsgDatabase.GetExtendMsgSet(ctx, conversationID, sessionType, maxMsgUpdateTime)
if err != nil { if err != nil {
return nil, err return nil, err
@ -923,6 +1239,20 @@ func (db *commonMsgDatabase) GetExtendMsg(ctx context.Context, conversationID st
}, nil }, nil
} }
func (db *commonMsgDatabase) DeleteReactionExtendMsgSet(ctx context.Context, conversationID string, sessionType int32, clientMsgID string, msgFirstModifyTime int64, reactionExtensions map[string]*sdkws.KeyValue) error { func (db *commonMsgDatabase) DeleteReactionExtendMsgSet(
return db.extendMsgDatabase.DeleteReactionExtendMsgSet(ctx, conversationID, sessionType, clientMsgID, msgFirstModifyTime, db.extendMsgSetModel.Pb2Model(reactionExtensions)) ctx context.Context,
conversationID string,
sessionType int32,
clientMsgID string,
msgFirstModifyTime int64,
reactionExtensions map[string]*sdkws.KeyValue,
) error {
return db.extendMsgDatabase.DeleteReactionExtendMsgSet(
ctx,
conversationID,
sessionType,
clientMsgID,
msgFirstModifyTime,
db.extendMsgSetModel.Pb2Model(reactionExtensions),
)
} }

View File

@ -11,10 +11,11 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"go.mongodb.org/mongo-driver/bson"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
"go.mongodb.org/mongo-driver/bson"
) )
func Test_BatchInsertChat2DB(t *testing.T) { func Test_BatchInsertChat2DB(t *testing.T) {
@ -193,7 +194,9 @@ func Test_FindBySeq(t *testing.T) {
} }
db := GetDB() db := GetDB()
ctx := context.Background() ctx := context.Background()
fmt.Println(db.msgDocDatabase.(*unrelation.MsgMongoDriver).GetMsgBySeqIndexIn1Doc(ctx, "100", "si_100_101:0", []int64{1})) fmt.Println(
db.msgDocDatabase.(*unrelation.MsgMongoDriver).GetMsgBySeqIndexIn1Doc(ctx, "100", "si_100_101:0", []int64{1}),
)
//res, err := db.msgDocDatabase.GetMsgBySeqIndexIn1Doc(ctx, "123456", "test:0", []int64{1, 2, 3}) //res, err := db.msgDocDatabase.GetMsgBySeqIndexIn1Doc(ctx, "123456", "test:0", []int64{1, 2, 3})
//if err != nil { //if err != nil {
// t.Fatal(err) // t.Fatal(err)

View File

@ -15,13 +15,14 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/google/uuid"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/obj" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/obj"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third" "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/google/uuid"
) )
const ( const (
@ -40,7 +41,13 @@ type S3Database interface {
CleanExpirationObject(ctx context.Context, t time.Time) CleanExpirationObject(ctx context.Context, t time.Time)
} }
func NewS3Database(obj obj.Interface, hash relation.ObjectHashModelInterface, info relation.ObjectInfoModelInterface, put relation.ObjectPutModelInterface, url *url.URL) S3Database { func NewS3Database(
obj obj.Interface,
hash relation.ObjectHashModelInterface,
info relation.ObjectInfoModelInterface,
put relation.ObjectPutModelInterface,
url *url.URL,
) S3Database {
return &s3Database{ return &s3Database{
url: url, url: url,
obj: obj, obj: obj,
@ -207,7 +214,12 @@ func (c *s3Database) ApplyPut(ctx context.Context, req *third.ApplyPutReq) (*thi
} }
t := md5.Sum(urlsJsonData) t := md5.Sum(urlsJsonData)
put.PutURLsHash = hex.EncodeToString(t[:]) put.PutURLsHash = hex.EncodeToString(t[:])
_, err = c.obj.PutObject(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: path.Join(put.Path, urlsName)}, bytes.NewReader(urlsJsonData), int64(len(urlsJsonData))) _, err = c.obj.PutObject(
ctx,
&obj.BucketObject{Bucket: c.obj.TempBucket(), Name: path.Join(put.Path, urlsName)},
bytes.NewReader(urlsJsonData),
int64(len(urlsJsonData)),
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -228,7 +240,10 @@ func (c *s3Database) GetPut(ctx context.Context, req *third.GetPutReq) (*third.G
if err != nil { if err != nil {
return nil, err return nil, err
} }
reader, err := c.obj.GetObject(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: path.Join(up.Path, urlsName)}) reader, err := c.obj.GetObject(
ctx,
&obj.BucketObject{Bucket: c.obj.TempBucket(), Name: path.Join(up.Path, urlsName)},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -19,7 +19,13 @@ func NewThirdDatabase(cache cache.MsgModel) ThirdDatabase {
return &thirdDatabase{cache: cache} return &thirdDatabase{cache: cache}
} }
func (t *thirdDatabase) FcmUpdateToken(ctx context.Context, account string, platformID int, fcmToken string, expireTime int64) error { func (t *thirdDatabase) FcmUpdateToken(
ctx context.Context,
account string,
platformID int,
fcmToken string,
expireTime int64,
) error {
return t.cache.SetFcmToken(ctx, account, platformID, fcmToken, expireTime) return t.cache.SetFcmToken(ctx, account, platformID, fcmToken, expireTime)
} }

View File

@ -114,7 +114,10 @@ func (u *userDatabase) UpdateByMap(ctx context.Context, userID string, args map[
} }
// 获取,如果没找到,不返回错误 // 获取,如果没找到,不返回错误
func (u *userDatabase) Page(ctx context.Context, pageNumber, showNumber int32) (users []*relation.UserModel, count int64, err error) { func (u *userDatabase) Page(
ctx context.Context,
pageNumber, showNumber int32,
) (users []*relation.UserModel, count int64, err error) {
return u.userDB.Page(ctx, pageNumber, showNumber) return u.userDB.Page(ctx, pageNumber, showNumber)
} }
@ -138,6 +141,10 @@ func (u *userDatabase) CountTotal(ctx context.Context) (count int64, err error)
return u.userDB.CountTotal(ctx) return u.userDB.CountTotal(ctx)
} }
func (u *userDatabase) CountRangeEverydayTotal(ctx context.Context, start time.Time, end time.Time) (map[string]int64, error) { func (u *userDatabase) CountRangeEverydayTotal(
ctx context.Context,
start time.Time,
end time.Time,
) (map[string]int64, error) {
return u.userDB.CountRangeEverydayTotal(ctx, start, end) return u.userDB.CountRangeEverydayTotal(ctx, start, end)
} }

View File

@ -9,11 +9,12 @@ import (
"net/url" "net/url"
"time" "time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/s3utils" "github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
) )
func NewMinioInterface() (Interface, error) { func NewMinioInterface() (Interface, error) {
@ -94,7 +95,13 @@ func (m *minioImpl) DataBucket() string {
return m.dataBucket return m.dataBucket
} }
func (m *minioImpl) PresignedGetURL(ctx context.Context, bucket string, name string, expires time.Duration, opt *HeaderOption) (string, error) { func (m *minioImpl) PresignedGetURL(
ctx context.Context,
bucket string,
name string,
expires time.Duration,
opt *HeaderOption,
) (string, error) {
var reqParams url.Values var reqParams url.Values
if opt != nil { if opt != nil {
reqParams = make(url.Values) reqParams = make(url.Values)
@ -204,7 +211,12 @@ func (m *minioImpl) IsNotFound(err error) bool {
} }
} }
func (m *minioImpl) PutObject(ctx context.Context, info *BucketObject, reader io.Reader, size int64) (*ObjectInfo, error) { func (m *minioImpl) PutObject(
ctx context.Context,
info *BucketObject,
reader io.Reader,
size int64,
) (*ObjectInfo, error) {
update, err := m.client.PutObject(ctx, info.Bucket, info.Name, reader, size, minio.PutObjectOptions{}) update, err := m.client.PutObject(ctx, info.Bucket, info.Name, reader, size, minio.PutObjectOptions{})
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -68,7 +68,13 @@ type Interface interface {
// DataBucket 永久存储的桶名 // DataBucket 永久存储的桶名
DataBucket() string DataBucket() string
// PresignedGetURL 通过桶名和对象名返回URL // PresignedGetURL 通过桶名和对象名返回URL
PresignedGetURL(ctx context.Context, bucket string, name string, expires time.Duration, opt *HeaderOption) (string, error) PresignedGetURL(
ctx context.Context,
bucket string,
name string,
expires time.Duration,
opt *HeaderOption,
) (string, error)
// PresignedPutURL 申请上传,返回PUT的上传地址 // PresignedPutURL 申请上传,返回PUT的上传地址
PresignedPutURL(ctx context.Context, args *ApplyPutArgs) (string, error) PresignedPutURL(ctx context.Context, args *ApplyPutArgs) (string, error)
// GetObjectInfo 获取对象信息 // GetObjectInfo 获取对象信息

View File

@ -4,8 +4,9 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"gorm.io/gorm" "gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
) )
func GormPage[E any](db *gorm.DB, pageNumber, showNumber int32) (uint32, []*E, error) { func GormPage[E any](db *gorm.DB, pageNumber, showNumber int32) (uint32, []*E, error) {

View File

@ -5,9 +5,10 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
) )
type BlackGorm struct { type BlackGorm struct {
@ -26,37 +27,64 @@ func (b *BlackGorm) Delete(ctx context.Context, blacks []*relation.BlackModel) (
return utils.Wrap(b.db(ctx).Delete(blacks).Error, "") return utils.Wrap(b.db(ctx).Delete(blacks).Error, "")
} }
func (b *BlackGorm) UpdateByMap(ctx context.Context, ownerUserID, blockUserID string, args map[string]interface{}) (err error) { func (b *BlackGorm) UpdateByMap(
return utils.Wrap(b.db(ctx).Where("block_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Updates(args).Error, "") ctx context.Context,
ownerUserID, blockUserID string,
args map[string]interface{},
) (err error) {
return utils.Wrap(
b.db(ctx).Where("block_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Updates(args).Error,
"",
)
} }
func (b *BlackGorm) Update(ctx context.Context, blacks []*relation.BlackModel) (err error) { func (b *BlackGorm) Update(ctx context.Context, blacks []*relation.BlackModel) (err error) {
return utils.Wrap(b.db(ctx).Updates(&blacks).Error, "") return utils.Wrap(b.db(ctx).Updates(&blacks).Error, "")
} }
func (b *BlackGorm) Find(ctx context.Context, blacks []*relation.BlackModel) (blackList []*relation.BlackModel, err error) { func (b *BlackGorm) Find(
ctx context.Context,
blacks []*relation.BlackModel,
) (blackList []*relation.BlackModel, err error) {
var where [][]interface{} var where [][]interface{}
for _, black := range blacks { for _, black := range blacks {
where = append(where, []interface{}{black.OwnerUserID, black.BlockUserID}) where = append(where, []interface{}{black.OwnerUserID, black.BlockUserID})
} }
return blackList, utils.Wrap(b.db(ctx).Where("(owner_user_id, block_user_id) in ?", where).Find(&blackList).Error, "") return blackList, utils.Wrap(
b.db(ctx).Where("(owner_user_id, block_user_id) in ?", where).Find(&blackList).Error,
"",
)
} }
func (b *BlackGorm) Take(ctx context.Context, ownerUserID, blockUserID string) (black *relation.BlackModel, err error) { func (b *BlackGorm) Take(ctx context.Context, ownerUserID, blockUserID string) (black *relation.BlackModel, err error) {
black = &relation.BlackModel{} black = &relation.BlackModel{}
return black, utils.Wrap(b.db(ctx).Where("owner_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Take(black).Error, "") return black, utils.Wrap(
b.db(ctx).Where("owner_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Take(black).Error,
"",
)
} }
func (b *BlackGorm) FindOwnerBlacks(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (blacks []*relation.BlackModel, total int64, err error) { func (b *BlackGorm) FindOwnerBlacks(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (blacks []*relation.BlackModel, total int64, err error) {
err = b.db(ctx).Count(&total).Error err = b.db(ctx).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
} }
totalUint32, blacks, err := ormutil.GormPage[relation.BlackModel](b.db(ctx).Where("owner_user_id = ?", ownerUserID), pageNumber, showNumber) totalUint32, blacks, err := ormutil.GormPage[relation.BlackModel](
b.db(ctx).Where("owner_user_id = ?", ownerUserID),
pageNumber,
showNumber,
)
total = int64(totalUint32) total = int64(totalUint32)
return return
} }
func (b *BlackGorm) FindBlackUserIDs(ctx context.Context, ownerUserID string) (blackUserIDs []string, err error) { func (b *BlackGorm) FindBlackUserIDs(ctx context.Context, ownerUserID string) (blackUserIDs []string, err error) {
return blackUserIDs, utils.Wrap(b.db(ctx).Where("owner_user_id = ?", ownerUserID).Pluck("block_user_id", &blackUserIDs).Error, "") return blackUserIDs, utils.Wrap(
b.db(ctx).Where("owner_user_id = ?", ownerUserID).Pluck("block_user_id", &blackUserIDs).Error,
"",
)
} }

View File

@ -3,15 +3,16 @@ package relation
import ( import (
"fmt" "fmt"
"github.com/golang/protobuf/jsonpb"
"github.com/jinzhu/copier"
"google.golang.org/protobuf/proto"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg" pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws" sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/jinzhu/copier"
"google.golang.org/protobuf/proto"
"gorm.io/gorm"
) )
type ChatLogGorm struct { type ChatLogGorm struct {
@ -48,7 +49,11 @@ func (c *ChatLogGorm) Create(msg *pbMsg.MsgDataToMQ) error {
return c.DB.Create(chatLog).Error return c.DB.Create(chatLog).Error
} }
func (c *ChatLogGorm) GetChatLog(chatLog *relation.ChatLogModel, pageNumber, showNumber int32, contentTypeList []int32) (int64, []relation.ChatLogModel, error) { func (c *ChatLogGorm) GetChatLog(
chatLog *relation.ChatLogModel,
pageNumber, showNumber int32,
contentTypeList []int32,
) (int64, []relation.ChatLogModel, error) {
mdb := c.DB.Model(chatLog) mdb := c.DB.Model(chatLog)
if chatLog.SendTime.Unix() > 0 { if chatLog.SendTime.Unix() > 0 {
mdb = mdb.Where("send_time > ? and send_time < ?", chatLog.SendTime, chatLog.SendTime.AddDate(0, 0, 1)) mdb = mdb.Where("send_time > ? and send_time < ?", chatLog.SendTime, chatLog.SendTime.AddDate(0, 0, 1))

View File

@ -3,10 +3,11 @@ package relation
import ( import (
"context" "context"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
) )
type ConversationGorm struct { type ConversationGorm struct {
@ -29,61 +30,160 @@ func (c *ConversationGorm) Delete(ctx context.Context, groupIDs []string) (err e
return utils.Wrap(c.db(ctx).Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "") return utils.Wrap(c.db(ctx).Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "")
} }
func (c *ConversationGorm) UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}) (rows int64, err error) { func (c *ConversationGorm) UpdateByMap(
ctx context.Context,
userIDList []string,
conversationID string,
args map[string]interface{},
) (rows int64, err error) {
result := c.db(ctx).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args) result := c.db(ctx).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args)
return result.RowsAffected, utils.Wrap(result.Error, "") return result.RowsAffected, utils.Wrap(result.Error, "")
} }
func (c *ConversationGorm) Update(ctx context.Context, conversation *relation.ConversationModel) (err error) { func (c *ConversationGorm) Update(ctx context.Context, conversation *relation.ConversationModel) (err error) {
return utils.Wrap(c.db(ctx).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).Updates(conversation).Error, "") return utils.Wrap(
c.db(ctx).
Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Updates(conversation).
Error,
"",
)
} }
func (c *ConversationGorm) Find(ctx context.Context, ownerUserID string, conversationIDs []string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) Find(
err = utils.Wrap(c.db(ctx).Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).Find(&conversations).Error, "") ctx context.Context,
ownerUserID string,
conversationIDs []string,
) (conversations []*relation.ConversationModel, err error) {
err = utils.Wrap(
c.db(ctx).
Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).
Find(&conversations).
Error,
"",
)
return conversations, err return conversations, err
} }
func (c *ConversationGorm) Take(ctx context.Context, userID, conversationID string) (conversation *relation.ConversationModel, err error) { func (c *ConversationGorm) Take(
ctx context.Context,
userID, conversationID string,
) (conversation *relation.ConversationModel, err error) {
cc := &relation.ConversationModel{} cc := &relation.ConversationModel{}
return cc, utils.Wrap(c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error, "") return cc, utils.Wrap(
c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error,
"",
)
} }
func (c *ConversationGorm) FindUserID(ctx context.Context, userIDs []string, conversationIDs []string) (existUserID []string, err error) { func (c *ConversationGorm) FindUserID(
return existUserID, utils.Wrap(c.db(ctx).Where(" owner_user_id IN (?) and conversation_id in (?)", userIDs, conversationIDs).Pluck("owner_user_id", &existUserID).Error, "") ctx context.Context,
userIDs []string,
conversationIDs []string,
) (existUserID []string, err error) {
return existUserID, utils.Wrap(
c.db(ctx).
Where(" owner_user_id IN (?) and conversation_id in (?)", userIDs, conversationIDs).
Pluck("owner_user_id", &existUserID).
Error,
"",
)
} }
func (c *ConversationGorm) FindConversationID(ctx context.Context, userID string, conversationIDList []string) (existConversationID []string, err error) { func (c *ConversationGorm) FindConversationID(
return existConversationID, utils.Wrap(c.db(ctx).Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).Pluck("conversation_id", &existConversationID).Error, "") ctx context.Context,
userID string,
conversationIDList []string,
) (existConversationID []string, err error) {
return existConversationID, utils.Wrap(
c.db(ctx).
Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).
Pluck("conversation_id", &existConversationID).
Error,
"",
)
} }
func (c *ConversationGorm) FindUserIDAllConversationID(ctx context.Context, userID string) (conversationIDList []string, err error) { func (c *ConversationGorm) FindUserIDAllConversationID(
return conversationIDList, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error, "") ctx context.Context,
userID string,
) (conversationIDList []string, err error) {
return conversationIDList, utils.Wrap(
c.db(ctx).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error,
"",
)
} }
func (c *ConversationGorm) FindUserIDAllConversations(ctx context.Context, userID string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) FindUserIDAllConversations(
ctx context.Context,
userID string,
) (conversations []*relation.ConversationModel, err error) {
return conversations, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Find(&conversations).Error, "") return conversations, utils.Wrap(c.db(ctx).Where("owner_user_id=?", userID).Find(&conversations).Error, "")
} }
func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(
return userIDs, utils.Wrap(c.db(ctx).Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).Pluck("user_id", &userIDs).Error, "") ctx context.Context,
groupID string,
) (userIDs []string, err error) {
return userIDs, utils.Wrap(
c.db(ctx).
Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).
Pluck("user_id", &userIDs).
Error,
"",
)
} }
func (c *ConversationGorm) FindSuperGroupRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationGorm) FindSuperGroupRecvMsgNotNotifyUserIDs(
return userIDs, utils.Wrap(c.db(ctx).Where("group_id = ? and recv_msg_opt = ? and conversation_type = ?", groupID, constant.ReceiveNotNotifyMessage, constant.SuperGroupChatType).Pluck("user_id", &userIDs).Error, "") ctx context.Context,
groupID string,
) (userIDs []string, err error) {
return userIDs, utils.Wrap(
c.db(ctx).
Where("group_id = ? and recv_msg_opt = ? and conversation_type = ?", groupID, constant.ReceiveNotNotifyMessage, constant.SuperGroupChatType).
Pluck("user_id", &userIDs).
Error,
"",
)
} }
func (c *ConversationGorm) GetUserRecvMsgOpt(ctx context.Context, ownerUserID, conversationID string) (opt int, err error) { func (c *ConversationGorm) GetUserRecvMsgOpt(
ctx context.Context,
ownerUserID, conversationID string,
) (opt int, err error) {
var conversation relation.ConversationModel var conversation relation.ConversationModel
return int(conversation.RecvMsgOpt), utils.Wrap(c.db(ctx).Where("conversation_id = ? And owner_user_id = ?", conversationID, ownerUserID).Select("recv_msg_opt").Find(&conversation).Error, "") return int(
conversation.RecvMsgOpt,
), utils.Wrap(
c.db(ctx).
Where("conversation_id = ? And owner_user_id = ?", conversationID, ownerUserID).
Select("recv_msg_opt").
Find(&conversation).
Error,
"",
)
} }
func (c *ConversationGorm) GetAllConversationIDs(ctx context.Context) (conversationIDs []string, err error) { func (c *ConversationGorm) GetAllConversationIDs(ctx context.Context) (conversationIDs []string, err error) {
return conversationIDs, utils.Wrap(c.db(ctx).Distinct("conversation_id").Pluck("conversation_id", &conversationIDs).Error, "") return conversationIDs, utils.Wrap(
c.db(ctx).Distinct("conversation_id").Pluck("conversation_id", &conversationIDs).Error,
"",
)
} }
func (c *ConversationGorm) GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (hasReadSeqs map[string]int64, err error) { func (c *ConversationGorm) GetUserAllHasReadSeqs(
ctx context.Context,
ownerUserID string,
) (hasReadSeqs map[string]int64, err error) {
var conversations []*relation.ConversationModel var conversations []*relation.ConversationModel
err = utils.Wrap(c.db(ctx).Where("owner_user_id = ?", ownerUserID).Select("conversation_id", "has_read_seq").Find(&conversations).Error, "") err = utils.Wrap(
c.db(ctx).
Where("owner_user_id = ?", ownerUserID).
Select("conversation_id", "has_read_seq").
Find(&conversations).
Error,
"",
)
hasReadSeqs = make(map[string]int64, len(conversations)) hasReadSeqs = make(map[string]int64, len(conversations))
// for _, conversation := range conversations { // for _, conversation := range conversations {
// hasReadSeqs[conversation.ConversationID] = conversation.HasReadSeq // hasReadSeqs[conversation.ConversationID] = conversation.HasReadSeq
@ -91,6 +191,12 @@ func (c *ConversationGorm) GetUserAllHasReadSeqs(ctx context.Context, ownerUserI
return hasReadSeqs, err return hasReadSeqs, err
} }
func (c *ConversationGorm) GetConversationsByConversationID(ctx context.Context, conversationIDs []string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) GetConversationsByConversationID(
return conversations, utils.Wrap(c.db(ctx).Where("conversation_id IN (?)", conversationIDs).Find(&conversations).Error, "") ctx context.Context,
conversationIDs []string,
) (conversations []*relation.ConversationModel, err error) {
return conversations, utils.Wrap(
c.db(ctx).Where("conversation_id IN (?)", conversationIDs).Find(&conversations).Error,
"",
)
} }

View File

@ -3,9 +3,10 @@ package relation
import ( import (
"context" "context"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
) )
type FriendGorm struct { type FriendGorm struct {
@ -27,13 +28,27 @@ func (f *FriendGorm) Create(ctx context.Context, friends []*relation.FriendModel
// 删除ownerUserID指定的好友 // 删除ownerUserID指定的好友
func (f *FriendGorm) Delete(ctx context.Context, ownerUserID string, friendUserIDs []string) (err error) { func (f *FriendGorm) Delete(ctx context.Context, ownerUserID string, friendUserIDs []string) (err error) {
err = utils.Wrap(f.db(ctx).Where("owner_user_id = ? AND friend_user_id in ( ?)", ownerUserID, friendUserIDs).Delete(&relation.FriendModel{}).Error, "") err = utils.Wrap(
f.db(ctx).
Where("owner_user_id = ? AND friend_user_id in ( ?)", ownerUserID, friendUserIDs).
Delete(&relation.FriendModel{}).
Error,
"",
)
return err return err
} }
// 更新ownerUserID单个好友信息 更新零值 // 更新ownerUserID单个好友信息 更新零值
func (f *FriendGorm) UpdateByMap(ctx context.Context, ownerUserID string, friendUserID string, args map[string]interface{}) (err error) { func (f *FriendGorm) UpdateByMap(
return utils.Wrap(f.db(ctx).Where("owner_user_id = ? AND friend_user_id = ? ", ownerUserID, friendUserID).Updates(args).Error, "") ctx context.Context,
ownerUserID string,
friendUserID string,
args map[string]interface{},
) (err error) {
return utils.Wrap(
f.db(ctx).Where("owner_user_id = ? AND friend_user_id = ? ", ownerUserID, friendUserID).Updates(args).Error,
"",
)
} }
// 更新好友信息的非零值 // 更新好友信息的非零值
@ -44,7 +59,13 @@ func (f *FriendGorm) Update(ctx context.Context, friends []*relation.FriendModel
// 更新好友备注(也支持零值 // 更新好友备注(也支持零值
func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error) { func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error) {
if remark != "" { if remark != "" {
return utils.Wrap(f.db(ctx).Where("owner_user_id = ? and friend_user_id = ?", ownerUserID, friendUserID).Update("remark", remark).Error, "") return utils.Wrap(
f.db(ctx).
Where("owner_user_id = ? and friend_user_id = ?", ownerUserID, friendUserID).
Update("remark", remark).
Error,
"",
)
} }
m := make(map[string]interface{}, 1) m := make(map[string]interface{}, 1)
m["remark"] = "" m["remark"] = ""
@ -52,46 +73,106 @@ func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID
} }
// 获取单个好友信息,如没找到 返回错误 // 获取单个好友信息,如没找到 返回错误
func (f *FriendGorm) Take(ctx context.Context, ownerUserID, friendUserID string) (friend *relation.FriendModel, err error) { func (f *FriendGorm) Take(
ctx context.Context,
ownerUserID, friendUserID string,
) (friend *relation.FriendModel, err error) {
friend = &relation.FriendModel{} friend = &relation.FriendModel{}
return friend, utils.Wrap(f.db(ctx).Where("owner_user_id = ? and friend_user_id", ownerUserID, friendUserID).Take(friend).Error, "") return friend, utils.Wrap(
f.db(ctx).Where("owner_user_id = ? and friend_user_id", ownerUserID, friendUserID).Take(friend).Error,
"",
)
} }
// 查找好友关系,如果是双向关系,则都返回 // 查找好友关系,如果是双向关系,则都返回
func (f *FriendGorm) FindUserState(ctx context.Context, userID1, userID2 string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindUserState(
return friends, utils.Wrap(f.db(ctx).Where("(owner_user_id = ? and friend_user_id = ?) or (owner_user_id = ? and friend_user_id = ?)", userID1, userID2, userID2, userID1).Find(&friends).Error, "") ctx context.Context,
userID1, userID2 string,
) (friends []*relation.FriendModel, err error) {
return friends, utils.Wrap(
f.db(ctx).
Where("(owner_user_id = ? and friend_user_id = ?) or (owner_user_id = ? and friend_user_id = ?)", userID1, userID2, userID2, userID1).
Find(&friends).
Error,
"",
)
} }
// 获取 owner指定的好友列表 如果有friendUserIDs不存在也不返回错误 // 获取 owner指定的好友列表 如果有friendUserIDs不存在也不返回错误
func (f *FriendGorm) FindFriends(ctx context.Context, ownerUserID string, friendUserIDs []string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindFriends(
return friends, utils.Wrap(f.db(ctx).Where("owner_user_id = ? AND friend_user_id in (?)", ownerUserID, friendUserIDs).Find(&friends).Error, "") ctx context.Context,
ownerUserID string,
friendUserIDs []string,
) (friends []*relation.FriendModel, err error) {
return friends, utils.Wrap(
f.db(ctx).Where("owner_user_id = ? AND friend_user_id in (?)", ownerUserID, friendUserIDs).Find(&friends).Error,
"",
)
} }
// 获取哪些人添加了friendUserID 如果有ownerUserIDs不存在也不返回错误 // 获取哪些人添加了friendUserID 如果有ownerUserIDs不存在也不返回错误
func (f *FriendGorm) FindReversalFriends(ctx context.Context, friendUserID string, ownerUserIDs []string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindReversalFriends(
return friends, utils.Wrap(f.db(ctx).Where("friend_user_id = ? AND owner_user_id in (?)", friendUserID, ownerUserIDs).Find(&friends).Error, "") ctx context.Context,
friendUserID string,
ownerUserIDs []string,
) (friends []*relation.FriendModel, err error) {
return friends, utils.Wrap(
f.db(ctx).Where("friend_user_id = ? AND owner_user_id in (?)", friendUserID, ownerUserIDs).Find(&friends).Error,
"",
)
} }
// 获取ownerUserID好友列表 支持翻页 // 获取ownerUserID好友列表 支持翻页
func (f *FriendGorm) FindOwnerFriends(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *FriendGorm) FindOwnerFriends(
ctx context.Context,
ownerUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error) {
err = f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Count(&total).Error err = f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
} }
err = utils.Wrap(f.db(ctx).Where("owner_user_id = ? ", ownerUserID).Limit(int(showNumber)).Offset(int((pageNumber-1)*showNumber)).Find(&friends).Error, "") err = utils.Wrap(
f.db(ctx).
Where("owner_user_id = ? ", ownerUserID).
Limit(int(showNumber)).
Offset(int((pageNumber-1)*showNumber)).
Find(&friends).
Error,
"",
)
return return
} }
// 获取哪些人添加了friendUserID 支持翻页 // 获取哪些人添加了friendUserID 支持翻页
func (f *FriendGorm) FindInWhoseFriends(ctx context.Context, friendUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *FriendGorm) FindInWhoseFriends(
ctx context.Context,
friendUserID string,
pageNumber, showNumber int32,
) (friends []*relation.FriendModel, total int64, err error) {
err = f.DB.Model(&relation.FriendModel{}).Where("friend_user_id = ? ", friendUserID).Count(&total).Error err = f.DB.Model(&relation.FriendModel{}).Where("friend_user_id = ? ", friendUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
} }
err = utils.Wrap(f.db(ctx).Where("friend_user_id = ? ", friendUserID).Limit(int(showNumber)).Offset(int((pageNumber-1)*showNumber)).Find(&friends).Error, "") err = utils.Wrap(
f.db(ctx).
Where("friend_user_id = ? ", friendUserID).
Limit(int(showNumber)).
Offset(int((pageNumber-1)*showNumber)).
Find(&friends).
Error,
"",
)
return return
} }
func (f *FriendGorm) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) { func (f *FriendGorm) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) {
return friendUserIDs, utils.Wrap(f.db(ctx).Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Pluck("friend_user_id", &friendUserIDs).Error, "") return friendUserIDs, utils.Wrap(
f.db(ctx).
Model(&relation.FriendModel{}).
Where("owner_user_id = ? ", ownerUserID).
Pluck("friend_user_id", &friendUserIDs).
Error,
"",
)
} }

Some files were not shown because too many files have changed in this diff Show More