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")
var client discoveryregistry.SvcDiscoveryRegistry
client, err = openKeeper.NewClient(config.Config.Zookeeper.ZkAddr, config.Config.Zookeeper.Schema,
openKeeper.WithFreq(time.Hour), openKeeper.WithUserNameAndPassword(config.Config.Zookeeper.Username,
config.Config.Zookeeper.Password), openKeeper.WithRoundRobin(), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger()))
openKeeper.WithFreq(time.Hour), openKeeper.WithUserNameAndPassword(
config.Config.Zookeeper.Username,
config.Config.Zookeeper.Password,
), openKeeper.WithRoundRobin(), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger()))
if err != nil {
return err
}

View File

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

View File

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

View File

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

View File

@ -1,6 +1,11 @@
package api
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/apiresp"
"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/rpcclient"
"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 {

View File

@ -3,17 +3,18 @@ package api
import (
"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/binding"
"github.com/go-playground/validator/v10"
"github.com/redis/go-redis/v9"
"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/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 {

View File

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

View File

@ -5,6 +5,8 @@ import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"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/mcontext"
@ -12,7 +14,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
)
type ThirdApi rpcclient.Third
@ -65,7 +66,10 @@ func (o *ThirdApi) GetURL(c *gin.Context) {
}
attachment, _ := strconv.ParseBool(c.Query("attachment"))
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 errs.ErrArgs.Is(err) {
c.String(http.StatusBadRequest, err.Error())

View File

@ -1,6 +1,8 @@
package api
import (
"github.com/gin-gonic/gin"
"github.com/OpenIMSDK/Open-IM-Server/pkg/a2r"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"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/proto/user"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/gin-gonic/gin"
)
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)
}
//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}
// if !config.Config.Callback.CallbackUserOnline.Enable {
// return callbackResp
@ -99,7 +100,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// ConnID: connID,
// }
// 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.ErrMsg = err.Error()
// }
@ -124,7 +127,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// ConnID: connID,
// }
// 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.ErrMsg = err.Error()
// }
@ -148,7 +153,9 @@ func CallbackUserKickOff(ctx context.Context, userID string, platformID int) err
// Seq: int(time.Now().UnixNano() / 1e6),
// }
// 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.ErrMsg = err.Error()
// }

View File

