chore: tools, pb replaced by public warehouse (#662)

* fix: StringValue When there are double quotes in the string value, serialization and deserialization fail

Signed-off-by: withchao <993506633@qq.com>

* test: StatusTemporaryRedirect -> StatusFound

Signed-off-by: withchao <993506633@qq.com>

* chore: pb a2r

Signed-off-by: withchao <993506633@qq.com>

* chore: replacement package

Signed-off-by: withchao <993506633@qq.com>

* chore: replacement package

Signed-off-by: withchao <993506633@qq.com>

* chore: replacement package

Signed-off-by: withchao <993506633@qq.com>

* fix: remove go mod replace

Signed-off-by: withchao <993506633@qq.com>

* fix: tools version

Signed-off-by: withchao <993506633@qq.com>

* fix: config.yaml

Signed-off-by: withchao <993506633@qq.com>

---------

Signed-off-by: withchao <993506633@qq.com>
This commit is contained in:
withchao
2023-07-25 20:13:32 +08:00
committed by GitHub
parent 166fb3ca62
commit 5f6b2b7f9d
255 changed files with 721 additions and 43133 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ import (
//"github.com/OpenIMSDK/Open-IM-Server/internal/msggateway".
"github.com/spf13/cobra"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/tools/constant"
)
type MsgGatewayCmd struct {
+5 -4
View File
@@ -16,12 +16,13 @@ package cmd
import (
"fmt"
config2 "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"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/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/log"
)
type RootCmd struct {
@@ -108,7 +109,7 @@ func (r *RootCmd) GetPrometheusPortFlag() int {
func (r *RootCmd) getConfFromCmdAndInit(cmdLines *cobra.Command) error {
configFolderPath, _ := cmdLines.Flags().GetString(constant.FlagConf)
fmt.Println("configFolderPath:", configFolderPath)
return config.InitConfig(configFolderPath)
return config2.InitConfig(configFolderPath)
}
func (r *RootCmd) Execute() error {
+2 -2
View File
@@ -20,8 +20,8 @@ import (
"github.com/spf13/cobra"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry"
"github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc"
"github.com/OpenIMSDK/tools/discoveryregistry"
"github.com/OpenIMSDK/tools/startrpc"
)
type RpcCmd struct {
-312
View File
@@ -1,312 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
_ "embed"
)
//go:embed version
var Version string
var Config config
type CallBackConfig struct {
Enable bool `yaml:"enable"`
CallbackTimeOut int `yaml:"timeout"`
CallbackFailedContinue *bool `yaml:"failedContinue"`
}
type NotificationConf struct {
IsSendMsg bool `yaml:"isSendMsg"`
ReliabilityLevel int `yaml:"reliabilityLevel"` // 1 online 2 persistent
UnreadCount bool `yaml:"unreadCount"`
OfflinePush POfflinePush `yaml:"offlinePush"`
}
type POfflinePush struct {
Enable bool `yaml:"enable"`
Title string `yaml:"title"`
Desc string `yaml:"desc"`
Ext string `yaml:"ext"`
}
type config struct {
Zookeeper struct {
Schema string `yaml:"schema"`
ZkAddr []string `yaml:"address"`
Username string `yaml:"username"`
Password string `yaml:"password"`
} `yaml:"zookeeper"`
Mysql struct {
Address []string `yaml:"address"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Database string `yaml:"database"`
MaxOpenConn int `yaml:"maxOpenConn"`
MaxIdleConn int `yaml:"maxIdleConn"`
MaxLifeTime int `yaml:"maxLifeTime"`
LogLevel int `yaml:"logLevel"`
SlowThreshold int `yaml:"slowThreshold"`
} `yaml:"mysql"`
Mongo struct {
Uri string `yaml:"uri"`
Address []string `yaml:"address"`
Database string `yaml:"database"`
Username string `yaml:"username"`
Password string `yaml:"password"`
MaxPoolSize int `yaml:"maxPoolSize"`
} `yaml:"mongo"`
Redis struct {
Address []string `yaml:"address"`
Username string `yaml:"username"`
Password string `yaml:"password"`
} `yaml:"redis"`
Kafka struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
Addr []string `yaml:"addr"`
LatestMsgToRedis struct {
Topic string `yaml:"topic"`
} `yaml:"latestMsgToRedis"`
MsgToMongo struct {
Topic string `yaml:"topic"`
} `yaml:"offlineMsgToMongo"`
MsgToPush struct {
Topic string `yaml:"topic"`
} `yaml:"msgToPush"`
ConsumerGroupID struct {
MsgToRedis string `yaml:"msgToRedis"`
MsgToMongo string `yaml:"msgToMongo"`
MsgToMySql string `yaml:"msgToMySql"`
MsgToPush string `yaml:"msgToPush"`
} `yaml:"consumerGroupID"`
} `yaml:"kafka"`
Rpc struct {
RegisterIP string `yaml:"registerIP"`
ListenIP string `yaml:"listenIP"`
} `yaml:"rpc"`
Api struct {
OpenImApiPort []int `yaml:"openImApiPort"`
ListenIP string `yaml:"listenIP"`
} `yaml:"api"`
Object struct {
Enable string `yaml:"enable"`
ApiURL string `yaml:"apiURL"`
Minio struct {
Bucket string `yaml:"bucket"`
Endpoint string `yaml:"endpoint"`
AccessKeyID string `yaml:"accessKeyID"`
SecretAccessKey string `yaml:"secretAccessKey"`
SessionToken string `yaml:"sessionToken"`
} `yaml:"minio"`
Cos struct {
BucketURL string `yaml:"bucketURL"`
SecretID string `yaml:"secretID"`
SecretKey string `yaml:"secretKey"`
SessionToken string `yaml:"sessionToken"`
} `yaml:"cos"`
Oss struct {
Endpoint string `yaml:"endpoint"`
Bucket string `yaml:"bucket"`
BucketURL string `yaml:"bucketURL"`
AccessKeyID string `yaml:"accessKeyID"`
AccessKeySecret string `yaml:"accessKeySecret"`
SessionToken string `yaml:"sessionToken"`
} `yaml:"oss"`
} `yaml:"object"`
RpcPort struct {
OpenImUserPort []int `yaml:"openImUserPort"`
OpenImFriendPort []int `yaml:"openImFriendPort"`
OpenImMessagePort []int `yaml:"openImMessagePort"`
OpenImMessageGatewayPort []int `yaml:"openImMessageGatewayPort"`
OpenImGroupPort []int `yaml:"openImGroupPort"`
OpenImAuthPort []int `yaml:"openImAuthPort"`
OpenImPushPort []int `yaml:"openImPushPort"`
OpenImConversationPort []int `yaml:"openImConversationPort"`
OpenImRtcPort []int `yaml:"openImRtcPort"`
OpenImThirdPort []int `yaml:"openImThirdPort"`
} `yaml:"rpcPort"`
RpcRegisterName struct {
OpenImUserName string `yaml:"openImUserName"`
OpenImFriendName string `yaml:"openImFriendName"`
OpenImMsgName string `yaml:"openImMsgName"`
OpenImPushName string `yaml:"openImPushName"`
OpenImMessageGatewayName string `yaml:"openImMessageGatewayName"`
OpenImGroupName string `yaml:"openImGroupName"`
OpenImAuthName string `yaml:"openImAuthName"`
OpenImConversationName string `yaml:"openImConversationName"`
OpenImThirdName string `yaml:"openImThirdName"`
} `yaml:"rpcRegisterName"`
Log struct {
StorageLocation string `yaml:"storageLocation"`
RotationTime int `yaml:"rotationTime"`
RemainRotationCount uint `yaml:"remainRotationCount"`
RemainLogLevel int `yaml:"remainLogLevel"`
IsStdout bool `yaml:"isStdout"`
IsJson bool `yaml:"isJson"`
WithStack bool `yaml:"withStack"`
} `yaml:"log"`
LongConnSvr struct {
OpenImWsPort []int `yaml:"openImWsPort"`
WebsocketMaxConnNum int `yaml:"websocketMaxConnNum"`
WebsocketMaxMsgLen int `yaml:"websocketMaxMsgLen"`
WebsocketTimeout int `yaml:"websocketTimeout"`
} `yaml:"longConnSvr"`
Push struct {
Enable string `yaml:"enable"`
GeTui struct {
PushUrl string `yaml:"pushUrl"`
AppKey string `yaml:"appKey"`
Intent string `yaml:"intent"`
MasterSecret string `yaml:"masterSecret"`
ChannelID string `yaml:"channelID"`
ChannelName string `yaml:"channelName"`
} `yaml:"geTui"`
Fcm struct {
ServiceAccount string `yaml:"serviceAccount"`
} `yaml:"fcm"`
Jpns struct {
AppKey string `yaml:"appKey"`
MasterSecret string `yaml:"masterSecret"`
PushUrl string `yaml:"pushUrl"`
PushIntent string `yaml:"pushIntent"`
} `yaml:"jpns"`
}
Manager struct {
UserID []string `yaml:"userID"`
Nickname []string `yaml:"nickname"`
} `yaml:"manager"`
MultiLoginPolicy int `yaml:"multiLoginPolicy"`
ChatPersistenceMysql bool `yaml:"chatPersistenceMysql"`
MsgCacheTimeout int `yaml:"msgCacheTimeout"`
GroupMessageHasReadReceiptEnable bool `yaml:"groupMessageHasReadReceiptEnable"`
SingleMessageHasReadReceiptEnable bool `yaml:"singleMessageHasReadReceiptEnable"`
RetainChatRecords int `yaml:"retainChatRecords"`
ChatRecordsClearTime string `yaml:"chatRecordsClearTime"`
MsgDestructTime string `yaml:"msgDestructTime"`
Secret string `yaml:"secret"`
TokenPolicy struct {
Expire int64 `yaml:"expire"`
} `yaml:"tokenPolicy"`
MessageVerify struct {
FriendVerify *bool `yaml:"friendVerify"`
} `yaml:"messageVerify"`
IOSPush struct {
PushSound string `yaml:"pushSound"`
BadgeCount bool `yaml:"badgeCount"`
Production bool `yaml:"production"`
} `yaml:"iosPush"`
Callback struct {
CallbackUrl string `yaml:"url"`
CallbackBeforeSendSingleMsg CallBackConfig `yaml:"beforeSendSingleMsg"`
CallbackAfterSendSingleMsg CallBackConfig `yaml:"afterSendSingleMsg"`
CallbackBeforeSendGroupMsg CallBackConfig `yaml:"beforeSendGroupMsg"`
CallbackAfterSendGroupMsg CallBackConfig `yaml:"afterSendGroupMsg"`
CallbackMsgModify CallBackConfig `yaml:"msgModify"`
CallbackUserOnline CallBackConfig `yaml:"userOnline"`
CallbackUserOffline CallBackConfig `yaml:"userOffline"`
CallbackUserKickOff CallBackConfig `yaml:"userKickOff"`
CallbackOfflinePush CallBackConfig `yaml:"offlinePush"`
CallbackOnlinePush CallBackConfig `yaml:"onlinePush"`
CallbackBeforeSuperGroupOnlinePush CallBackConfig `yaml:"superGroupOnlinePush"`
CallbackBeforeAddFriend CallBackConfig `yaml:"beforeAddFriend"`
CallbackBeforeCreateGroup CallBackConfig `yaml:"beforeCreateGroup"`
CallbackBeforeMemberJoinGroup CallBackConfig `yaml:"beforeMemberJoinGroup"`
CallbackBeforeSetGroupMemberInfo CallBackConfig `yaml:"beforeSetGroupMemberInfo"`
} `yaml:"callback"`
Prometheus struct {
Enable bool `yaml:"enable"`
UserPrometheusPort []int `yaml:"userPrometheusPort"`
FriendPrometheusPort []int `yaml:"friendPrometheusPort"`
MessagePrometheusPort []int `yaml:"messagePrometheusPort"`
MessageGatewayPrometheusPort []int `yaml:"messageGatewayPrometheusPort"`
GroupPrometheusPort []int `yaml:"groupPrometheusPort"`
AuthPrometheusPort []int `yaml:"authPrometheusPort"`
PushPrometheusPort []int `yaml:"pushPrometheusPort"`
ConversationPrometheusPort []int `yaml:"conversationPrometheusPort"`
RtcPrometheusPort []int `yaml:"rtcPrometheusPort"`
MessageTransferPrometheusPort []int `yaml:"messageTransferPrometheusPort"`
ThirdPrometheusPort []int `yaml:"thirdPrometheusPort"`
} `yaml:"prometheus"`
Notification notification `yaml:"notification"`
}
type notification struct {
GroupCreated NotificationConf `yaml:"groupCreated"`
GroupInfoSet NotificationConf `yaml:"groupInfoSet"`
JoinGroupApplication NotificationConf `yaml:"joinGroupApplication"`
MemberQuit NotificationConf `yaml:"memberQuit"`
GroupApplicationAccepted NotificationConf `yaml:"groupApplicationAccepted"`
GroupApplicationRejected NotificationConf `yaml:"groupApplicationRejected"`
GroupOwnerTransferred NotificationConf `yaml:"groupOwnerTransferred"`
MemberKicked NotificationConf `yaml:"memberKicked"`
MemberInvited NotificationConf `yaml:"memberInvited"`
MemberEnter NotificationConf `yaml:"memberEnter"`
GroupDismissed NotificationConf `yaml:"groupDismissed"`
GroupMuted NotificationConf `yaml:"groupMuted"`
GroupCancelMuted NotificationConf `yaml:"groupCancelMuted"`
GroupMemberMuted NotificationConf `yaml:"groupMemberMuted"`
GroupMemberCancelMuted NotificationConf `yaml:"groupMemberCancelMuted"`
GroupMemberInfoSet NotificationConf `yaml:"groupMemberInfoSet"`
GroupMemberSetToAdmin NotificationConf `yaml:"groupMemberSetToAdmin"`
GroupMemberSetToOrdinary NotificationConf `yaml:"groupMemberSetToOrdinaryUser"`
GroupInfoSetAnnouncement NotificationConf `yaml:"groupInfoSetAnnouncement"`
GroupInfoSetName NotificationConf `yaml:"groupInfoSetName"`
////////////////////////user///////////////////////
UserInfoUpdated NotificationConf `yaml:"userInfoUpdated"`
//////////////////////friend///////////////////////
FriendApplicationAdded NotificationConf `yaml:"friendApplicationAdded"`
FriendApplicationApproved NotificationConf `yaml:"friendApplicationApproved"`
FriendApplicationRejected NotificationConf `yaml:"friendApplicationRejected"`
FriendAdded NotificationConf `yaml:"friendAdded"`
FriendDeleted NotificationConf `yaml:"friendDeleted"`
FriendRemarkSet NotificationConf `yaml:"friendRemarkSet"`
BlackAdded NotificationConf `yaml:"blackAdded"`
BlackDeleted NotificationConf `yaml:"blackDeleted"`
FriendInfoUpdated NotificationConf `yaml:"friendInfoUpdated"`
//////////////////////conversation///////////////////////
ConversationChanged NotificationConf `yaml:"conversationChanged"`
ConversationSetPrivate NotificationConf `yaml:"conversationSetPrivate"`
}
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,
}
}
+24 -43
View File
@@ -15,19 +15,26 @@
package config
import (
"bytes"
_ "embed"
"fmt"
"github.com/OpenIMSDK/tools/config"
"os"
"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"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/utils"
)
//go:embed version
var version string
func init() {
config.Version = version
}
var (
_, b, _, _ = runtime.Caller(0)
// Root folder of this project.
@@ -37,12 +44,10 @@ var (
const (
FileName = "config.yaml"
NotificationFileName = "notification.yaml"
ENV = "CONFIG_NAME"
DefaultFolderPath = "../config/"
ConfKey = "conf"
)
func GetOptionsByNotification(cfg NotificationConf) utils.Options {
func GetOptionsByNotification(cfg config.NotificationConf) utils.Options {
opts := utils.NewOptions()
if cfg.UnreadCount {
opts = utils.WithOptions(opts, utils.WithUnreadCount(true))
@@ -59,18 +64,7 @@ func GetOptionsByNotification(cfg NotificationConf) utils.Options {
return opts
}
func (c *config) unmarshalConfig(config interface{}, configPath string) error {
bytes, err := os.ReadFile(configPath)
if err != nil {
return err
}
if err = yaml.Unmarshal(bytes, config); err != nil {
return err
}
return nil
}
func (c *config) initConfig(config interface{}, configName, configFolderPath string) error {
func initConfig(config interface{}, configName, configFolderPath string) error {
if configFolderPath == "" {
configFolderPath = DefaultFolderPath
}
@@ -87,37 +81,24 @@ func (c *config) initConfig(config interface{}, configName, configFolderPath str
} else {
Root = filepath.Dir(configPath)
}
return c.unmarshalConfig(config, configPath)
}
func (c *config) RegisterConf2Registry(registry discoveryregistry.SvcDiscoveryRegistry) error {
bytes, err := yaml.Marshal(Config)
data, err := os.ReadFile(configPath)
if err != nil {
return err
}
return registry.RegisterConf2Registry(ConfKey, bytes)
}
func (c *config) GetConfFromRegistry(registry discoveryregistry.SvcDiscoveryRegistry) ([]byte, error) {
return registry.GetConfFromRegistry(ConfKey)
}
func InitConfig(configFolderPath string) error {
err := Config.initConfig(&Config, FileName, configFolderPath)
if err != nil {
return err
}
err = Config.initConfig(&Config.Notification, NotificationFileName, configFolderPath)
if err != nil {
if err = yaml.Unmarshal(data, config); err != nil {
return err
}
return nil
}
func EncodeConfig() []byte {
buf := bytes.NewBuffer(nil)
if err := yaml.NewEncoder(buf).Encode(Config); err != nil {
panic(err)
func InitConfig(configFolderPath string) error {
err := initConfig(&config.Config, FileName, configFolderPath)
if err != nil {
return err
}
return buf.Bytes()
err = initConfig(&config.Config.Notification, NotificationFileName, configFolderPath)
if err != nil {
return err
}
return nil
}
-363
View File
@@ -1,363 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package constant
const (
///ContentType
//UserRelated.
ContentTypeBegin = 100
Text = 101
Picture = 102
Voice = 103
Video = 104
File = 105
AtText = 106
Merger = 107
Card = 108
Location = 109
Custom = 110
Revoke = 111
Typing = 113
Quote = 114
AdvancedText = 117
CustomNotTriggerConversation = 119
CustomOnlineOnly = 120
ReactionMessageModifier = 121
ReactionMessageDeleter = 122
Common = 200
GroupMsg = 201
SignalMsg = 202
CustomNotification = 203
// SysRelated.
NotificationBegin = 1000
FriendApplicationApprovedNotification = 1201 // add_friend_response
FriendApplicationRejectedNotification = 1202 // add_friend_response
FriendApplicationNotification = 1203 // add_friend
FriendAddedNotification = 1204
FriendDeletedNotification = 1205 // delete_friend
FriendRemarkSetNotification = 1206 // set_friend_remark?
BlackAddedNotification = 1207 // add_black
BlackDeletedNotification = 1208 // remove_black
FriendInfoUpdatedNotification = 1209
ConversationChangeNotification = 1300 // change conversation opt
UserNotificationBegin = 1301
UserInfoUpdatedNotification = 1303 // SetSelfInfoTip = 204
UserNotificationEnd = 1399
OANotification = 1400
GroupNotificationBegin = 1500
GroupCreatedNotification = 1501
GroupInfoSetNotification = 1502
JoinGroupApplicationNotification = 1503
MemberQuitNotification = 1504
GroupApplicationAcceptedNotification = 1505
GroupApplicationRejectedNotification = 1506
GroupOwnerTransferredNotification = 1507
MemberKickedNotification = 1508
MemberInvitedNotification = 1509
MemberEnterNotification = 1510
GroupDismissedNotification = 1511
GroupMemberMutedNotification = 1512
GroupMemberCancelMutedNotification = 1513
GroupMutedNotification = 1514
GroupCancelMutedNotification = 1515
GroupMemberInfoSetNotification = 1516
GroupMemberSetToAdminNotification = 1517
GroupMemberSetToOrdinaryUserNotification = 1518
GroupInfoSetAnnouncementNotification = 1519
GroupInfoSetNameNotification = 1520
SignalingNotificationBegin = 1600
SignalingNotification = 1601
SignalingNotificationEnd = 1649
SuperGroupNotificationBegin = 1650
SuperGroupUpdateNotification = 1651
MsgDeleteNotification = 1652
SuperGroupNotificationEnd = 1699
ConversationPrivateChatNotification = 1701
ConversationUnreadNotification = 1702
MsgRevokeNotification = 2101
BusinessNotificationBegin = 2000
BusinessNotification = 2001
BusinessNotificationEnd = 2099
ClearConversationNotification = 2101
DeleteMsgsNotification = 2102
HasReadReceipt = 2200
NotificationEnd = 5000
// status.
MsgNormal = 1
MsgDeleted = 4
// MsgFrom.
UserMsgType = 100
SysMsgType = 200
// SessionType.
SingleChatType = 1
GroupChatType = 2
SuperGroupChatType = 3
NotificationChatType = 4
// token.
NormalToken = 0
InValidToken = 1
KickedToken = 2
ExpiredToken = 3
// MultiTerminalLogin.
DefalutNotKick = 0
// Full-end login, but the same end is mutually exclusive.
AllLoginButSameTermKick = 1
// Only one of the endpoints can log in.
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.
PcMobileAndWeb = 4
// The PC terminal can be online at the same time,but other terminal only one of the endpoints can login.
PCAndOther = 5
OnlineStatus = "online"
OfflineStatus = "offline"
Registered = "registered"
UnRegistered = "unregistered"
// MsgReceiveOpt.
ReceiveMessage = 0
NotReceiveMessage = 1
ReceiveNotNotifyMessage = 2
// OptionsKey.
IsHistory = "history"
IsPersistent = "persistent"
IsOfflinePush = "offlinePush"
IsUnreadCount = "unreadCount"
IsConversationUpdate = "conversationUpdate"
IsSenderSync = "senderSync"
IsNotPrivate = "notPrivate"
IsSenderConversationUpdate = "senderConversationUpdate"
IsSenderNotificationPush = "senderNotificationPush"
IsReactionFromCache = "reactionFromCache"
IsNotNotification = "isNotNotification"
IsSendMsg = "isSendMsg"
// GroupStatus.
GroupOk = 0
GroupBanChat = 1
GroupStatusDismissed = 2
GroupStatusMuted = 3
// GroupType.
NormalGroup = 0
SuperGroup = 1
WorkingGroup = 2
GroupBaned = 3
GroupBanPrivateChat = 4
// UserJoinGroupSource.
JoinByAdmin = 1
JoinByInvitation = 2
JoinBySearch = 3
JoinByQRCode = 4
// Minio.
MinioDurationTimes = 3600
// Aws.
AwsDurationTimes = 3600
// callbackCommand.
CallbackBeforeSendSingleMsgCommand = "callbackBeforeSendSingleMsgCommand"
CallbackAfterSendSingleMsgCommand = "callbackAfterSendSingleMsgCommand"
CallbackBeforeSendGroupMsgCommand = "callbackBeforeSendGroupMsgCommand"
CallbackAfterSendGroupMsgCommand = "callbackAfterSendGroupMsgCommand"
CallbackMsgModifyCommand = "callbackMsgModifyCommand"
CallbackUserOnlineCommand = "callbackUserOnlineCommand"
CallbackUserOfflineCommand = "callbackUserOfflineCommand"
CallbackUserKickOffCommand = "callbackUserKickOffCommand"
CallbackOfflinePushCommand = "callbackOfflinePushCommand"
CallbackOnlinePushCommand = "callbackOnlinePushCommand"
CallbackSuperGroupOnlinePushCommand = "callbackSuperGroupOnlinePushCommand"
CallbackBeforeAddFriendCommand = "callbackBeforeAddFriendCommand"
CallbackBeforeCreateGroupCommand = "callbackBeforeCreateGroupCommand"
CallbackBeforeMemberJoinGroupCommand = "callbackBeforeMemberJoinGroupCommand"
CallbackBeforeSetGroupMemberInfoCommand = "CallbackBeforeSetGroupMemberInfoCommand"
CallbackBeforeSetMessageReactionExtensionCommand = "callbackBeforeSetMessageReactionExtensionCommand"
CallbackBeforeDeleteMessageReactionExtensionsCommand = "callbackBeforeDeleteMessageReactionExtensionsCommand"
CallbackGetMessageListReactionExtensionsCommand = "callbackGetMessageListReactionExtensionsCommand"
CallbackAddMessageListReactionExtensionsCommand = "callbackAddMessageListReactionExtensionsCommand"
// callback actionCode.
ActionAllow = 0
ActionForbidden = 1
// callback callbackHandleCode.
CallbackHandleSuccess = 0
CallbackHandleFailed = 1
// minioUpload.
OtherType = 1
VideoType = 2
ImageType = 3
// sendMsgStaus.
MsgStatusNotExist = 0
MsgIsSending = 1
MsgSendSuccessed = 2
MsgSendFailed = 3
)
const (
WriteDiffusion = 0
ReadDiffusion = 1
)
const (
UnreliableNotification = 1
ReliableNotificationNoMsg = 2
ReliableNotificationMsg = 3
)
const (
AtAllString = "AtAllTag"
AtNormal = 0
AtMe = 1
AtAll = 2
AtAllAtMe = 3
GroupNotification = 4
)
var ContentType2PushContent = map[int64]string{
Picture: "[PICTURE]",
Voice: "[VOICE]",
Video: "[VIDEO]",
File: "[File]",
Text: "[TEXT]",
AtText: "[@TEXT]",
GroupMsg: "[GROUPMSG]]",
Common: "[NEWMSG]",
SignalMsg: "[SIGNALINVITE]",
}
const (
FieldRecvMsgOpt = 1
FieldIsPinned = 2
FieldAttachedInfo = 3
FieldIsPrivateChat = 4
FieldGroupAtType = 5
FieldEx = 7
FieldUnread = 8
FieldBurnDuration = 9
FieldHasReadSeq = 10
)
const (
AppOrdinaryUsers = 1
AppAdmin = 2
GroupOwner = 100
GroupAdmin = 60
GroupOrdinaryUsers = 20
GroupResponseAgree = 1
GroupResponseRefuse = -1
FriendResponseNotHandle = 0
FriendResponseAgree = 1
FriendResponseRefuse = -1
Male = 1
Female = 2
)
const (
OperationID = "operationID"
OpUserID = "opUserID"
ConnID = "connID"
OpUserPlatform = "platform"
Token = "token"
RpcCustomHeader = "customHeader" // rpc中间件自定义ctx参数
CheckKey = "CheckKey"
TriggerID = "triggerID"
RemoteAddr = "remoteAddr"
)
const (
BecomeFriendByImport = 1 // 管理员导入
BecomeFriendByApply = 2 // 申请添加
)
const (
ApplyNeedVerificationInviteDirectly = 0 // 申请需要同意 邀请直接进
AllNeedVerification = 1 // 所有人进群需要验证,除了群主管理员邀请进群
Directly = 2 // 直接进群
)
const (
GroupRPCRecvSize = 30
GroupRPCSendSize = 30
)
const FriendAcceptTip = "You have successfully become friends, so start chatting"
func GroupIsBanChat(status int32) bool {
if status != GroupStatusMuted {
return false
}
return true
}
func GroupIsBanPrivateChat(status int32) bool {
if status != GroupBanPrivateChat {
return false
}
return true
}
const LogFileName = "OpenIM.log"
const LocalHost = "0.0.0.0"
// flag parse.
const (
FlagPort = "port"
FlagWsPort = "ws_port"
FlagPrometheusPort = "prometheus_port"
FlagConf = "config_folder_path"
)
const OpenIMCommonConfigKey = "OpenIMServerConfig"
const CallbackCommand = "command"
const BatchNum = 100
-21
View File
@@ -1,21 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package constant
const (
ShowNumber = 1000
StatisticsTimeInterval = 60
MaxNotificationNum = 500
)
-109
View File
@@ -1,109 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package constant
// fixme 1<--->IOS 2<--->Android 3<--->Windows
// fixme 4<--->OSX 5<--->Web 6<--->MiniWeb 7<--->Linux.
const (
// Platform ID.
IOSPlatformID = 1
AndroidPlatformID = 2
WindowsPlatformID = 3
OSXPlatformID = 4
WebPlatformID = 5
MiniWebPlatformID = 6
LinuxPlatformID = 7
AndroidPadPlatformID = 8
IPadPlatformID = 9
AdminPlatformID = 10
// Platform string match to Platform ID.
IOSPlatformStr = "IOS"
AndroidPlatformStr = "Android"
WindowsPlatformStr = "Windows"
OSXPlatformStr = "OSX"
WebPlatformStr = "Web"
MiniWebPlatformStr = "MiniWeb"
LinuxPlatformStr = "Linux"
AndroidPadPlatformStr = "APad"
IPadPlatformStr = "IPad"
AdminPlatformStr = "Admin"
// terminal types.
TerminalPC = "PC"
TerminalMobile = "Mobile"
)
var PlatformID2Name = map[int]string{
IOSPlatformID: IOSPlatformStr,
AndroidPlatformID: AndroidPlatformStr,
WindowsPlatformID: WindowsPlatformStr,
OSXPlatformID: OSXPlatformStr,
WebPlatformID: WebPlatformStr,
MiniWebPlatformID: MiniWebPlatformStr,
LinuxPlatformID: LinuxPlatformStr,
AndroidPadPlatformID: AndroidPadPlatformStr,
IPadPlatformID: IPadPlatformStr,
AdminPlatformID: AdminPlatformStr,
}
var PlatformName2ID = map[string]int{
IOSPlatformStr: IOSPlatformID,
AndroidPlatformStr: AndroidPlatformID,
WindowsPlatformStr: WindowsPlatformID,
OSXPlatformStr: OSXPlatformID,
WebPlatformStr: WebPlatformID,
MiniWebPlatformStr: MiniWebPlatformID,
LinuxPlatformStr: LinuxPlatformID,
AndroidPadPlatformStr: AndroidPadPlatformID,
IPadPlatformStr: IPadPlatformID,
AdminPlatformStr: AdminPlatformID,
}
var PlatformName2class = map[string]string{
IOSPlatformStr: TerminalMobile,
AndroidPlatformStr: TerminalMobile,
MiniWebPlatformStr: WebPlatformStr,
WebPlatformStr: WebPlatformStr,
WindowsPlatformStr: TerminalPC,
OSXPlatformStr: TerminalPC,
LinuxPlatformStr: TerminalPC,
}
var PlatformID2class = map[int]string{
IOSPlatformID: TerminalMobile,
AndroidPlatformID: TerminalMobile,
MiniWebPlatformID: WebPlatformStr,
WebPlatformID: WebPlatformStr,
WindowsPlatformID: TerminalPC,
OSXPlatformID: TerminalPC,
LinuxPlatformID: TerminalPC,
}
func PlatformIDToName(num int) string {
return PlatformID2Name[num]
}
func PlatformNameToID(name string) int {
return PlatformName2ID[name]
}
func PlatformNameToClass(name string) string {
return PlatformName2class[name]
}
func PlatformIDToClass(num int) string {
return PlatformID2class[num]
}
+2 -2
View File
@@ -18,8 +18,8 @@ import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sdk "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/protocol/sdkws"
sdk "github.com/OpenIMSDK/protocol/sdkws"
)
func BlackDB2Pb(
+2 -2
View File
@@ -16,8 +16,8 @@ package convert
import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/protocol/conversation"
"github.com/OpenIMSDK/tools/utils"
)
func ConversationDB2Pb(conversationDB *relation.ConversationModel) *conversation.Conversation {
+2 -2
View File
@@ -18,8 +18,8 @@ import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/utils"
)
func FriendPb2DB(friend *sdkws.FriendInfo) *relation.FriendModel {
+2 -2
View File
@@ -18,8 +18,8 @@ import (
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
pbGroup "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
pbGroup "github.com/OpenIMSDK/protocol/group"
sdkws "github.com/OpenIMSDK/protocol/sdkws"
)
func Db2PbGroupInfo(m *relation.GroupModel, ownerUserID string, memberCount uint32) *sdkws.GroupInfo {
+1 -1
View File
@@ -16,7 +16,7 @@ package convert
import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/protocol/sdkws"
)
func MsgPb2DB(msg *sdkws.MsgData) *unrelation.MsgDataModel {
+1 -1
View File
@@ -18,7 +18,7 @@ import (
"time"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/protocol/sdkws"
)
func UsersDB2Pb(users []*relationTb.UserModel) (result []*sdkws.UserInfo) {
+1 -1
View File
@@ -26,7 +26,7 @@ import (
"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/OpenIMSDK/tools/utils"
)
const (
+1 -1
View File
@@ -22,7 +22,7 @@ import (
"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"
"github.com/OpenIMSDK/tools/utils"
)
const (
+1 -1
View File
@@ -25,7 +25,7 @@ import (
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/OpenIMSDK/tools/utils"
)
const (
+3 -3
View File
@@ -22,9 +22,9 @@ import (
"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/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/mw/specialerror"
)
const (
-37
View File
@@ -1,37 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"fmt"
"testing"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
)
// TestNewRedis Test redis connection
func TestNewRedis(t *testing.T) {
err := config.InitConfig("config_folder_path")
if err != nil {
fmt.Println("config load error")
return
}
redis, err := NewRedis()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(redis)
}
+3 -3
View File
@@ -23,9 +23,9 @@ import (
"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/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils"
)
const (
+6 -6
View File
@@ -21,16 +21,16 @@ import (
"github.com/dtm-labs/rockscache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/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/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils"
"github.com/redis/go-redis/v9"
)
+3 -3
View File
@@ -19,10 +19,10 @@ import (
"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/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/tokenverify"
"github.com/OpenIMSDK/tools/utils"
)
type AuthDatabase interface {
+2 -2
View File
@@ -19,8 +19,8 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils"
)
type BlackDatabase interface {
+1 -1
View File
@@ -16,7 +16,7 @@ package controller
import (
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
pbMsg "github.com/OpenIMSDK/protocol/msg"
)
type ChatLogDatabase interface {
+4 -4
View File
@@ -18,12 +18,12 @@ import (
"context"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/tools/utils"
)
type ConversationDatabase interface {
+5 -5
View File
@@ -20,13 +20,13 @@ import (
"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"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx"
"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"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/mcontext"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/tools/utils"
)
type FriendDatabase interface {
+3 -3
View File
@@ -24,14 +24,14 @@ import (
"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"
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/common/db/tx"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/tools/utils"
)
type GroupDatabase interface {
+6 -6
View File
@@ -21,21 +21,21 @@ import (
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"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"
pbMsg "github.com/OpenIMSDK/protocol/msg"
"github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/utils"
)
const (
+2 -2
View File
@@ -23,13 +23,13 @@ import (
"testing"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/tools/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"
"github.com/OpenIMSDK/tools/config"
)
func Test_BatchInsertChat2DB(t *testing.T) {
+3 -3
View File
@@ -20,9 +20,9 @@ import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/tools/utils"
)
type UserDatabase interface {
+1 -1
View File
@@ -18,8 +18,8 @@ import (
"context"
"sync"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/conversation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/protocol/conversation"
)
type ConversationLocalCache struct {
+2 -2
View File
@@ -18,9 +18,9 @@ import (
"context"
"sync"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/group"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
"github.com/OpenIMSDK/protocol/group"
"github.com/OpenIMSDK/tools/errs"
)
type GroupLocalCache struct {
-73
View File
@@ -1,73 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ormutil
import (
"fmt"
"strings"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
)
func GormPage[E any](db *gorm.DB, pageNumber, showNumber int32) (uint32, []*E, error) {
var count int64
var model E
if err := db.Model(&model).Count(&count).Error; err != nil {
return 0, nil, errs.Wrap(err)
}
var es []*E
if err := db.Limit(int(showNumber)).Offset(int((pageNumber - 1) * showNumber)).Find(&es).Error; err != nil {
return 0, nil, errs.Wrap(err)
}
return uint32(count), es, nil
}
func GormSearch[E any](db *gorm.DB, fields []string, value string, pageNumber, showNumber int32) (uint32, []*E, error) {
if len(fields) > 0 && value != "" {
val := "%" + value + "%"
arr := make([]string, 0, len(fields))
vals := make([]interface{}, 0, len(fields))
for _, field := range fields {
arr = append(arr, fmt.Sprintf("`%s` like ?", field))
vals = append(vals, val)
}
db = db.Where(strings.Join(arr, " or "), vals...)
}
return GormPage[E](db, pageNumber, showNumber)
}
func GormIn[E any](db **gorm.DB, field string, es []E) {
if len(es) == 0 {
return
}
*db = (*db).Where(field+" in (?)", es)
}
func MapCount(db *gorm.DB, field string) (map[string]uint32, error) {
var items []struct {
ID string `gorm:"column:id"`
Count uint32 `gorm:"column:count"`
}
if err := db.Select(field + " as id, count(1) as count").Group(field).Find(&items).Error; err != nil {
return nil, errs.Wrap(err)
}
m := make(map[string]uint32)
for _, item := range items {
m[item.ID] = item.Count
}
return m, nil
}
+2 -2
View File
@@ -17,12 +17,12 @@ package relation
import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"github.com/OpenIMSDK/tools/ormutil"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type BlackGorm struct {
+4 -4
View File
@@ -20,11 +20,11 @@ import (
"google.golang.org/protobuf/proto"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
pbMsg "github.com/OpenIMSDK/protocol/msg"
sdkws "github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/utils"
)
type ChatLogGorm struct {
+2 -2
View File
@@ -19,9 +19,9 @@ import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/utils"
)
type ConversationGorm struct {
+1 -1
View File
@@ -20,7 +20,7 @@ import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type FriendGorm struct {
@@ -20,7 +20,7 @@ import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type FriendRequestGorm struct {
+3 -3
View File
@@ -19,10 +19,10 @@ import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/ormutil"
"github.com/OpenIMSDK/tools/utils"
)
var _ relation.GroupMemberModelInterface = (*GroupMemberGorm)(nil)
+4 -4
View File
@@ -18,14 +18,14 @@ import (
"context"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/tools/constant"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/ormutil"
"github.com/OpenIMSDK/tools/utils"
)
var _ relation.GroupModelInterface = (*GroupGorm)(nil)
@@ -17,12 +17,12 @@ package relation
import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/ormutil"
"github.com/OpenIMSDK/tools/ormutil"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type GroupRequestGorm struct {
+4 -4
View File
@@ -21,10 +21,10 @@ import (
mysqlDriver "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql"
"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/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/mw/specialerror"
"gorm.io/gorm"
"gorm.io/gorm/logger"
+1 -1
View File
@@ -20,7 +20,7 @@ import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/errs"
)
type ObjectInfoGorm struct {
+2 -2
View File
@@ -18,12 +18,12 @@ import (
"context"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/errs"
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type UserGorm struct {
+2 -2
View File
@@ -27,8 +27,8 @@ import (
"github.com/google/uuid"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
)
func New(impl s3.Interface) *Controller {
+1 -1
View File
@@ -26,8 +26,8 @@ import (
"github.com/tencentyun/cos-go-sdk-v5"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3"
"github.com/OpenIMSDK/tools/config"
)
const (
+1 -1
View File
@@ -29,8 +29,8 @@ import (
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/signer"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3"
"github.com/OpenIMSDK/tools/config"
)
const (
+1 -1
View File
@@ -26,8 +26,8 @@ import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3"
"github.com/OpenIMSDK/tools/config"
)
const (
+1 -1
View File
@@ -17,7 +17,7 @@ package relation
import (
"time"
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
pbMsg "github.com/OpenIMSDK/protocol/msg"
)
const (
+1 -1
View File
@@ -17,7 +17,7 @@ package relation
import (
"gorm.io/gorm"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
type BatchUpdateGroupMember struct {
+2 -2
View File
@@ -19,11 +19,11 @@ import (
"strconv"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/protocol/msg"
"go.mongodb.org/mongo-driver/mongo"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/protocol/sdkws"
)
const (
-33
View File
@@ -1,33 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tx
import (
"gorm.io/gorm"
)
func NewGorm(db *gorm.DB) Tx {
return &_Gorm{tx: db}
}
type _Gorm struct {
tx *gorm.DB
}
func (g *_Gorm) Transaction(fn func(tx any) error) error {
return g.tx.Transaction(func(tx *gorm.DB) error {
return fn(tx)
})
}
-47
View File
@@ -1,47 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tx
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
)
func NewMongo(client *mongo.Client) CtxTx {
return &_Mongo{
client: client,
}
}
type _Mongo struct {
client *mongo.Client
}
func (m *_Mongo) Transaction(ctx context.Context, fn func(ctx context.Context) error) error {
sess, err := m.client.StartSession()
if err != nil {
return err
}
sCtx := mongo.NewSessionContext(ctx, sess)
defer sess.EndSession(sCtx)
if err := fn(sCtx); err != nil {
_ = sess.AbortTransaction(sCtx)
return err
}
return utils.Wrap(sess.CommitTransaction(sCtx), "")
}
-25
View File
@@ -1,25 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tx
import "context"
type Tx interface {
Transaction(fn func(tx any) error) error
}
type CtxTx interface {
Transaction(ctx context.Context, fn func(ctx context.Context) error) error
}
+10 -8
View File
@@ -17,18 +17,18 @@ package unrelation
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"strings"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/bsonx"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/mw/specialerror"
"github.com/OpenIMSDK/tools/utils"
)
const (
@@ -111,13 +111,15 @@ func (m *Mongo) createMongoIndex(collection string, isUnique bool, keys ...strin
db := m.db.Database(config.Config.Mongo.Database).Collection(collection)
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
indexView := db.Indexes()
keysDoc := bsonx.Doc{}
keysDoc := bson.D{}
// create composite indexes
for _, key := range keys {
if strings.HasPrefix(key, "-") {
keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
keysDoc = append(keysDoc, bson.E{Key: strings.TrimLeft(key, "-"), Value: -1})
//keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
} else {
keysDoc = keysDoc.Append(key, bsonx.Int32(1))
keysDoc = append(keysDoc, bson.E{Key: key, Value: 1})
//keysDoc = keysDoc.Append(key, bsonx.Int32(1))
}
}
// create index
+5 -5
View File
@@ -21,9 +21,9 @@ import (
"fmt"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/protocol/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/tools/constant"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
@@ -32,9 +32,9 @@ import (
"google.golang.org/protobuf/proto"
table "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/utils"
)
var ErrMsgListNotExist = errors.New("user not have msg in mongoDB")
+1 -1
View File
@@ -22,7 +22,7 @@ import (
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/utils"
)
func NewSuperGroupMongoDriver(database *mongo.Database) unrelation.SuperGroupModelInterface {
+4 -4
View File
@@ -25,10 +25,10 @@ import (
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/callbackstruct"
"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/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/constant"
"github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
)
var client http.Client
+1 -1
View File
@@ -17,7 +17,7 @@ package kafka
import (
"sync"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/tools/config"
"github.com/Shopify/sarama"
)
+1 -1
View File
@@ -17,7 +17,7 @@ package kafka
import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/tools/log"
"github.com/Shopify/sarama"
)
+5 -5
View File
@@ -19,11 +19,11 @@ import (
"errors"
"time"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
log "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/OpenIMSDK/tools/config"
"github.com/OpenIMSDK/tools/constant"
log "github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/mcontext"
"github.com/OpenIMSDK/tools/utils"
"github.com/Shopify/sarama"
"google.golang.org/protobuf/proto"
-64
View File
@@ -1,64 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"fmt"
"go.uber.org/zap/zapcore"
)
// Foreground colors.
const (
Black Color = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
White
)
var (
_levelToColor = map[zapcore.Level]Color{
zapcore.DebugLevel: White,
zapcore.InfoLevel: Blue,
zapcore.WarnLevel: Yellow,
zapcore.ErrorLevel: Red,
zapcore.DPanicLevel: Red,
zapcore.PanicLevel: Red,
zapcore.FatalLevel: Red,
}
_unknownLevelColor = make(map[zapcore.Level]string, len(_levelToColor))
_levelToLowercaseColorString = make(map[zapcore.Level]string, len(_levelToColor))
_levelToCapitalColorString = make(map[zapcore.Level]string, len(_levelToColor))
)
func init() {
for level, color := range _levelToColor {
_levelToLowercaseColorString[level] = color.Add(level.String())
_levelToCapitalColorString[level] = color.Add(level.CapitalString())
}
}
// Color represents a text color.
type Color uint8
// Add adds the coloring to the given string.
func (c Color) Add(s string) string {
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s)
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import "context"
type Logger interface {
Debug(ctx context.Context, msg string, keysAndValues ...interface{})
Info(ctx context.Context, msg string, keysAndValues ...interface{})
Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{})
Error(ctx context.Context, msg string, err error, keysAndValues ...interface{})
WithValues(keysAndValues ...interface{}) Logger
WithName(name string) Logger
WithCallDepth(depth int) Logger
}
-89
View File
@@ -1,89 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
gormUtils "gorm.io/gorm/utils"
)
type SqlLogger struct {
LogLevel gormLogger.LogLevel
IgnoreRecordNotFoundError bool
SlowThreshold time.Duration
}
func NewSqlLogger(logLevel gormLogger.LogLevel, ignoreRecordNotFoundError bool, slowThreshold time.Duration) *SqlLogger {
return &SqlLogger{
LogLevel: logLevel,
IgnoreRecordNotFoundError: ignoreRecordNotFoundError,
SlowThreshold: slowThreshold,
}
}
func (l *SqlLogger) LogMode(logLevel gormLogger.LogLevel) gormLogger.Interface {
newLogger := *l
newLogger.LogLevel = logLevel
return &newLogger
}
func (SqlLogger) Info(ctx context.Context, msg string, args ...interface{}) {
ZInfo(ctx, msg, args)
}
func (SqlLogger) Warn(ctx context.Context, msg string, args ...interface{}) {
ZWarn(ctx, msg, nil, args)
}
func (SqlLogger) Error(ctx context.Context, msg string, args ...interface{}) {
ZError(ctx, msg, nil, args)
}
func (l *SqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if l.LogLevel <= gormLogger.Silent {
return
}
elapsed := time.Since(begin)
switch {
case err != nil && l.LogLevel >= gormLogger.Error && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
sql, rows := fc()
if rows == -1 {
ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
} else {
ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
}
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gormLogger.Warn:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
if rows == -1 {
ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
} else {
ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
}
case l.LogLevel == gormLogger.Info:
sql, rows := fc()
if rows == -1 {
ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
} else {
ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
}
}
}
-302
View File
@@ -1,302 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"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/mcontext"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
pkgLogger Logger
sp = string(filepath.Separator)
logLevelMap = map[int]zapcore.Level{
6: zapcore.DebugLevel,
5: zapcore.DebugLevel,
4: zapcore.InfoLevel,
3: zapcore.WarnLevel,
2: zapcore.ErrorLevel,
1: zapcore.FatalLevel,
0: zapcore.PanicLevel,
}
)
// InitFromConfig initializes a Zap-based logger.
func InitFromConfig(
loggerPrefixName, moduleName string,
logLevel int,
isStdout bool,
isJson bool,
logLocation string,
rotateCount uint,
) error {
l, err := NewZapLogger(loggerPrefixName, moduleName, logLevel, isStdout, isJson, logLocation, rotateCount)
if err != nil {
return err
}
pkgLogger = l.WithCallDepth(2)
if isJson {
pkgLogger = pkgLogger.WithName(moduleName)
}
return nil
}
func ZDebug(ctx context.Context, msg string, keysAndValues ...interface{}) {
if pkgLogger == nil {
return
}
pkgLogger.Debug(ctx, msg, keysAndValues...)
}
func ZInfo(ctx context.Context, msg string, keysAndValues ...interface{}) {
if pkgLogger == nil {
return
}
pkgLogger.Info(ctx, msg, keysAndValues...)
}
func ZWarn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
if pkgLogger == nil {
return
}
pkgLogger.Warn(ctx, msg, err, keysAndValues...)
}
func ZError(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
if pkgLogger == nil {
return
}
pkgLogger.Error(ctx, msg, err, keysAndValues...)
}
type ZapLogger struct {
zap *zap.SugaredLogger
level zapcore.Level
loggerName string
loggerPrefixName string
}
func NewZapLogger(
loggerPrefixName, loggerName string,
logLevel int,
isStdout bool,
isJson bool,
logLocation string,
rotateCount uint,
) (*ZapLogger, error) {
zapConfig := zap.Config{
Level: zap.NewAtomicLevelAt(logLevelMap[logLevel]),
// EncoderConfig: zap.NewProductionEncoderConfig(),
// InitialFields: map[string]interface{}{"PID": os.Getegid()},
DisableStacktrace: true,
}
if isJson {
zapConfig.Encoding = "json"
} else {
zapConfig.Encoding = "console"
}
// if isStdout {
// zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stdout", "stderr")
// }
zl := &ZapLogger{level: logLevelMap[logLevel], loggerName: loggerName, loggerPrefixName: loggerPrefixName}
opts, err := zl.cores(isStdout, isJson, logLocation, rotateCount)
if err != nil {
return nil, err
}
l, err := zapConfig.Build(opts)
if err != nil {
return nil, err
}
zl.zap = l.Sugar()
return zl, nil
}
func (l *ZapLogger) cores(isStdout bool, isJson bool, logLocation string, rotateCount uint) (zap.Option, error) {
c := zap.NewProductionEncoderConfig()
c.EncodeTime = l.timeEncoder
c.EncodeDuration = zapcore.SecondsDurationEncoder
c.MessageKey = "msg"
c.LevelKey = "level"
c.TimeKey = "time"
c.CallerKey = "caller"
c.NameKey = "logger"
var fileEncoder zapcore.Encoder
if isJson {
c.EncodeLevel = zapcore.CapitalLevelEncoder
fileEncoder = zapcore.NewJSONEncoder(c)
fileEncoder.AddInt("PID", os.Getpid())
} else {
c.EncodeLevel = l.capitalColorLevelEncoder
c.EncodeCaller = l.customCallerEncoder
fileEncoder = zapcore.NewConsoleEncoder(c)
}
writer, err := l.getWriter(logLocation, rotateCount)
if err != nil {
return nil, err
}
var cores []zapcore.Core
// if logLocation == "" && !isStdout {
// return nil, errors.New("log storage location is empty and not stdout")
// }
if logLocation != "" {
cores = []zapcore.Core{
zapcore.NewCore(fileEncoder, writer, zap.NewAtomicLevelAt(l.level)),
}
}
if isStdout {
cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(l.level)))
// cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stderr), zap.NewAtomicLevelAt(l.level)))
}
return zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewTee(cores...)
}), nil
}
func (l *ZapLogger) customCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
s := "[" + caller.TrimmedPath() + "]"
// color, ok := _levelToColor[l.level]
// if !ok {
// color = _levelToColor[zapcore.ErrorLevel]
// }
enc.AppendString(s)
}
func (l *ZapLogger) timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
layout := "2006-01-02 15:04:05.000"
type appendTimeEncoder interface {
AppendTimeLayout(time.Time, string)
}
if enc, ok := enc.(appendTimeEncoder); ok {
enc.AppendTimeLayout(t, layout)
return
}
enc.AppendString(t.Format(layout))
}
func (l *ZapLogger) getWriter(logLocation string, rorateCount uint) (zapcore.WriteSyncer, error) {
logf, err := rotatelogs.New(logLocation+sp+l.loggerPrefixName+".%Y-%m-%d",
rotatelogs.WithRotationCount(rorateCount),
rotatelogs.WithRotationTime(time.Duration(config.Config.Log.RotationTime)*time.Hour),
)
if err != nil {
return nil, err
}
return zapcore.AddSync(logf), nil
}
func (l *ZapLogger) capitalColorLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
s, ok := _levelToCapitalColorString[level]
if !ok {
s = _unknownLevelColor[zapcore.ErrorLevel]
}
pid := fmt.Sprintf("["+"PID:"+"%d"+"]", os.Getpid())
color := _levelToColor[level]
enc.AppendString(s)
enc.AppendString(color.Add(pid))
if l.loggerName != "" {
enc.AppendString(color.Add(l.loggerName))
}
}
func (l *ZapLogger) ToZap() *zap.SugaredLogger {
return l.zap
}
func (l *ZapLogger) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) {
keysAndValues = l.kvAppend(ctx, keysAndValues)
l.zap.Debugw(msg, keysAndValues...)
}
func (l *ZapLogger) Info(ctx context.Context, msg string, keysAndValues ...interface{}) {
keysAndValues = l.kvAppend(ctx, keysAndValues)
l.zap.Infow(msg, keysAndValues...)
}
func (l *ZapLogger) Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
if err != nil {
keysAndValues = append(keysAndValues, "error", err.Error())
}
keysAndValues = l.kvAppend(ctx, keysAndValues)
l.zap.Warnw(msg, keysAndValues...)
}
func (l *ZapLogger) Error(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
if err != nil {
keysAndValues = append(keysAndValues, "error", err.Error())
}
keysAndValues = l.kvAppend(ctx, keysAndValues)
l.zap.Errorw(msg, keysAndValues...)
}
func (l *ZapLogger) kvAppend(ctx context.Context, keysAndValues []interface{}) []interface{} {
if ctx == nil {
return keysAndValues
}
operationID := mcontext.GetOperationID(ctx)
opUserID := mcontext.GetOpUserID(ctx)
connID := mcontext.GetConnID(ctx)
triggerID := mcontext.GetTriggerID(ctx)
opUserPlatform := mcontext.GetOpUserPlatform(ctx)
remoteAddr := mcontext.GetRemoteAddr(ctx)
if opUserID != "" {
keysAndValues = append([]interface{}{constant.OpUserID, opUserID}, keysAndValues...)
}
if operationID != "" {
keysAndValues = append([]interface{}{constant.OperationID, operationID}, keysAndValues...)
}
if connID != "" {
keysAndValues = append([]interface{}{constant.ConnID, connID}, keysAndValues...)
}
if triggerID != "" {
keysAndValues = append([]interface{}{constant.TriggerID, triggerID}, keysAndValues...)
}
if opUserPlatform != "" {
keysAndValues = append([]interface{}{constant.OpUserPlatform, opUserPlatform}, keysAndValues...)
}
if remoteAddr != "" {
keysAndValues = append([]interface{}{constant.RemoteAddr, remoteAddr}, keysAndValues...)
}
return keysAndValues
}
func (l *ZapLogger) WithValues(keysAndValues ...interface{}) Logger {
dup := *l
dup.zap = l.zap.With(keysAndValues...)
return &dup
}
func (l *ZapLogger) WithName(name string) Logger {
dup := *l
dup.zap = l.zap.Named(name)
return &dup
}
func (l *ZapLogger) WithCallDepth(depth int) Logger {
dup := *l
dup.zap = l.zap.WithOptions(zap.AddCallerSkip(depth))
return &dup
}
-30
View File
@@ -1,30 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"context"
"fmt"
)
type ZkLogger struct{}
func NewZkLogger() *ZkLogger {
return &ZkLogger{}
}
func (l *ZkLogger) Printf(format string, a ...interface{}) {
ZInfo(context.Background(), "zookeeper output", "msg", fmt.Sprintf(format, a...))
}
-154
View File
@@ -1,154 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mcontext
import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
)
var mapper = []string{constant.OperationID, constant.OpUserID, constant.OpUserPlatform, constant.ConnID}
func WithOpUserIDContext(ctx context.Context, opUserID string) context.Context {
return context.WithValue(ctx, constant.OpUserID, opUserID)
}
func WithOpUserPlatformContext(ctx context.Context, platform string) context.Context {
return context.WithValue(ctx, constant.OpUserPlatform, platform)
}
func WithTriggerIDContext(ctx context.Context, triggerID string) context.Context {
return context.WithValue(ctx, constant.TriggerID, triggerID)
}
func NewCtx(operationID string) context.Context {
c := context.Background()
ctx := context.WithValue(c, constant.OperationID, operationID)
return SetOperationID(ctx, operationID)
}
func SetOperationID(ctx context.Context, operationID string) context.Context {
return context.WithValue(ctx, constant.OperationID, operationID)
}
func SetOpUserID(ctx context.Context, opUserID string) context.Context {
return context.WithValue(ctx, constant.OpUserID, opUserID)
}
func SetConnID(ctx context.Context, connID string) context.Context {
return context.WithValue(ctx, constant.ConnID, connID)
}
func GetOperationID(ctx context.Context) string {
if ctx.Value(constant.OperationID) != nil {
s, ok := ctx.Value(constant.OperationID).(string)
if ok {
return s
}
}
return ""
}
func GetOpUserID(ctx context.Context) string {
if ctx.Value(constant.OpUserID) != "" {
s, ok := ctx.Value(constant.OpUserID).(string)
if ok {
return s
}
}
return ""
}
func GetConnID(ctx context.Context) string {
if ctx.Value(constant.ConnID) != "" {
s, ok := ctx.Value(constant.ConnID).(string)
if ok {
return s
}
}
return ""
}
func GetTriggerID(ctx context.Context) string {
if ctx.Value(constant.TriggerID) != "" {
s, ok := ctx.Value(constant.TriggerID).(string)
if ok {
return s
}
}
return ""
}
func GetOpUserPlatform(ctx context.Context) string {
if ctx.Value(constant.OpUserPlatform) != "" {
s, ok := ctx.Value(constant.OpUserPlatform).(string)
if ok {
return s
}
}
return ""
}
func GetRemoteAddr(ctx context.Context) string {
if ctx.Value(constant.RemoteAddr) != "" {
s, ok := ctx.Value(constant.RemoteAddr).(string)
if ok {
return s
}
}
return ""
}
func GetMustCtxInfo(ctx context.Context) (operationID, opUserID, platform, connID string, err error) {
operationID, ok := ctx.Value(constant.OperationID).(string)
if !ok {
err = errs.ErrArgs.Wrap("ctx missing operationID")
return
}
opUserID, ok1 := ctx.Value(constant.OpUserID).(string)
if !ok1 {
err = errs.ErrArgs.Wrap("ctx missing opUserID")
return
}
platform, ok2 := ctx.Value(constant.OpUserPlatform).(string)
if !ok2 {
err = errs.ErrArgs.Wrap("ctx missing platform")
return
}
connID, _ = ctx.Value(constant.ConnID).(string)
return
}
func GetCtxInfos(ctx context.Context) (operationID, opUserID, platform, connID string, err error) {
operationID, ok := ctx.Value(constant.OperationID).(string)
if !ok {
err = errs.ErrArgs.Wrap("ctx missing operationID")
return
}
opUserID, _ = ctx.Value(constant.OpUserID).(string)
platform, _ = ctx.Value(constant.OpUserPlatform).(string)
connID, _ = ctx.Value(constant.ConnID).(string)
return
}
func WithMustInfoCtx(values []string) context.Context {
ctx := context.Background()
for i, v := range values {
ctx = context.WithValue(ctx, mapper[i], v)
}
return ctx
}
-142
View File
@@ -1,142 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mw
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"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/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
"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"
)
// CorsHandler gin cross-domain configuration.
func CorsHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "*")
c.Header("Access-Control-Allow-Headers", "*")
c.Header(
"Access-Control-Expose-Headers",
"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar",
) // Cross-domain key settings allow browsers to resolve.
c.Header(
"Access-Control-Max-Age",
"172800",
) // Cache request information in seconds.
c.Header(
"Access-Control-Allow-Credentials",
"false",
) // Whether cross-domain requests need to carry cookie information, the default setting is true.
c.Header(
"content-type",
"application/json",
) // Set the return format to json.
// Release all option pre-requests
if c.Request.Method == http.MethodOptions {
c.JSON(http.StatusOK, "Options Request!")
c.Abort()
return
}
c.Next()
}
}
func GinParseOperationID() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodPost {
operationID := c.Request.Header.Get(constant.OperationID)
if operationID == "" {
err := errors.New("header must have operationID")
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error()))
c.Abort()
return
}
c.Set(constant.OperationID, operationID)
}
c.Next()
}
}
func GinParseToken(rdb redis.UniversalClient) gin.HandlerFunc {
dataBase := controller.NewAuthDatabase(
cache.NewMsgCacheModel(rdb),
config.Config.Secret,
config.Config.TokenPolicy.Expire,
)
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodPost:
token := c.Request.Header.Get(constant.Token)
if token == "" {
log.ZWarn(c, "header get token error", errs.ErrArgs.Wrap("header must have token"))
apiresp.GinError(c, errs.ErrArgs.Wrap("header must have token"))
c.Abort()
return
}
claims, err := tokenverify.GetClaimFromToken(token)
if err != nil {
log.ZWarn(c, "jwt get token error", errs.ErrTokenUnknown.Wrap())
apiresp.GinError(c, errs.ErrTokenUnknown.Wrap())
c.Abort()
return
}
m, err := dataBase.GetTokensWithoutError(c, claims.UserID, claims.PlatformID)
if err != nil {
log.ZWarn(c, "cache get token error", errs.ErrTokenNotExist.Wrap())
apiresp.GinError(c, errs.ErrTokenNotExist.Wrap())
c.Abort()
return
}
if len(m) == 0 {
log.ZWarn(c, "cache do not exist token error", errs.ErrTokenNotExist.Wrap())
apiresp.GinError(c, errs.ErrTokenNotExist.Wrap())
c.Abort()
return
}
if v, ok := m[token]; ok {
switch v {
case constant.NormalToken:
case constant.KickedToken:
log.ZWarn(c, "cache kicked token error", errs.ErrTokenKicked.Wrap())
apiresp.GinError(c, errs.ErrTokenKicked.Wrap())
c.Abort()
return
default:
log.ZWarn(c, "cache unknown token error", errs.ErrTokenUnknown.Wrap())
apiresp.GinError(c, errs.ErrTokenUnknown.Wrap())
c.Abort()
return
}
} else {
apiresp.GinError(c, errs.ErrTokenNotExist.Wrap())
c.Abort()
return
}
c.Set(constant.OpUserPlatform, constant.PlatformIDToName(claims.PlatformID))
c.Set(constant.OpUserID, claims.UserID)
c.Next()
}
}
}
-41
View File
@@ -1,41 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mw
import (
"context"
"google.golang.org/grpc"
)
func InterceptChain(intercepts ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
l := len(intercepts)
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
chain := func(currentInter grpc.UnaryServerInterceptor, currentHandler grpc.UnaryHandler) grpc.UnaryHandler {
return func(currentCtx context.Context, currentReq interface{}) (interface{}, error) {
return currentInter(
currentCtx,
currentReq,
info,
currentHandler)
}
}
chainHandler := handler
for i := l - 1; i >= 0; i-- {
chainHandler = chain(intercepts[i], chainHandler)
}
return chainHandler(ctx, req)
}
}
-114
View File
@@ -1,114 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mw
import (
"context"
"errors"
"fmt"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"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/errinfo"
)
func GrpcClient() grpc.DialOption {
return grpc.WithChainUnaryInterceptor(RpcClientInterceptor)
}
func RpcClientInterceptor(
ctx context.Context,
method string,
req, resp interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) (err error) {
if ctx == nil {
return errs.ErrInternalServer.Wrap("call rpc request context is nil")
}
ctx, err = getRpcContext(ctx, method)
if err != nil {
return err
}
log.ZDebug(ctx, "get rpc ctx success", "conn target", cc.Target())
err = invoker(ctx, method, req, resp, cc, opts...)
if err == nil {
log.ZInfo(ctx, "rpc client resp", "funcName", method, "resp", rpcString(resp))
return nil
}
log.ZError(ctx, "rpc resp error", err)
rpcErr, ok := err.(interface{ GRPCStatus() *status.Status })
if !ok {
return errs.ErrInternalServer.Wrap(err.Error())
}
sta := rpcErr.GRPCStatus()
if sta.Code() == 0 {
return errs.NewCodeError(errs.ServerInternalError, err.Error()).Wrap()
}
if details := sta.Details(); len(details) > 0 {
errInfo, ok := details[0].(*errinfo.ErrorInfo)
if ok {
s := strings.Join(errInfo.Warp, "->") + errInfo.Cause
return errs.NewCodeError(int(sta.Code()), sta.Message()).WithDetail(s).Wrap()
}
}
return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap()
}
func getRpcContext(ctx context.Context, method string) (context.Context, error) {
md := metadata.Pairs()
if keys, _ := ctx.Value(constant.RpcCustomHeader).([]string); len(keys) > 0 {
for _, key := range keys {
val, ok := ctx.Value(key).([]string)
if !ok {
return nil, errs.ErrInternalServer.Wrap(fmt.Sprintf("ctx missing key %s", key))
}
if len(val) == 0 {
return nil, errs.ErrInternalServer.Wrap(fmt.Sprintf("ctx key %s value is empty", key))
}
md.Set(key, val...)
}
md.Set(constant.RpcCustomHeader, keys...)
}
operationID, ok := ctx.Value(constant.OperationID).(string)
if !ok {
log.ZWarn(ctx, "ctx missing operationID", errors.New("ctx missing operationID"), "funcName", method)
return nil, errs.ErrArgs.Wrap("ctx missing operationID")
}
md.Set(constant.OperationID, operationID)
var checkArgs []string
checkArgs = append(checkArgs, constant.OperationID, operationID)
opUserID, ok := ctx.Value(constant.OpUserID).(string)
if ok {
md.Set(constant.OpUserID, opUserID)
checkArgs = append(checkArgs, constant.OpUserID, opUserID)
}
opUserIDPlatformID, ok := ctx.Value(constant.OpUserPlatform).(string)
if ok {
md.Set(constant.OpUserPlatform, opUserIDPlatformID)
}
connID, ok := ctx.Value(constant.ConnID).(string)
if ok {
md.Set(constant.ConnID, connID)
}
return metadata.NewOutgoingContext(ctx, md), nil
}
-181
View File
@@ -1,181 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mw
import (
"context"
"fmt"
"math"
"runtime"
"strings"
"github.com/OpenIMSDK/Open-IM-Server/pkg/checker"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"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/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/errinfo"
)
func rpcString(v interface{}) string {
if s, ok := v.(interface{ String() string }); ok {
return s.String()
}
return fmt.Sprintf("%+v", v)
}
func RpcServerInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
log.ZDebug(ctx, "rpc server req", "req", rpcString(req))
//defer func() {
// if r := recover(); r != nil {
// log.ZError(ctx, "rpc panic", nil, "FullMethod", info.FullMethod, "type:", fmt.Sprintf("%T", r), "panic:", r)
// fmt.Printf("panic: %+v\nstack info: %s\n", r, string(debug.Stack()))
// pc, file, line, ok := runtime.Caller(4)
// if !ok {
// panic("get runtime.Caller failed")
// }
// errInfo := &errinfo.ErrorInfo{
// Path: file,
// Line: uint32(line),
// Name: runtime.FuncForPC(pc).Name(),
// Cause: fmt.Sprintf("%s", r),
// Warp: nil,
// }
// sta, err_ := status.New(codes.Code(errs.ErrInternalServer.Code()),
// errs.ErrInternalServer.Msg()).WithDetails(errInfo)
// if err_ != nil {
// panic(err_)
// }
// err = sta.Err()
// }
//}()
funcName := info.FullMethod
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.New(codes.InvalidArgument, "missing metadata").Err()
}
if keys := md.Get(constant.RpcCustomHeader); len(keys) > 0 {
for _, key := range keys {
values := md.Get(key)
if len(values) == 0 {
return nil, status.New(codes.InvalidArgument, fmt.Sprintf("missing metadata key %s", key)).Err()
}
ctx = context.WithValue(ctx, key, values)
}
}
args := make([]string, 0, 4)
if opts := md.Get(constant.OperationID); len(opts) != 1 || opts[0] == "" {
return nil, status.New(codes.InvalidArgument, "operationID error").Err()
} else {
args = append(args, constant.OperationID, opts[0])
ctx = context.WithValue(ctx, constant.OperationID, opts[0])
}
if opts := md.Get(constant.OpUserID); len(opts) == 1 {
args = append(args, constant.OpUserID, opts[0])
ctx = context.WithValue(ctx, constant.OpUserID, opts[0])
}
if opts := md.Get(constant.OpUserPlatform); len(opts) == 1 {
ctx = context.WithValue(ctx, constant.OpUserPlatform, opts[0])
}
if opts := md.Get(constant.ConnID); len(opts) == 1 {
ctx = context.WithValue(ctx, constant.ConnID, opts[0])
}
log.ZInfo(ctx, "rpc server req", "funcName", funcName, "req", rpcString(req))
resp, err = func() (interface{}, error) {
if err := checker.Validate(req); err != nil {
return nil, err
}
return handler(ctx, req)
}()
if err == nil {
log.ZInfo(ctx, "rpc server resp", "funcName", funcName, "resp", rpcString(resp))
return resp, nil
}
log.ZError(ctx, "rpc server resp", err, "funcName", funcName)
unwrap := errs.Unwrap(err)
codeErr := specialerror.ErrCode(unwrap)
if codeErr == nil {
log.ZError(ctx, "rpc InternalServer error", err, "req", req)
codeErr = errs.ErrInternalServer
}
code := codeErr.Code()
if code <= 0 || code > math.MaxUint32 {
log.ZError(ctx, "rpc UnknownError", err, "rpc UnknownCode:", code)
code = errs.ServerInternalError
}
grpcStatus := status.New(codes.Code(code), codeErr.Msg())
var errInfo *errinfo.ErrorInfo
if config.Config.Log.WithStack {
if unwrap != err {
sti, ok := err.(interface{ StackTrace() errors.StackTrace })
if ok {
log.ZWarn(
ctx,
"rpc server resp",
err,
"funcName",
funcName,
"unwrap",
unwrap.Error(),
"stack",
fmt.Sprintf("%+v", err),
)
if fs := sti.StackTrace(); len(fs) > 0 {
pc := uintptr(fs[0])
fn := runtime.FuncForPC(pc)
file, line := fn.FileLine(pc)
errInfo = &errinfo.ErrorInfo{
Path: file,
Line: uint32(line),
Name: fn.Name(),
Cause: unwrap.Error(),
Warp: nil,
}
if arr := strings.Split(err.Error(), ": "); len(arr) > 1 {
errInfo.Warp = arr[:len(arr)-1]
}
}
}
}
}
if errInfo == nil {
errInfo = &errinfo.ErrorInfo{Cause: err.Error()}
}
details, err := grpcStatus.WithDetails(errInfo)
if err != nil {
log.ZWarn(ctx, "rpc server resp WithDetails error", err, "funcName", funcName)
return nil, errs.Wrap(err)
}
log.ZWarn(ctx, "rpc server resp", err, "funcName", funcName)
return nil, details.Err()
}
func GrpcServer() grpc.ServerOption {
return grpc.ChainUnaryInterceptor(RpcServerInterceptor)
}
-47
View File
@@ -1,47 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package specialerror
import "github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
var handlers []func(err error) errs.CodeError
func AddErrHandler(h func(err error) errs.CodeError) {
if h == nil {
panic("nil handler")
}
handlers = append(handlers, h)
}
func AddReplace(target error, codeErr errs.CodeError) {
AddErrHandler(func(err error) errs.CodeError {
if err == target {
return codeErr
}
return nil
})
}
func ErrCode(err error) errs.CodeError {
if codeErr, ok := err.(errs.CodeError); ok {
return codeErr
}
for i := 0; i < len(handlers); i++ {
if codeErr := handlers[i](err); codeErr != nil {
return codeErr
}
}
return nil
}
-41
View File
@@ -1,41 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package network
import (
utils "github.com/OpenIMSDK/open_utils"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
)
func GetRpcRegisterIP(configIP string) (string, error) {
registerIP := configIP
if registerIP == "" {
ip, err := utils.GetLocalIP()
if err != nil {
return "", err
}
registerIP = ip
}
return registerIP, nil
}
func GetListenIP(configIP string) string {
if configIP == "" {
return constant.LocalHost
} else {
return configIP
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ import (
"net/http"
"strconv"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/tools/config"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
-122
View File
@@ -1,122 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tokenverify
import (
"context"
"fmt"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"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"
)
type Claims struct {
UserID string
PlatformID int // login platform
jwt.RegisteredClaims
}
func BuildClaims(uid string, platformID int, ttl int64) Claims {
now := time.Now()
before := now.Add(-time.Minute * 5)
return Claims{
UserID: uid,
PlatformID: platformID,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*24) * time.Hour)), // Expiration time
IssuedAt: jwt.NewNumericDate(now), // Issuing time
NotBefore: jwt.NewNumericDate(before), // Begin Effective time
},
}
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.Secret), nil
}
}
func GetClaimFromToken(tokensString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, utils.Wrap(errs.ErrTokenMalformed, "")
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, utils.Wrap(errs.ErrTokenExpired, "")
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, utils.Wrap(errs.ErrTokenNotValidYet, "")
} else {
return nil, utils.Wrap(errs.ErrTokenUnknown, "")
}
} else {
return nil, utils.Wrap(errs.ErrTokenUnknown, "")
}
} else {
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, utils.Wrap(errs.ErrTokenUnknown, "")
}
}
func CheckAccessV3(ctx context.Context, ownerUserID string) (err error) {
opUserID := mcontext.GetOpUserID(ctx)
if utils.IsContain(opUserID, config.Config.Manager.UserID) {
return nil
}
if opUserID == ownerUserID {
return nil
}
return errs.ErrNoPermission.Wrap(utils.GetSelfFuncName())
}
func IsAppManagerUid(ctx context.Context) bool {
return utils.IsContain(mcontext.GetOpUserID(ctx), config.Config.Manager.UserID)
}
func CheckAdmin(ctx context.Context) error {
if utils.IsContain(mcontext.GetOpUserID(ctx), config.Config.Manager.UserID) {
return nil
}
return errs.ErrNoPermission.Wrap(fmt.Sprintf("user %s is not admin userID", mcontext.GetOpUserID(ctx)))
}
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
return GetClaimFromToken(string(redisToken.([]uint8)))
}
func IsManagerUserID(opUserID string) bool {
return utils.IsContain(opUserID, config.Config.Manager.UserID)
}
func WsVerifyToken(token, userID string, platformID int) error {
claim, err := GetClaimFromToken(token)
if err != nil {
return err
}
if claim.UserID != userID {
return errs.ErrTokenInvalid.Wrap(fmt.Sprintf("token uid %s != userID %s", claim.UserID, userID))
}
if claim.PlatformID != platformID {
return errs.ErrTokenInvalid.Wrap(fmt.Sprintf("token platform %d != %d", claim.PlatformID, platformID))
}
return nil
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tokenverify
import (
"testing"
"github.com/golang-jwt/jwt/v4"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
)
func Test_ParseToken(t *testing.T) {
config.Config.Secret = "OpenIM_server"
claims1 := BuildClaims("123456", constant.AndroidPadPlatformID, 10)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims1)
tokenString, err := token.SignedString([]byte(config.Config.Secret))
if err != nil {
t.Fatal(err)
}
claim2, err := GetClaimFromToken(tokenString)
if err != nil {
t.Fatal(err)
}
t.Log(claim2)
}