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
-51
View File
@@ -1,51 +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 a2r
import (
"context"
"github.com/OpenIMSDK/Open-IM-Server/pkg/checker"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
"github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
)
func Call[A, B, C any](
rpc func(client C, ctx context.Context, req *A, options ...grpc.CallOption) (*B, error),
client C,
c *gin.Context,
) {
var req A
if err := c.BindJSON(&req); err != nil {
log.ZWarn(c, "gin bind json error", err, "req", req)
apiresp.GinError(c, errs.ErrArgs.WithDetail(err.Error()).Wrap()) // 参数错误
return
}
if err := checker.Validate(&req); err != nil {
apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error())) // 参数校验失败
return
}
data, err := rpc(client, c, &req)
if err != nil {
apiresp.GinError(c, err) // RPC调用失败
return
}
apiresp.GinSuccess(c, data) // 成功
}
-19
View File
@@ -1,19 +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 apiresp
type ApiFormat interface {
ApiFormat()
}
-29
View File
@@ -1,29 +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 apiresp
import (
"net/http"
"github.com/gin-gonic/gin"
)
func GinError(c *gin.Context, err error) {
c.JSON(http.StatusOK, ParseError(err))
}
func GinSuccess(c *gin.Context, data any) {
c.JSON(http.StatusOK, ApiSuccess(data))
}
-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 apiresp
import (
"encoding/json"
"net/http"
)
func httpJson(w http.ResponseWriter, data any) {
body, err := json.Marshal(data)
if err != nil {
http.Error(w, "json marshal error: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}
func HttpError(w http.ResponseWriter, err error) {
httpJson(w, ParseError(err))
}
func HttpSuccess(w http.ResponseWriter, data any) {
httpJson(w, ApiSuccess(data))
}
-76
View File
@@ -1,76 +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 apiresp
import (
"reflect"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
)
type ApiResponse struct {
ErrCode int `json:"errCode"`
ErrMsg string `json:"errMsg"`
ErrDlt string `json:"errDlt"`
Data any `json:"data,omitempty"`
}
func isAllFieldsPrivate(v any) bool {
typeOf := reflect.TypeOf(v)
if typeOf == nil {
return false
}
if typeOf.Kind() == reflect.Ptr {
typeOf = typeOf.Elem()
}
if typeOf.Kind() != reflect.Struct {
return false
}
num := typeOf.NumField()
for i := 0; i < num; i++ {
c := typeOf.Field(i).Name[0]
if c >= 'A' && c <= 'Z' {
return false
}
}
return true
}
func ApiSuccess(data any) *ApiResponse {
if format, ok := data.(ApiFormat); ok {
format.ApiFormat()
}
if isAllFieldsPrivate(data) {
return &ApiResponse{}
}
return &ApiResponse{
Data: data,
}
}
func ParseError(err error) *ApiResponse {
if err == nil {
return ApiSuccess(nil)
}
unwrap := errs.Unwrap(err)
if codeErr, ok := unwrap.(errs.CodeError); ok {
resp := ApiResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()}
if resp.ErrDlt == "" {
resp.ErrDlt = err.Error()
}
return &resp
}
return &ApiResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()}
}
+1 -1
View File
@@ -15,7 +15,7 @@
package apistruct
import (
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sdkws "github.com/OpenIMSDK/protocol/sdkws"
)
type SendMsg struct {
+1 -1
View File
@@ -15,7 +15,7 @@
package callbackstruct
import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/OpenIMSDK/tools/errs"
)
type CommonCallbackReq struct {
+1 -1
View File
@@ -16,7 +16,7 @@ package callbackstruct
import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct"
common "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
common "github.com/OpenIMSDK/protocol/sdkws"
)
type CallbackCommand string
+1 -1
View File
@@ -15,7 +15,7 @@
package callbackstruct
import (
sdkws "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
sdkws "github.com/OpenIMSDK/protocol/sdkws"
)
type CallbackBeforeSendSingleMsgReq struct {
+1 -1
View File
@@ -14,7 +14,7 @@
package callbackstruct
import common "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
import common "github.com/OpenIMSDK/protocol/sdkws"
type CallbackBeforePushReq struct {
UserStatusBatchCallbackReq
-28
View File
@@ -1,28 +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 checker
type Checker interface {
Check() error
}
func Validate(args any) error {
if checker, ok := args.(Checker); ok {
if err := checker.Check(); err != nil {
return err
}
}
return nil
}
+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)
}
@@ -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 discoveryregistry
import (
"context"
"google.golang.org/grpc"
)
type Conn interface {
GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]grpc.ClientConnInterface, error)
GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (grpc.ClientConnInterface, error)
AddOption(opts ...grpc.DialOption)
CloseConn(conn grpc.ClientConnInterface)
// do not use this method for call rpc
GetClientLocalConns() map[string][]grpc.ClientConnInterface
}
type SvcDiscoveryRegistry interface {
Conn
Register(serviceName, host string, port int, opts ...grpc.DialOption) error
UnRegister() error
CreateRpcRootNodes(serviceNames []string) error
RegisterConf2Registry(key string, conf []byte) error
GetConfFromRegistry(key string) ([]byte, error)
}
-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 zookeeper
import (
"github.com/go-zookeeper/zk"
)
func (s *ZkClient) RegisterConf2Registry(key string, conf []byte) error {
exists, _, err := s.conn.Exists(s.getPath(key))
if err != nil {
return err
}
if exists {
if err := s.conn.Delete(s.getPath(key), 0); err != nil {
return err
}
}
_, err = s.conn.Create(s.getPath(key), conf, 0, zk.WorldACL(zk.PermAll))
if err != zk.ErrNodeExists {
return err
}
return nil
}
func (s *ZkClient) GetConfFromRegistry(key string) ([]byte, error) {
bytes, _, err := s.conn.Get(s.getPath(key))
return bytes, err
}
-136
View File
@@ -1,136 +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 zookeeper
import (
"context"
"fmt"
"io"
"strings"
"github.com/pkg/errors"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
"github.com/go-zookeeper/zk"
"google.golang.org/grpc"
"google.golang.org/grpc/resolver"
)
var (
ErrConnIsNil = errors.New("conn is nil")
ErrConnIsNilButLocalNotNil = errors.New("conn is nil, but local is not nil")
)
func (s *ZkClient) watch() {
for {
event := <-s.eventChan
switch event.Type {
case zk.EventSession:
if event.State == zk.StateHasSession && s.isRegistered {
s.logger.Printf("zk session event stateHasSession: %+v, client prepare to create new temp node", event)
node, err := s.CreateTempNode(s.rpcRegisterName, s.rpcRegisterAddr)
if err != nil {
s.logger.Printf("zk session event stateHasSession: %+v, create temp node error: %v", event, err)
} else {
s.node = node
}
} else {
s.logger.Printf("zk session event: %+v", event)
}
case zk.EventNodeChildrenChanged:
s.logger.Printf("zk event: %s", event.Path)
l := strings.Split(event.Path, "/")
if len(l) > 1 {
serviceName := l[len(l)-1]
s.lock.Lock()
s.flushResolverAndDeleteLocal(serviceName)
s.lock.Unlock()
}
s.logger.Printf("zk event handle success: %s", event.Path)
case zk.EventNodeDataChanged:
case zk.EventNodeCreated:
case zk.EventNodeDeleted:
case zk.EventNotWatching:
}
}
}
func (s *ZkClient) GetConnsRemote(serviceName string) (conns []resolver.Address, err error) {
path := s.getPath(serviceName)
_, _, _, err = s.conn.ChildrenW(path)
if err != nil {
return nil, errors.Wrap(err, "children watch error")
}
childNodes, _, err := s.conn.Children(path)
if err != nil {
return nil, errors.Wrap(err, "get children error")
} else {
for _, child := range childNodes {
fullPath := path + "/" + child
data, _, err := s.conn.Get(fullPath)
if err != nil {
if err == zk.ErrNoNode {
return nil, errors.Wrap(err, "this is zk ErrNoNode")
}
return nil, errors.Wrap(err, "get children error")
}
log.ZDebug(context.Background(), "get addrs from remote", "conn", string(data))
conns = append(conns, resolver.Address{Addr: string(data), ServerName: serviceName})
}
}
return conns, nil
}
func (s *ZkClient) GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]grpc.ClientConnInterface, error) {
s.logger.Printf("get conns from client, serviceName: %s", serviceName)
s.lock.Lock()
defer s.lock.Unlock()
conns := s.localConns[serviceName]
if len(conns) == 0 {
var err error
s.logger.Printf("get conns from zk remote, serviceName: %s", serviceName)
addrs, err := s.GetConnsRemote(serviceName)
if err != nil {
return nil, err
}
if len(addrs) == 0 {
return nil, fmt.Errorf("no conn for service %s, grpc server may not exist, local conn is %v, please check zookeeper server %v, path: %s", serviceName, s.localConns, s.zkServers, s.zkRoot)
}
for _, addr := range addrs {
cc, err := grpc.DialContext(ctx, addr.Addr, append(s.options, opts...)...)
if err != nil {
log.ZError(context.Background(), "dialContext failed", err, "addr", addr.Addr, "opts", append(s.options, opts...))
return nil, errs.Wrap(err)
}
conns = append(conns, cc)
}
s.localConns[serviceName] = conns
}
return conns, nil
}
func (s *ZkClient) GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (grpc.ClientConnInterface, error) {
newOpts := append(s.options, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, s.balancerName)))
s.logger.Printf("get conn from client, serviceName: %s", serviceName)
return grpc.DialContext(ctx, fmt.Sprintf("%s:///%s", s.scheme, serviceName), append(newOpts, opts...)...)
}
func (s *ZkClient) CloseConn(conn grpc.ClientConnInterface) {
if closer, ok := conn.(io.Closer); ok {
closer.Close()
}
}
@@ -1,76 +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 zookeeper
import (
"time"
"github.com/go-zookeeper/zk"
"google.golang.org/grpc"
)
func (s *ZkClient) CreateRpcRootNodes(serviceNames []string) error {
for _, serviceName := range serviceNames {
if err := s.ensureName(serviceName); err != nil && err != zk.ErrNodeExists {
return err
}
}
return nil
}
func (s *ZkClient) CreateTempNode(rpcRegisterName, addr string) (node string, err error) {
return s.conn.CreateProtectedEphemeralSequential(
s.getPath(rpcRegisterName)+"/"+addr+"_",
[]byte(addr),
zk.WorldACL(zk.PermAll),
)
}
func (s *ZkClient) Register(rpcRegisterName, host string, port int, opts ...grpc.DialOption) error {
if err := s.ensureName(rpcRegisterName); err != nil {
return err
}
addr := s.getAddr(host, port)
_, err := grpc.Dial(addr, opts...)
if err != nil {
return err
}
node, err := s.CreateTempNode(rpcRegisterName, addr)
if err != nil {
return err
}
s.rpcRegisterName = rpcRegisterName
s.rpcRegisterAddr = addr
s.node = node
s.isRegistered = true
return nil
}
func (s *ZkClient) UnRegister() error {
s.lock.Lock()
defer s.lock.Unlock()
err := s.conn.Delete(s.node, -1)
if err != nil {
return err
}
time.Sleep(time.Second)
s.node = ""
s.rpcRegisterName = ""
s.rpcRegisterAddr = ""
s.isRegistered = false
s.localConns = make(map[string][]grpc.ClientConnInterface)
s.resolvers = make(map[string]*Resolver)
return nil
}
@@ -1,93 +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 zookeeper
import (
"context"
"strings"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"google.golang.org/grpc/resolver"
)
type Resolver struct {
target resolver.Target
cc resolver.ClientConn
addrs []resolver.Address
getConnsRemote func(serviceName string) (conns []resolver.Address, err error)
}
func (r *Resolver) ResolveNowZK(o resolver.ResolveNowOptions) {
log.ZDebug(
context.Background(),
"start resolve now",
"target",
r.target,
"cc",
r.cc.UpdateState,
"serviceName",
strings.TrimLeft(r.target.URL.Path, "/"),
)
newConns, err := r.getConnsRemote(strings.TrimLeft(r.target.URL.Path, "/"))
if err != nil {
log.ZError(context.Background(), "resolve now error", err, "target", r.target)
return
}
r.addrs = newConns
if err := r.cc.UpdateState(resolver.State{Addresses: newConns}); err != nil {
log.ZError(
context.Background(),
"UpdateState error, conns is nil from svr",
err,
"conns",
newConns,
"zk path",
r.target.URL.Path,
)
return
}
log.ZDebug(context.Background(), "resolve now finished", "target", r.target, "conns", r.addrs)
}
func (r *Resolver) ResolveNow(o resolver.ResolveNowOptions) {}
func (s *Resolver) Close() {}
func (s *ZkClient) Build(
target resolver.Target,
cc resolver.ClientConn,
opts resolver.BuildOptions,
) (resolver.Resolver, error) {
s.logger.Printf("build resolver: %+v, cc: %+v", target, cc.UpdateState)
serviceName := strings.TrimLeft(target.URL.Path, "/")
if oldResolver, ok := s.resolvers[serviceName]; ok {
s.logger.Printf("rpc resolver exist: %+v, cc: %+v, key: %s", target, cc.UpdateState, serviceName)
return oldResolver, nil
}
r := &Resolver{}
r.target = target
r.cc = cc
r.getConnsRemote = s.GetConnsRemote
r.ResolveNowZK(resolver.ResolveNowOptions{})
s.lock.Lock()
defer s.lock.Unlock()
s.resolvers[serviceName] = r
s.logger.Printf("build resolver finished: %+v, cc: %+v, key: %s", target, cc.UpdateState, serviceName)
return r, nil
}
func (s *ZkClient) Scheme() string { return s.scheme }
-226
View File
@@ -1,226 +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 zookeeper
import (
"net"
"strconv"
"sync"
"time"
"github.com/go-zookeeper/zk"
"google.golang.org/grpc"
"google.golang.org/grpc/resolver"
)
const (
defaultFreq = time.Minute * 30
timeout = 5
)
type Logger interface {
Printf(string, ...interface{})
}
type ZkClient struct {
zkServers []string
zkRoot string
userName string
password string
rpcRegisterName string
rpcRegisterAddr string
isRegistered bool
scheme string
timeout int
conn *zk.Conn
eventChan <-chan zk.Event
node string
ticker *time.Ticker
lock sync.Locker
options []grpc.DialOption
resolvers map[string]*Resolver
localConns map[string][]grpc.ClientConnInterface
balancerName string
logger Logger
}
type ZkOption func(*ZkClient)
func WithRoundRobin() ZkOption {
return func(client *ZkClient) {
client.balancerName = "round_robin"
}
}
func WithUserNameAndPassword(userName, password string) ZkOption {
return func(client *ZkClient) {
client.userName = userName
client.password = password
}
}
func WithOptions(opts ...grpc.DialOption) ZkOption {
return func(client *ZkClient) {
client.options = opts
}
}
func WithFreq(freq time.Duration) ZkOption {
return func(client *ZkClient) {
client.ticker = time.NewTicker(freq)
}
}
func WithTimeout(timeout int) ZkOption {
return func(client *ZkClient) {
client.timeout = timeout
}
}
func WithLogger(logger Logger) ZkOption {
return func(client *ZkClient) {
client.logger = logger
}
}
func NewClient(zkServers []string, zkRoot string, options ...ZkOption) (*ZkClient, error) {
client := &ZkClient{
zkServers: zkServers,
zkRoot: "/",
scheme: zkRoot,
timeout: timeout,
localConns: make(map[string][]grpc.ClientConnInterface),
resolvers: make(map[string]*Resolver),
lock: &sync.Mutex{},
}
client.ticker = time.NewTicker(defaultFreq)
for _, option := range options {
option(client)
}
conn, eventChan, err := zk.Connect(
zkServers,
time.Duration(client.timeout)*time.Second,
zk.WithLogInfo(true),
zk.WithLogger(client.logger),
)
if err != nil {
return nil, err
}
if client.userName != "" && client.password != "" {
if err := conn.AddAuth("digest", []byte(client.userName+":"+client.password)); err != nil {
return nil, err
}
}
client.zkRoot += zkRoot
client.eventChan = eventChan
client.conn = conn
if err := client.ensureRoot(); err != nil {
client.CloseZK()
return nil, err
}
resolver.Register(client)
go client.refresh()
go client.watch()
time.Sleep(time.Millisecond * 50)
return client, nil
}
func (s *ZkClient) CloseZK() {
s.conn.Close()
}
func (s *ZkClient) ensureAndCreate(node string) error {
exists, _, err := s.conn.Exists(node)
if err != nil {
return err
}
if !exists {
_, err := s.conn.Create(node, []byte(""), 0, zk.WorldACL(zk.PermAll))
if err != nil && err != zk.ErrNodeExists {
return err
}
}
return nil
}
func (s *ZkClient) refresh() {
for range s.ticker.C {
s.logger.Printf("refresh local conns")
s.lock.Lock()
for rpcName := range s.resolvers {
s.flushResolver(rpcName)
}
for rpcName := range s.localConns {
delete(s.localConns, rpcName)
}
s.lock.Unlock()
s.logger.Printf("refresh local conns success")
}
}
func (s *ZkClient) flushResolverAndDeleteLocal(serviceName string) {
s.logger.Printf("start flush %s", serviceName)
s.flushResolver(serviceName)
delete(s.localConns, serviceName)
}
func (s *ZkClient) flushResolver(serviceName string) {
r, ok := s.resolvers[serviceName]
if ok {
r.ResolveNowZK(resolver.ResolveNowOptions{})
}
}
func (s *ZkClient) GetZkConn() *zk.Conn {
return s.conn
}
func (s *ZkClient) GetRootPath() string {
return s.zkRoot
}
func (s *ZkClient) GetNode() string {
return s.node
}
func (s *ZkClient) ensureRoot() error {
return s.ensureAndCreate(s.zkRoot)
}
func (s *ZkClient) ensureName(rpcRegisterName string) error {
return s.ensureAndCreate(s.getPath(rpcRegisterName))
}
func (s *ZkClient) getPath(rpcRegisterName string) string {
return s.zkRoot + "/" + rpcRegisterName
}
func (s *ZkClient) getAddr(host string, port int) string {
return net.JoinHostPort(host, strconv.Itoa(port))
}
func (s *ZkClient) AddOption(opts ...grpc.DialOption) {
s.options = append(s.options, opts...)
}
func (s *ZkClient) GetClientLocalConns() map[string][]grpc.ClientConnInterface {
return s.localConns
}
-92
View File
@@ -1,92 +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 errs
// UnknownCode 没有解析到code或解析的code=0.
const UnknownCode = 1000
const (
FormattingError = 10001
HasRegistered = 10002
NotRegistered = 10003
PasswordErr = 10004
GetIMTokenErr = 10005
RepeatSendCode = 10006
MailSendCodeErr = 10007
SmsSendCodeErr = 10008
CodeInvalidOrExpired = 10009
RegisterFailed = 10010
ResetPasswordFailed = 10011
RegisterLimit = 10012
LoginLimit = 10013
InvitationError = 10014
)
// 通用错误码.
const (
NoError = 0 // 无错误
DatabaseError = 90002 // redis/mysql等db错误
NetworkError = 90004 // 网络错误
DataError = 90007 // 数据错误
CallbackError = 80000
// 通用错误码.
ServerInternalError = 500 // 服务器内部错误
ArgsError = 1001 // 输入参数错误
NoPermissionError = 1002 // 权限不足
DuplicateKeyError = 1003
RecordNotFoundError = 1004 // 记录不存在
// 账号错误码.
UserIDNotFoundError = 1101 // UserID不存在 或未注册
RegisteredAlreadyError = 1102 // 用户已经注册过了
// 群组错误码.
GroupIDNotFoundError = 1201 // GroupID不存在
GroupIDExisted = 1202 // GroupID已存在
NotInGroupYetError = 1203 // 不在群组中
DismissedAlreadyError = 1204 // 群组已经解散
GroupTypeNotSupport = 1205
GroupRequestHandled = 1206
// 关系链错误码.
CanNotAddYourselfError = 1301 // 不能添加自己为好友
BlockedByPeer = 1302 // 被对方拉黑
NotPeersFriend = 1303 // 不是对方的好友
RelationshipAlreadyError = 1304 // 已经是好友关系
// 消息错误码.
MessageHasReadDisable = 1401
MutedInGroup = 1402 // 群成员被禁言
MutedGroup = 1403 // 群被禁言
MsgAlreadyRevoke = 1404 // 消息已撤回
// token错误码.
TokenExpiredError = 1501
TokenInvalidError = 1502
TokenMalformedError = 1503
TokenNotValidYetError = 1504
TokenUnknownError = 1505
TokenKickedError = 1506
TokenNotExistError = 1507
// 长连接网关错误码.
ConnOverMaxNumLimit = 1601
ConnArgsErr = 1602
// S3错误码.
FileUploadedExpiredError = 1701 // 上传过期
)
-124
View File
@@ -1,124 +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 errs
import (
"fmt"
"strings"
"github.com/pkg/errors"
)
type CodeError interface {
Code() int
Msg() string
Detail() string
WithDetail(detail string) CodeError
// Is 判断是否是某个错误, loose为false时, 只有错误码相同就认为是同一个错误, 默认为true
Is(err error, loose ...bool) bool
Wrap(msg ...string) error
error
}
func NewCodeError(code int, msg string) CodeError {
return &codeError{
code: code,
msg: msg,
}
}
type codeError struct {
code int
msg string
detail string
}
func (e *codeError) Code() int {
return e.code
}
func (e *codeError) Msg() string {
return e.msg
}
func (e *codeError) Detail() string {
return e.detail
}
func (e *codeError) WithDetail(detail string) CodeError {
var d string
if e.detail == "" {
d = detail
} else {
d = e.detail + ", " + detail
}
return &codeError{
code: e.code,
msg: e.msg,
detail: d,
}
}
func (e *codeError) Wrap(w ...string) error {
return errors.Wrap(e, strings.Join(w, ", "))
}
func (e *codeError) Is(err error, loose ...bool) bool {
if err == nil {
return false
}
var allowSubclasses bool
if len(loose) == 0 {
allowSubclasses = true
} else {
allowSubclasses = loose[0]
}
codeErr, ok := Unwrap(err).(CodeError)
if ok {
if allowSubclasses {
return Relation.Is(e.code, codeErr.Code())
} else {
return codeErr.Code() == e.code
}
}
return false
}
func (e *codeError) Error() string {
return fmt.Sprintf("%s", e.msg)
}
func Unwrap(err error) error {
for err != nil {
unwrap, ok := err.(interface {
Unwrap() error
})
if !ok {
break
}
err = unwrap.Unwrap()
}
return err
}
func Wrap(err error, msg ...string) error {
if err == nil {
return nil
}
if len(msg) == 0 {
return errors.WithStack(err)
}
return errors.Wrap(err, strings.Join(msg, ", "))
}
-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 errs
var (
ErrArgs = NewCodeError(ArgsError, "ArgsError")
ErrNoPermission = NewCodeError(NoPermissionError, "NoPermissionError")
ErrDatabase = NewCodeError(DatabaseError, "DatabaseError")
ErrInternalServer = NewCodeError(ServerInternalError, "ServerInternalError")
ErrNetwork = NewCodeError(NetworkError, "NetworkError")
ErrCallback = NewCodeError(CallbackError, "CallbackError")
ErrCallbackContinue = NewCodeError(CallbackError, "ErrCallbackContinue")
ErrUserIDNotFound = NewCodeError(UserIDNotFoundError, "UserIDNotFoundError")
ErrGroupIDNotFound = NewCodeError(GroupIDNotFoundError, "GroupIDNotFoundError")
ErrGroupIDExisted = NewCodeError(GroupIDExisted, "GroupIDExisted")
ErrRecordNotFound = NewCodeError(RecordNotFoundError, "RecordNotFoundError")
ErrNotInGroupYet = NewCodeError(NotInGroupYetError, "NotInGroupYetError")
ErrDismissedAlready = NewCodeError(DismissedAlreadyError, "DismissedAlreadyError")
ErrRegisteredAlready = NewCodeError(RegisteredAlreadyError, "RegisteredAlreadyError")
ErrGroupTypeNotSupport = NewCodeError(GroupTypeNotSupport, "")
ErrGroupRequestHandled = NewCodeError(GroupRequestHandled, "GroupRequestHandled")
ErrData = NewCodeError(DataError, "DataError")
ErrTokenExpired = NewCodeError(TokenExpiredError, "TokenExpiredError")
ErrTokenInvalid = NewCodeError(TokenInvalidError, "TokenInvalidError") //
ErrTokenMalformed = NewCodeError(TokenMalformedError, "TokenMalformedError") // 格式错误
ErrTokenNotValidYet = NewCodeError(TokenNotValidYetError, "TokenNotValidYetError") // 还未生效
ErrTokenUnknown = NewCodeError(TokenUnknownError, "TokenUnknownError") // 未知错误
ErrTokenKicked = NewCodeError(TokenKickedError, "TokenKickedError")
ErrTokenNotExist = NewCodeError(TokenNotExistError, "TokenNotExistError") // 在redis中不存在
ErrDuplicateKey = NewCodeError(DuplicateKeyError, "DuplicateKeyError")
ErrMessageHasReadDisable = NewCodeError(MessageHasReadDisable, "MessageHasReadDisable")
ErrCanNotAddYourself = NewCodeError(CanNotAddYourselfError, "CanNotAddYourselfError")
ErrBlockedByPeer = NewCodeError(BlockedByPeer, "BlockedByPeer")
ErrNotPeersFriend = NewCodeError(NotPeersFriend, "NotPeersFriend")
ErrRelationshipAlready = NewCodeError(RelationshipAlreadyError, "RelationshipAlreadyError")
ErrMutedInGroup = NewCodeError(MutedInGroup, "MutedInGroup")
ErrMutedGroup = NewCodeError(MutedGroup, "MutedGroup")
ErrMsgAlreadyRevoke = NewCodeError(MsgAlreadyRevoke, "MsgAlreadyRevoke")
ErrConnOverMaxNumLimit = NewCodeError(ConnOverMaxNumLimit, "ConnOverMaxNumLimit")
ErrConnArgsErr = NewCodeError(ConnArgsErr, "args err, need token, sendID, platformID")
ErrFileUploadedExpired = NewCodeError(FileUploadedExpiredError, "FileUploadedExpiredError")
)
-56
View File
@@ -1,56 +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 errs
var Relation = &relation{m: make(map[int]map[int]struct{})}
func init() {
Relation.Add(RecordNotFoundError, UserIDNotFoundError)
Relation.Add(RecordNotFoundError, GroupIDNotFoundError)
Relation.Add(DuplicateKeyError, GroupIDExisted)
}
type relation struct {
m map[int]map[int]struct{}
}
func (r *relation) Add(codes ...int) {
if len(codes) < 2 {
panic("codes length must be greater than 2")
}
for i := 1; i < len(codes); i++ {
parent := codes[i-1]
s, ok := r.m[parent]
if !ok {
s = make(map[int]struct{})
r.m[parent] = s
}
for _, code := range codes[i:] {
s[code] = struct{}{}
}
}
}
func (r *relation) Is(parent, child int) bool {
if parent == child {
return true
}
s, ok := r.m[parent]
if !ok {
return false
}
_, ok = s[child]
return ok
}
-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 auth
import (
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
)
func (x *UserTokenReq) Check() error {
if x.UserID == "" {
return errs.ErrArgs.Wrap("userID is empty")
}
if x.PlatformID > constant.AdminPlatformID || x.PlatformID < constant.IOSPlatformID {
return errs.ErrArgs.Wrap("platform is invalidate")
}
return nil
}
func (x *ForceLogoutReq) Check() error {
if x.UserID == "" {
return errs.ErrArgs.Wrap("userID is empty")
}
if x.PlatformID > constant.AdminPlatformID || x.PlatformID < constant.IOSPlatformID {
return errs.ErrArgs.Wrap("platformID is invalidate")
}
return nil
}
func (x *ParseTokenReq) Check() error {
if x.Token == "" {
return errs.ErrArgs.Wrap("userID is empty")
}
return nil
}
-707
View File
@@ -1,707 +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.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.29.1
// protoc v4.22.0
// source: auth/auth.proto
package auth
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type UserTokenReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Secret string `protobuf:"bytes,1,opt,name=secret,proto3" json:"secret"`
PlatformID int32 `protobuf:"varint,2,opt,name=platformID,proto3" json:"platformID"`
UserID string `protobuf:"bytes,3,opt,name=userID,proto3" json:"userID"`
}
func (x *UserTokenReq) Reset() {
*x = UserTokenReq{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserTokenReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserTokenReq) ProtoMessage() {}
func (x *UserTokenReq) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserTokenReq.ProtoReflect.Descriptor instead.
func (*UserTokenReq) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{0}
}
func (x *UserTokenReq) GetSecret() string {
if x != nil {
return x.Secret
}
return ""
}
func (x *UserTokenReq) GetPlatformID() int32 {
if x != nil {
return x.PlatformID
}
return 0
}
func (x *UserTokenReq) GetUserID() string {
if x != nil {
return x.UserID
}
return ""
}
type UserTokenResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Token string `protobuf:"bytes,2,opt,name=token,proto3" json:"token"`
ExpireTimeSeconds int64 `protobuf:"varint,3,opt,name=expireTimeSeconds,proto3" json:"expireTimeSeconds"`
}
func (x *UserTokenResp) Reset() {
*x = UserTokenResp{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserTokenResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserTokenResp) ProtoMessage() {}
func (x *UserTokenResp) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserTokenResp.ProtoReflect.Descriptor instead.
func (*UserTokenResp) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{1}
}
func (x *UserTokenResp) GetToken() string {
if x != nil {
return x.Token
}
return ""
}
func (x *UserTokenResp) GetExpireTimeSeconds() int64 {
if x != nil {
return x.ExpireTimeSeconds
}
return 0
}
type ForceLogoutReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
PlatformID int32 `protobuf:"varint,1,opt,name=platformID,proto3" json:"platformID"`
UserID string `protobuf:"bytes,2,opt,name=userID,proto3" json:"userID"`
}
func (x *ForceLogoutReq) Reset() {
*x = ForceLogoutReq{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ForceLogoutReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ForceLogoutReq) ProtoMessage() {}
func (x *ForceLogoutReq) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ForceLogoutReq.ProtoReflect.Descriptor instead.
func (*ForceLogoutReq) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{2}
}
func (x *ForceLogoutReq) GetPlatformID() int32 {
if x != nil {
return x.PlatformID
}
return 0
}
func (x *ForceLogoutReq) GetUserID() string {
if x != nil {
return x.UserID
}
return ""
}
type ForceLogoutResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *ForceLogoutResp) Reset() {
*x = ForceLogoutResp{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ForceLogoutResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ForceLogoutResp) ProtoMessage() {}
func (x *ForceLogoutResp) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ForceLogoutResp.ProtoReflect.Descriptor instead.
func (*ForceLogoutResp) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{3}
}
type ParseTokenReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token"`
}
func (x *ParseTokenReq) Reset() {
*x = ParseTokenReq{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ParseTokenReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ParseTokenReq) ProtoMessage() {}
func (x *ParseTokenReq) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ParseTokenReq.ProtoReflect.Descriptor instead.
func (*ParseTokenReq) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{4}
}
func (x *ParseTokenReq) GetToken() string {
if x != nil {
return x.Token
}
return ""
}
type ParseTokenResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
UserID string `protobuf:"bytes,1,opt,name=userID,proto3" json:"userID"`
Platform string `protobuf:"bytes,2,opt,name=platform,proto3" json:"platform"`
ExpireTimeSeconds int64 `protobuf:"varint,4,opt,name=expireTimeSeconds,proto3" json:"expireTimeSeconds"`
}
func (x *ParseTokenResp) Reset() {
*x = ParseTokenResp{}
if protoimpl.UnsafeEnabled {
mi := &file_auth_auth_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ParseTokenResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ParseTokenResp) ProtoMessage() {}
func (x *ParseTokenResp) ProtoReflect() protoreflect.Message {
mi := &file_auth_auth_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ParseTokenResp.ProtoReflect.Descriptor instead.
func (*ParseTokenResp) Descriptor() ([]byte, []int) {
return file_auth_auth_proto_rawDescGZIP(), []int{5}
}
func (x *ParseTokenResp) GetUserID() string {
if x != nil {
return x.UserID
}
return ""
}
func (x *ParseTokenResp) GetPlatform() string {
if x != nil {
return x.Platform
}
return ""
}
func (x *ParseTokenResp) GetExpireTimeSeconds() int64 {
if x != nil {
return x.ExpireTimeSeconds
}
return 0
}
var File_auth_auth_proto protoreflect.FileDescriptor
var file_auth_auth_proto_rawDesc = []byte{
0x0a, 0x0f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x11, 0x4f, 0x70, 0x65, 0x6e, 0x49, 0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e,
0x61, 0x75, 0x74, 0x68, 0x22, 0x5e, 0x0a, 0x0c, 0x75, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x6b, 0x65,
0x6e, 0x52, 0x65, 0x71, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x12, 0x1e, 0x0a, 0x0a,
0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05,
0x52, 0x0a, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x49, 0x44, 0x12, 0x16, 0x0a, 0x06,
0x75, 0x73, 0x65, 0x72, 0x49, 0x44, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73,
0x65, 0x72, 0x49, 0x44, 0x22, 0x53, 0x0a, 0x0d, 0x75, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x6b, 0x65,
0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02,
0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x2c, 0x0a, 0x11, 0x65,
0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73,
0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69,
0x6d, 0x65, 0x53, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x22, 0x48, 0x0a, 0x0e, 0x66, 0x6f, 0x72,
0x63, 0x65, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x12, 0x1e, 0x0a, 0x0a, 0x70,
0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52,
0x0a, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x49, 0x44, 0x12, 0x16, 0x0a, 0x06, 0x75,
0x73, 0x65, 0x72, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65,
0x72, 0x49, 0x44, 0x22, 0x11, 0x0a, 0x0f, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x6f,
0x75, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, 0x25, 0x0a, 0x0d, 0x70, 0x61, 0x72, 0x73, 0x65, 0x54,
0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e,
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x72, 0x0a,
0x0e, 0x70, 0x61, 0x72, 0x73, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12,
0x16, 0x0a, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x44, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x6c, 0x61, 0x74, 0x66,
0x6f, 0x72, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x6c, 0x61, 0x74, 0x66,
0x6f, 0x72, 0x6d, 0x12, 0x2c, 0x0a, 0x11, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d,
0x65, 0x53, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x11,
0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x53, 0x65, 0x63, 0x6f, 0x6e, 0x64,
0x73, 0x32, 0xff, 0x01, 0x0a, 0x04, 0x41, 0x75, 0x74, 0x68, 0x12, 0x4e, 0x0a, 0x09, 0x75, 0x73,
0x65, 0x72, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x1f, 0x2e, 0x4f, 0x70, 0x65, 0x6e, 0x49, 0x4d,
0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x75, 0x73, 0x65, 0x72,
0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x71, 0x1a, 0x20, 0x2e, 0x4f, 0x70, 0x65, 0x6e, 0x49,
0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x75, 0x73, 0x65,
0x72, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x54, 0x0a, 0x0b, 0x66, 0x6f,
0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x12, 0x21, 0x2e, 0x4f, 0x70, 0x65, 0x6e,
0x49, 0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x66, 0x6f,
0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x22, 0x2e, 0x4f,
0x70, 0x65, 0x6e, 0x49, 0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x61, 0x75, 0x74, 0x68,
0x2e, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x73, 0x70,
0x12, 0x51, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x73, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x20,
0x2e, 0x4f, 0x70, 0x65, 0x6e, 0x49, 0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x61, 0x75,
0x74, 0x68, 0x2e, 0x70, 0x61, 0x72, 0x73, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x71,
0x1a, 0x21, 0x2e, 0x4f, 0x70, 0x65, 0x6e, 0x49, 0x4d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e,
0x61, 0x75, 0x74, 0x68, 0x2e, 0x70, 0x61, 0x72, 0x73, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52,
0x65, 0x73, 0x70, 0x42, 0x34, 0x5a, 0x32, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f,
0x6d, 0x2f, 0x4f, 0x70, 0x65, 0x6e, 0x49, 0x4d, 0x53, 0x44, 0x4b, 0x2f, 0x4f, 0x70, 0x65, 0x6e,
0x2d, 0x49, 0x4d, 0x2d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var (
file_auth_auth_proto_rawDescOnce sync.Once
file_auth_auth_proto_rawDescData = file_auth_auth_proto_rawDesc
)
func file_auth_auth_proto_rawDescGZIP() []byte {
file_auth_auth_proto_rawDescOnce.Do(func() {
file_auth_auth_proto_rawDescData = protoimpl.X.CompressGZIP(file_auth_auth_proto_rawDescData)
})
return file_auth_auth_proto_rawDescData
}
var file_auth_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_auth_auth_proto_goTypes = []interface{}{
(*UserTokenReq)(nil), // 0: OpenIMServer.auth.userTokenReq
(*UserTokenResp)(nil), // 1: OpenIMServer.auth.userTokenResp
(*ForceLogoutReq)(nil), // 2: OpenIMServer.auth.forceLogoutReq
(*ForceLogoutResp)(nil), // 3: OpenIMServer.auth.forceLogoutResp
(*ParseTokenReq)(nil), // 4: OpenIMServer.auth.parseTokenReq
(*ParseTokenResp)(nil), // 5: OpenIMServer.auth.parseTokenResp
}
var file_auth_auth_proto_depIdxs = []int32{
0, // 0: OpenIMServer.auth.Auth.userToken:input_type -> OpenIMServer.auth.userTokenReq
2, // 1: OpenIMServer.auth.Auth.forceLogout:input_type -> OpenIMServer.auth.forceLogoutReq
4, // 2: OpenIMServer.auth.Auth.parseToken:input_type -> OpenIMServer.auth.parseTokenReq
1, // 3: OpenIMServer.auth.Auth.userToken:output_type -> OpenIMServer.auth.userTokenResp
3, // 4: OpenIMServer.auth.Auth.forceLogout:output_type -> OpenIMServer.auth.forceLogoutResp
5, // 5: OpenIMServer.auth.Auth.parseToken:output_type -> OpenIMServer.auth.parseTokenResp
3, // [3:6] is the sub-list for method output_type
0, // [0:3] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_auth_auth_proto_init() }
func file_auth_auth_proto_init() {
if File_auth_auth_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_auth_auth_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserTokenReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_auth_auth_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserTokenResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_auth_auth_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ForceLogoutReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_auth_auth_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ForceLogoutResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_auth_auth_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ParseTokenReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_auth_auth_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ParseTokenResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_auth_auth_proto_rawDesc,
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_auth_auth_proto_goTypes,
DependencyIndexes: file_auth_auth_proto_depIdxs,
MessageInfos: file_auth_auth_proto_msgTypes,
}.Build()
File_auth_auth_proto = out.File
file_auth_auth_proto_rawDesc = nil
file_auth_auth_proto_goTypes = nil
file_auth_auth_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// AuthClient is the client API for Auth service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AuthClient interface {
// 生成token
UserToken(ctx context.Context, in *UserTokenReq, opts ...grpc.CallOption) (*UserTokenResp, error)
// 强制退出登录
ForceLogout(ctx context.Context, in *ForceLogoutReq, opts ...grpc.CallOption) (*ForceLogoutResp, error)
// 解析token
ParseToken(ctx context.Context, in *ParseTokenReq, opts ...grpc.CallOption) (*ParseTokenResp, error)
}
type authClient struct {
cc grpc.ClientConnInterface
}
func NewAuthClient(cc grpc.ClientConnInterface) AuthClient {
return &authClient{cc}
}
func (c *authClient) UserToken(ctx context.Context, in *UserTokenReq, opts ...grpc.CallOption) (*UserTokenResp, error) {
out := new(UserTokenResp)
err := c.cc.Invoke(ctx, "/OpenIMServer.auth.Auth/userToken", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authClient) ForceLogout(ctx context.Context, in *ForceLogoutReq, opts ...grpc.CallOption) (*ForceLogoutResp, error) {
out := new(ForceLogoutResp)
err := c.cc.Invoke(ctx, "/OpenIMServer.auth.Auth/forceLogout", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authClient) ParseToken(ctx context.Context, in *ParseTokenReq, opts ...grpc.CallOption) (*ParseTokenResp, error) {
out := new(ParseTokenResp)
err := c.cc.Invoke(ctx, "/OpenIMServer.auth.Auth/parseToken", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// AuthServer is the server API for Auth service.
type AuthServer interface {
// 生成token
UserToken(context.Context, *UserTokenReq) (*UserTokenResp, error)
// 强制退出登录
ForceLogout(context.Context, *ForceLogoutReq) (*ForceLogoutResp, error)
// 解析token
ParseToken(context.Context, *ParseTokenReq) (*ParseTokenResp, error)
}
// UnimplementedAuthServer can be embedded to have forward compatible implementations.
type UnimplementedAuthServer struct {
}
func (*UnimplementedAuthServer) UserToken(context.Context, *UserTokenReq) (*UserTokenResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method UserToken not implemented")
}
func (*UnimplementedAuthServer) ForceLogout(context.Context, *ForceLogoutReq) (*ForceLogoutResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ForceLogout not implemented")
}
func (*UnimplementedAuthServer) ParseToken(context.Context, *ParseTokenReq) (*ParseTokenResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ParseToken not implemented")
}
func RegisterAuthServer(s *grpc.Server, srv AuthServer) {
s.RegisterService(&_Auth_serviceDesc, srv)
}
func _Auth_UserToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserTokenReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServer).UserToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/OpenIMServer.auth.Auth/UserToken",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServer).UserToken(ctx, req.(*UserTokenReq))
}
return interceptor(ctx, in, info, handler)
}
func _Auth_ForceLogout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ForceLogoutReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServer).ForceLogout(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/OpenIMServer.auth.Auth/ForceLogout",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServer).ForceLogout(ctx, req.(*ForceLogoutReq))
}
return interceptor(ctx, in, info, handler)
}
func _Auth_ParseToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ParseTokenReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServer).ParseToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/OpenIMServer.auth.Auth/ParseToken",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServer).ParseToken(ctx, req.(*ParseTokenReq))
}
return interceptor(ctx, in, info, handler)
}
var _Auth_serviceDesc = grpc.ServiceDesc{
ServiceName: "OpenIMServer.auth.Auth",
HandlerType: (*AuthServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "userToken",
Handler: _Auth_UserToken_Handler,
},
{
MethodName: "forceLogout",
Handler: _Auth_ForceLogout_Handler,
},
{
MethodName: "parseToken",
Handler: _Auth_ParseToken_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "auth/auth.proto",
}
-55
View File
@@ -1,55 +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.
syntax = "proto3";
package OpenIMServer.auth;
option go_package = "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/auth";
message userTokenReq {
string secret = 1;
int32 platformID = 2;
string userID = 3;
}
message userTokenResp {
string token = 2;
int64 expireTimeSeconds = 3;
}
message forceLogoutReq {
int32 platformID = 1;
string userID = 2;
}
message forceLogoutResp {
}
message parseTokenReq{
string token = 1;
}
message parseTokenResp{
string userID = 1;
string platform = 2;
int64 expireTimeSeconds = 4;
}
service Auth {
//token
rpc userToken(userTokenReq) returns(userTokenResp);
//退
rpc forceLogout(forceLogoutReq) returns(forceLogoutResp);
//token
rpc parseToken(parseTokenReq)returns(parseTokenResp);
}

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