@ -7,13 +7,14 @@ import (
"runtime/debug"
"sync"
"google.golang.org/protobuf/proto"
"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/log"
"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/utils"
"google.golang.org/protobuf/proto"
)
var ErrConnClosed = errors.New("conn has closed")
@ -65,7 +66,13 @@ func newClient(ctx *UserConnContext, conn LongConn, isCompress bool) *Client {
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.conn = conn
c.PlatformID = utils.StringToInt(ctx.GetPlatformID())
@ -145,7 +152,9 @@ func (c *Client) handleMessage(message []byte) error {
if binaryReq.SendID != c.UserID {
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())
var messageErr error
var resp []byte
@ -163,7 +172,12 @@ func (c *Client) handleMessage(message []byte) error {
case WsSetBackgroundStatus:
resp, messageErr = c.setAppBackgroundStatus(ctx, binaryReq)
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)
return nil

View File

@ -5,6 +5,8 @@ import (
"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/constant"
"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/startrpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
)
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 {
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 {
@ -46,14 +52,24 @@ func (s *Server) SetLongConnServer(LongConnServer LongConnServer) {
}
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")
}
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) {
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
}
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")
}
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
for _, v := range req.PushToUserIDs {
var resp []*msggateway.SingleMsgToUserPlatform
@ -108,7 +130,8 @@ func (s *Server) SuperGroupOnlineBatchPushOneMsg(ctx context.Context, req *msgga
RecvID: v,
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)
if err != nil {
temp.ResultCode = -2
@ -135,7 +158,10 @@ func (s *Server) SuperGroupOnlineBatchPushOneMsg(ctx context.Context, req *msgga
}, 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 {
if clients, _, ok := s.LongConnServer.GetUserPlatformCons(v, int(req.PlatformID)); ok {
for _, client := range clients {
@ -149,7 +175,10 @@ func (s *Server) KickUserOffline(ctx context.Context, req *msggateway.KickUserOf
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
panic("implement me")
}

View File

@ -8,7 +8,14 @@ import (
)
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(
WithPort(wsPort),
WithMaxConnNum(int64(config.Config.LongConnSvr.WebsocketMaxConnNum)),

View File

@ -6,20 +6,21 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"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/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/go-playground/validator/v10"
"google.golang.org/protobuf/proto"
)
type Req struct {
ReqIdentifier int32 `json:"reqIdentifier" validate:"required"`
Token string `json:"token" `
SendID string `json:"sendID" validate:"required"`
OperationID string `json:"operationID" validate:"required"`
MsgIncr string `json:"msgIncr" validate:"required"`
Token string `json:"token"`
SendID string `json:"sendID" validate:"required"`
OperationID string `json:"operationID" validate:"required"`
MsgIncr string `json:"msgIncr" validate:"required"`
Data []byte `json:"data"`
}
@ -160,7 +161,8 @@ func (g GrpcHandler) SetUserDeviceBackground(_ context.Context, data Req) ([]byt
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 {
// 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/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"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/tokenverify"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/go-playground/validator/v10"
)
type LongConnServer interface {
@ -169,7 +171,14 @@ func (ws *WsServer) registerClient(client *Client) {
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 {
var ret string
@ -200,18 +209,47 @@ func (ws *WsServer) multiTerminalLoginChecker(info *kickHandler) {
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 {
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
}
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
}
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() {
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)
err = ws.cache.SetTokenMapByUidPid(info.newClient.ctx, info.newClient.UserID, info.newClient.PlatformID, m)
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
}
}
@ -233,7 +279,16 @@ func (ws *WsServer) unregisterClient(client *Client) {
atomic.AddInt64(&ws.onlineUserNum, -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) {

View File

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

View File

@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"github.com/Shopify/sarama"
"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/db/controller"
@ -14,7 +16,6 @@ import (
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/utils"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
)
@ -41,7 +42,18 @@ func (mmc *ModifyMsgConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSessi
claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() {
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 {
mmc.ModifyMsg(ctx, msg, string(msg.Key), sess)
} else {
@ -52,7 +64,12 @@ func (mmc *ModifyMsgConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSessi
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{}
operationID := mcontext.GetOperationID(ctx)
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 {
// 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
}
} else {

View File

@ -9,6 +9,10 @@ import (
"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/constant"
"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/rpcclient"
"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
@ -63,7 +64,11 @@ type OnlineHistoryRedisConsumerHandler struct {
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
och.msgDatabase = database
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,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.LatestMsgToRedis.Topic},
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
}
@ -90,16 +96,53 @@ func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
msgChannelValue := cmd.Value.(MsgChannelValue)
ctxMsgList := msgChannelValue.ctxMsgList
ctx := msgChannelValue.ctx
log.ZDebug(ctx, "msg arrived channel", "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))
log.ZDebug(
ctx,
"msg arrived channel",
"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)
conversationIDNotification := utils.GetNotificationConversationID(ctxMsgList[0].message)
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 {
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 {
options2 := utils.Options(msg.Options)
if options2.IsHistory() {
@ -130,11 +175,17 @@ func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []
msg.Options = utils.NewMsgOptions()
}
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))
}
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))
}
storageMsgList = append(storageMsgList, msg)
@ -151,19 +202,32 @@ func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []
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)
}
}
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)
if len(storageList) > 0 {
lastSeq, _, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
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
}
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 {
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)
if len(storageList) > 0 {
lastSeq, isNewConversation, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
@ -240,11 +312,26 @@ func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
for i, header := range consumerMessages[i].Headers {
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.message = msgFromMQ
log.ZDebug(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)
log.ZDebug(
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 {
oldM = append(oldM, ctxMsg)
aggregationMsgs[string(consumerMessages[i].Key)] = oldM
@ -260,7 +347,16 @@ func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
hashCode := utils.GetHashCode(uniqueKey)
channelID := hashCode % ChannelNum
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}}
}
}
@ -288,7 +384,10 @@ func (och *OnlineHistoryRedisConsumerHandler) Cleanup(_ sarama.ConsumerGroupSess
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 {
if sess == nil {
log.ZWarn(context.Background(), "sess == nil, waiting", nil)

View File

@ -3,13 +3,14 @@ package msgtransfer
import (
"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/db/controller"
kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
)
type OnlineHistoryMongoConsumerHandler struct {
@ -27,7 +28,12 @@ func NewOnlineHistoryMongoConsumerHandler(database controller.CommonMsgDatabase)
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
msgFromMQ := pbMsg.MsgDataToMongoByMQ{}
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)
err = mc.msgDatabase.BatchInsertChat2DB(ctx, msgFromMQ.ConversationID, msgFromMQ.MsgData, msgFromMQ.LastSeq)
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
for _, msg := range msgFromMQ.MsgData {
@ -50,14 +64,26 @@ func (mc *OnlineHistoryMongoConsumerHandler) handleChatWs2Mongo(ctx context.Cont
}
err = mc.msgDatabase.DeleteMessagesFromCache(ctx, msgFromMQ.ConversationID, seqs)
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)
}
func (OnlineHistoryMongoConsumerHandler) Setup(_ 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",
claim.HighWaterMarkOffset(), "topic", claim.Topic(), "partition", claim.Partition())
for msg := range claim.Messages() {

View File

@ -3,8 +3,7 @@
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/5/11 15:37).
*/
package msgtransfer
*/package msgtransfer
import (
"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
var tag bool
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) 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() {
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 {
pc.handleChatWs2Mysql(ctx, msg, string(msg.Key), sess)
} else {

View File

@ -17,7 +17,12 @@ func url() string {
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 {
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)
}
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 {
return nil
}

View File

@ -21,6 +21,7 @@ func (c *Consumer) initPrometheus() {
}
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)
}

View File

@ -6,12 +6,13 @@ import (
firebase "firebase.google.com/go"
"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/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/redis/go-redis/v9"
"google.golang.org/api/option"
)
const SinglePushCountLimit = 400

View File

@ -4,9 +4,10 @@ import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/stretchr/testify/assert"
)
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) {
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))
reqAuth := AuthReq{
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)
}
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)
if err != nil {
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 {
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 (
"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/constant"
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"
pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
)
type ConsumerHandler struct {

View File

@ -4,6 +4,8 @@ import (
"context"
"sync"
"google.golang.org/grpc"
"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/controller"
@ -12,7 +14,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
pbPush "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/push"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
)
type pushServer struct {
@ -30,7 +31,16 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
groupRpcClient := rpcclient.NewGroupRpcClient(client)
conversationRpcClient := rpcclient.NewConversationRpcClient(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
wg.Add(2)
go func() {
@ -66,7 +76,10 @@ func (r *pushServer) PushMsg(ctx context.Context, pbData *pbPush.PushMsgReq) (re
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 {
return nil, err
}

View File

@ -38,9 +38,16 @@ type Pusher struct {
var errNoOfflinePusher = errors.New("no offlinePusher is configured")
func NewPusher(discov discoveryregistry.SvcDiscoveryRegistry, offlinePusher offlinepush.OfflinePusher, database controller.PushDatabase,
groupLocalCache *localcache.GroupLocalCache, conversationLocalCache *localcache.ConversationLocalCache,
conversationRpcClient *rpcclient.ConversationRpcClient, groupRpcClient *rpcclient.GroupRpcClient, msgRpcClient *rpcclient.MessageRpcClient) *Pusher {
func NewPusher(
discov discoveryregistry.SvcDiscoveryRegistry,
offlinePusher offlinepush.OfflinePusher,
database controller.PushDatabase,
groupLocalCache *localcache.GroupLocalCache,
conversationLocalCache *localcache.ConversationLocalCache,
conversationRpcClient *rpcclient.ConversationRpcClient,
groupRpcClient *rpcclient.GroupRpcClient,
msgRpcClient *rpcclient.MessageRpcClient,
) *Pusher {
return &Pusher{
discov: discov,
database: database,
@ -87,7 +94,18 @@ func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.Msg
return err
}
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++
for _, userID := range userIDs {
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) {
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})
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 {
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) {
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)
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 {
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 {
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)
return err
}
_, err := p.GetConnsAndOnlinePush(ctx, msg, utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs))
_, err := p.GetConnsAndOnlinePush(
ctx,
msg,
utils.IntersectString(needOfflinePushUserIDs, WebAndPcBackgroundUserIDs),
)
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
}
}
@ -234,7 +294,11 @@ func (p *Pusher) Push2SuperGroup(ctx context.Context, groupID string, msg *sdkws
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)
log.ZDebug(ctx, "get gateway conn", "conn length", len(conns))
if err != nil {
@ -243,7 +307,10 @@ func (p *Pusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
//Online push message
for _, v := range conns {
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)
if err != nil {
continue
@ -257,7 +324,12 @@ func (p *Pusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
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)
if err != nil {
return err
@ -291,7 +363,10 @@ func (p *Pusher) GetOfflinePushOpts(msg *sdkws.MsgData) (opts *offlinepush.Opts,
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 {
err = errNoOfflinePusher
return

View File

@ -3,6 +3,8 @@ package auth
import (
"context"
"google.golang.org/grpc"
"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/db/cache"
@ -15,7 +17,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msggateway"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
)
type authServer struct {
@ -33,7 +34,11 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
pbAuth.RegisterAuthServer(server, &authServer{
userRpcClient: &userRpcClient,
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
}
@ -80,7 +85,10 @@ func (s *authServer) parseToken(ctx context.Context, tokensString string) (claim
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{}
claims, err := s.parseToken(ctx, req.Token)
if err != nil {

View File

@ -3,6 +3,8 @@ package conversation
import (
"context"
"google.golang.org/grpc"
"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/db/cache"
@ -17,7 +19,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
)
type conversationServer struct {
@ -44,12 +45,19 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
pbConversation.RegisterConversationServer(server, &conversationServer{
conversationNotificationSender: notification.NewConversationNotificationSender(&msgRpcClient),
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
}
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})
if err != nil {
return nil, err
@ -62,7 +70,10 @@ func (c *conversationServer) GetConversation(ctx context.Context, req *pbConvers
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)
if err != nil {
return nil, err
@ -72,7 +83,10 @@ func (c *conversationServer) GetAllConversations(ctx context.Context, req *pbCon
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)
if err != nil {
return nil, err
@ -82,7 +96,10 @@ func (c *conversationServer) GetConversations(ctx context.Context, req *pbConver
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)
err := c.conversationDatabase.SetUserConversations(ctx, req.OwnerUserID, conversations)
if err != nil {
@ -92,12 +109,19 @@ func (c *conversationServer) BatchSetConversations(ctx context.Context, req *pbC
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
if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil {
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 {
return nil, err
}
@ -106,7 +130,10 @@ func (c *conversationServer) SetConversation(ctx context.Context, req *pbConvers
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 {
return nil, err
}
@ -115,7 +142,10 @@ func (c *conversationServer) SetRecvMsgOpt(ctx context.Context, req *pbConversat
}
// 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{}
var err error
if req.Conversation.ConversationType == constant.GroupChatType {
@ -129,11 +159,19 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
}
conversation := convert.ConversationPb2DB(req.Conversation)
if req.FieldType == constant.FieldIsPrivateChat {
err := c.conversationDatabase.SyncPeerUserPrivateConversationTx(ctx, []*tableRelation.ConversationModel{conversation})
err := c.conversationDatabase.SyncPeerUserPrivateConversationTx(
ctx,
[]*tableRelation.ConversationModel{conversation},
)
if err != nil {
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
}
filedMap := make(map[string]interface{})
@ -161,7 +199,10 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
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 {
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
}
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 {
@ -224,7 +270,10 @@ func (c *conversationServer) SetConversations(ctx context.Context, req *pbConver
}
// 获取超级大群开启免打扰的用户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)
if err != nil {
return nil, err
@ -233,7 +282,10 @@ func (c *conversationServer) GetRecvMsgNotNotifyUserIDs(ctx context.Context, req
}
// 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
conversation.ConversationID = utils.GetConversationIDBySessionType(constant.SingleChatType, req.RecvID, req.SendID)
conversation.ConversationType = constant.SingleChatType
@ -254,7 +306,10 @@ func (c *conversationServer) CreateSingleChatConversations(ctx context.Context,
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)
if err != nil {
return nil, err
@ -262,7 +317,10 @@ func (c *conversationServer) CreateGroupChatConversations(ctx context.Context, r
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,
map[string]interface{}{"max_seq": req.MaxSeq}); err != nil {
return nil, err
@ -270,7 +328,10 @@ func (c *conversationServer) SetConversationMaxSeq(ctx context.Context, req *pbC
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)
if err != nil {
return nil, err
@ -278,7 +339,10 @@ func (c *conversationServer) GetConversationIDs(ctx context.Context, req *pbConv
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)
if err != nil {
return nil, err
@ -286,10 +350,15 @@ func (c *conversationServer) GetUserConversationIDsHash(ctx context.Context, req
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)
if err != nil {
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"
)
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 {
return nil, err
}
@ -44,7 +47,10 @@ func (s *friendServer) IsBlack(ctx context.Context, req *pbFriend.IsBlackReq) (*
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 {
return nil, err
}
@ -63,7 +69,12 @@ func (s *friendServer) AddBlack(ctx context.Context, req *pbFriend.AddBlackReq)
if err != nil {
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 {
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/rpcclient"
"google.golang.org/grpc"
"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/controller"
@ -19,7 +21,6 @@ import (
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/utils"
"google.golang.org/grpc"
)
type friendServer struct {
@ -46,10 +47,21 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
friendDB := relation.NewFriendGorm(db)
userRpcClient := rpcclient.NewUserRpcClient(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{
friendDatabase: controller.NewFriendDatabase(friendDB, relation.NewFriendRequestGorm(db), cache.NewFriendCacheRedis(rdb, friendDB, cache.GetDefaultOpt()), tx.NewGorm(db)),
blackDatabase: controller.NewBlackDatabase(blackDB, cache.NewBlackCacheRedis(rdb, blackDB, cache.GetDefaultOpt())),
friendDatabase: controller.NewFriendDatabase(
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,
notificationSender: notificationSender,
RegisterCenter: client,
@ -58,7 +70,10 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
}
// 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")
resp = &pbfriend.ApplyToAddFriendResp{}
if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil {
@ -88,7 +103,10 @@ func (s *friendServer) ApplyToAddFriend(ctx context.Context, req *pbfriend.Apply
}
// 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")
if err := tokenverify.CheckAdmin(ctx); err != nil {
return nil, err
@ -111,14 +129,22 @@ func (s *friendServer) ImportFriends(ctx context.Context, req *pbfriend.ImportFr
}
// 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")
resp = &pbfriend.RespondFriendApplyResp{}
if err := tokenverify.CheckAccessV3(ctx, req.ToUserID); err != nil {
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 {
err := s.friendDatabase.AgreeFriendRequest(ctx, &friendRequest)
if err != nil {
@ -139,7 +165,10 @@ func (s *friendServer) RespondFriendApply(ctx context.Context, req *pbfriend.Res
}
// 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")
resp = &pbfriend.DeleteFriendResp{}
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
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")
resp = &pbfriend.SetFriendRemarkResp{}
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
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")
resp = &pbfriend.GetDesignatedFriendsResp{}
if utils.Duplicate(req.FriendUserIDs) {
@ -192,7 +227,10 @@ func (s *friendServer) GetDesignatedFriends(ctx context.Context, req *pbfriend.G
}
// 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")
resp = &pbfriend.GetPaginationFriendsApplyToResp{}
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
@ -212,7 +250,10 @@ func (s *friendServer) GetPaginationFriendsApplyTo(ctx context.Context, req *pbf
}
// 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")
resp = &pbfriend.GetPaginationFriendsApplyFromResp{}
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
@ -232,7 +273,10 @@ func (s *friendServer) GetPaginationFriendsApplyFrom(ctx context.Context, req *p
}
// 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")
resp = &pbfriend.IsFriendResp{}
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
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")
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err
@ -262,7 +309,10 @@ func (s *friendServer) GetPaginationFriends(ctx context.Context, req *pbfriend.G
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")
if err := s.userRpcClient.Access(ctx, req.UserID); err != nil {
return nil, err

View File

@ -7,7 +7,10 @@ import (
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)
if err != nil {
return nil, err
@ -16,7 +19,10 @@ func (s *groupServer) GetGroupInfoCache(ctx context.Context, req *pbGroup.GetGro
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)
if err != nil {
return nil, err

View File

@ -43,7 +43,13 @@ func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (
})
}
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 == errs.ErrCallbackContinue {
return nil
@ -65,7 +71,11 @@ func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (
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 {
return nil
}
@ -78,7 +88,13 @@ func CallbackBeforeMemberJoinGroup(ctx context.Context, groupMember *relation.Gr
GroupEx: groupEx,
}
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 == errs.ErrCallbackContinue {
return nil
@ -118,7 +134,13 @@ func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *group.SetGroupMe
callbackReq.Ex = &req.Ex.Value
}
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 == errs.ErrCallbackContinue {
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{
GroupID: member.GroupID,
UserID: member.UserID,

View File

@ -7,7 +7,12 @@ import (
"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)
if err != nil {
return nil, err
@ -39,7 +44,11 @@ func (s *groupServer) FindGroupMember(ctx context.Context, groupIDs []string, us
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)
if err != nil {
return nil, err
@ -79,7 +88,11 @@ func (s *groupServer) TakeGroupOwner(ctx context.Context, groupID string) (*rela
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)
if err != nil {
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/rpcclient"
"google.golang.org/grpc"
"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/controller"
@ -29,7 +31,6 @@ import (
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/utils"
"google.golang.org/grpc"
)
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{
GroupDatabase: database,
User: userRpcClient,
Notification: notification.NewGroupNotificationSender(database, &msgRpcClient, func(ctx context.Context, userIDs []string) ([]notification.CommonUser, error) {
users, err := userRpcClient.GetUsersInfo(ctx, userIDs)
if err != nil {
return nil, err
}
return utils.Slice(users, func(e *sdkws.UserInfo) notification.CommonUser { return e }), nil
}),
Notification: notification.NewGroupNotificationSender(
database,
&msgRpcClient,
func(ctx context.Context, userIDs []string) ([]notification.CommonUser, error) {
users, err := userRpcClient.GetUsersInfo(ctx, userIDs)
if err != nil {
return nil, err
}
return utils.Slice(users, func(e *sdkws.UserInfo) notification.CommonUser { return e }), nil
},
),
conversationRpcClient: conversationRpcClient,
msgRpcClient: msgRpcClient,
})
@ -118,7 +123,16 @@ func (s *groupServer) GenGroupID(ctx context.Context, groupID *string) error {
}
}
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.SetString(id[0:8], 16)
id = bi.String()
@ -232,7 +246,10 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
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{}
if err := tokenverify.CheckAccessV3(ctx, req.FromUserID); err != nil {
return nil, err
@ -242,7 +259,8 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
pageNumber = req.Pagination.PageNumber
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)
if err != nil {
return nil, err
@ -281,7 +299,10 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
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{}
if len(req.InvitedUserIDs) == 0 {
return nil, errs.ErrArgs.Wrap("user empty")
@ -382,7 +403,10 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
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{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil {
@ -410,7 +434,10 @@ func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGro
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{}
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))
@ -423,7 +450,10 @@ func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGr
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{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil {
@ -531,7 +561,10 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
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{}
if len(req.UserIDs) == 0 {
return nil, errs.ErrArgs.Wrap("userIDs empty")
@ -558,7 +591,10 @@ func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetG
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)
groupIDs, err := s.GroupDatabase.FindUserManagedGroupID(ctx, req.FromUserID)
@ -609,12 +645,19 @@ func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.
return e.GroupID
})
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
}
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{}
if len(req.GroupIDs) == 0 {
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
}
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")
if !utils.Contain(req.HandleResult, constant.GroupResponseAgree, constant.GroupResponseRefuse) {
return nil, errs.ErrArgs.Wrap("HandleResult unknown")
@ -716,7 +762,10 @@ func (s *groupServer) GroupApplicationResponse(ctx context.Context, req *pbGroup
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")
user, err := s.User.GetUserInfo(ctx, req.InviterUserID)
if err != nil {
@ -816,7 +865,10 @@ func (s *groupServer) deleteMemberAndSetConversationSeq(ctx context.Context, gro
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
if !tokenverify.IsAppManagerUid(ctx) {
var err error
@ -866,7 +918,10 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
var num int
if req.GroupInfoForSet.Notification != "" {
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 {
@ -883,7 +938,10 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
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{}
group, err := s.GroupDatabase.TakeGroup(ctx, req.GroupID)
if err != nil {
@ -962,9 +1020,20 @@ func (s *groupServer) GetGroups(ctx context.Context, req *pbGroup.GetGroupsReq)
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{}
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 {
return nil, err
}
@ -984,7 +1053,10 @@ func (s *groupServer) GetGroupMembersCMS(ctx context.Context, req *pbGroup.GetGr
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{}
user, err := s.User.GetPublicUserInfo(ctx, req.UserID)
if err != nil {
@ -1031,12 +1103,19 @@ func (s *groupServer) GetUserReqApplicationList(ctx context.Context, req *pbGrou
return nil, err
}
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
}
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")
resp := &pbGroup.DismissGroupResp{}
owner, err := s.TakeGroupOwner(ctx, req.GroupID)
@ -1085,7 +1164,10 @@ func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGrou
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{}
//if err := tokenverify.CheckAccessV3(ctx, req.UserID); err != nil {
// return nil, err
@ -1120,7 +1202,10 @@ func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGrou
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{}
//member, err := s.GroupDatabase.TakeGroupMember(ctx, req.GroupID, req.UserID)
//if err != nil {
@ -1132,7 +1217,8 @@ func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.Ca
// return nil, err
// }
// 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 {
@ -1180,7 +1266,10 @@ func (s *groupServer) MuteGroup(ctx context.Context, req *pbGroup.MuteGroupReq)
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{}
if err := s.CheckGroupAdmin(ctx, req.GroupID); err != nil {
return nil, err
@ -1192,7 +1281,10 @@ func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMu
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{}
if len(req.Members) == 0 {
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})
}
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 fmt.Sprintf("[group: %s user: %s]", e[0], e[1])
}), ","))
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])
}), ","),
)
}
memberMap := utils.SliceToMap(members, func(e *relationTb.GroupMemberModel) [2]string {
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}]
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 {
// 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 {
log.ZDebug(ctx, "setGroupMemberInfo notification", "member", member.UserID)
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
}
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{}
if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupIDs empty")
@ -1351,7 +1458,10 @@ func (s *groupServer) GetGroupAbstractInfo(ctx context.Context, req *pbGroup.Get
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{}
if len(req.GroupIDs) == 0 {
return nil, errs.ErrArgs.Wrap("groupIDs empty")
@ -1375,7 +1485,10 @@ func (s *groupServer) GetUserInGroupMembers(ctx context.Context, req *pbGroup.Ge
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.UserIDs, err = s.GroupDatabase.FindGroupMemberUserID(ctx, req.GroupID)
if err != nil {
@ -1384,7 +1497,10 @@ func (s *groupServer) GetGroupMemberUserIDs(ctx context.Context, req *pbGroup.Ge
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{}
if len(req.RoleLevels) == 0 {
return nil, errs.ErrArgs.Wrap("RoleLevels empty")

View File

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

View File

@ -3,15 +3,19 @@ package msg
import (
"context"
"github.com/redis/go-redis/v9"
"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/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"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)
if err != nil {
return nil, err
@ -47,7 +51,10 @@ func (m *msgServer) GetConversationsHasReadAndMaxSeq(ctx context.Context, req *m
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)
if err != nil {
return
@ -64,7 +71,10 @@ func (m *msgServer) SetConversationHasReadSeq(ctx context.Context, req *msg.SetC
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 {
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
}
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)
if err != nil {
return
@ -136,7 +149,14 @@ func (m *msgServer) MarkConversationAsRead(ctx context.Context, req *msg.MarkCon
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{
MarkAsReadUserID: sendID,
ConversationID: conversationID,

View File

@ -27,7 +27,10 @@ func (m *msgServer) validateDeleteSyncOpt(opt *msg.DeleteSyncOpt) (isSyncSelf, i
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 {
return nil, err
}
@ -37,7 +40,10 @@ func (m *msgServer) ClearConversationsMsg(ctx context.Context, req *msg.ClearCon
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 {
return nil, err
}
@ -66,7 +72,14 @@ func (m *msgServer) DeleteMsgs(ctx context.Context, req *msg.DeleteMsgsReq) (*ms
return nil, err
}
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 {
if err := m.MsgDatabase.DeleteUserMsgsBySeqs(ctx, req.UserID, req.ConversationID, req.Seqs); err != nil {
return nil, err
@ -79,7 +92,10 @@ func (m *msgServer) DeleteMsgs(ctx context.Context, req *msg.DeleteMsgsReq) (*ms
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)
if err != nil {
return nil, err
@ -87,20 +103,36 @@ func (m *msgServer) DeleteMsgPhysicalBySeq(ctx context.Context, req *msg.DeleteM
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 {
return nil, err
}
remainTime := utils.GetCurrentTimestampBySecond() - req.Timestamp
for _, conversationID := range req.ConversationIDs {
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
}
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")
conversations, err := m.Conversation.GetConversationsByConversationID(ctx, conversationIDs)
if err != nil {
@ -125,7 +157,14 @@ func (m *msgServer) clearConversation(ctx context.Context, conversationIDs []str
// notification 2 self
if isSyncSelf {
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 {
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"
)
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.ClientMsgID = req.ClientMsgID
////resp.MsgFirstModifyTime = req.MsgFirstModifyTime
@ -18,7 +21,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
////if ExternalExtension
//if req.IsExternalExtensions {
// 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
//}
//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
// }
// 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
// }
// }
// 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 {
// return nil, err
// }
@ -49,7 +55,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// if err != nil {
// 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 {
// return nil, err
// }
@ -69,7 +76,8 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// temp.LatestUpdateTime = utils.GetCurrentTimestampByMill()
// 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 {
// for _, value := range setValue {
// temp := new(msg.KeyValueResp)
@ -112,7 +120,7 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
// continue
// } else {
// v.LatestUpdateTime = utils.GetCurrentTimestampByMill()
// newerr := db.DB.SetMessageTypeKeyValue(req.ClientMsgID, req.SessionType, k, utils.StructToJsonString(v))
// newerr := db.DB.SetMessageTypeKeyValue(req.ClientMsgID, req.SessionType, k, utils.StructToJsonString(v))
// if newerr != nil {
// setKeyResultInfo(&resp, 201, newerr.Error(), req.ClientMsgID, k, temp)
// continue
@ -124,26 +132,28 @@ func (m *msgServer) SetMessageReactionExtensions(ctx context.Context, req *msg.S
//}
//if !isExists {
// 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 {
// 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 {
// 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())
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)
temp.KeyValue = keyValue
temp.ErrCode = errCode
temp.ErrMsg = errMsg
r.Result = append(r.Result, temp)
_ = m.MessageLocker.UnLockMessageTypeKey(ctx, clientMsgID, typeKey)
}
func (m *msgServer) setDeleteKeyResultInfo(ctx context.Context, r *msg.DeleteMessagesReactionExtensionsResp, errCode int32, errMsg, clientMsgID, typeKey string, keyValue *sdkws.KeyValue) {
func (m *msgServer) setKeyResultInfo(
ctx context.Context,
r *msg.SetMessageReactionExtensionsResp,
errCode int32,
errMsg, clientMsgID, typeKey string,
keyValue *sdkws.KeyValue,
) {
temp := new(msg.KeyValueResp)
temp.KeyValue = keyValue
temp.ErrCode = errCode
@ -152,7 +162,25 @@ func (m *msgServer) setDeleteKeyResultInfo(ctx context.Context, r *msg.DeleteMes
_ = 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())
//var rResp msg.GetMessageListReactionExtensionsResp
//for _, messageValue := range req.MessageReactionKeyList {
@ -183,7 +211,8 @@ func (m *msgServer) GetMessagesReactionExtensions(ctx context.Context, req *msg.
// oneMessage.Pb2Model = keyMap
//
// } 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 {
// oneMessage.ErrCode = 100
// 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
}
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())
//var rResp msg.DeleteMessagesReactionExtensionsResp
//callbackResp := notification.callbackDeleteMessageReactionExtensions(req)
@ -231,7 +266,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
////if ExternalExtension
//if req.IsExternalExtensions {
// 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
//
//}
@ -303,7 +339,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
// }
// 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 {
// rResp.ErrCode = 200
// rResp.ErrMsg = err.Error()
@ -333,7 +370,8 @@ func (m *msgServer) DeleteMessageReactionExtensions(ctx context.Context, req *ms
// temp.TypeKey = v.TypeKey
// 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 {
// for _, value := range setValue {
// 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())
return resp, nil
}

View File

@ -35,7 +35,10 @@ func callbackSetMessageReactionExtensions(ctx context.Context, setReq *msg.SetMe
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 {
return nil
}

View File

@ -8,7 +8,10 @@ import (
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{}
if err := m.MsgDatabase.SetSendMsgStatus(ctx, mcontext.GetOperationID(ctx), req.Status); err != nil {
return nil, err
@ -16,7 +19,10 @@ func (m *msgServer) SetSendMsgStatus(ctx context.Context, req *pbMsg.SetSendMsgS
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{}
status, err := m.MsgDatabase.GetSendMsgStatus(ctx, mcontext.GetOperationID(ctx))
if IsNotFound(err) {

View File

@ -56,7 +56,12 @@ func (m *msgServer) RevokeMsg(ctx context.Context, req *msg.RevokeMsgReq) (*msg.
}
role = user.AppMangerLevel
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 {
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)
if err = m.messageVerification(ctx, req); err != nil {
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)
if err := m.MsgDatabase.MsgToMQ(ctx, utils.GenConversationUniqueKeyForSingle(req.MsgData.SendID, req.MsgData.RecvID), req.MsgData); err != nil {
promePkg.Inc(promePkg.SingleChatMsgProcessFailedCounter)
@ -127,7 +133,13 @@ func (m *msgServer) sendMsgSingleChat(ctx context.Context, req *pbMsg.SendMsgReq
var isSend bool = true
isNotification := utils.IsNotificationByMsg(req.MsgData)
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 {
return nil, err
}

View File

@ -6,7 +6,10 @@ import (
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)
if err != nil {
return nil, err

View File

@ -3,6 +3,8 @@ package msg
import (
"context"
"google.golang.org/grpc"
"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/controller"
@ -14,7 +16,6 @@ import (
"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/rpcclient"
"google.golang.org/grpc"
)
type MessageInterceptorChain []MessageInterceptorFunc
@ -64,7 +65,11 @@ func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
msgDocModel := unrelation.NewMsgMongoDriver(mongo.GetDatabase())
extendMsgModel := unrelation.NewExtendMsgSetMongoDriver(mongo.GetDatabase())
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)
conversationClient := rpcclient.NewConversationRpcClient(client)
userRpcClient := rpcclient.NewUserRpcClient(client)
@ -106,7 +111,8 @@ func (m *msgServer) initPrometheus() {
}
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 {
recvID = conversation.UserID
} else {

View File

@ -9,7 +9,10 @@ import (
"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.Msgs = 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)
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 {
log.ZWarn(ctx, "GetMsgBySeqsRange error", err, "conversationID", seq.ConversationID, "seq", seq)
continue

View File

@ -1,12 +1,13 @@
package msg
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/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
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) {
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
}
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 {
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()
}
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) {
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
}
// 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()))
}
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)
if err != nil {
return false, err

View File

@ -4,6 +4,8 @@ import (
"context"
"net/url"
"google.golang.org/grpc"
"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/controller"
@ -13,7 +15,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"google.golang.org/grpc"
)
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{
thirdDatabase: controller.NewThirdDatabase(cache.NewMsgCacheModel(rdb)),
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
}
@ -50,7 +57,10 @@ type thirdServer struct {
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)
if err != nil {
return nil, err
@ -58,7 +68,10 @@ func (t *thirdServer) FcmUpdateToken(ctx context.Context, req *third.FcmUpdateTo
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))
if err != nil {
return nil, err

View File

@ -8,7 +8,10 @@ import (
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 {
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/notification"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
)
type userServer struct {
@ -59,16 +60,22 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
friendRpcClient := rpcclient.NewFriendRpcClient(client)
msgRpcClient := rpcclient.NewMessageRpcClient(client)
u := &userServer{
UserDatabase: database,
RegisterCenter: client,
friendRpcClient: &friendRpcClient,
notificationSender: notification.NewFriendNotificationSender(&msgRpcClient, notification.WithDBFunc(database.FindWithError)),
UserDatabase: database,
RegisterCenter: client,
friendRpcClient: &friendRpcClient,
notificationSender: notification.NewFriendNotificationSender(
&msgRpcClient,
notification.WithDBFunc(database.FindWithError),
),
}
pbuser.RegisterUserServer(server, u)
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{}
users, err := s.FindWithError(ctx, req.UserIDs)
if err != nil {
@ -81,7 +88,10 @@ func (s *userServer) GetDesignateUsers(ctx context.Context, req *pbuser.GetDesig
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{}
err = tokenverify.CheckAccessV3(ctx, req.UserInfo.UserID)
if err != nil {
@ -106,7 +116,10 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbuser.UpdateUserI
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{}
if _, err := s.FindWithError(ctx, []string{req.UserID}); err != nil {
return nil, err
@ -120,7 +133,10 @@ func (s *userServer) SetGlobalRecvMessageOpt(ctx context.Context, req *pbuser.Se
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{}
if utils.Duplicate(req.CheckUserIDs) {
return nil, errs.ErrArgs.Wrap("userID repeated")
@ -149,7 +165,10 @@ func (s *userServer) AccountCheck(ctx context.Context, req *pbuser.AccountCheckR
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
if req.Pagination != nil {
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
}
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{}
if len(req.Users) == 0 {
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
}
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})
if err != nil {
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
}
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)
if err != nil {
return nil, err

View File

@ -5,9 +5,10 @@ import (
"fmt"
"sync"
"github.com/robfig/cron/v3"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/robfig/cron/v3"
)
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")
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{
msgDatabase: msgDatabase,
userDatabase: userDatabase,
@ -50,9 +55,17 @@ func InitMsgTool() (*MsgTool, error) {
}
userDB := relation.NewUserGorm(db)
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())
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)
return msgTool, nil
}
@ -75,7 +88,15 @@ func (c *MsgTool) AllConversationClearMsgAndFixSeq() {
func (c *MsgTool) ClearConversationsMsg(ctx context.Context, conversationIDs []string) {
for _, conversationID := range conversationIDs {
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 {
log.ZError(ctx, "fixSeq failed", err, "conversationID", conversationID)

View File

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

View File

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

View File

@ -1,8 +1,8 @@
package apistruct
type UserRegisterReq struct {
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
ApiUserInfo
OperationID string `json:"operationID" binding:"required"`
}
@ -17,9 +17,9 @@ type UserRegisterResp struct {
}
type UserTokenReq struct {
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
UserID string `json:"userID" binding:"required,min=1,max=64"`
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
UserID string `json:"userID" binding:"required,min=1,max=64"`
OperationID string `json:"operationID" binding:"required"`
}
@ -28,8 +28,8 @@ type UserTokenResp struct {
}
type ForceLogoutReq struct {
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
FromUserID string `json:"fromUserID" binding:"required,min=1,max=64"`
Platform int32 `json:"platform" binding:"required,min=1,max=12"`
FromUserID string `json:"fromUserID" binding:"required,min=1,max=64"`
OperationID string `json:"operationID" binding:"required"`
}
@ -46,7 +46,7 @@ type ParseTokenReq struct {
//}
type ExpireTime struct {
ExpireTimeSeconds uint32 `json:"expireTimeSeconds" `
ExpireTimeSeconds uint32 `json:"expireTimeSeconds"`
}
type ParseTokenResp struct {

View File

@ -6,23 +6,23 @@ type OptResult struct {
}
type GetAllConversationMessageOptReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetAllConversationMessageOptResp struct {
ConversationOptResultList []*OptResult `json:"data"`
}
type GetReceiveMessageOptReq struct {
ConversationIDList []string `json:"conversationIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetReceiveMessageOptResp struct {
ConversationOptResultList []*OptResult `json:"data"`
}
type SetReceiveMessageOptReq struct {
FromUserID string `json:"fromUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
Opt *int32 `json:"opt" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
Opt *int32 `json:"opt" binding:"required"`
ConversationIDList []string `json:"conversationIDList" binding:"required"`
}
type SetReceiveMessageOptResp struct {
@ -30,15 +30,15 @@ type SetReceiveMessageOptResp struct {
}
type Conversation struct {
OwnerUserID string `json:"ownerUserID" binding:"required"`
ConversationID string `json:"conversationID" binding:"required"`
ConversationType int32 `json:"conversationType" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
ConversationID string `json:"conversationID" binding:"required"`
ConversationType int32 `json:"conversationType" binding:"required"`
UserID string `json:"userID"`
GroupID string `json:"groupID"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
UnreadCount int32 `json:"unreadCount" binding:"omitempty"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
UnreadCount int32 `json:"unreadCount" binding:"omitempty"`
DraftTextTime int64 `json:"draftTextTime"`
IsPinned bool `json:"isPinned" binding:"omitempty"`
IsPinned bool `json:"isPinned" binding:"omitempty"`
IsPrivateChat bool `json:"isPrivateChat"`
BurnDuration int32 `json:"burnDuration"`
GroupAtType int32 `json:"groupAtType"`
@ -51,25 +51,25 @@ type Conversation struct {
type SetConversationReq struct {
Conversation
NotificationType int32 `json:"notificationType"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type SetConversationResp struct {
}
type ModifyConversationFieldReq struct {
Conversation
FieldType int32 `json:"fieldType" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
FieldType int32 `json:"fieldType" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type ModifyConversationFieldResp struct {
}
type BatchSetConversationsReq struct {
Conversations []Conversation `json:"conversations" binding:"required"`
Conversations []Conversation `json:"conversations" binding:"required"`
NotificationType int32 `json:"notificationType"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type BatchSetConversationsResp struct {
@ -81,8 +81,8 @@ type BatchSetConversationsResp struct {
type GetConversationReq struct {
ConversationID string `json:"conversationID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetConversationResp struct {
@ -100,8 +100,8 @@ type GetAllConversationsResp struct {
type GetConversationsReq struct {
ConversationIDs []string `json:"conversationIDs" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetConversationsResp struct {
@ -109,10 +109,10 @@ type GetConversationsResp struct {
}
type SetRecvMsgOptReq struct {
OwnerUserID string `json:"ownerUserID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
ConversationID string `json:"conversationID"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
OperationID string `json:"operationID" binding:"required"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
OperationID string `json:"operationID" binding:"required"`
NotificationType int32 `json:"notificationType"`
}

View File

@ -168,7 +168,7 @@ type FriendRequest struct {
}
type AddBlacklistReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type AddBlacklistResp struct {
@ -176,7 +176,7 @@ type AddBlacklistResp struct {
type ImportFriendReq struct {
FriendUserIDList []string `json:"friendUserIDList" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type ImportFriendResp struct {
@ -184,7 +184,7 @@ type ImportFriendResp struct {
}
type AddFriendReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
ReqMsg string `json:"reqMsg"`
}
@ -193,16 +193,16 @@ type AddFriendResp struct {
}
type AddFriendResponseReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
HandleResult int32 `json:"flag" binding:"required,oneof=-1 0 1"`
HandleResult int32 `json:"flag" binding:"required,oneof=-1 0 1"`
HandleMsg string `json:"handleMsg"`
}
type AddFriendResponseResp struct {
}
type DeleteFriendReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type DeleteFriendResp struct {
@ -216,7 +216,7 @@ type GetBlackListResp struct {
}
type SetFriendRemarkReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
Remark string `json:"remark"`
}
@ -224,14 +224,14 @@ type SetFriendRemarkResp struct {
}
type RemoveBlacklistReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type RemoveBlacklistResp struct {
}
type IsFriendReq struct {
ToUserID string `json:"toUserID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type Response struct {
@ -243,7 +243,7 @@ type IsFriendResp struct {
type GetFriendListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetFriendListResp struct {
OwnerUserID string `json:"ownerUserID"`
@ -257,7 +257,7 @@ type GetFriendListResp struct {
type GetFriendApplyListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetFriendApplyListResp struct {
@ -266,7 +266,7 @@ type GetFriendApplyListResp struct {
type GetSelfApplyListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetSelfApplyListResp struct {
FriendRequestList []FriendRequest `json:"friendRequestList"`

View File

@ -5,10 +5,10 @@ import (
)
type KickGroupMemberReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
KickedUserIDList []string `json:"kickedUserIDList" binding:"required"`
Reason string `json:"reason"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type KickGroupMemberResp struct {
@ -16,8 +16,8 @@ type KickGroupMemberResp struct {
}
type GetGroupMembersInfoReq struct {
GroupID string `json:"groupID" binding:"required"`
MemberList []string `json:"memberList" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
MemberList []string `json:"memberList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetGroupMembersInfoResp struct {
@ -26,10 +26,10 @@ type GetGroupMembersInfoResp struct {
}
type InviteUserToGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
InvitedUserIDList []string `json:"invitedUserIDList" binding:"required"`
Reason string `json:"reason"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type InviteUserToGroupResp struct {
@ -38,7 +38,7 @@ type InviteUserToGroupResp struct {
type GetJoinedGroupListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetJoinedGroupListResp struct {
GroupInfoList []*sdkws.GroupInfo `json:"-"`
@ -54,11 +54,11 @@ type GetGroupMemberListReq struct {
type GetGroupMemberListResp struct {
NextSeq int32 `json:"nextSeq"`
MemberList []*sdkws.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
type GetGroupAllMemberReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
Offset int32 `json:"offset"`
Count int32 `json:"count"`
@ -90,7 +90,7 @@ type CreateGroupReq struct {
Introduction string `json:"introduction"`
FaceURL string `json:"faceURL"`
Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID"`
}
type CreateGroupResp struct {
@ -100,7 +100,7 @@ type CreateGroupResp struct {
type GetGroupApplicationListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //作为管理员或群主收到的 进群申请
FromUserID string `json:"fromUserID" binding:"required"` //作为管理员或群主收到的 进群申请
}
type GetGroupApplicationListResp struct {
GroupRequestList []*sdkws.GroupRequest `json:"-"`
@ -109,7 +109,7 @@ type GetGroupApplicationListResp struct {
type GetUserReqGroupApplicationListReq struct {
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type GetUserRespGroupApplicationResp struct {
@ -147,9 +147,9 @@ type GetGroupInfoResp struct {
//}
type ApplicationGroupResponseReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //application from FromUserID
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //application from FromUserID
HandledMsg string `json:"handledMsg"`
HandleResult int32 `json:"handleResult" binding:"required,oneof=-1 1"`
}
@ -157,9 +157,9 @@ type ApplicationGroupResponseResp struct {
}
type JoinGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
ReqMessage string `json:"reqMessage"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
JoinSource int32 `json:"joinSource"`
InviterUserID string `json:"inviterUserID"`
}
@ -168,20 +168,20 @@ type JoinGroupResp struct {
}
type QuitGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type QuitGroupResp struct {
}
type SetGroupInfoReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
GroupName string `json:"groupName"`
Notification string `json:"notification"`
Introduction string `json:"introduction"`
FaceURL string `json:"faceURL"`
Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
NeedVerification *int32 `json:"needVerification"`
LookMemberInfo *int32 `json:"lookMemberInfo"`
ApplyMemberFriend *int32 `json:"applyMemberFriend"`
@ -191,25 +191,25 @@ type SetGroupInfoResp struct {
}
type TransferGroupOwnerReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
OldOwnerUserID string `json:"oldOwnerUserID" binding:"required"`
NewOwnerUserID string `json:"newOwnerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type TransferGroupOwnerResp struct {
}
type DismissGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DismissGroupResp struct {
}
type MuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
MutedSeconds uint32 `json:"mutedSeconds" binding:"required"`
}
type MuteGroupMemberResp struct {
@ -217,30 +217,30 @@ type MuteGroupMemberResp struct {
type CancelMuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type CancelMuteGroupMemberResp struct {
}
type MuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
}
type MuteGroupResp struct {
}
type CancelMuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
}
type CancelMuteGroupResp struct {
}
type SetGroupMemberNicknameReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
Nickname string `json:"nickname"`
}
@ -248,12 +248,12 @@ type SetGroupMemberNicknameResp struct {
}
type SetGroupMemberInfoReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
Nickname *string `json:"nickname"`
FaceURL *string `json:"userGroupFaceUrl"`
RoleLevel *int32 `json:"roleLevel" validate:"gte=1,lte=3"`
RoleLevel *int32 `json:"roleLevel" validate:"gte=1,lte=3"`
Ex *string `json:"ex"`
}

View File

@ -5,7 +5,7 @@ import (
)
type DeleteUsersReq struct {
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
DeleteUserIDList []string `json:"deleteUserIDList" binding:"required"`
}
type DeleteUsersResp struct {
@ -19,43 +19,43 @@ type GetAllUsersUidResp struct {
}
type GetUsersOnlineStatusReq struct {
OperationID string `json:"operationID" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required,lte=200"`
UserIDList []string `json:"userIDList" binding:"required,lte=200"`
}
type GetUsersOnlineStatusResp struct {
//SuccessResult []*msggateway.GetUsersOnlineStatusResp_SuccessResult `json:"data"`
}
type AccountCheckReq struct {
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
CheckUserIDList []string `json:"checkUserIDList" binding:"required,lte=100"`
}
type AccountCheckResp struct {
}
type ManagementSendMsg struct {
SendID string `json:"sendID" binding:"required"`
GroupID string `json:"groupID" binding:"required_if=SessionType 2|required_if=SessionType 3"`
SenderNickname string `json:"senderNickname" `
SenderFaceURL string `json:"senderFaceURL" `
SendID string `json:"sendID" binding:"required"`
GroupID string `json:"groupID" binding:"required_if=SessionType 2|required_if=SessionType 3"`
SenderNickname string `json:"senderNickname"`
SenderFaceURL string `json:"senderFaceURL"`
SenderPlatformID int32 `json:"senderPlatformID"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
IsOnlineOnly bool `json:"isOnlineOnly"`
NotOfflinePush bool `json:"notOfflinePush"`
OfflinePushInfo *sdkws.OfflinePushInfo `json:"offlinePushInfo"`
}
type ManagementSendMsgReq struct {
SendID string `json:"sendID" binding:"required"`
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"`
SenderNickname string `json:"senderNickname" `
SenderFaceURL string `json:"senderFaceURL" `
SendID string `json:"sendID" binding:"required"`
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"`
SenderNickname string `json:"senderNickname"`
SenderFaceURL string `json:"senderFaceURL"`
SenderPlatformID int32 `json:"senderPlatformID"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
Content map[string]interface{} `json:"content" binding:"required" swaggerignore:"true"`
ContentType int32 `json:"contentType" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
IsOnlineOnly bool `json:"isOnlineOnly"`
NotOfflinePush bool `json:"notOfflinePush"`
OfflinePushInfo *sdkws.OfflinePushInfo `json:"offlinePushInfo"`
@ -81,7 +81,7 @@ type SingleReturnResult struct {
ServerMsgID string `json:"serverMsgID"`
ClientMsgID string `json:"clientMsgID"`
SendTime int64 `json:"sendTime"`
RecvID string `json:"recvID" `
RecvID string `json:"recvID"`
}
type CheckMsgIsSendSuccessReq struct {

View File

@ -6,8 +6,8 @@ import (
)
type DelMsgReq struct {
UserID string `json:"userID,omitempty" binding:"required"`
SeqList []uint32 `json:"seqList,omitempty" binding:"required"`
UserID string `json:"userID,omitempty" binding:"required"`
SeqList []uint32 `json:"seqList,omitempty" binding:"required"`
OperationID string `json:"operationID,omitempty" binding:"required"`
}
@ -15,19 +15,19 @@ type DelMsgResp struct {
}
type CleanUpMsgReq struct {
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type CleanUpMsgResp struct {
}
type DelSuperGroupMsgReq struct {
UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
SeqList []uint32 `json:"seqList,omitempty"`
IsAllDelete bool `json:"isAllDelete"`
OperationID string `json:"operationID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DelSuperGroupMsgResp struct {
@ -40,21 +40,21 @@ type MsgDeleteNotificationElem struct {
}
type SetMsgMinSeqReq struct {
UserID string `json:"userID" binding:"required"`
UserID string `json:"userID" binding:"required"`
GroupID string `json:"groupID"`
MinSeq uint32 `json:"minSeq" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
MinSeq uint32 `json:"minSeq" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type SetMsgMinSeqResp struct {
}
type ModifyMessageReactionExtensionsReq struct {
OperationID string `json:"operationID" binding:"required"`
conversationID string `json:"conversationID" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
conversationID string `json:"conversationID" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
ReactionExtensionList map[string]*sdkws.KeyValue `json:"reactionExtensionList,omitempty" binding:"required"`
ClientMsgID string `json:"clientMsgID" binding:"required"`
ClientMsgID string `json:"clientMsgID" binding:"required"`
Ex *string `json:"ex"`
AttachedInfo *string `json:"attachedInfo"`
IsReact bool `json:"isReact"`
@ -71,10 +71,11 @@ type ModifyMessageReactionExtensionsResp struct {
}
//type OperateMessageListReactionExtensionsReq struct {
// OperationID string `json:"operationID" binding:"required"`
// conversationID string `json:"conversationID" binding:"required"`
// SessionType string `json:"sessionType" binding:"required"`
// MessageReactionKeyList []*msg.GetMessageListReactionExtensionsReq_MessageReactionKey `json:"messageReactionKeyList" binding:"required"`
// OperationID string `json:"operationID"
// binding:"required"` conversationID string
// `json:"conversationID" binding:"required"` SessionType string
// `json:"sessionType" binding:"required"` MessageReactionKeyList
// []*msg.GetMessageListReactionExtensionsReq_MessageReactionKey `json:"messageReactionKeyList" binding:"required"`
//}
type OperateMessageListReactionExtensionsResp struct {
@ -99,12 +100,12 @@ type AddMessageReactionExtensionsReq ModifyMessageReactionExtensionsReq
type AddMessageReactionExtensionsResp ModifyMessageReactionExtensionsResp
type DeleteMessageReactionExtensionsReq struct {
OperationID string `json:"operationID" binding:"required"`
conversationID string `json:"conversationID" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
ClientMsgID string `json:"clientMsgID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
conversationID string `json:"conversationID" binding:"required"`
SessionType int32 `json:"sessionType" binding:"required"`
ClientMsgID string `json:"clientMsgID" binding:"required"`
IsExternalExtensions bool `json:"isExternalExtensions"`
MsgFirstModifyTime int64 `json:"msgFirstModifyTime" binding:"required"`
MsgFirstModifyTime int64 `json:"msgFirstModifyTime" binding:"required"`
ReactionExtensionList []*sdkws.KeyValue `json:"reactionExtensionList" binding:"required"`
}
@ -114,17 +115,17 @@ type DeleteMessageReactionExtensionsResp struct {
type PictureBaseInfo struct {
UUID string `mapstructure:"uuid"`
Type string `mapstructure:"type" `
Size int64 `mapstructure:"size" `
Width int32 `mapstructure:"width" `
Type string `mapstructure:"type"`
Size int64 `mapstructure:"size"`
Width int32 `mapstructure:"width"`
Height int32 `mapstructure:"height"`
Url string `mapstructure:"url" `
Url string `mapstructure:"url"`
}
type PictureElem struct {
SourcePath string `mapstructure:"sourcePath"`
SourcePicture PictureBaseInfo `mapstructure:"sourcePicture"`
BigPicture PictureBaseInfo `mapstructure:"bigPicture" `
BigPicture PictureBaseInfo `mapstructure:"bigPicture"`
SnapshotPicture PictureBaseInfo `mapstructure:"snapshotPicture"`
}
type SoundElem struct {
@ -166,7 +167,7 @@ type LocationElem struct {
Latitude float64 `mapstructure:"latitude"`
}
type CustomElem struct {
Data string `mapstructure:"data" validate:"required"`
Data string `mapstructure:"data" validate:"required"`
Description string `mapstructure:"description"`
Extension string `mapstructure:"extension"`
}
@ -178,23 +179,23 @@ type RevokeElem struct {
RevokeMsgClientID string `mapstructure:"revokeMsgClientID" validate:"required"`
}
type OANotificationElem struct {
NotificationName string `mapstructure:"notificationName" json:"notificationName" validate:"required"`
NotificationName string `mapstructure:"notificationName" json:"notificationName" validate:"required"`
NotificationFaceURL string `mapstructure:"notificationFaceURL" json:"notificationFaceURL"`
NotificationType int32 `mapstructure:"notificationType" json:"notificationType" validate:"required"`
Text string `mapstructure:"text" json:"text" validate:"required"`
Url string `mapstructure:"url" json:"url"`
MixType int32 `mapstructure:"mixType" json:"mixType"`
PictureElem PictureElem `mapstructure:"pictureElem" json:"pictureElem"`
SoundElem SoundElem `mapstructure:"soundElem" json:"soundElem"`
VideoElem VideoElem `mapstructure:"videoElem" json:"videoElem"`
FileElem FileElem `mapstructure:"fileElem" json:"fileElem"`
Ex string `mapstructure:"ex" json:"ex"`
NotificationType int32 `mapstructure:"notificationType" json:"notificationType" validate:"required"`
Text string `mapstructure:"text" json:"text" validate:"required"`
Url string `mapstructure:"url" json:"url"`
MixType int32 `mapstructure:"mixType" json:"mixType"`
PictureElem PictureElem `mapstructure:"pictureElem" json:"pictureElem"`
SoundElem SoundElem `mapstructure:"soundElem" json:"soundElem"`
VideoElem VideoElem `mapstructure:"videoElem" json:"videoElem"`
FileElem FileElem `mapstructure:"fileElem" json:"fileElem"`
Ex string `mapstructure:"ex" json:"ex"`
}
type MessageRevoked struct {
RevokerID string `mapstructure:"revokerID" json:"revokerID" validate:"required"`
RevokerRole int32 `mapstructure:"revokerRole" json:"revokerRole" validate:"required"`
ClientMsgID string `mapstructure:"clientMsgID" json:"clientMsgID" validate:"required"`
RevokerID string `mapstructure:"revokerID" json:"revokerID" validate:"required"`
RevokerRole int32 `mapstructure:"revokerRole" json:"revokerRole" validate:"required"`
ClientMsgID string `mapstructure:"clientMsgID" json:"clientMsgID" validate:"required"`
RevokerNickname string `mapstructure:"revokerNickname" json:"revokerNickname"`
SessionType int32 `mapstructure:"sessionType" json:"sessionType" validate:"required"`
Seq uint32 `mapstructure:"seq" json:"seq" validate:"required"`
SessionType int32 `mapstructure:"sessionType" json:"sessionType" validate:"required"`
Seq uint32 `mapstructure:"seq" json:"seq" validate:"required"`
}

View File

@ -1,18 +1,18 @@
package apistruct
type ApiUserInfo struct {
UserID string `json:"userID" binding:"required,min=1,max=64" swaggo:"true,用户ID,"`
Nickname string `json:"nickname" binding:"omitempty,min=1,max=64" swaggo:"true,my id,19"`
FaceURL string `json:"faceURL" binding:"omitempty,max=1024"`
Gender int32 `json:"gender" binding:"omitempty,oneof=0 1 2"`
UserID string `json:"userID" binding:"required,min=1,max=64" swaggo:"true,用户ID,"`
Nickname string `json:"nickname" binding:"omitempty,min=1,max=64" swaggo:"true,my id,19"`
FaceURL string `json:"faceURL" binding:"omitempty,max=1024"`
Gender int32 `json:"gender" binding:"omitempty,oneof=0 1 2"`
PhoneNumber string `json:"phoneNumber" binding:"omitempty,max=32"`
Birth int64 `json:"birth" binding:"omitempty"`
Email string `json:"email" binding:"omitempty,max=64"`
Birth int64 `json:"birth" binding:"omitempty"`
Email string `json:"email" binding:"omitempty,max=64"`
CreateTime int64 `json:"createTime"`
Ex string `json:"ex" binding:"omitempty,max=1024"`
Ex string `json:"ex" binding:"omitempty,max=1024"`
}
type GroupAddMemberInfo struct {
UserID string `json:"userID" binding:"required"`
UserID string `json:"userID" binding:"required"`
RoleLevel int32 `json:"roleLevel" binding:"required,oneof= 1 3"`
}

View File

@ -18,7 +18,7 @@ type MiniostorageCredentialResp struct {
type MinioUploadFileReq struct {
OperationID string `form:"operationID" binding:"required"`
FileType int `form:"fileType" binding:"required"`
FileType int `form:"fileType" binding:"required"`
}
type MinioUploadFile struct {
@ -36,12 +36,12 @@ type MinioUploadFileResp struct {
type UploadUpdateAppReq struct {
OperationID string `form:"operationID" binding:"required"`
Type int `form:"type" binding:"required"`
Version string `form:"version" binding:"required"`
File *multipart.FileHeader `form:"file" binding:"required"`
Type int `form:"type" binding:"required"`
Version string `form:"version" binding:"required"`
File *multipart.FileHeader `form:"file" binding:"required"`
Yaml *multipart.FileHeader `form:"yaml"`
ForceUpdate bool `form:"forceUpdate"`
UpdateLog string `form:"updateLog" binding:"required"`
UpdateLog string `form:"updateLog" binding:"required"`
}
type UploadUpdateAppResp struct {
@ -49,8 +49,8 @@ type UploadUpdateAppResp struct {
type GetDownloadURLReq struct {
OperationID string `json:"operationID" binding:"required"`
Type int `json:"type" binding:"required"`
Version string `json:"version" binding:"required"`
Type int `json:"type" binding:"required"`
Version string `json:"version" binding:"required"`
}
type GetDownloadURLResp struct {
@ -101,15 +101,15 @@ type GetRTCInvitationInfoStartAppResp struct {
*/
type FcmUpdateTokenReq struct {
OperationID string `json:"operationID" binding:"required"`
Platform int `json:"platform" binding:"required,min=1,max=2"` //only for ios + android
FcmToken string `json:"fcmToken" binding:"required"`
Platform int `json:"platform" binding:"required,min=1,max=2"` //only for ios + android
FcmToken string `json:"fcmToken" binding:"required"`
}
type FcmUpdateTokenResp struct {
}
type SetAppBadgeReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
AppUnreadCount int32 `json:"appUnreadCount"`
}

View File

@ -3,8 +3,9 @@ package cmd
import (
"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/OpenIMSDK/Open-IM-Server/pkg/common/constant"
)
type MsgGatewayCmd struct {

View File

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

View File

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

View File

@ -3,10 +3,11 @@ package cmd
import (
"fmt"
"github.com/spf13/cobra"
"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/log"
"github.com/spf13/cobra"
)
type RootCmd struct {

View File

@ -3,10 +3,11 @@ package cmd
import (
"errors"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
)
type RpcCmd struct {
@ -26,7 +27,10 @@ func (a *RpcCmd) Exec() error {
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 {
return errors.New("port is required")
}

View File

@ -303,6 +303,15 @@ type notification struct {
}
func GetServiceNames() []string {
return []string{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}
return []string{
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"
"runtime"
"gopkg.in/yaml.v3"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gopkg.in/yaml.v3"
)
var (

View File

@ -125,7 +125,8 @@ const (
SingleTerminalLogin = 2
//The web side can be online at the same time, and the other side can only log in at one end
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
//The PC terminal can be online at the same time,but other terminal only one of the endpoints can login
PCAndOther = 5

View File

@ -8,7 +8,11 @@ import (
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
for _, blackDB := range blackDBs {
userIDs = append(userIDs, blackDB.BlockUserID)

View File

@ -16,7 +16,11 @@ func FriendPb2DB(friend *sdkws.FriendInfo) *relation.FriendModel {
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{}}
utils.CopyStructFields(pbfriend, friendDB)
users, err := getUsers(ctx, []string{friendDB.FriendUserID})
@ -31,7 +35,11 @@ func FriendDB2Pb(ctx context.Context, friendDB *relation.FriendModel, getUsers f
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
for _, friendDB := range friendsDB {
userID = append(userID, friendDB.FriendUserID)
@ -53,7 +61,11 @@ func FriendsDB2Pb(ctx context.Context, friendsDB []*relation.FriendModel, getUse
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{})
for _, friendRequest := range friendRequests {
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{
GroupInfo: Db2PbGroupInfo(m, ownerUserID, memberCount),
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{
UserInfo: user,
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{
GroupID: groupID,
GroupMemberNumber: groupMemberNumber,

View File

@ -4,9 +4,10 @@ import (
"context"
"time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
)
const (
@ -31,7 +32,11 @@ type BlackCacheRedis struct {
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)
return &BlackCacheRedis{
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) {
return getCache(ctx, b.rcClient, b.getBlackIDsKey(userID), b.expireTime, func(ctx context.Context) ([]string, error) {
return b.blackDB.FindBlackUserIDs(ctx, userID)
})
return getCache(
ctx,
b.rcClient,
b.getBlackIDsKey(userID),
b.expireTime,
func(ctx context.Context) ([]string, error) {
return b.blackDB.FindBlackUserIDs(ctx, userID)
},
)
}
func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) BlackCache {

View File

@ -7,11 +7,12 @@ import (
"strings"
"time"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation"
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/redis/go-redis/v9"
)
const (
@ -42,7 +43,11 @@ type ConversationCache interface {
DelConvsersations(ownerUserID string, conversationIDs ...string) ConversationCache
DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache
// 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
GetUserAllConversations(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error)
// get user conversation recv msg from msgCache
@ -58,13 +63,25 @@ type ConversationCache interface {
GetUserAllHasReadSeqs(ctx context.Context, ownerUserID string) (map[string]int64, error)
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
}
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)
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 {
@ -74,13 +91,27 @@ type ConversationRedisCache struct {
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)
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 {
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 {
@ -108,9 +139,15 @@ func (c *ConversationRedisCache) getConversationHasReadSeqKey(ownerUserID, conve
}
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 c.conversationDB.FindUserIDAllConversationID(ctx, ownerUserID)
})
return getCache(
ctx,
c.rcClient,
c.getConversationIDsKey(ownerUserID),
c.expireTime,
func(ctx context.Context) ([]string, error) {
return c.conversationDB.FindUserIDAllConversationID(ctx, ownerUserID)
},
)
}
func (c *ConversationRedisCache) DelConversationIDs(userIDs ...string) ConversationCache {
@ -127,17 +164,26 @@ func (c *ConversationRedisCache) getUserConversationIDsHashKey(ownerUserID strin
return conversationIDsHashKey + ownerUserID
}
func (c *ConversationRedisCache) GetUserConversationIDsHash(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)
if err != nil {
return 0, err
}
utils.Sort(conversationIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(conversationIDs, ";"))[0:8], 16)
return bi.Uint64(), nil
})
func (c *ConversationRedisCache) GetUserConversationIDsHash(
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)
if err != nil {
return 0, err
}
utils.Sort(conversationIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(conversationIDs, ";"))[0:8], 16)
return bi.Uint64(), nil
},
)
}
func (c *ConversationRedisCache) DelUserConversationIDsHash(ownerUserIDs ...string) ConversationCache {
@ -150,10 +196,19 @@ func (c *ConversationRedisCache) DelUserConversationIDsHash(ownerUserIDs ...stri
return cache
}
func (c *ConversationRedisCache) GetConversation(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)
})
func (c *ConversationRedisCache) GetConversation(
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)
},
)
}
func (c *ConversationRedisCache) DelConvsersations(ownerUserID string, convsersationIDs ...string) ConversationCache {
@ -166,7 +221,10 @@ func (c *ConversationRedisCache) DelConvsersations(ownerUserID string, convsersa
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)
for _i, _key := range keys {
if _key == key {
@ -176,17 +234,31 @@ func (c *ConversationRedisCache) getConversationIndex(convsation *relationTb.Con
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
for _, conversarionID := range conversationIDs {
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 c.conversationDB.Find(ctx, ownerUserID, conversationIDs)
})
return batchGetCache(
ctx,
c.rcClient,
keys,
c.expireTime,
c.getConversationIndex,
func(ctx context.Context) ([]*relationTb.ConversationModel, error) {
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)
if err != nil {
return nil, err
@ -195,21 +267,46 @@ func (c *ConversationRedisCache) GetUserAllConversations(ctx context.Context, ow
for _, conversarionID := range conversationIDs {
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 c.conversationDB.FindUserIDAllConversations(ctx, ownerUserID)
})
return batchGetCache(
ctx,
c.rcClient,
keys,
c.expireTime,
c.getConversationIndex,
func(ctx context.Context) ([]*relationTb.ConversationModel, error) {
return c.conversationDB.FindUserIDAllConversations(ctx, ownerUserID)
},
)
}
func (c *ConversationRedisCache) GetUserRecvMsgOpt(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)
})
func (c *ConversationRedisCache) GetUserRecvMsgOpt(
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)
},
)
}
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDs(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)
})
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDs(
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)
},
)
}
func (c *ConversationRedisCache) DelUsersConversation(conversationID string, ownerUserIDs ...string) ConversationCache {
@ -234,17 +331,26 @@ func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDs(groupID st
return cache
}
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDsHash(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)
if err != nil {
return 0, err
}
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
return bi.Uint64(), nil
})
func (c *ConversationRedisCache) GetSuperGroupRecvMsgNotNotifyUserIDsHash(
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)
if err != nil {
return 0, err
}
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
return bi.Uint64(), nil
},
)
}
func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDsHash(groupID string) ConversationCache {
@ -253,7 +359,10 @@ func (c *ConversationRedisCache) DelSuperGroupRecvMsgNotNotifyUserIDsHash(groupI
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 {
if _conversationID == conversationID {
return _i, nil
@ -262,7 +371,10 @@ func (c *ConversationRedisCache) getUserAllHasReadSeqsIndex(conversationID strin
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)
if err != nil {
return nil, err
@ -271,12 +383,23 @@ func (c *ConversationRedisCache) GetUserAllHasReadSeqs(ctx context.Context, owne
for _, conversarionID := range conversationIDs {
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 c.conversationDB.GetUserAllHasReadSeqs(ctx, ownerUserID)
})
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)
},
)
}
func (c *ConversationRedisCache) DelUserAllHasReadSeqs(ownerUserID string, conversationIDs ...string) ConversationCache {
func (c *ConversationRedisCache) DelUserAllHasReadSeqs(
ownerUserID string,
conversationIDs ...string,
) ConversationCache {
cache := c.NewCache()
for _, conversationID := range conversationIDs {
cache.AddKeys(c.getConversationHasReadSeqKey(ownerUserID, conversationID))
@ -284,7 +407,10 @@ func (c *ConversationRedisCache) DelUserAllHasReadSeqs(ownerUserID string, conve
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")
}

View File

@ -4,9 +4,10 @@ import (
"context"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
)
const (
@ -17,7 +18,13 @@ const (
type ExtendMsgSetCache interface {
metaCache
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
}
@ -28,7 +35,11 @@ type ExtendMsgSetCacheRedis struct {
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)
return &ExtendMsgSetCacheRedis{
metaCache: NewMetaCacheRedis(rcClient),
@ -51,10 +62,22 @@ func (e *ExtendMsgSetCacheRedis) getKey(clientMsgID string) string {
return extendMsgCache + clientMsgID
}
func (e *ExtendMsgSetCacheRedis) GetExtendMsg(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)
})
func (e *ExtendMsgSetCacheRedis) GetExtendMsg(
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)
},
)
}
func (e *ExtendMsgSetCacheRedis) DelExtendMsg(clientMsgID string) ExtendMsgSetCache {

View File

@ -4,10 +4,11 @@ import (
"context"
"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/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 (
@ -37,7 +38,11 @@ type FriendCacheRedis struct {
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)
return &FriendCacheRedis{
metaCache: NewMetaCacheRedis(rcClient),
@ -48,7 +53,12 @@ func NewFriendCacheRedis(rdb redis.UniversalClient, friendDB relationTb.FriendMo
}
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 {
@ -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) {
return getCache(ctx, f.rcClient, f.getFriendIDsKey(ownerUserID), f.expireTime, func(ctx context.Context) ([]string, error) {
return f.friendDB.FindFriendUserIDs(ctx, ownerUserID)
})
return getCache(
ctx,
f.rcClient,
f.getFriendIDsKey(ownerUserID),
f.expireTime,
func(ctx context.Context) ([]string, error) {
return f.friendDB.FindFriendUserIDs(ctx, ownerUserID)
},
)
}
func (f *FriendCacheRedis) DelFriendIDs(ownerUserID ...string) FriendCache {
@ -80,7 +96,10 @@ func (f *FriendCacheRedis) DelFriendIDs(ownerUserID ...string) FriendCache {
}
// 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)
if err != nil {
return nil, err
@ -103,10 +122,19 @@ func (f *FriendCacheRedis) DelTwoWayFriendIDs(ctx context.Context, ownerUserID s
return new
}
func (f *FriendCacheRedis) GetFriend(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)
})
func (f *FriendCacheRedis) GetFriend(
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)
},
)
}
func (f *FriendCacheRedis) DelFriend(ownerUserID, friendUserID string) FriendCache {

View File

@ -6,11 +6,12 @@ import (
"strings"
"time"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
unrelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
)
const (
@ -49,10 +50,22 @@ type GroupCache interface {
GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error)
DelJoinedGroupID(userID ...string) GroupCache
GetGroupMemberInfo(ctx context.Context, groupID, userID string) (groupMember *relationTb.GroupMemberModel, err error)
GetGroupMembersInfo(ctx context.Context, groupID string, userID []string) (groupMembers []*relationTb.GroupMemberModel, err error)
GetGroupMemberInfo(
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)
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
@ -70,7 +83,14 @@ type GroupCacheRedis struct {
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)
return &GroupCacheRedis{rcClient: rcClient, expireTime: groupExpireTime,
groupDB: groupDB, groupMemberDB: groupMemberDB, groupRequestDB: groupRequestDB,
@ -79,7 +99,15 @@ func NewGroupCacheRedis(rdb redis.UniversalClient, groupDB relationTb.GroupModel
}
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 {
@ -135,20 +163,36 @@ func (g *GroupCacheRedis) GetGroupMemberIndex(groupMember *relationTb.GroupMembe
}
// / 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
for _, group := range groupIDs {
keys = append(keys, g.getGroupInfoKey(group))
}
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, g.GetGroupIndex, func(ctx context.Context) ([]*relationTb.GroupModel, error) {
return g.groupDB.Find(ctx, groupIDs)
})
return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
g.GetGroupIndex,
func(ctx context.Context) ([]*relationTb.GroupModel, error) {
return g.groupDB.Find(ctx, groupIDs)
},
)
}
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 g.groupDB.Take(ctx, groupID)
})
return getCache(
ctx,
g.rcClient,
g.getGroupInfoKey(groupID),
g.expireTime,
func(ctx context.Context) (*relationTb.GroupModel, error) {
return g.groupDB.Take(ctx, groupID)
},
)
}
func (g *GroupCacheRedis) DelGroupsInfo(groupIDs ...string) GroupCache {
@ -161,31 +205,50 @@ func (g *GroupCacheRedis) DelGroupsInfo(groupIDs ...string) GroupCache {
return new
}
func (g *GroupCacheRedis) GetJoinedSuperGroupIDs(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)
if err != nil {
return nil, err
}
return userGroup.GroupIDs, nil
})
func (g *GroupCacheRedis) GetJoinedSuperGroupIDs(
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)
if err != nil {
return nil, err
}
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
for _, group := range groupIDs {
keys = append(keys, g.getSuperGroupMemberIDsKey(group))
}
return batchGetCache(ctx, g.rcClient, keys, g.expireTime, func(model *unrelationTb.SuperGroupModel, keys []string) (int, error) {
for i, key := range keys {
if g.getSuperGroupMemberIDsKey(model.GroupID) == key {
return i, nil
return batchGetCache(
ctx,
g.rcClient,
keys,
g.expireTime,
func(model *unrelationTb.SuperGroupModel, keys []string) (int, error) {
for i, key := range keys {
if g.getSuperGroupMemberIDsKey(model.GroupID) == key {
return i, nil
}
}
}
return 0, errIndex
}, func(ctx context.Context) ([]*unrelationTb.SuperGroupModel, error) {
return g.mongoDB.FindSuperGroup(ctx, groupIDs)
})
return 0, errIndex
},
func(ctx context.Context) ([]*unrelationTb.SuperGroupModel, error) {
return g.mongoDB.FindSuperGroup(ctx, groupIDs)
},
)
}
// userJoinSuperGroup
@ -211,19 +274,28 @@ func (g *GroupCacheRedis) DelSuperGroupMemberIDs(groupIDs ...string) GroupCache
// groupMembersHash
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) {
userIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil {
return 0, err
}
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
return bi.Uint64(), nil
})
return getCache(
ctx,
g.rcClient,
g.getGroupMembersHashKey(groupID),
g.expireTime,
func(ctx context.Context) (uint64, error) {
userIDs, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil {
return 0, err
}
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
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)
for _, groupID := range groupIDs {
hash, err := g.GetGroupMembersHash(ctx, groupID)
@ -247,9 +319,15 @@ func (g *GroupCacheRedis) DelGroupMembersHash(groupID string) GroupCache {
// groupMemberIDs
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 g.groupMemberDB.FindMemberUserID(ctx, groupID)
})
return getCache(
ctx,
g.rcClient,
g.getGroupMemberIDsKey(groupID),
g.expireTime,
func(ctx context.Context) ([]string, error) {
return g.groupMemberDB.FindMemberUserID(ctx, groupID)
},
)
}
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) {
return getCache(ctx, g.rcClient, g.getJoinedGroupsKey(userID), g.expireTime, func(ctx context.Context) ([]string, error) {
return g.groupMemberDB.FindUserJoinedGroupID(ctx, userID)
})
return getCache(
ctx,
g.rcClient,
g.getJoinedGroupsKey(userID),
g.expireTime,
func(ctx context.Context) ([]string, error) {
return g.groupMemberDB.FindUserJoinedGroupID(ctx, userID)
},
)
}
func (g *GroupCacheRedis) DelJoinedGroupID(userIDs ...string) GroupCache {
@ -286,23 +370,48 @@ func (g *GroupCacheRedis) DelJoinedGroupID(userIDs ...string) GroupCache {
return cache
}
func (g *GroupCacheRedis) GetGroupMemberInfo(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)
})
func (g *GroupCacheRedis) GetGroupMemberInfo(
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)
},
)
}
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
for _, userID := range userIDs {
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 g.groupMemberDB.Find(ctx, []string{groupID}, userIDs, nil)
})
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)
},
)
}
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)
if err != nil {
return 0, nil, err
@ -316,7 +425,10 @@ func (g *GroupCacheRedis) GetGroupMembersPage(ctx context.Context, groupID strin
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)
if err != nil {
return nil, err
@ -324,7 +436,10 @@ func (g *GroupCacheRedis) GetAllGroupMembersInfo(ctx context.Context, groupID st
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)
if err != nil {
return nil, err
@ -333,9 +448,16 @@ func (g *GroupCacheRedis) GetAllGroupMemberInfo(ctx context.Context, groupID str
for _, groupMemberID := range groupMemberIDs {
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 g.groupMemberDB.Find(ctx, []string{groupID}, groupMemberIDs, nil)
})
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)
},
)
}
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) {
return getCache(ctx, g.rcClient, g.getGroupMemberNumKey(groupID), g.expireTime, func(ctx context.Context) (int64, error) {
return g.groupMemberDB.TakeGroupMemberNum(ctx, groupID)
})
return getCache(
ctx,
g.rcClient,
g.getGroupMemberNumKey(groupID),
g.expireTime,
func(ctx context.Context) (int64, error) {
return g.groupMemberDB.TakeGroupMemberNum(ctx, groupID)
},
)
}
func (g *GroupCacheRedis) DelGroupsMemberNum(groupID ...string) GroupCache {

View File

@ -6,10 +6,11 @@ import (
"fmt"
"time"
"github.com/redis/go-redis/v9"
"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/errs"
"github.com/redis/go-redis/v9"
)
func NewRedis() (redis.UniversalClient, error) {

View File

@ -7,10 +7,11 @@ import (
"fmt"
"time"
"github.com/dtm-labs/rockscache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/dtm-labs/rockscache"
)
const (
@ -48,7 +49,14 @@ func (m *metaCacheRedis) ExecDel(ctx context.Context) error {
for {
if err := m.rcClient.TagAsDeletedBatch2(ctx, m.keys); err != nil {
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)
return err
}
@ -84,7 +92,13 @@ func GetDefaultOpt() rockscache.Options {
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 write bool
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
}
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) {
values := make(map[int]string)
tArrays, err := fn(ctx)
@ -153,7 +174,14 @@ func batchGetCache[T any](ctx context.Context, rcClient *rockscache.Client, keys
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) {
tArrays, err := fn(ctx)
if err != nil {

View File

@ -5,16 +5,18 @@ import (
"strconv"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"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/constant"
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/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/gogo/protobuf/jsonpb"
"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)
SetTokenMapByUidPid(ctx context.Context, userID string, platformID int, m map[string]int) 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)
UserDeleteMsgs(ctx context.Context, conversationID string, seqs []int64, userID string) error
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)
GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]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)
SetMessageTypeKeyValue(ctx context.Context, clientMsgID string, sessionType int32, typeKey, value 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
}
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())
}
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())
}
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()
for _, v := range items {
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())
}
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.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())
}
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.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.getHasReadSeqKey(conversationID, userID)
})
@ -296,7 +338,11 @@ func (c *msgCache) allMessageCacheKey(conversationID string) string {
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()
for _, v := range seqs {
//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()
if err != nil {
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 {
@ -499,8 +555,17 @@ func (c *msgCache) GetSendMsgStatus(ctx context.Context, id string) (int32, erro
return int32(result), errs.Wrap(err)
}
func (c *msgCache) SetFcmToken(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) SetFcmToken(
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) {
@ -556,22 +621,46 @@ func (c *msgCache) JudgeMessageReactionExist(ctx context.Context, clientMsgID st
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())
}
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())
}
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())
}
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())
}
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())
}

View File

@ -4,9 +4,10 @@ import (
"context"
"time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
)
const (
@ -32,7 +33,11 @@ type UserCacheRedis struct {
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)
return &UserCacheRedis{
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) {
return getCache(ctx, u.rcClient, u.getUserInfoKey(userID), u.expireTime, func(ctx context.Context) (*relationTb.UserModel, error) {
return u.userDB.Take(ctx, userID)
})
return getCache(
ctx,
u.rcClient,
u.getUserInfoKey(userID),
u.expireTime,
func(ctx context.Context) (*relationTb.UserModel, error) {
return u.userDB.Take(ctx, userID)
},
)
}
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 {
keys = append(keys, u.getUserInfoKey(userID))
}
return batchGetCache(ctx, u.rcClient, keys, u.expireTime, func(user *relationTb.UserModel, keys []string) (int, error) {
for i, key := range keys {
if key == u.getUserInfoKey(user.UserID) {
return i, nil
return batchGetCache(
ctx,
u.rcClient,
keys,
u.expireTime,
func(user *relationTb.UserModel, keys []string) (int, error) {
for i, key := range keys {
if key == u.getUserInfoKey(user.UserID) {
return i, nil
}
}
}
return 0, errIndex
}, func(ctx context.Context) ([]*relationTb.UserModel, error) {
return u.userDB.Find(ctx, userIDs)
})
return 0, errIndex
},
func(ctx context.Context) ([]*relationTb.UserModel, error) {
return u.userDB.Find(ctx, userIDs)
},
)
}
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) {
return getCache(ctx, u.rcClient, u.getUserGlobalRecvMsgOptKey(userID), u.expireTime, func(ctx context.Context) (int, error) {
return u.userDB.GetUserGlobalRecvMsgOpt(ctx, userID)
})
return getCache(
ctx,
u.rcClient,
u.getUserGlobalRecvMsgOptKey(userID),
u.expireTime,
func(ctx context.Context) (int, error) {
return u.userDB.GetUserGlobalRecvMsgOpt(ctx, userID)
},
)
}
func (u *UserCacheRedis) DelUsersGlobalRecvMsgOpt(userIDs ...string) UserCache {

View File

@ -3,11 +3,12 @@ package controller
import (
"context"
"github.com/golang-jwt/jwt/v4"
"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/tokenverify"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/golang-jwt/jwt/v4"
)
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)
}

View File

@ -15,7 +15,11 @@ type BlackDatabase interface {
// Delete 删除黑名单
Delete(ctx context.Context, blacks []*relation.BlackModel) (err error)
// 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)
// CheckIn 检查user2是否在user1的黑名单列表中(inUser1Blacks==true) 检查user1是否在user2的黑名单列表中(inUser2Blacks==true)
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 获取黑名单列表
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)
}
// 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)
if err != nil {
return

View File

@ -7,7 +7,11 @@ import (
type ChatLogDatabase interface {
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 {
@ -22,6 +26,10 @@ func (c *chatLogDatabase) CreateChatLog(msg *pbMsg.MsgDataToMQ) error {
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)
}

View File

@ -13,13 +13,22 @@ import (
type ConversationDatabase interface {
//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(ctx context.Context, conversations []*relationTb.ConversationModel) error
//SyncPeerUserPrivateConversation 同步对端私聊会话内部保证事务操作
SyncPeerUserPrivateConversationTx(ctx context.Context, conversation []*relationTb.ConversationModel) error
//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(ctx context.Context, groupID string) ([]string, error)
//GetUserAllConversation 获取一个用户在服务器上所有的会话
@ -27,16 +36,28 @@ type ConversationDatabase interface {
//SetUserConversations 设置用户多个会话属性,如果会话不存在则创建,否则更新,内部保证原子性
SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error
//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
GetConversationIDs(ctx context.Context, userID string) ([]string, error)
GetUserConversationIDsHash(ctx context.Context, ownerUserID string) (hash uint64, err error)
GetAllConversationIDs(ctx context.Context) ([]string, 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{
conversationDB: conversation,
cache: cache,
@ -50,7 +71,12 @@ type conversationDatabase struct {
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()
if err := c.tx.Transaction(func(tx any) error {
conversationTx := c.conversationDB.NewTx(tx)
@ -96,7 +122,12 @@ func (c *conversationDatabase) SetUsersConversationFiledTx(ctx context.Context,
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)
if err != nil {
return err
@ -104,7 +135,10 @@ func (c *conversationDatabase) UpdateUsersConversationFiled(ctx context.Context,
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 {
return err
}
@ -117,7 +151,10 @@ func (c *conversationDatabase) CreateConversation(ctx context.Context, conversat
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()
if err := c.tx.Transaction(func(tx any) error {
conversationTx := c.conversationDB.NewTx(tx)
@ -153,19 +190,34 @@ func (c *conversationDatabase) SyncPeerUserPrivateConversationTx(ctx context.Con
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)
}
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)
}
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)
}
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()
if err := c.tx.Transaction(func(tx any) error {
var conversationIDs []string
@ -215,7 +267,11 @@ func (c *conversationDatabase) FindRecvMsgNotNotifyUserIDs(ctx context.Context,
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()
conversationID := utils.GetConversationIDBySessionType(constant.SuperGroupChatType, groupID)
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)
}
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)
}
@ -263,10 +322,16 @@ func (c *conversationDatabase) GetAllConversationIDs(ctx context.Context) ([]str
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)
}
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)
}

View File

@ -11,12 +11,46 @@ import (
// for mongoDB
type ExtendMsgDatabase interface {
CreateExtendMsgSet(ctx context.Context, set *unRelationTb.ExtendMsgSetModel) error
GetAllExtendMsgSet(ctx context.Context, ID string, opts *unRelationTb.GetAllExtendMsgSetOpts) (sets []*unRelationTb.ExtendMsgSetModel, 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)
GetAllExtendMsgSet(
ctx context.Context,
ID string,
opts *unRelationTb.GetAllExtendMsgSetOpts,
) (sets []*unRelationTb.ExtendMsgSetModel, 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 {
@ -25,7 +59,11 @@ type extendMsgDatabase struct {
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}
}
@ -33,26 +71,74 @@ func (e *extendMsgDatabase) CreateExtendMsgSet(ctx context.Context, set *unRelat
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)
}
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)
}
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)
}
func (e *extendMsgDatabase) InsertOrUpdateReactionExtendMsgSet(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) InsertOrUpdateReactionExtendMsgSet(
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 {
return e.database.DeleteReactionExtendMsgSet(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 {
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)
}

View File

@ -4,6 +4,8 @@ import (
"context"
"time"
"gorm.io/gorm"
"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/table/relation"
@ -11,7 +13,6 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"gorm.io/gorm"
)
type FriendDatabase interface {
@ -30,15 +31,35 @@ type FriendDatabase interface {
// 更新好友备注
UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error)
// 获取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在哪些人的好友列表中
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)
}
@ -49,12 +70,20 @@ type friendDatabase struct {
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}
}
// 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)
if err != nil {
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 {
_, err := f.friendRequest.NewTx(tx).Take(ctx, fromUserID, toUserID)
//有db错误
@ -96,7 +130,12 @@ func (f *friendDatabase) AddFriendRequest(ctx context.Context, fromUserID, toUse
}
// (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()
if err := f.tx.Transaction(func(tx any) error {
//先find 找出重复的 去掉重复的
@ -142,7 +181,10 @@ func (f *friendDatabase) BecomeFriends(ctx context.Context, ownerUserID string,
}
// 拒绝好友申请 (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)
if err != nil {
return err
@ -160,7 +202,10 @@ func (f *friendDatabase) RefuseFriendRequest(ctx context.Context, friendRequest
}
// 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 {
fr, err := f.friendRequest.NewTx(tx).Take(ctx, friendRequest.FromUserID, friendRequest.ToUserID)
if err != nil {
@ -185,10 +230,26 @@ func (f *friendDatabase) AgreeFriendRequest(ctx context.Context, friendRequest *
}))
var adds []*relation.FriendModel
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 { // 好友 - 自己
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 err := f.friend.NewTx(tx).Create(ctx, adds); err != nil {
@ -216,27 +277,47 @@ func (f *friendDatabase) UpdateRemark(ctx context.Context, ownerUserID, friendUs
}
// 获取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)
}
// 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)
}
// 获取我发出去的好友申请 无结果不返回错误
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)
}
// 获取我收到的的好友申请 无结果不返回错误
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)
}
// 获取某人指定好友的信息 如果有好友不存在,也返回错误
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)
if err != nil {
return
@ -247,6 +328,9 @@ func (f *friendDatabase) FindFriendsWithError(ctx context.Context, ownerUserID s
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)
}

View File

@ -4,6 +4,11 @@ import (
"context"
"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/db/cache"
"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/unrelation"
"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 {
@ -23,33 +24,82 @@ type GroupDatabase interface {
CreateGroup(ctx context.Context, groups []*relationTb.GroupModel, groupMembers []*relationTb.GroupMemberModel) error
TakeGroup(ctx context.Context, groupID string) (group *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
DismissGroup(ctx context.Context, groupID string, deleteMember bool) error // 解散群,并删除群成员
GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error)
// 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)
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)
FindGroupMemberNum(ctx context.Context, groupID string) (uint32, error)
FindUserManagedGroupID(ctx context.Context, userID string) (groupIDs []string, err error)
PageGroupRequest(ctx context.Context, groupIDs []string, pageNumber, showNumber int32) (uint32, []*relationTb.GroupRequestModel, 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
PageGroupRequest(
ctx context.Context,
groupIDs []string,
pageNumber, showNumber int32,
) (uint32, []*relationTb.GroupRequestModel, 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
MapGroupMemberUserID(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, 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
UpdateGroupMembers(ctx context.Context, data []*relationTb.BatchUpdateGroupMember) error
// GroupRequest
CreateGroupRequest(ctx context.Context, requests []*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
FindSuperGroup(ctx context.Context, groupIDs []string) ([]*unRelationTb.SuperGroupModel, 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.NewMongo(database.Client()),
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
}
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()
if err := g.tx.Transaction(func(tx any) error {
if len(groups) > 0 {
@ -162,7 +223,11 @@ func (g *groupDatabase) FindGroup(ctx context.Context, groupIDs []string) (group
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)
}
@ -197,7 +262,11 @@ func (g *groupDatabase) DismissGroup(ctx context.Context, groupID string, delete
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)
}
@ -209,11 +278,20 @@ func (g *groupDatabase) FindUserManagedGroupID(ctx context.Context, userID strin
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)
}
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 {
for _, groupID := range groupIDs {
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)
}
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)
if err != nil {
return 0, nil, err
@ -242,7 +324,11 @@ func (g *groupDatabase) PageGetJoinGroup(ctx context.Context, userID string, pag
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)
if err != nil {
return 0, nil, err
@ -258,11 +344,25 @@ func (g *groupDatabase) PageGetGroupMember(ctx context.Context, groupID string,
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)
}
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()
if err := g.tx.Transaction(func(tx any) error {
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 {
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)
}
@ -304,7 +412,12 @@ func (g *groupDatabase) MapGroupMemberNum(ctx context.Context, groupIDs []string
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 {
rowsAffected, err := g.groupMemberDB.NewTx(tx).UpdateRoleLevel(ctx, groupID, oldOwnerUserID, roleLevel)
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)
}
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 {
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)
}
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)
}
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...)
}

View File

@ -19,10 +19,11 @@ import (
"context"
"errors"
"go.mongodb.org/mongo-driver/mongo"
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/utils"
"go.mongodb.org/mongo-driver/mongo"
)
const (
@ -41,12 +42,26 @@ type CommonMsgDatabase interface {
DeleteMessagesFromCache(ctx context.Context, conversationID string, seqs []int64) error
DelUserDeleteMsgsList(ctx context.Context, conversationID string, seqs []int64)
// 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中写扩散消息
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里面的消息
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)
DeleteConversationMsgsAndSetMinSeq(ctx context.Context, conversationID string, remainTime int64) error
// 用户根据seq删除消息
@ -73,7 +88,10 @@ type CommonMsgDatabase interface {
UserSetHasReadSeqs(ctx context.Context, userID string, hasReadSeqs map[string]int64) 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
GetSendMsgStatus(ctx context.Context, id string) (int32, error)
@ -86,13 +104,38 @@ type CommonMsgDatabase interface {
// modify
JudgeMessageReactionExist(ctx context.Context, clientMsgID string, sessionType int32) (bool, 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)
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
SetMessageReactionExpire(
ctx context.Context,
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)
GetOneMessageAllReactionList(ctx context.Context, clientMsgID string, sessionType int32) (map[string]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 {
@ -130,16 +173,32 @@ func (db *commonMsgDatabase) MsgToMQ(ctx context.Context, key string, msg2mq *sd
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 {
_, _, 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 nil
}
func (db *commonMsgDatabase) MsgToPushMQ(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})
func (db *commonMsgDatabase) MsgToPushMQ(
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 {
log.ZError(ctx, "MsgToPushMQ", err, "key", key, "msg2mq", msg2mq)
return 0, 0, err
@ -147,15 +206,30 @@ func (db *commonMsgDatabase) MsgToPushMQ(ctx context.Context, key, conversationI
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 {
_, _, 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 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 {
return nil
}
@ -256,7 +330,12 @@ func (db *commonMsgDatabase) BatchInsertBlock(ctx context.Context, conversationI
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 {
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)
}
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)
}
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) {
var indexes []int64
for _, seq := range seqs {
@ -329,7 +418,11 @@ func (db *commonMsgDatabase) DelUserDeleteMsgsList(ctx context.Context, conversa
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)
if err != nil && errs.Unwrap(err) != redis.Nil {
prome.Inc(prome.SeqGetFailedCounter)
@ -376,7 +469,11 @@ func (db *commonMsgDatabase) BatchInsertChat2Cache(ctx context.Context, conversa
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) {
//log.ZDebug(ctx, "getMsgBySeqs", "docID", docID, "seqs", 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
}
// 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
// if delNums > 0 {
// newBeginSeq := rangeBegin - delNums
@ -428,7 +526,11 @@ func (db *commonMsgDatabase) getMsgBySeqs(ctx context.Context, userID, conversat
// 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)
for _, msg := range msgs {
if msg.IsRead {
@ -438,8 +540,25 @@ func (db *commonMsgDatabase) findMsgInfoBySeq(ctx context.Context, userID, docID
return msgs, err
}
func (db *commonMsgDatabase) getMsgBySeqsRange(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)
func (db *commonMsgDatabase) getMsgBySeqsRange(
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) {
log.ZDebug(ctx, "getMsgBySeqsRange", "docID", docID, "seqs", 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
}
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)
if err != nil && errs.Unwrap(err) != redis.Nil {
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 {
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 < maxSeq {
maxSeq = userMaxSeq
@ -526,7 +661,18 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
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
for i := 1; i <= cacheDelNum; {
newSeq := newBegin - int64(i)
@ -546,7 +692,15 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
if err != nil {
if err != redis.Nil {
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...)
@ -572,7 +726,12 @@ func (db *commonMsgDatabase) GetMsgBySeqsRange(ctx context.Context, userID strin
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)
if err != nil && errs.Unwrap(err) != redis.Nil {
return 0, 0, nil, err
@ -598,10 +757,33 @@ func (db *commonMsgDatabase) GetMsgBySeqs(ctx context.Context, userID string, co
if err != nil {
if err != redis.Nil {
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))
if len(failedSeqs) > 0 {
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
}
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 skip int64
minSeq, err := db.deleteMsgRecursion(ctx, conversationID, skip, &delStruct, remainTime)
@ -649,13 +835,26 @@ func (d *delMsgRecursionStruct) getSetMinSeq() int64 {
// seq 70
// set minSeq 21
// 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
msgDocModel, err := db.msgDocDatabase.GetMsgDocModelByIndex(ctx, conversationID, index, 1)
if err != nil || msgDocModel.DocID == "" {
if err != nil {
if err == unrelation.ErrMsgListNotExist {
log.ZDebug(ctx, "deleteMsgRecursion ErrMsgListNotExist", "conversationID", conversationID, "index:", index)
log.ZDebug(
ctx,
"deleteMsgRecursion ErrMsgListNotExist",
"conversationID",
conversationID,
"index:",
index,
)
} else {
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
}
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() {
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)
delStruct.delDocIDs = append(delStruct.delDocIDs, msgDocModel.DocID)
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
}
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 {
return err
}
@ -724,7 +939,12 @@ func (db *commonMsgDatabase) DeleteMsgsPhysicalBySeqs(ctx context.Context, conve
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)
if err != nil && errs.Unwrap(err) != redis.Nil {
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) {
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
@ -833,7 +1092,10 @@ func (db *commonMsgDatabase) GetSendMsgStatus(ctx context.Context, id string) (i
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)
if err != nil {
return
@ -849,11 +1111,17 @@ func (db *commonMsgDatabase) GetConversationMinMaxSeqInMongoAndCache(ctx context
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)
}
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)
if err != nil {
return
@ -867,35 +1135,83 @@ func (db *commonMsgDatabase) GetMinMaxSeqMongo(ctx context.Context, conversation
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
func (db *commonMsgDatabase) InsertOrUpdateReactionExtendMsgSet(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) InsertOrUpdateReactionExtendMsgSet(
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)
if err != nil {
return nil, err
@ -923,6 +1239,20 @@ func (db *commonMsgDatabase) GetExtendMsg(ctx context.Context, conversationID st
}, nil
}
func (db *commonMsgDatabase) DeleteReactionExtendMsgSet(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))
func (db *commonMsgDatabase) DeleteReactionExtendMsgSet(
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"
"go.mongodb.org/mongo-driver/bson"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
"go.mongodb.org/mongo-driver/bson"
)
func Test_BatchInsertChat2DB(t *testing.T) {
@ -193,7 +194,9 @@ func Test_FindBySeq(t *testing.T) {
}
db := GetDB()
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})
//if err != nil {
// t.Fatal(err)

View File

@ -15,13 +15,14 @@ import (
"strconv"
"time"
"github.com/google/uuid"
"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/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/third"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/google/uuid"
)
const (
@ -40,7 +41,13 @@ type S3Database interface {
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{
url: url,
obj: obj,
@ -207,7 +214,12 @@ func (c *s3Database) ApplyPut(ctx context.Context, req *third.ApplyPutReq) (*thi
}
t := md5.Sum(urlsJsonData)
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 {
return nil, err
}
@ -228,7 +240,10 @@ func (c *s3Database) GetPut(ctx context.Context, req *third.GetPutReq) (*third.G
if err != nil {
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 {
return nil, err
}

View File

@ -19,7 +19,13 @@ func NewThirdDatabase(cache cache.MsgModel) ThirdDatabase {
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)
}

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)
}
@ -138,6 +141,10 @@ func (u *userDatabase) CountTotal(ctx context.Context) (count int64, err error)
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)
}

View File

@ -9,11 +9,12 @@ import (
"net/url"
"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/pkg/credentials"
"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) {
@ -94,7 +95,13 @@ func (m *minioImpl) DataBucket() string {
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
if opt != nil {
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{})
if err != nil {
return nil, err

View File

@ -68,7 +68,13 @@ type Interface interface {
// DataBucket 永久存储的桶名
DataBucket() string
// 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(ctx context.Context, args *ApplyPutArgs) (string, error)
// GetObjectInfo 获取对象信息

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