diff --git a/cmd/openim-api/main.go b/cmd/openim-api/main.go index dbc117edf..925ea4045 100644 --- a/cmd/openim-api/main.go +++ b/cmd/openim-api/main.go @@ -28,12 +28,12 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/internal/api" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "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/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - openKeeper "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + openKeeper "github.com/OpenIMSDK/tools/discoveryregistry/zookeeper" + "github.com/OpenIMSDK/tools/log" ) func main() { diff --git a/cmd/openim-push/main.go b/cmd/openim-push/main.go index 03db8ae03..adc3a7cb7 100644 --- a/cmd/openim-push/main.go +++ b/cmd/openim-push/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/push" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-auth/main.go b/cmd/openim-rpc/openim-rpc-auth/main.go index 524804988..62bb65fab 100644 --- a/cmd/openim-rpc/openim-rpc-auth/main.go +++ b/cmd/openim-rpc/openim-rpc-auth/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/auth" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-conversation/main.go b/cmd/openim-rpc/openim-rpc-conversation/main.go index fec8226f8..0465de868 100644 --- a/cmd/openim-rpc/openim-rpc-conversation/main.go +++ b/cmd/openim-rpc/openim-rpc-conversation/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/conversation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-friend/main.go b/cmd/openim-rpc/openim-rpc-friend/main.go index fbd44038e..7a0631a20 100644 --- a/cmd/openim-rpc/openim-rpc-friend/main.go +++ b/cmd/openim-rpc/openim-rpc-friend/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/friend" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-group/main.go b/cmd/openim-rpc/openim-rpc-group/main.go index 06baac155..af78868d2 100644 --- a/cmd/openim-rpc/openim-rpc-group/main.go +++ b/cmd/openim-rpc/openim-rpc-group/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/group" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-msg/main.go b/cmd/openim-rpc/openim-rpc-msg/main.go index 356081d33..6bdd4842d 100644 --- a/cmd/openim-rpc/openim-rpc-msg/main.go +++ b/cmd/openim-rpc/openim-rpc-msg/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/msg" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-third/main.go b/cmd/openim-rpc/openim-rpc-third/main.go index c070e6811..2136bc157 100644 --- a/cmd/openim-rpc/openim-rpc-third/main.go +++ b/cmd/openim-rpc/openim-rpc-third/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/third" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/cmd/openim-rpc/openim-rpc-user/main.go b/cmd/openim-rpc/openim-rpc-user/main.go index 6d6d9008d..16a24c812 100644 --- a/cmd/openim-rpc/openim-rpc-user/main.go +++ b/cmd/openim-rpc/openim-rpc-user/main.go @@ -17,7 +17,7 @@ package main import ( "github.com/OpenIMSDK/Open-IM-Server/internal/rpc/user" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/cmd" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func main() { diff --git a/internal/api/custom_validator.go b/internal/api/custom_validator.go index 42e50647f..7425ecb38 100644 --- a/internal/api/custom_validator.go +++ b/internal/api/custom_validator.go @@ -17,7 +17,7 @@ package api import ( "github.com/go-playground/validator/v10" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" + "github.com/OpenIMSDK/tools/constant" ) func RequiredIf(fl validator.FieldLevel) bool { diff --git a/internal/api/msg.go b/internal/api/msg.go index c08912ac8..d79be716b 100644 --- a/internal/api/msg.go +++ b/internal/api/msg.go @@ -20,17 +20,17 @@ import ( "github.com/mitchellh/mapstructure" "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" "github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/tools/a2r" + "github.com/OpenIMSDK/tools/apiresp" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) type MessageApi struct { diff --git a/internal/api/route.go b/internal/api/route.go index 2dfb9f6c4..bc69ff8b3 100644 --- a/internal/api/route.go +++ b/internal/api/route.go @@ -24,12 +24,12 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mw" ) func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.UniversalClient) *gin.Engine { diff --git a/internal/api/third.go b/internal/api/third.go index 86daccb17..e480d4c11 100644 --- a/internal/api/third.go +++ b/internal/api/third.go @@ -20,11 +20,11 @@ import ( "net/http" "strconv" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/third" "github.com/OpenIMSDK/tools/a2r" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/mcontext" ) type ThirdApi rpcclient.Third diff --git a/internal/api/user.go b/internal/api/user.go index f1e1245b8..c7bcf7862 100644 --- a/internal/api/user.go +++ b/internal/api/user.go @@ -17,15 +17,15 @@ package api import ( "github.com/gin-gonic/gin" - "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/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/msggateway" "github.com/OpenIMSDK/protocol/user" "github.com/OpenIMSDK/tools/a2r" + "github.com/OpenIMSDK/tools/apiresp" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" ) type UserApi rpcclient.User diff --git a/internal/msggateway/callback.go b/internal/msggateway/callback.go index d705e25f0..530c18102 100644 --- a/internal/msggateway/callback.go +++ b/internal/msggateway/callback.go @@ -19,10 +19,10 @@ import ( "time" cbapi "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/http" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/mcontext" ) func url() string { diff --git a/internal/msggateway/client.go b/internal/msggateway/client.go index 212d8e8b2..bc5fa1511 100644 --- a/internal/msggateway/client.go +++ b/internal/msggateway/client.go @@ -23,12 +23,12 @@ import ( "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/apiresp" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) var ( diff --git a/internal/msggateway/compressor.go b/internal/msggateway/compressor.go index 99b827454..0639fb4f0 100644 --- a/internal/msggateway/compressor.go +++ b/internal/msggateway/compressor.go @@ -19,7 +19,7 @@ import ( "compress/gzip" "io" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/utils" ) type Compressor interface { diff --git a/internal/msggateway/context.go b/internal/msggateway/context.go index e1d066467..672ba1dbe 100644 --- a/internal/msggateway/context.go +++ b/internal/msggateway/context.go @@ -19,8 +19,8 @@ import ( "strconv" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/utils" ) type UserConnContext struct { diff --git a/internal/msggateway/encoder.go b/internal/msggateway/encoder.go index 41ab02d0c..9791acb39 100644 --- a/internal/msggateway/encoder.go +++ b/internal/msggateway/encoder.go @@ -18,7 +18,7 @@ import ( "bytes" "encoding/gob" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/utils" ) type Encoder interface { diff --git a/internal/msggateway/http_error.go b/internal/msggateway/http_error.go index 03121aba3..03881cf27 100644 --- a/internal/msggateway/http_error.go +++ b/internal/msggateway/http_error.go @@ -14,7 +14,7 @@ package msggateway -import "github.com/OpenIMSDK/Open-IM-Server/pkg/apiresp" +import "github.com/OpenIMSDK/tools/apiresp" func httpError(ctx *UserConnContext, err error) { apiresp.HttpError(ctx.RespWriter, err) diff --git a/internal/msggateway/hub_server.go b/internal/msggateway/hub_server.go index e32e8f7fe..dc440a7c8 100644 --- a/internal/msggateway/hub_server.go +++ b/internal/msggateway/hub_server.go @@ -18,19 +18,19 @@ import ( "context" "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/errs" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/tokenverify" "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/startrpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msggateway" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/startrpc" + "github.com/OpenIMSDK/tools/utils" ) func (s *Server) InitServer(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { diff --git a/internal/msggateway/init.go b/internal/msggateway/init.go index 3ec2a56ac..b6d4d3b58 100644 --- a/internal/msggateway/init.go +++ b/internal/msggateway/init.go @@ -18,7 +18,7 @@ import ( "fmt" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) func RunWsAndServer(rpcPort, wsPort, prometheusPort int) error { diff --git a/internal/msggateway/message_handler.go b/internal/msggateway/message_handler.go index 61157473c..8e3512238 100644 --- a/internal/msggateway/message_handler.go +++ b/internal/msggateway/message_handler.go @@ -17,16 +17,16 @@ package msggateway import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/protocol/push" + "github.com/OpenIMSDK/tools/discoveryregistry" "github.com/go-playground/validator/v10" "google.golang.org/protobuf/proto" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/utils" ) type Req struct { diff --git a/internal/msggateway/n_ws_server.go b/internal/msggateway/n_ws_server.go index c2b46cf1f..9715f21b6 100644 --- a/internal/msggateway/n_ws_server.go +++ b/internal/msggateway/n_ws_server.go @@ -23,20 +23,20 @@ import ( "sync/atomic" "time" - "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/tools/config" + "github.com/OpenIMSDK/tools/constant" "github.com/redis/go-redis/v9" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" + "github.com/OpenIMSDK/tools/discoveryregistry" "github.com/go-playground/validator/v10" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) type LongConnServer interface { diff --git a/internal/msggateway/user_map.go b/internal/msggateway/user_map.go index 7e62557b2..052d7de2d 100644 --- a/internal/msggateway/user_map.go +++ b/internal/msggateway/user_map.go @@ -18,8 +18,8 @@ import ( "context" "sync" - "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 UserMap struct { diff --git a/internal/msgtransfer/init.go b/internal/msgtransfer/init.go index 61e154655..53c1dfcab 100644 --- a/internal/msgtransfer/init.go +++ b/internal/msgtransfer/init.go @@ -22,17 +22,17 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "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/common/db/unrelation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - openKeeper "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" + "github.com/OpenIMSDK/tools/config" + openKeeper "github.com/OpenIMSDK/tools/discoveryregistry/zookeeper" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mw" ) type MsgTransfer struct { diff --git a/internal/msgtransfer/online_history_msg_handler.go b/internal/msgtransfer/online_history_msg_handler.go index 504ad9d61..19121334a 100644 --- a/internal/msgtransfer/online_history_msg_handler.go +++ b/internal/msgtransfer/online_history_msg_handler.go @@ -21,21 +21,21 @@ import ( "sync" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" + "github.com/OpenIMSDK/tools/errs" "github.com/Shopify/sarama" "github.com/go-redis/redis" "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "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/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "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/mcontext" + "github.com/OpenIMSDK/tools/utils" ) const ( diff --git a/internal/msgtransfer/online_msg_to_mongo_handler.go b/internal/msgtransfer/online_msg_to_mongo_handler.go index f048a0513..9ba4cb7b9 100644 --- a/internal/msgtransfer/online_msg_to_mongo_handler.go +++ b/internal/msgtransfer/online_msg_to_mongo_handler.go @@ -20,11 +20,11 @@ import ( "github.com/Shopify/sarama" "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" pbMsg "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/log" ) type OnlineHistoryMongoConsumerHandler struct { diff --git a/internal/msgtransfer/persistent_msg_handler.go b/internal/msgtransfer/persistent_msg_handler.go index a1ecdefbe..7256a3442 100644 --- a/internal/msgtransfer/persistent_msg_handler.go +++ b/internal/msgtransfer/persistent_msg_handler.go @@ -17,13 +17,13 @@ package msgtransfer import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbMsg "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/utils" "github.com/Shopify/sarama" "google.golang.org/protobuf/proto" diff --git a/internal/push/callback.go b/internal/push/callback.go index ca29113c5..9264df22a 100644 --- a/internal/push/callback.go +++ b/internal/push/callback.go @@ -18,13 +18,13 @@ import ( "context" "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/http" - "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/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func url() string { diff --git a/internal/push/offlinepush/fcm/push.go b/internal/push/offlinepush/fcm/push.go index a5294961d..1f519a523 100644 --- a/internal/push/offlinepush/fcm/push.go +++ b/internal/push/offlinepush/fcm/push.go @@ -24,9 +24,9 @@ import ( "google.golang.org/api/option" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" ) const SinglePushCountLimit = 400 diff --git a/internal/push/offlinepush/getui/body.go b/internal/push/offlinepush/getui/body.go index 915c6f603..43fcc84cc 100644 --- a/internal/push/offlinepush/getui/body.go +++ b/internal/push/offlinepush/getui/body.go @@ -17,7 +17,7 @@ package getui import ( "fmt" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) type Resp struct { diff --git a/internal/push/offlinepush/getui/push.go b/internal/push/offlinepush/getui/push.go index ada5ac8b6..670874da7 100644 --- a/internal/push/offlinepush/getui/push.go +++ b/internal/push/offlinepush/getui/push.go @@ -26,15 +26,15 @@ import ( "github.com/go-redis/redis" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" http2 "github.com/OpenIMSDK/Open-IM-Server/pkg/common/http" - "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/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/utils/splitter" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/utils" ) var ( diff --git a/internal/push/offlinepush/jpush/body/notification.go b/internal/push/offlinepush/jpush/body/notification.go index cec725784..85581cb1f 100644 --- a/internal/push/offlinepush/jpush/body/notification.go +++ b/internal/push/offlinepush/jpush/body/notification.go @@ -15,7 +15,7 @@ package body import ( - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) type Notification struct { diff --git a/internal/push/offlinepush/jpush/body/platform.go b/internal/push/offlinepush/jpush/body/platform.go index a4bc1526c..c779c8bdc 100644 --- a/internal/push/offlinepush/jpush/body/platform.go +++ b/internal/push/offlinepush/jpush/body/platform.go @@ -17,7 +17,7 @@ package body import ( "errors" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" + "github.com/OpenIMSDK/tools/constant" ) const ( diff --git a/internal/push/offlinepush/jpush/push.go b/internal/push/offlinepush/jpush/push.go index 64933db50..d661daee9 100644 --- a/internal/push/offlinepush/jpush/push.go +++ b/internal/push/offlinepush/jpush/push.go @@ -21,8 +21,8 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush/jpush/body" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" http2 "github.com/OpenIMSDK/Open-IM-Server/pkg/common/http" + "github.com/OpenIMSDK/tools/config" ) type JPush struct{} diff --git a/internal/push/push_handler.go b/internal/push/push_handler.go index 273fa12a9..f0a67faac 100644 --- a/internal/push/push_handler.go +++ b/internal/push/push_handler.go @@ -20,13 +20,13 @@ import ( "github.com/Shopify/sarama" "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" kfk "github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbChat "github.com/OpenIMSDK/protocol/msg" pbPush "github.com/OpenIMSDK/protocol/push" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/utils" ) type ConsumerHandler struct { diff --git a/internal/push/push_rpc_server.go b/internal/push/push_rpc_server.go index 505b0a3aa..dfcf07469 100644 --- a/internal/push/push_rpc_server.go +++ b/internal/push/push_rpc_server.go @@ -20,14 +20,14 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/localcache" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" pbPush "github.com/OpenIMSDK/protocol/push" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/log" ) type pushServer struct { diff --git a/internal/push/push_to_client.go b/internal/push/push_to_client.go index 836492046..de6b78782 100644 --- a/internal/push/push_to_client.go +++ b/internal/push/push_to_client.go @@ -23,19 +23,19 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush/fcm" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush/getui" "github.com/OpenIMSDK/Open-IM-Server/internal/push/offlinepush/jpush" - "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/db/localcache" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msggateway" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) type Pusher struct { diff --git a/internal/rpc/auth/auth.go b/internal/rpc/auth/auth.go index b9dab13d5..48e4e5922 100644 --- a/internal/rpc/auth/auth.go +++ b/internal/rpc/auth/auth.go @@ -19,19 +19,19 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "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/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbAuth "github.com/OpenIMSDK/protocol/auth" "github.com/OpenIMSDK/protocol/msggateway" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) type authServer struct { diff --git a/internal/rpc/conversation/conversaion.go b/internal/rpc/conversation/conversaion.go index 51fd1b8a1..e27756749 100644 --- a/internal/rpc/conversation/conversaion.go +++ b/internal/rpc/conversation/conversaion.go @@ -19,20 +19,20 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" tableRelation "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/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbConversation "github.com/OpenIMSDK/protocol/conversation" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tx" + "github.com/OpenIMSDK/tools/utils" ) type conversationServer struct { diff --git a/internal/rpc/friend/black.go b/internal/rpc/friend/black.go index 4b83e56f6..6f7ed58dd 100644 --- a/internal/rpc/friend/black.go +++ b/internal/rpc/friend/black.go @@ -20,9 +20,9 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" pbFriend "github.com/OpenIMSDK/protocol/friend" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/tokenverify" ) func (s *friendServer) GetPaginationBlacks( diff --git a/internal/rpc/friend/callback.go b/internal/rpc/friend/callback.go index eaf6509ce..d3a793a6f 100644 --- a/internal/rpc/friend/callback.go +++ b/internal/rpc/friend/callback.go @@ -18,12 +18,12 @@ import ( "context" cbapi "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/http" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" pbfriend "github.com/OpenIMSDK/protocol/friend" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/mcontext" ) func CallbackBeforeAddFriend(ctx context.Context, req *pbfriend.ApplyToAddFriendReq) error { diff --git a/internal/rpc/friend/friend.go b/internal/rpc/friend/friend.go index 283e89c90..de3c398c6 100644 --- a/internal/rpc/friend/friend.go +++ b/internal/rpc/friend/friend.go @@ -18,23 +18,23 @@ import ( "context" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" + "github.com/OpenIMSDK/tools/log" "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" tablerelation "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/tokenverify" - registry "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbfriend "github.com/OpenIMSDK/protocol/friend" + "github.com/OpenIMSDK/tools/constant" + registry "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/tx" + "github.com/OpenIMSDK/tools/utils" ) type friendServer struct { @@ -83,6 +83,11 @@ func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error { return nil } +func (s *friendServer) GetDesignatedFriendsApply(ctx context.Context, req *pbfriend.GetDesignatedFriendsApplyReq) (*pbfriend.GetDesignatedFriendsApplyResp, error) { + //TODO implement me + panic("implement me") +} + // ok. func (s *friendServer) ApplyToAddFriend( ctx context.Context, diff --git a/internal/rpc/group/callback.go b/internal/rpc/group/callback.go index 9a215b692..2f85a6674 100644 --- a/internal/rpc/group/callback.go +++ b/internal/rpc/group/callback.go @@ -20,15 +20,15 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/pkg/apistruct" "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/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/http" - "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/protocol/group" "github.com/OpenIMSDK/protocol/wrapperspb" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (err error) { diff --git a/internal/rpc/group/db_map.go b/internal/rpc/group/db_map.go index c7e485d3c..bdb4d41d2 100644 --- a/internal/rpc/group/db_map.go +++ b/internal/rpc/group/db_map.go @@ -18,7 +18,7 @@ import ( "context" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" + "github.com/OpenIMSDK/tools/mcontext" pbGroup "github.com/OpenIMSDK/protocol/group" "github.com/OpenIMSDK/protocol/sdkws" diff --git a/internal/rpc/group/fill.go b/internal/rpc/group/fill.go index 47b536301..9cf15f8a2 100644 --- a/internal/rpc/group/fill.go +++ b/internal/rpc/group/fill.go @@ -18,7 +18,7 @@ import ( "context" 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" ) func (s *groupServer) FindGroupMember( diff --git a/internal/rpc/group/group.go b/internal/rpc/group/group.go index 14ca5aec9..4c041e13a 100644 --- a/internal/rpc/group/group.go +++ b/internal/rpc/group/group.go @@ -29,25 +29,25 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" + "github.com/OpenIMSDK/tools/mw/specialerror" "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "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/common/db/unrelation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbGroup "github.com/OpenIMSDK/protocol/group" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { @@ -94,6 +94,11 @@ type groupServer struct { msgRpcClient rpcclient.MessageRpcClient } +func (s *groupServer) GetGroupUsersReqApplicationList(ctx context.Context, req *pbGroup.GetGroupUsersReqApplicationListReq) (*pbGroup.GetGroupUsersReqApplicationListResp, error) { + //TODO implement me + panic("implement me") +} + func (s *groupServer) CheckGroupAdmin(ctx context.Context, groupID string) error { if !tokenverify.IsAppManagerUid(ctx) { groupMember, err := s.GroupDatabase.TakeGroupMember(ctx, groupID, mcontext.GetOpUserID(ctx)) @@ -577,8 +582,6 @@ func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetG } func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.GetGroupApplicationListReq) (*pbGroup.GetGroupApplicationListResp, error) { - pageNumber, showNumber := utils.GetPage(req.Pagination) - groupIDs, err := s.GroupDatabase.FindUserManagedGroupID(ctx, req.FromUserID) if err != nil { return nil, err @@ -587,7 +590,7 @@ func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup. if len(groupIDs) == 0 { return resp, nil } - total, groupRequests, err := s.GroupDatabase.PageGroupRequest(ctx, groupIDs, pageNumber, showNumber) + total, groupRequests, err := s.GroupDatabase.PageGroupRequest(ctx, groupIDs, req.Pagination.PageNumber, req.Pagination.ShowNumber) if err != nil { return nil, err } diff --git a/internal/rpc/group/statistics.go b/internal/rpc/group/statistics.go index 1ce2d8d8a..8aeefbee3 100644 --- a/internal/rpc/group/statistics.go +++ b/internal/rpc/group/statistics.go @@ -18,8 +18,8 @@ import ( "context" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/protocol/group" + "github.com/OpenIMSDK/tools/errs" ) func (s *groupServer) GroupCreateCount(ctx context.Context, req *group.GroupCreateCountReq) (*group.GroupCreateCountResp, error) { diff --git a/internal/rpc/group/super_group.go b/internal/rpc/group/super_group.go index ff3ecbe32..bdd810ba9 100644 --- a/internal/rpc/group/super_group.go +++ b/internal/rpc/group/super_group.go @@ -19,14 +19,14 @@ import ( "fmt" "strings" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "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/utils" pbGroup "github.com/OpenIMSDK/protocol/group" sdkws "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/utils" ) func (s *groupServer) GetJoinedSuperGroupList( diff --git a/internal/rpc/msg/as_read.go b/internal/rpc/msg/as_read.go index 92a1c12c4..c2f07bd8e 100644 --- a/internal/rpc/msg/as_read.go +++ b/internal/rpc/msg/as_read.go @@ -19,11 +19,11 @@ import ( "github.com/redis/go-redis/v9" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" ) func (m *msgServer) GetConversationsHasReadAndMaxSeq(ctx context.Context, req *msg.GetConversationsHasReadAndMaxSeqReq) (*msg.GetConversationsHasReadAndMaxSeqResp, error) { diff --git a/internal/rpc/msg/callback.go b/internal/rpc/msg/callback.go index 224827d5c..52662ace2 100644 --- a/internal/rpc/msg/callback.go +++ b/internal/rpc/msg/callback.go @@ -18,14 +18,14 @@ import ( "context" cbapi "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/http" - "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/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbChat "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func cbURL() string { diff --git a/internal/rpc/msg/delete.go b/internal/rpc/msg/delete.go index 9aee71675..8c20a5bc3 100644 --- a/internal/rpc/msg/delete.go +++ b/internal/rpc/msg/delete.go @@ -17,13 +17,13 @@ package msg import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/conversation" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) func (m *msgServer) getMinSeqs(maxSeqs map[string]int64) map[string]int64 { diff --git a/internal/rpc/msg/message_interceptor.go b/internal/rpc/msg/message_interceptor.go index a88753de3..915a04ab1 100644 --- a/internal/rpc/msg/message_interceptor.go +++ b/internal/rpc/msg/message_interceptor.go @@ -17,11 +17,11 @@ package msg import ( "context" - "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/errs" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" ) type MessageInterceptorFunc func(ctx context.Context, req *msg.SendMsgReq) (*sdkws.MsgData, error) diff --git a/internal/rpc/msg/msg_status.go b/internal/rpc/msg/msg_status.go index 8f423fd04..bd89d61f4 100644 --- a/internal/rpc/msg/msg_status.go +++ b/internal/rpc/msg/msg_status.go @@ -17,9 +17,9 @@ package msg import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" pbMsg "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/mcontext" ) func (m *msgServer) SetSendMsgStatus( diff --git a/internal/rpc/msg/revoke.go b/internal/rpc/msg/revoke.go index 53b3fef48..5651e79e0 100644 --- a/internal/rpc/msg/revoke.go +++ b/internal/rpc/msg/revoke.go @@ -19,14 +19,14 @@ import ( "encoding/json" "time" - "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/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) func (m *msgServer) RevokeMsg(ctx context.Context, req *msg.RevokeMsgReq) (*msg.RevokeMsgResp, error) { diff --git a/internal/rpc/msg/send.go b/internal/rpc/msg/send.go index c911bc258..2c5df6408 100644 --- a/internal/rpc/msg/send.go +++ b/internal/rpc/msg/send.go @@ -17,16 +17,16 @@ package msg import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" promePkg "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbConversation "github.com/OpenIMSDK/protocol/conversation" pbMsg "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/wrapperspb" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func (m *msgServer) SendMsg(ctx context.Context, req *pbMsg.SendMsgReq) (resp *pbMsg.SendMsgResp, error error) { diff --git a/internal/rpc/msg/server.go b/internal/rpc/msg/server.go index 7f7e3f9c3..542f59d4b 100644 --- a/internal/rpc/msg/server.go +++ b/internal/rpc/msg/server.go @@ -19,16 +19,16 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/localcache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/conversation" "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" ) type ( diff --git a/internal/rpc/msg/statistics.go b/internal/rpc/msg/statistics.go index f21fd904f..c5a4658bb 100644 --- a/internal/rpc/msg/statistics.go +++ b/internal/rpc/msg/statistics.go @@ -19,9 +19,9 @@ import ( "time" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/utils" ) func (m *msgServer) GetActiveUser(ctx context.Context, req *msg.GetActiveUserReq) (*msg.GetActiveUserResp, error) { diff --git a/internal/rpc/msg/sync_msg.go b/internal/rpc/msg/sync_msg.go index d70f6f514..edcb4ff89 100644 --- a/internal/rpc/msg/sync_msg.go +++ b/internal/rpc/msg/sync_msg.go @@ -17,13 +17,13 @@ package msg import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/protocol/msg" + "github.com/OpenIMSDK/tools/constant" - "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/utils" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) func (m *msgServer) PullMessageBySeqs( diff --git a/internal/rpc/msg/utils.go b/internal/rpc/msg/utils.go index fc996399e..48f7b03f3 100644 --- a/internal/rpc/msg/utils.go +++ b/internal/rpc/msg/utils.go @@ -18,10 +18,10 @@ import ( "github.com/redis/go-redis/v9" "gorm.io/gorm" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/utils" ) func isMessageHasReadEnabled(msgData *sdkws.MsgData) bool { diff --git a/internal/rpc/msg/verify.go b/internal/rpc/msg/verify.go index 1fed50699..32c05ec82 100644 --- a/internal/rpc/msg/verify.go +++ b/internal/rpc/msg/verify.go @@ -20,12 +20,12 @@ import ( "strconv" "time" - "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/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/utils" ) var ExcludeContentType = []int{constant.HasReadReceipt} diff --git a/internal/rpc/third/s3.go b/internal/rpc/third/s3.go index 719d9fdeb..38b0eb03c 100644 --- a/internal/rpc/third/s3.go +++ b/internal/rpc/third/s3.go @@ -20,11 +20,11 @@ import ( "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/s3/cont" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/third" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func (t *thirdServer) PartLimit(ctx context.Context, req *third.PartLimitReq) (*third.PartLimitResp, error) { diff --git a/internal/rpc/third/third.go b/internal/rpc/third/third.go index ecf21b2c4..5db6c39e4 100644 --- a/internal/rpc/third/third.go +++ b/internal/rpc/third/third.go @@ -27,14 +27,14 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "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/discoveryregistry" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/third" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" ) func Start(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error { diff --git a/internal/rpc/third/tool.go b/internal/rpc/third/tool.go index 5a25cf342..5a7d1697b 100644 --- a/internal/rpc/third/tool.go +++ b/internal/rpc/third/tool.go @@ -21,10 +21,10 @@ import ( "strings" "unicode/utf8" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/protocol/third" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/tokenverify" ) func toPbMapArray(m map[string][]string) []*third.KeyValues { diff --git a/internal/rpc/user/statistics.go b/internal/rpc/user/statistics.go index 48f05108d..42068f2ce 100644 --- a/internal/rpc/user/statistics.go +++ b/internal/rpc/user/statistics.go @@ -18,8 +18,8 @@ import ( "context" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" pbuser "github.com/OpenIMSDK/protocol/user" + "github.com/OpenIMSDK/tools/errs" ) func (s *userServer) UserRegisterCount( diff --git a/internal/rpc/user/user.go b/internal/rpc/user/user.go index 4473fd677..65e977274 100644 --- a/internal/rpc/user/user.go +++ b/internal/rpc/user/user.go @@ -20,27 +20,27 @@ import ( "strings" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" + "github.com/OpenIMSDK/tools/log" - "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/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" tablerelation "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/tokenverify" - registry "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" "github.com/OpenIMSDK/protocol/sdkws" pbuser "github.com/OpenIMSDK/protocol/user" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + registry "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/tx" "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/utils" ) type userServer struct { diff --git a/internal/tools/conversation.go b/internal/tools/conversation.go index 2651cf10e..4adec99ee 100644 --- a/internal/tools/conversation.go +++ b/internal/tools/conversation.go @@ -18,9 +18,9 @@ import ( "context" "time" - "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/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func (c *MsgTool) ConversationsDestructMsgs() { diff --git a/internal/tools/cron_task.go b/internal/tools/cron_task.go index 5e4183615..354682f8e 100644 --- a/internal/tools/cron_task.go +++ b/internal/tools/cron_task.go @@ -21,8 +21,8 @@ import ( "github.com/robfig/cron/v3" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/log" ) func StartCronTask() error { diff --git a/internal/tools/msg.go b/internal/tools/msg.go index 76299b6ac..8e67bc350 100644 --- a/internal/tools/msg.go +++ b/internal/tools/msg.go @@ -24,20 +24,20 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/relation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/tx" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient/notification" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry/zookeeper" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/mw" + "github.com/OpenIMSDK/tools/tx" + "github.com/OpenIMSDK/tools/utils" ) type MsgTool struct { diff --git a/internal/tools/msg_test.go b/internal/tools/msg_test.go index 4b1ea0384..f4ce4d054 100644 --- a/internal/tools/msg_test.go +++ b/internal/tools/msg_test.go @@ -20,10 +20,10 @@ import ( "go.mongodb.org/mongo-driver/bson" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/cache" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" unRelationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/unrelation" diff --git a/pkg/apiresp/format.go b/pkg/apiresp/format.go deleted file mode 100644 index b53f31cbd..000000000 --- a/pkg/apiresp/format.go +++ /dev/null @@ -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() -} diff --git a/pkg/apiresp/gin.go b/pkg/apiresp/gin.go deleted file mode 100644 index 9d5637bfd..000000000 --- a/pkg/apiresp/gin.go +++ /dev/null @@ -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)) -} diff --git a/pkg/apiresp/http.go b/pkg/apiresp/http.go deleted file mode 100644 index db1c847cf..000000000 --- a/pkg/apiresp/http.go +++ /dev/null @@ -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)) -} diff --git a/pkg/apiresp/resp.go b/pkg/apiresp/resp.go deleted file mode 100644 index 638c70dbe..000000000 --- a/pkg/apiresp/resp.go +++ /dev/null @@ -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()} -} diff --git a/pkg/callbackstruct/common.go b/pkg/callbackstruct/common.go index 4a83bb09f..ef84d52b9 100644 --- a/pkg/callbackstruct/common.go +++ b/pkg/callbackstruct/common.go @@ -15,7 +15,7 @@ package callbackstruct import ( - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" + "github.com/OpenIMSDK/tools/errs" ) type CommonCallbackReq struct { diff --git a/pkg/checker/check.go b/pkg/checker/check.go deleted file mode 100644 index f3f3811a4..000000000 --- a/pkg/checker/check.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/cmd/msg_gateway.go b/pkg/common/cmd/msg_gateway.go index 6629b2d2c..f7b7a03ea 100644 --- a/pkg/common/cmd/msg_gateway.go +++ b/pkg/common/cmd/msg_gateway.go @@ -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 { diff --git a/pkg/common/cmd/root.go b/pkg/common/cmd/root.go index c5fce2c95..80a9aebee 100644 --- a/pkg/common/cmd/root.go +++ b/pkg/common/cmd/root.go @@ -19,9 +19,9 @@ import ( "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 { diff --git a/pkg/common/cmd/rpc.go b/pkg/common/cmd/rpc.go index 239858764..a2fbea34c 100644 --- a/pkg/common/cmd/rpc.go +++ b/pkg/common/cmd/rpc.go @@ -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 { diff --git a/pkg/common/config/parse.go b/pkg/common/config/parse.go index 60c4802a4..3e15fe57a 100644 --- a/pkg/common/config/parse.go +++ b/pkg/common/config/parse.go @@ -23,9 +23,9 @@ import ( "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/discoveryregistry" + "github.com/OpenIMSDK/tools/utils" ) var ( diff --git a/pkg/common/convert/conversation.go b/pkg/common/convert/conversation.go index c4f860e36..7eccad9b0 100644 --- a/pkg/common/convert/conversation.go +++ b/pkg/common/convert/conversation.go @@ -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/utils" "github.com/OpenIMSDK/protocol/conversation" + "github.com/OpenIMSDK/tools/utils" ) func ConversationDB2Pb(conversationDB *relation.ConversationModel) *conversation.Conversation { diff --git a/pkg/common/convert/friend.go b/pkg/common/convert/friend.go index ee2b368a8..322f9d10a 100644 --- a/pkg/common/convert/friend.go +++ b/pkg/common/convert/friend.go @@ -18,8 +18,8 @@ import ( "context" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" - "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 { diff --git a/pkg/common/db/cache/conversation.go b/pkg/common/db/cache/conversation.go index 119967c70..7f0290c8f 100644 --- a/pkg/common/db/cache/conversation.go +++ b/pkg/common/db/cache/conversation.go @@ -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 ( diff --git a/pkg/common/db/cache/friend.go b/pkg/common/db/cache/friend.go index b15ed95d1..698f1364c 100644 --- a/pkg/common/db/cache/friend.go +++ b/pkg/common/db/cache/friend.go @@ -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 ( diff --git a/pkg/common/db/cache/group.go b/pkg/common/db/cache/group.go index 44ae04ecf..d72f06908 100644 --- a/pkg/common/db/cache/group.go +++ b/pkg/common/db/cache/group.go @@ -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 ( diff --git a/pkg/common/db/cache/init_redis.go b/pkg/common/db/cache/init_redis.go index 104d48ffd..307e40327 100644 --- a/pkg/common/db/cache/init_redis.go +++ b/pkg/common/db/cache/init_redis.go @@ -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 ( diff --git a/pkg/common/db/cache/init_redis_test.go b/pkg/common/db/cache/init_redis_test.go index 4b3f57066..5c9c66339 100644 --- a/pkg/common/db/cache/init_redis_test.go +++ b/pkg/common/db/cache/init_redis_test.go @@ -18,7 +18,7 @@ import ( "fmt" "testing" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" + "github.com/OpenIMSDK/tools/config" ) // TestNewRedis Test redis connection diff --git a/pkg/common/db/cache/meta_cache.go b/pkg/common/db/cache/meta_cache.go index 86a47f04b..ca742d4a3 100644 --- a/pkg/common/db/cache/meta_cache.go +++ b/pkg/common/db/cache/meta_cache.go @@ -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 ( diff --git a/pkg/common/db/cache/msg.go b/pkg/common/db/cache/msg.go index 0702cd235..66f3cacee 100644 --- a/pkg/common/db/cache/msg.go +++ b/pkg/common/db/cache/msg.go @@ -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/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" ) diff --git a/pkg/common/db/controller/auth.go b/pkg/common/db/controller/auth.go index 678d98b11..491a1394b 100644 --- a/pkg/common/db/controller/auth.go +++ b/pkg/common/db/controller/auth.go @@ -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 { diff --git a/pkg/common/db/controller/black.go b/pkg/common/db/controller/black.go index 99cf25ebd..767797eb1 100644 --- a/pkg/common/db/controller/black.go +++ b/pkg/common/db/controller/black.go @@ -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 { diff --git a/pkg/common/db/controller/conversation.go b/pkg/common/db/controller/conversation.go index d65315918..0f3403084 100644 --- a/pkg/common/db/controller/conversation.go +++ b/pkg/common/db/controller/conversation.go @@ -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 { diff --git a/pkg/common/db/controller/friend.go b/pkg/common/db/controller/friend.go index 6b41b87f2..3c8d61a40 100644 --- a/pkg/common/db/controller/friend.go +++ b/pkg/common/db/controller/friend.go @@ -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 { diff --git a/pkg/common/db/controller/group.go b/pkg/common/db/controller/group.go index dff427580..ad0b4e548 100644 --- a/pkg/common/db/controller/group.go +++ b/pkg/common/db/controller/group.go @@ -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 { diff --git a/pkg/common/db/controller/msg.go b/pkg/common/db/controller/msg.go index c18a6e17e..555828c22 100644 --- a/pkg/common/db/controller/msg.go +++ b/pkg/common/db/controller/msg.go @@ -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" - "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 ( diff --git a/pkg/common/db/controller/msg_test.go b/pkg/common/db/controller/msg_test.go index 7e50b8489..e322e6218 100644 --- a/pkg/common/db/controller/msg_test.go +++ b/pkg/common/db/controller/msg_test.go @@ -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) { diff --git a/pkg/common/db/controller/user.go b/pkg/common/db/controller/user.go index 81cabe0f6..4f9383b09 100644 --- a/pkg/common/db/controller/user.go +++ b/pkg/common/db/controller/user.go @@ -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 { diff --git a/pkg/common/db/localcache/group.go b/pkg/common/db/localcache/group.go index 809af0107..57cea7245 100644 --- a/pkg/common/db/localcache/group.go +++ b/pkg/common/db/localcache/group.go @@ -18,9 +18,9 @@ import ( "context" "sync" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/group" + "github.com/OpenIMSDK/tools/errs" ) type GroupLocalCache struct { diff --git a/pkg/common/db/ormutil/utils.go b/pkg/common/db/ormutil/utils.go deleted file mode 100644 index 7e4bd4f71..000000000 --- a/pkg/common/db/ormutil/utils.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/db/relation/black_model.go b/pkg/common/db/relation/black_model.go index ca90f43a7..eede403b1 100644 --- a/pkg/common/db/relation/black_model.go +++ b/pkg/common/db/relation/black_model.go @@ -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 { diff --git a/pkg/common/db/relation/chat_log_model.go b/pkg/common/db/relation/chat_log_model.go index a16f2d710..056295e15 100644 --- a/pkg/common/db/relation/chat_log_model.go +++ b/pkg/common/db/relation/chat_log_model.go @@ -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" - "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 { diff --git a/pkg/common/db/relation/conversation_model.go b/pkg/common/db/relation/conversation_model.go index fb88b8305..716d2cbe4 100644 --- a/pkg/common/db/relation/conversation_model.go +++ b/pkg/common/db/relation/conversation_model.go @@ -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 { diff --git a/pkg/common/db/relation/friend_model.go b/pkg/common/db/relation/friend_model.go index 10daf8e80..4b119c1f8 100644 --- a/pkg/common/db/relation/friend_model.go +++ b/pkg/common/db/relation/friend_model.go @@ -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 { diff --git a/pkg/common/db/relation/friend_request_model.go b/pkg/common/db/relation/friend_request_model.go index fe08ac06c..9f5cbbfee 100644 --- a/pkg/common/db/relation/friend_request_model.go +++ b/pkg/common/db/relation/friend_request_model.go @@ -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 { diff --git a/pkg/common/db/relation/group_member_model.go b/pkg/common/db/relation/group_member_model.go index 8f5aa937d..7c2ded83f 100644 --- a/pkg/common/db/relation/group_member_model.go +++ b/pkg/common/db/relation/group_member_model.go @@ -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) diff --git a/pkg/common/db/relation/group_model.go b/pkg/common/db/relation/group_model.go index 3a782e02a..c95d51861 100644 --- a/pkg/common/db/relation/group_model.go +++ b/pkg/common/db/relation/group_model.go @@ -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) diff --git a/pkg/common/db/relation/group_request_model.go b/pkg/common/db/relation/group_request_model.go index 0220f308e..a38f1f782 100644 --- a/pkg/common/db/relation/group_request_model.go +++ b/pkg/common/db/relation/group_request_model.go @@ -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 { diff --git a/pkg/common/db/relation/mysql_init.go b/pkg/common/db/relation/mysql_init.go index 267acce74..29873cc89 100644 --- a/pkg/common/db/relation/mysql_init.go +++ b/pkg/common/db/relation/mysql_init.go @@ -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" diff --git a/pkg/common/db/relation/object_model.go b/pkg/common/db/relation/object_model.go index 928c72fbe..02ba0bcf0 100644 --- a/pkg/common/db/relation/object_model.go +++ b/pkg/common/db/relation/object_model.go @@ -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 { diff --git a/pkg/common/db/relation/user_model.go b/pkg/common/db/relation/user_model.go index d3be5dd7e..b7c592eeb 100644 --- a/pkg/common/db/relation/user_model.go +++ b/pkg/common/db/relation/user_model.go @@ -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 { diff --git a/pkg/common/db/s3/cont/controller.go b/pkg/common/db/s3/cont/controller.go index 07eacc63b..01dbc787f 100644 --- a/pkg/common/db/s3/cont/controller.go +++ b/pkg/common/db/s3/cont/controller.go @@ -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 { diff --git a/pkg/common/db/s3/cos/cos.go b/pkg/common/db/s3/cos/cos.go index cfdaaa5e4..29d74ceb4 100644 --- a/pkg/common/db/s3/cos/cos.go +++ b/pkg/common/db/s3/cos/cos.go @@ -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 ( diff --git a/pkg/common/db/s3/minio/minio.go b/pkg/common/db/s3/minio/minio.go index bb6e6ce24..d5ac7de40 100644 --- a/pkg/common/db/s3/minio/minio.go +++ b/pkg/common/db/s3/minio/minio.go @@ -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 ( diff --git a/pkg/common/db/s3/oss/oss.go b/pkg/common/db/s3/oss/oss.go index 774150389..ee4d19464 100644 --- a/pkg/common/db/s3/oss/oss.go +++ b/pkg/common/db/s3/oss/oss.go @@ -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 ( diff --git a/pkg/common/db/table/relation/utils.go b/pkg/common/db/table/relation/utils.go index c8c59b390..c944eae8b 100644 --- a/pkg/common/db/table/relation/utils.go +++ b/pkg/common/db/table/relation/utils.go @@ -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 { diff --git a/pkg/common/db/tx/gorm.go b/pkg/common/db/tx/gorm.go deleted file mode 100644 index 98e71cb9f..000000000 --- a/pkg/common/db/tx/gorm.go +++ /dev/null @@ -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) - }) -} diff --git a/pkg/common/db/tx/mongo.go b/pkg/common/db/tx/mongo.go deleted file mode 100644 index a0c38e372..000000000 --- a/pkg/common/db/tx/mongo.go +++ /dev/null @@ -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), "") -} diff --git a/pkg/common/db/tx/tx.go b/pkg/common/db/tx/tx.go deleted file mode 100644 index 9a6fe02ef..000000000 --- a/pkg/common/db/tx/tx.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/db/unrelation/mongo.go b/pkg/common/db/unrelation/mongo.go index d5ac9c9de..44077a838 100644 --- a/pkg/common/db/unrelation/mongo.go +++ b/pkg/common/db/unrelation/mongo.go @@ -24,11 +24,11 @@ import ( "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" - "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 ( diff --git a/pkg/common/db/unrelation/msg.go b/pkg/common/db/unrelation/msg.go index 32d5f43f5..2f4a166e9 100644 --- a/pkg/common/db/unrelation/msg.go +++ b/pkg/common/db/unrelation/msg.go @@ -23,7 +23,7 @@ import ( "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/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") diff --git a/pkg/common/db/unrelation/super_group.go b/pkg/common/db/unrelation/super_group.go index f2f867c49..e93ab2b43 100644 --- a/pkg/common/db/unrelation/super_group.go +++ b/pkg/common/db/unrelation/super_group.go @@ -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 { diff --git a/pkg/common/http/http_client.go b/pkg/common/http/http_client.go index 153deb30e..46d5f23c3 100644 --- a/pkg/common/http/http_client.go +++ b/pkg/common/http/http_client.go @@ -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 diff --git a/pkg/common/kafka/consumer.go b/pkg/common/kafka/consumer.go index 67bc3977b..e04abe944 100644 --- a/pkg/common/kafka/consumer.go +++ b/pkg/common/kafka/consumer.go @@ -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" ) diff --git a/pkg/common/kafka/consumer_group.go b/pkg/common/kafka/consumer_group.go index 60e69d4a6..b4bd81660 100644 --- a/pkg/common/kafka/consumer_group.go +++ b/pkg/common/kafka/consumer_group.go @@ -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" ) diff --git a/pkg/common/kafka/producer.go b/pkg/common/kafka/producer.go index d52d76817..8eeaa6825 100644 --- a/pkg/common/kafka/producer.go +++ b/pkg/common/kafka/producer.go @@ -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" diff --git a/pkg/common/log/color.go b/pkg/common/log/color.go deleted file mode 100644 index 9d1121d61..000000000 --- a/pkg/common/log/color.go +++ /dev/null @@ -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) -} diff --git a/pkg/common/log/logger.go b/pkg/common/log/logger.go deleted file mode 100644 index cfbb91bdd..000000000 --- a/pkg/common/log/logger.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/log/sql_logger.go b/pkg/common/log/sql_logger.go deleted file mode 100644 index ae6cafb34..000000000 --- a/pkg/common/log/sql_logger.go +++ /dev/null @@ -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) - } - } -} diff --git a/pkg/common/log/zap.go b/pkg/common/log/zap.go deleted file mode 100644 index 9d57acf85..000000000 --- a/pkg/common/log/zap.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/log/zk_logger.go b/pkg/common/log/zk_logger.go deleted file mode 100644 index 3579e2022..000000000 --- a/pkg/common/log/zk_logger.go +++ /dev/null @@ -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...)) -} diff --git a/pkg/common/mcontext/ctx.go b/pkg/common/mcontext/ctx.go deleted file mode 100644 index 79234e2e0..000000000 --- a/pkg/common/mcontext/ctx.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/mw/gin.go b/pkg/common/mw/gin.go deleted file mode 100644 index 287cd5f53..000000000 --- a/pkg/common/mw/gin.go +++ /dev/null @@ -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() - } - } -} diff --git a/pkg/common/mw/intercept_chain.go b/pkg/common/mw/intercept_chain.go deleted file mode 100644 index ae5361631..000000000 --- a/pkg/common/mw/intercept_chain.go +++ /dev/null @@ -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) - } -} diff --git a/pkg/common/mw/rpc_client_interceptor.go b/pkg/common/mw/rpc_client_interceptor.go deleted file mode 100644 index 1374b3af6..000000000 --- a/pkg/common/mw/rpc_client_interceptor.go +++ /dev/null @@ -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/protocol/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 -} diff --git a/pkg/common/mw/rpc_server_interceptor.go b/pkg/common/mw/rpc_server_interceptor.go deleted file mode 100644 index 143c5f8e7..000000000 --- a/pkg/common/mw/rpc_server_interceptor.go +++ /dev/null @@ -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/protocol/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) -} diff --git a/pkg/common/mw/specialerror/error.go b/pkg/common/mw/specialerror/error.go deleted file mode 100644 index b8b8d27ae..000000000 --- a/pkg/common/mw/specialerror/error.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/network/ip.go b/pkg/common/network/ip.go deleted file mode 100644 index bf062429d..000000000 --- a/pkg/common/network/ip.go +++ /dev/null @@ -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 - } -} diff --git a/pkg/common/prome/prometheus.go b/pkg/common/prome/prometheus.go index d66b1df70..26efb9dae 100644 --- a/pkg/common/prome/prometheus.go +++ b/pkg/common/prome/prometheus.go @@ -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" diff --git a/pkg/common/tokenverify/jwt_token.go b/pkg/common/tokenverify/jwt_token.go deleted file mode 100644 index 317347b1d..000000000 --- a/pkg/common/tokenverify/jwt_token.go +++ /dev/null @@ -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 -} diff --git a/pkg/common/tokenverify/jwt_token_test.go b/pkg/common/tokenverify/jwt_token_test.go deleted file mode 100644 index 4e8e98c41..000000000 --- a/pkg/common/tokenverify/jwt_token_test.go +++ /dev/null @@ -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) -} diff --git a/pkg/discoveryregistry/discovery_register.go b/pkg/discoveryregistry/discovery_register.go deleted file mode 100644 index 4ebabe7a8..000000000 --- a/pkg/discoveryregistry/discovery_register.go +++ /dev/null @@ -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) -} diff --git a/pkg/discoveryregistry/zookeeper/conf.go b/pkg/discoveryregistry/zookeeper/conf.go deleted file mode 100644 index 034c525ba..000000000 --- a/pkg/discoveryregistry/zookeeper/conf.go +++ /dev/null @@ -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 -} diff --git a/pkg/discoveryregistry/zookeeper/discover.go b/pkg/discoveryregistry/zookeeper/discover.go deleted file mode 100644 index 94cf1f84a..000000000 --- a/pkg/discoveryregistry/zookeeper/discover.go +++ /dev/null @@ -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() - } -} diff --git a/pkg/discoveryregistry/zookeeper/register.go b/pkg/discoveryregistry/zookeeper/register.go deleted file mode 100644 index 8fc5fa34e..000000000 --- a/pkg/discoveryregistry/zookeeper/register.go +++ /dev/null @@ -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 -} diff --git a/pkg/discoveryregistry/zookeeper/resolver.go b/pkg/discoveryregistry/zookeeper/resolver.go deleted file mode 100644 index 7e9c8c125..000000000 --- a/pkg/discoveryregistry/zookeeper/resolver.go +++ /dev/null @@ -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 } diff --git a/pkg/discoveryregistry/zookeeper/zk.go b/pkg/discoveryregistry/zookeeper/zk.go deleted file mode 100644 index cc333c4b6..000000000 --- a/pkg/discoveryregistry/zookeeper/zk.go +++ /dev/null @@ -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 -} diff --git a/pkg/errs/code.go b/pkg/errs/code.go deleted file mode 100644 index 9f70ab5e6..000000000 --- a/pkg/errs/code.go +++ /dev/null @@ -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 // 上传过期 -) diff --git a/pkg/errs/coderr.go b/pkg/errs/coderr.go deleted file mode 100644 index af88a6353..000000000 --- a/pkg/errs/coderr.go +++ /dev/null @@ -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, ", ")) -} diff --git a/pkg/errs/predefine.go b/pkg/errs/predefine.go deleted file mode 100644 index f11349891..000000000 --- a/pkg/errs/predefine.go +++ /dev/null @@ -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") -) diff --git a/pkg/errs/relation.go b/pkg/errs/relation.go deleted file mode 100644 index 0a7ad4997..000000000 --- a/pkg/errs/relation.go +++ /dev/null @@ -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 -} diff --git a/pkg/rpcclient/auth.go b/pkg/rpcclient/auth.go index 0bd3f56e9..9d667f1ad 100644 --- a/pkg/rpcclient/auth.go +++ b/pkg/rpcclient/auth.go @@ -19,9 +19,9 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/protocol/auth" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" ) func NewAuth(discov discoveryregistry.SvcDiscoveryRegistry) *Auth { diff --git a/pkg/rpcclient/conversation.go b/pkg/rpcclient/conversation.go index 79190995f..d4116e9f9 100644 --- a/pkg/rpcclient/conversation.go +++ b/pkg/rpcclient/conversation.go @@ -20,10 +20,10 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" pbConversation "github.com/OpenIMSDK/protocol/conversation" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" ) type Conversation struct { diff --git a/pkg/rpcclient/friend.go b/pkg/rpcclient/friend.go index d243c6fb3..c27f4ef3f 100644 --- a/pkg/rpcclient/friend.go +++ b/pkg/rpcclient/friend.go @@ -19,10 +19,10 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/protocol/friend" sdkws "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" ) type Friend struct { diff --git a/pkg/rpcclient/group.go b/pkg/rpcclient/group.go index 3d600160d..ce624a085 100644 --- a/pkg/rpcclient/group.go +++ b/pkg/rpcclient/group.go @@ -20,13 +20,13 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/group" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/utils" ) type Group struct { diff --git a/pkg/rpcclient/msg.go b/pkg/rpcclient/msg.go index cfd5dff23..bfc7bf73f 100644 --- a/pkg/rpcclient/msg.go +++ b/pkg/rpcclient/msg.go @@ -21,13 +21,13 @@ import ( "google.golang.org/grpc" "google.golang.org/protobuf/proto" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/utils" // "google.golang.org/protobuf/proto". ) diff --git a/pkg/rpcclient/notification/conevrsation.go b/pkg/rpcclient/notification/conevrsation.go index 96111a33b..ac40eb887 100644 --- a/pkg/rpcclient/notification/conevrsation.go +++ b/pkg/rpcclient/notification/conevrsation.go @@ -17,9 +17,9 @@ package notification import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" ) type ConversationNotificationSender struct { diff --git a/pkg/rpcclient/notification/friend.go b/pkg/rpcclient/notification/friend.go index 7b14b9df7..05c2b1e6f 100644 --- a/pkg/rpcclient/notification/friend.go +++ b/pkg/rpcclient/notification/friend.go @@ -17,15 +17,15 @@ package notification import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext" + "github.com/OpenIMSDK/tools/mcontext" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/convert" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" relationTb "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" pbFriend "github.com/OpenIMSDK/protocol/friend" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" ) type FriendNotificationSender struct { diff --git a/pkg/rpcclient/notification/group.go b/pkg/rpcclient/notification/group.go index e5c91a301..e70bf38e1 100644 --- a/pkg/rpcclient/notification/group.go +++ b/pkg/rpcclient/notification/group.go @@ -18,16 +18,16 @@ import ( "context" "fmt" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller" "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/relation" - "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/errs" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" pbGroup "github.com/OpenIMSDK/protocol/group" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/log" + "github.com/OpenIMSDK/tools/mcontext" + "github.com/OpenIMSDK/tools/utils" ) func NewGroupNotificationSender( diff --git a/pkg/rpcclient/notification/msg.go b/pkg/rpcclient/notification/msg.go index fc6d303e9..f9cf68bcb 100644 --- a/pkg/rpcclient/notification/msg.go +++ b/pkg/rpcclient/notification/msg.go @@ -17,9 +17,9 @@ package notification import ( "context" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" "github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient" "github.com/OpenIMSDK/protocol/sdkws" + "github.com/OpenIMSDK/tools/constant" ) type MsgNotificationSender struct { diff --git a/pkg/rpcclient/push.go b/pkg/rpcclient/push.go index 295d90f7c..a4b122a29 100644 --- a/pkg/rpcclient/push.go +++ b/pkg/rpcclient/push.go @@ -19,9 +19,9 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/protocol/push" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" ) type Push struct { diff --git a/pkg/rpcclient/third.go b/pkg/rpcclient/third.go index 237706d4f..9822f48fa 100644 --- a/pkg/rpcclient/third.go +++ b/pkg/rpcclient/third.go @@ -23,9 +23,9 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" "github.com/OpenIMSDK/protocol/third" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" ) type Third struct { diff --git a/pkg/rpcclient/user.go b/pkg/rpcclient/user.go index 018876523..7e5079f8c 100644 --- a/pkg/rpcclient/user.go +++ b/pkg/rpcclient/user.go @@ -20,13 +20,13 @@ import ( "google.golang.org/grpc" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/tokenverify" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - "github.com/OpenIMSDK/Open-IM-Server/pkg/errs" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" "github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/user" + "github.com/OpenIMSDK/tools/config" + "github.com/OpenIMSDK/tools/discoveryregistry" + "github.com/OpenIMSDK/tools/errs" + "github.com/OpenIMSDK/tools/tokenverify" + "github.com/OpenIMSDK/tools/utils" ) type User struct { diff --git a/pkg/startrpc/start.go b/pkg/startrpc/start.go deleted file mode 100644 index 3eeaaa3a2..000000000 --- a/pkg/startrpc/start.go +++ /dev/null @@ -1,112 +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 startrpc - -import ( - "fmt" - "net" - "strconv" - "time" - - grpcPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/config" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/network" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/prome" - "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry" - openKeeper "github.com/OpenIMSDK/Open-IM-Server/pkg/discoveryregistry/zookeeper" - "github.com/OpenIMSDK/Open-IM-Server/pkg/utils" -) - -func Start( - rpcPort int, - rpcRegisterName string, - prometheusPort int, - rpcFn func(client discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) error, - options ...grpc.ServerOption, -) error { - fmt.Println( - "start", - rpcRegisterName, - "server, port: ", - rpcPort, - "prometheusPort:", - prometheusPort, - ", OpenIM version: ", - config.Version, - ) - listener, err := net.Listen( - "tcp", - net.JoinHostPort(network.GetListenIP(config.Config.Rpc.ListenIP), strconv.Itoa(rpcPort)), - ) - if err != nil { - return err - } - defer listener.Close() - zkClient, err := openKeeper.NewClient(config.Config.Zookeeper.ZkAddr, config.Config.Zookeeper.Schema, - openKeeper.WithFreq(time.Hour), openKeeper.WithUserNameAndPassword( - config.Config.Zookeeper.Username, - config.Config.Zookeeper.Password, - ), openKeeper.WithRoundRobin(), openKeeper.WithTimeout(10), openKeeper.WithLogger(log.NewZkLogger())) - if err != nil { - return utils.Wrap1(err) - } - defer zkClient.CloseZK() - zkClient.AddOption(mw.GrpcClient(), grpc.WithTransportCredentials(insecure.NewCredentials())) - registerIP, err := network.GetRpcRegisterIP(config.Config.Rpc.RegisterIP) - if err != nil { - return err - } - // ctx 中间件 - if config.Config.Prometheus.Enable { - prome.NewGrpcRequestCounter() - prome.NewGrpcRequestFailedCounter() - prome.NewGrpcRequestSuccessCounter() - unaryInterceptor := mw.InterceptChain(grpcPrometheus.UnaryServerInterceptor, mw.RpcServerInterceptor) - options = append(options, []grpc.ServerOption{ - grpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor), - grpc.UnaryInterceptor(unaryInterceptor), - }...) - } else { - options = append(options, mw.GrpcServer()) - } - srv := grpc.NewServer(options...) - defer srv.GracefulStop() - err = rpcFn(zkClient, srv) - if err != nil { - return utils.Wrap1(err) - } - err = zkClient.Register( - rpcRegisterName, - registerIP, - rpcPort, - grpc.WithTransportCredentials(insecure.NewCredentials()), - ) - if err != nil { - return utils.Wrap1(err) - } - go func() { - if config.Config.Prometheus.Enable && prometheusPort != 0 { - if err := prome.StartPrometheusSrv(prometheusPort); err != nil { - panic(err.Error()) - } - } - }() - return utils.Wrap1(srv.Serve(listener)) -} diff --git a/pkg/statistics/statistics.go b/pkg/statistics/statistics.go index 2a6ae01ae..de6d04fec 100644 --- a/pkg/statistics/statistics.go +++ b/pkg/statistics/statistics.go @@ -18,7 +18,7 @@ import ( "context" "time" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/log" + "github.com/OpenIMSDK/tools/log" ) type Statistics struct { diff --git a/pkg/utils/base64.go b/pkg/utils/base64.go deleted file mode 100644 index 9502dcde8..000000000 --- a/pkg/utils/base64.go +++ /dev/null @@ -1,26 +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 utils - -import "encoding/base64" - -func Base64Encode(data string) string { - return base64.StdEncoding.EncodeToString([]byte(data)) -} - -func Base64Decode(data string) string { - decodedByte, _ := base64.StdEncoding.DecodeString(data) - return string(decodedByte) -} diff --git a/pkg/utils/callback.go b/pkg/utils/callback.go deleted file mode 100644 index 36f7ac3ca..000000000 --- a/pkg/utils/callback.go +++ /dev/null @@ -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 utils - -import ( - "google.golang.org/protobuf/proto" - - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - sdkws "github.com/OpenIMSDK/protocol/sdkws" -) - -func GetContent(msg *sdkws.MsgData) string { - if msg.ContentType >= constant.NotificationBegin && msg.ContentType <= constant.NotificationEnd { - var tips sdkws.TipsComm - _ = proto.Unmarshal(msg.Content, &tips) - content := tips.JsonDetail - return content - } else { - return string(msg.Content) - } -} diff --git a/pkg/utils/encryption.go b/pkg/utils/encryption.go deleted file mode 100644 index 23266d8f7..000000000 --- a/pkg/utils/encryption.go +++ /dev/null @@ -1,78 +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 utils - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/md5" - "encoding/hex" - "errors" -) - -func Md5(s string, salt ...string) string { - h := md5.New() - h.Write([]byte(s)) - if len(salt) > 0 { - h.Write([]byte(salt[0])) - } - cipher := h.Sum(nil) - return hex.EncodeToString(cipher) -} - -func AesEncrypt(data []byte, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - encryptBytes := pkcs7Padding(data, blockSize) - crypted := make([]byte, len(encryptBytes)) - blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) - blockMode.CryptBlocks(crypted, encryptBytes) - return crypted, nil -} - -func AesDecrypt(data []byte, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) - crypted := make([]byte, len(data)) - blockMode.CryptBlocks(crypted, data) - crypted, err = pkcs7UnPadding(crypted) - if err != nil { - return nil, err - } - return crypted, nil -} - -func pkcs7Padding(data []byte, blockSize int) []byte { - padding := blockSize - len(data)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(data, padText...) -} - -func pkcs7UnPadding(data []byte) ([]byte, error) { - length := len(data) - if length == 0 { - return nil, errors.New("encrypt error") - } - unPadding := int(data[length-1]) - return data[:(length - unPadding)], nil -} diff --git a/pkg/utils/file.go b/pkg/utils/file.go deleted file mode 100644 index 79528661d..000000000 --- a/pkg/utils/file.go +++ /dev/null @@ -1,98 +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 utils - -import ( - "fmt" - "math/rand" - "os" - "path" - "strconv" - "strings" - "time" - - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" -) - -const ( - BYTE = 1 << (10 * iota) - KILOBYTE - MEGABYTE - GIGABYTE - TERABYTE - PETABYTE - EXABYTE -) - -// Determine whether the given path is a folder -func IsDir(path string) bool { - s, err := os.Stat(path) - if err != nil { - return false - } - return s.IsDir() -} - -// Determine whether the given path is a file -func IsFile(path string) bool { - return !IsDir(path) -} - -// Create a directory -func MkDir(path string) error { - return os.MkdirAll(path, os.ModePerm) -} - -func GetNewFileNameAndContentType(fileName string, fileType int) (string, string) { - suffix := path.Ext(fileName) - newName := fmt.Sprintf("%d-%d%s", time.Now().UnixNano(), rand.Int(), fileName) - contentType := "" - if fileType == constant.ImageType { - contentType = "image/" + suffix[1:] - } - return newName, contentType -} - -func ByteSize(bytes uint64) string { - unit := "" - value := float64(bytes) - switch { - case bytes >= EXABYTE: - unit = "E" - value = value / EXABYTE - case bytes >= PETABYTE: - unit = "P" - value = value / PETABYTE - case bytes >= TERABYTE: - unit = "T" - value = value / TERABYTE - case bytes >= GIGABYTE: - unit = "G" - value = value / GIGABYTE - case bytes >= MEGABYTE: - unit = "M" - value = value / MEGABYTE - case bytes >= KILOBYTE: - unit = "K" - value = value / KILOBYTE - case bytes >= BYTE: - unit = "B" - case bytes == 0: - return "0" - } - result := strconv.FormatFloat(value, 'f', 1, 64) - result = strings.TrimSuffix(result, ".0") - return result + unit -} diff --git a/pkg/utils/get_server_ip.go b/pkg/utils/get_server_ip.go deleted file mode 100644 index aad0bf2cc..000000000 --- a/pkg/utils/get_server_ip.go +++ /dev/null @@ -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 utils - -import ( - "errors" - "net" -) - -var ServerIP = "" - -func GetLocalIP() (string, error) { - addrs, err := net.InterfaceAddrs() - if err != nil { - return "", err - } - for _, address := range addrs { - - if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - return ipnet.IP.String(), nil - } - } - } - - return "", errors.New("no ip") -} diff --git a/pkg/utils/id.go b/pkg/utils/id.go deleted file mode 100644 index 25e942f36..000000000 --- a/pkg/utils/id.go +++ /dev/null @@ -1,42 +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 utils - -import ( - "github.com/bwmarrin/snowflake" -) - -func init() { - var err error - idGenerator, err = snowflake.NewNode(getNodeNum()) - if err != nil { - panic(err) - } -} - -func getNodeNum() int64 { - return 1 -} - -var idGenerator *snowflake.Node - -func GenID() string { - return idGenerator.Generate().String() -} - -func GenIDs(count int) []string { - //impl - return []string{} -} diff --git a/pkg/utils/id_test.go b/pkg/utils/id_test.go deleted file mode 100644 index d6ab3e665..000000000 --- a/pkg/utils/id_test.go +++ /dev/null @@ -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 utils - -import "testing" - -func TestGenID(t *testing.T) { - m := map[string]struct{}{} - for i := 0; i < 2000; i++ { - got := GenID() - if _, ok := m[got]; !ok { - m[got] = struct{}{} - } else { - t.Error("id generate error", got) - } - } -} diff --git a/pkg/utils/image.go b/pkg/utils/image.go deleted file mode 100644 index f93591f9e..000000000 --- a/pkg/utils/image.go +++ /dev/null @@ -1,69 +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 utils - -import ( - "errors" - "image" - "image/gif" - "image/jpeg" - "image/png" - "io" - "os" - - "github.com/nfnt/resize" - "golang.org/x/image/bmp" -) - -func GenSmallImage(src, dst string) error { - fIn, _ := os.Open(src) - defer fIn.Close() - - fOut, _ := os.Create(dst) - defer fOut.Close() - - if err := scale(fIn, fOut, 0, 0, 0); err != nil { - return err - } - return nil -} - -func scale(in io.Reader, out io.Writer, width, height, quality int) error { - origin, fm, err := image.Decode(in) - if err != nil { - return err - } - if width == 0 || height == 0 { - width = origin.Bounds().Max.X / 2 - height = origin.Bounds().Max.Y / 2 - } - if quality == 0 { - quality = 25 - } - canvas := resize.Thumbnail(uint(width), uint(height), origin, resize.Lanczos3) - - switch fm { - case "jpeg": - return jpeg.Encode(out, canvas, &jpeg.Options{quality}) - case "png": - return png.Encode(out, canvas) - case "gif": - return gif.Encode(out, canvas, &gif.Options{}) - case "bmp": - return bmp.Encode(out, canvas) - default: - return errors.New("ERROR FORMAT") - } -} diff --git a/pkg/utils/image_test.go b/pkg/utils/image_test.go deleted file mode 100644 index 87d78620f..000000000 --- a/pkg/utils/image_test.go +++ /dev/null @@ -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 utils - -import ( - "path/filepath" - "runtime" - "testing" - - "github.com/stretchr/testify/assert" -) - -var ( - _, b, _, _ = runtime.Caller(0) - // Root folder of this project - Root = filepath.Join(filepath.Dir(b), "../..") -) - -func Test_GenSmallImage(t *testing.T) { - println(Root) - err := GenSmallImage(Root+"/docs/open-im-logo.png", Root+"/out-test/open-im-logo-test.png") - assert.Nil(t, err) - - err = GenSmallImage(Root+"/docs/open-im-logo.png", "out-test/open-im-logo-test.png") - assert.Nil(t, err) - - err = GenSmallImage(Root+"/docs/Architecture.jpg", "out-test/Architecture-test.jpg") - assert.Nil(t, err) -} diff --git a/pkg/utils/map.go b/pkg/utils/map.go deleted file mode 100644 index cd7f3f1de..000000000 --- a/pkg/utils/map.go +++ /dev/null @@ -1,147 +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 utils - -import ( - "encoding/json" - "sync" -) - -type Map struct { - sync.RWMutex - m map[interface{}]interface{} -} - -func (m *Map) init() { - if m.m == nil { - m.m = make(map[interface{}]interface{}) - } -} - -func (m *Map) UnsafeGet(key interface{}) interface{} { - if m.m == nil { - return nil - } else { - return m.m[key] - } -} - -func (m *Map) Get(key interface{}) interface{} { - m.RLock() - defer m.RUnlock() - return m.UnsafeGet(key) -} - -func (m *Map) UnsafeSet(key interface{}, value interface{}) { - m.init() - m.m[key] = value -} - -func (m *Map) Set(key interface{}, value interface{}) { - m.Lock() - defer m.Unlock() - m.UnsafeSet(key, value) -} - -func (m *Map) TestAndSet(key interface{}, value interface{}) interface{} { - m.Lock() - defer m.Unlock() - - m.init() - - if v, ok := m.m[key]; ok { - return v - } else { - m.m[key] = value - return nil - } -} - -func (m *Map) UnsafeDel(key interface{}) { - m.init() - delete(m.m, key) -} - -func (m *Map) Del(key interface{}) { - m.Lock() - defer m.Unlock() - m.UnsafeDel(key) -} - -func (m *Map) UnsafeLen() int { - if m.m == nil { - return 0 - } else { - return len(m.m) - } -} - -func (m *Map) Len() int { - m.RLock() - defer m.RUnlock() - return m.UnsafeLen() -} - -func (m *Map) UnsafeRange(f func(interface{}, interface{})) { - if m.m == nil { - return - } - for k, v := range m.m { - f(k, v) - } -} - -func (m *Map) RLockRange(f func(interface{}, interface{})) { - m.RLock() - defer m.RUnlock() - m.UnsafeRange(f) -} - -func (m *Map) LockRange(f func(interface{}, interface{})) { - m.Lock() - defer m.Unlock() - m.UnsafeRange(f) -} - -func MapToJsonString(param map[string]interface{}) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} -func MapIntToJsonString(param map[string]int32) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} -func JsonStringToMap(str string) (tempMap map[string]int32) { - _ = json.Unmarshal([]byte(str), &tempMap) - return tempMap -} -func GetSwitchFromOptions(Options map[string]bool, key string) (result bool) { - if Options == nil { - return true - } - if flag, ok := Options[key]; !ok || flag { - return true - } - return false -} - -func SetSwitchFromOptions(options map[string]bool, key string, value bool) { - if options == nil { - options = make(map[string]bool, 5) - } - options[key] = value -} diff --git a/pkg/utils/md5_test.go b/pkg/utils/md5_test.go deleted file mode 100644 index 1add67f32..000000000 --- a/pkg/utils/md5_test.go +++ /dev/null @@ -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 utils - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_Md5(t *testing.T) { - result := Md5("go") - assert.Equal(t, result, "34d1f91fb2e514b8576fab1a75a89a6b") - - result2 := Md5("go") - assert.Equal(t, result, result2) -} diff --git a/pkg/utils/options.go b/pkg/utils/options.go deleted file mode 100644 index 0ade70dfe..000000000 --- a/pkg/utils/options.go +++ /dev/null @@ -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 utils - -import "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - -type Options map[string]bool -type OptionsOpt func(Options) - -func NewOptions(opts ...OptionsOpt) Options { - options := make(map[string]bool, 11) - options[constant.IsNotNotification] = false - options[constant.IsSendMsg] = false - options[constant.IsHistory] = false - options[constant.IsPersistent] = false - options[constant.IsOfflinePush] = false - options[constant.IsUnreadCount] = false - options[constant.IsConversationUpdate] = false - options[constant.IsSenderSync] = false - options[constant.IsNotPrivate] = false - options[constant.IsSenderConversationUpdate] = false - options[constant.IsSenderNotificationPush] = false - options[constant.IsReactionFromCache] = false - for _, opt := range opts { - opt(options) - } - return options -} - -func NewMsgOptions() Options { - options := make(map[string]bool, 11) - options[constant.IsOfflinePush] = false - return make(map[string]bool) -} - -func WithOptions(options Options, opts ...OptionsOpt) Options { - for _, opt := range opts { - opt(options) - } - return options -} - -func WithNotNotification(b bool) OptionsOpt { - return func(options Options) { - options[constant.IsNotNotification] = b - } -} - -func WithSendMsg(b bool) OptionsOpt { - return func(options Options) { - options[constant.IsSendMsg] = b - } -} - -func WithHistory(b bool) OptionsOpt { - return func(options Options) { - options[constant.IsHistory] = b - } -} - -func WithPersistent() OptionsOpt { - return func(options Options) { - options[constant.IsPersistent] = true - } -} - -func WithOfflinePush(b bool) OptionsOpt { - return func(options Options) { - options[constant.IsOfflinePush] = b - } -} - -func WithUnreadCount(b bool) OptionsOpt { - return func(options Options) { - options[constant.IsUnreadCount] = b - } -} - -func WithConversationUpdate() OptionsOpt { - return func(options Options) { - options[constant.IsConversationUpdate] = true - } -} - -func WithSenderSync() OptionsOpt { - return func(options Options) { - options[constant.IsSenderSync] = true - } -} - -func WithNotPrivate() OptionsOpt { - return func(options Options) { - options[constant.IsNotPrivate] = true - } -} - -func WithSenderConversationUpdate() OptionsOpt { - return func(options Options) { - options[constant.IsSenderConversationUpdate] = true - } -} - -func WithSenderNotificationPush() OptionsOpt { - return func(options Options) { - options[constant.IsSenderNotificationPush] = true - } -} - -func WithReactionFromCache() OptionsOpt { - return func(options Options) { - options[constant.IsReactionFromCache] = true - } -} - -func (o Options) Is(notification string) bool { - v, ok := o[notification] - if !ok || v { - return true - } - return false -} - -func (o Options) IsNotNotification() bool { - return o.Is(constant.IsNotNotification) -} - -func (o Options) IsSendMsg() bool { - return o.Is(constant.IsSendMsg) -} - -func (o Options) IsHistory() bool { - return o.Is(constant.IsHistory) -} - -func (o Options) IsPersistent() bool { - return o.Is(constant.IsPersistent) -} - -func (o Options) IsOfflinePush() bool { - return o.Is(constant.IsOfflinePush) -} - -func (o Options) IsUnreadCount() bool { - return o.Is(constant.IsUnreadCount) -} - -func (o Options) IsConversationUpdate() bool { - return o.Is(constant.IsConversationUpdate) -} - -func (o Options) IsSenderSync() bool { - return o.Is(constant.IsSenderSync) -} - -func (o Options) IsNotPrivate() bool { - return o.Is(constant.IsNotPrivate) -} - -func (o Options) IsSenderConversationUpdate() bool { - return o.Is(constant.IsSenderConversationUpdate) -} - -func (o Options) IsSenderNotificationPush() bool { - return o.Is(constant.IsSenderNotificationPush) -} - -func (o Options) IsReactionFromCache() bool { - return o.Is(constant.IsReactionFromCache) -} diff --git a/pkg/utils/page.go b/pkg/utils/page.go deleted file mode 100644 index d33f666c3..000000000 --- a/pkg/utils/page.go +++ /dev/null @@ -1,24 +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 utils - -import "github.com/OpenIMSDK/protocol/sdkws" - -func GetPage(pagination *sdkws.RequestPagination) (pageNumber, showNumber int32) { - if pagination != nil { - return pagination.PageNumber, pagination.ShowNumber - } - return -} diff --git a/pkg/utils/platform_number_id_to_name_test.go b/pkg/utils/platform_number_id_to_name_test.go deleted file mode 100644 index 47c4016ed..000000000 --- a/pkg/utils/platform_number_id_to_name_test.go +++ /dev/null @@ -1,61 +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 utils - -import ( - "testing" - - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - - "github.com/stretchr/testify/assert" -) - -func Test_PlatformIDToName(t *testing.T) { - assert.Equal(t, constant.PlatformIDToName(1), "IOS") - assert.Equal(t, constant.PlatformIDToName(2), "Android") - assert.Equal(t, constant.PlatformIDToName(3), "Windows") - assert.Equal(t, constant.PlatformIDToName(4), "OSX") - assert.Equal(t, constant.PlatformIDToName(5), "Web") - assert.Equal(t, constant.PlatformIDToName(6), "MiniWeb") - assert.Equal(t, constant.PlatformIDToName(7), "Linux") - - assert.Equal(t, constant.PlatformIDToName(0), "") -} - -func Test_PlatformNameToID(t *testing.T) { - assert.Equal(t, constant.PlatformNameToID("IOS"), int32(1)) - assert.Equal(t, constant.PlatformNameToID("Android"), int32(2)) - assert.Equal(t, constant.PlatformNameToID("Windows"), int32(3)) - assert.Equal(t, constant.PlatformNameToID("OSX"), int32(4)) - assert.Equal(t, constant.PlatformNameToID("Web"), int32(5)) - assert.Equal(t, constant.PlatformNameToID("MiniWeb"), int32(6)) - assert.Equal(t, constant.PlatformNameToID("Linux"), int32(7)) - - assert.Equal(t, constant.PlatformNameToID("UnknownDevice"), int32(0)) - assert.Equal(t, constant.PlatformNameToID(""), int32(0)) -} - -func Test_PlatformNameToClass(t *testing.T) { - assert.Equal(t, constant.PlatformNameToClass("IOS"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("Android"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("OSX"), "PC") - assert.Equal(t, constant.PlatformNameToClass("Windows"), "PC") - assert.Equal(t, constant.PlatformNameToClass("Web"), "PC") - assert.Equal(t, constant.PlatformNameToClass("MiniWeb"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("Linux"), "PC") - - assert.Equal(t, constant.PlatformNameToClass("UnknownDevice"), "") - assert.Equal(t, constant.PlatformNameToClass(""), "") -} diff --git a/pkg/utils/retry/retry.go b/pkg/utils/retry/retry.go deleted file mode 100644 index eb2a387cb..000000000 --- a/pkg/utils/retry/retry.go +++ /dev/null @@ -1,198 +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 retry - -import ( - "context" - "errors" - "fmt" - "runtime/debug" - "time" -) - -var ( - ErrorAbort = errors.New("stop retry") - ErrorTimeout = errors.New("retry timeout") - ErrorContextDeadlineExceed = errors.New("context deadline exceeded") - ErrorEmptyRetryFunc = errors.New("empty retry function") - ErrorTimeFormat = errors.New("time out err") -) - -type RetriesFunc func() error -type Option func(c *Config) -type HookFunc func() -type RetriesChecker func(err error) (needRetry bool) -type Config struct { - MaxRetryTimes int - Timeout time.Duration - RetryChecker RetriesChecker - Strategy Strategy - RecoverPanic bool - BeforeTry HookFunc - AfterTry HookFunc -} - -var ( - DefaultMaxRetryTimes = 3 - DefaultTimeout = time.Minute - DefaultInterval = time.Second * 2 - DefaultRetryChecker = func(err error) bool { - return !errors.Is(err, ErrorAbort) // not abort error, should continue retry - } -) - -func newDefaultConfig() *Config { - return &Config{ - MaxRetryTimes: DefaultMaxRetryTimes, - RetryChecker: DefaultRetryChecker, - Timeout: DefaultTimeout, - Strategy: NewLinear(DefaultInterval), - BeforeTry: func() {}, - AfterTry: func() {}, - } -} - -func WithTimeout(timeout time.Duration) Option { - return func(c *Config) { - c.Timeout = timeout - } -} - -func WithMaxRetryTimes(times int) Option { - return func(c *Config) { - c.MaxRetryTimes = times - } -} - -func WithRecoverPanic() Option { - return func(c *Config) { - c.RecoverPanic = true - } -} - -func WithBeforeHook(hook HookFunc) Option { - return func(c *Config) { - c.BeforeTry = hook - } -} - -func WithAfterHook(hook HookFunc) Option { - return func(c *Config) { - c.AfterTry = hook - } -} - -func WithRetryChecker(checker RetriesChecker) Option { - return func(c *Config) { - c.RetryChecker = checker - } -} - -func WithBackOffStrategy(s BackoffStrategy, duration time.Duration) Option { - return func(c *Config) { - switch s { - case StrategyConstant: - c.Strategy = NewConstant(duration) - case StrategyLinear: - c.Strategy = NewLinear(duration) - case StrategyFibonacci: - c.Strategy = NewFibonacci(duration) - } - } -} - -func WithCustomStrategy(s Strategy) Option { - return func(c *Config) { - c.Strategy = s - } -} - -func Do(ctx context.Context, fn RetriesFunc, opts ...Option) error { - if fn == nil { - return ErrorEmptyRetryFunc - } - var ( - abort = make(chan struct{}, 1) // caller choose to abort retry - run = make(chan error, 1) - panicInfoChan = make(chan string, 1) - - timer *time.Timer - runErr error - ) - config := newDefaultConfig() - for _, o := range opts { - o(config) - } - if config.Timeout > 0 { - timer = time.NewTimer(config.Timeout) - } else { - return ErrorTimeFormat - } - go func() { - var err error - defer func() { - if e := recover(); e == nil { - return - } else { - panicInfoChan <- fmt.Sprintf("retry function panic has occured, err=%v, stack:%s", e, string(debug.Stack())) - } - }() - for i := 0; i < config.MaxRetryTimes; i++ { - config.BeforeTry() - err = fn() - config.AfterTry() - if err == nil { - run <- nil - return - } - // check whether to retry - if config.RetryChecker != nil { - needRetry := config.RetryChecker(err) - if !needRetry { - abort <- struct{}{} - return - } - } - if config.Strategy != nil { - interval := config.Strategy.Sleep(i + 1) - <-time.After(interval) - } - } - run <- err - }() - select { - case <-ctx.Done(): - // context deadline exceed - return ErrorContextDeadlineExceed - case <-timer.C: - // timeout - return ErrorTimeout - case <-abort: - // caller abort - return ErrorAbort - case msg := <-panicInfoChan: - // panic occurred - if !config.RecoverPanic { - panic(msg) - } - runErr = fmt.Errorf("panic occurred=%s", msg) - case e := <-run: - // normal run - if e != nil { - runErr = fmt.Errorf("retry failed, err=%w", e) - } - } - return runErr -} diff --git a/pkg/utils/retry/stratey.go b/pkg/utils/retry/stratey.go deleted file mode 100644 index 8dca54161..000000000 --- a/pkg/utils/retry/stratey.go +++ /dev/null @@ -1,70 +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 retry - -import "time" - -type BackoffStrategy int - -const ( - StrategyConstant BackoffStrategy = iota - StrategyLinear - StrategyFibonacci -) - -type Strategy interface { - Sleep(times int) time.Duration -} -type Constant struct { - startInterval time.Duration -} - -func NewConstant(d time.Duration) *Constant { - return &Constant{startInterval: d} -} - -type Linear struct { - startInterval time.Duration -} - -func NewLinear(d time.Duration) *Linear { - return &Linear{startInterval: d} -} - -type Fibonacci struct { - startInterval time.Duration -} - -func NewFibonacci(d time.Duration) *Fibonacci { - return &Fibonacci{startInterval: d} -} - -func (c *Constant) Sleep(_ int) time.Duration { - return c.startInterval -} -func (l *Linear) Sleep(times int) time.Duration { - return l.startInterval * time.Duration(times) - -} -func (f *Fibonacci) Sleep(times int) time.Duration { - return f.startInterval * time.Duration(fibonacciNumber(times)) - -} -func fibonacciNumber(n int) int { - if n == 0 || n == 1 { - return n - } - return fibonacciNumber(n-1) + fibonacciNumber(n-2) -} diff --git a/pkg/utils/splitter/tools.go b/pkg/utils/splitter/tools.go deleted file mode 100644 index d36b9c3be..000000000 --- a/pkg/utils/splitter/tools.go +++ /dev/null @@ -1,42 +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 splitter - -type SplitResult struct { - Item []string -} -type Splitter struct { - splitCount int - data []string -} - -func NewSplitter(splitCount int, data []string) *Splitter { - return &Splitter{splitCount: splitCount, data: data} -} -func (s *Splitter) GetSplitResult() (result []*SplitResult) { - remain := len(s.data) % s.splitCount - integer := len(s.data) / s.splitCount - for i := 0; i < integer; i++ { - r := new(SplitResult) - r.Item = s.data[i*s.splitCount : (i+1)*s.splitCount] - result = append(result, r) - } - if remain > 0 { - r := new(SplitResult) - r.Item = s.data[integer*s.splitCount:] - result = append(result, r) - } - return result -} diff --git a/pkg/utils/strings.go b/pkg/utils/strings.go deleted file mode 100644 index 641c43e9f..000000000 --- a/pkg/utils/strings.go +++ /dev/null @@ -1,141 +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 utils - -import ( - "encoding/json" - "math/rand" - "strconv" -) - -func IntToString(i int) string { - return strconv.FormatInt(int64(i), 10) -} - -func StringToInt(i string) int { - j, _ := strconv.Atoi(i) - return j -} -func StringToInt64(i string) int64 { - j, _ := strconv.ParseInt(i, 10, 64) - return j -} -func StringToInt32(i string) int32 { - j, _ := strconv.ParseInt(i, 10, 64) - return int32(j) -} -func Int32ToString(i int32) string { - return strconv.FormatInt(int64(i), 10) -} - -func Uint32ToString(i uint32) string { - return strconv.FormatInt(int64(i), 10) -} - -// judge a string whether in the string list -func IsContain(target string, List []string) bool { - for _, element := range List { - - if target == element { - return true - } - } - return false -} -func IsContainInt32(target int32, List []int32) bool { - for _, element := range List { - if target == element { - return true - } - } - return false -} -func IsContainInt(target int, List []int) bool { - for _, element := range List { - if target == element { - return true - } - } - return false -} -func InterfaceArrayToStringArray(data []interface{}) (i []string) { - for _, param := range data { - i = append(i, param.(string)) - } - return i -} -func StructToJsonString(param interface{}) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} - -func StructToJsonBytes(param interface{}) []byte { - dataType, _ := json.Marshal(param) - return dataType -} - -// The incoming parameter must be a pointer -func JsonStringToStruct(s string, args interface{}) error { - err := json.Unmarshal([]byte(s), args) - return err -} - -func GetMsgID(sendID string) string { - t := int64ToString(GetCurrentTimestampByNano()) - return Md5(t + sendID + int64ToString(rand.Int63n(GetCurrentTimestampByNano()))) -} - -func int64ToString(i int64) string { - return strconv.FormatInt(i, 10) -} -func Int64ToString(i int64) string { - return strconv.FormatInt(i, 10) -} - -func RemoveDuplicateElement(idList []string) []string { - result := make([]string, 0, len(idList)) - temp := map[string]struct{}{} - for _, item := range idList { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - result = append(result, item) - } - } - return result -} - -func RemoveDuplicate[T comparable](arr []T) []T { - result := make([]T, 0, len(arr)) - temp := map[T]struct{}{} - for _, item := range arr { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - result = append(result, item) - } - } - return result -} - -func IsDuplicateStringSlice(arr []string) bool { - t := make(map[string]struct{}) - for _, s := range arr { - if _, ok := t[s]; ok { - return true - } - t[s] = struct{}{} - } - return false -} diff --git a/pkg/utils/time_format.go b/pkg/utils/time_format.go deleted file mode 100644 index 9278a58ef..000000000 --- a/pkg/utils/time_format.go +++ /dev/null @@ -1,97 +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 utils - -import ( - "strconv" - "time" -) - -const ( - TimeOffset = 8 * 3600 //8 hour offset - HalfOffset = 12 * 3600 //Half-day hourly offset -) - -// Get the current timestamp by Second -func GetCurrentTimestampBySecond() int64 { - return time.Now().Unix() -} - -// Convert timestamp to time.Time type -func UnixSecondToTime(second int64) time.Time { - return time.Unix(second, 0) -} - -// Convert nano timestamp to time.Time type -func UnixNanoSecondToTime(nanoSecond int64) time.Time { - return time.Unix(0, nanoSecond) -} -func UnixMillSecondToTime(millSecond int64) time.Time { - return time.Unix(0, millSecond*1e6) -} - -// Get the current timestamp by Nano -func GetCurrentTimestampByNano() int64 { - return time.Now().UnixNano() -} - -// Get the current timestamp by Mill -func GetCurrentTimestampByMill() int64 { - return time.Now().UnixNano() / 1e6 -} - -// Get the timestamp at 0 o'clock of the day -func GetCurDayZeroTimestamp() int64 { - timeStr := time.Now().Format("2006-01-02") - t, _ := time.Parse("2006-01-02", timeStr) - return t.Unix() - TimeOffset -} - -// Get the timestamp at 12 o'clock on the day -func GetCurDayHalfTimestamp() int64 { - return GetCurDayZeroTimestamp() + HalfOffset - -} - -// Get the formatted time at 0 o'clock of the day, the format is "2006-01-02_00-00-00" -func GetCurDayZeroTimeFormat() string { - return time.Unix(GetCurDayZeroTimestamp(), 0).Format("2006-01-02_15-04-05") -} - -// Get the formatted time at 12 o'clock of the day, the format is "2006-01-02_12-00-00" -func GetCurDayHalfTimeFormat() string { - return time.Unix(GetCurDayZeroTimestamp()+HalfOffset, 0).Format("2006-01-02_15-04-05") -} -func GetTimeStampByFormat(datetime string) string { - timeLayout := "2006-01-02 15:04:05" - loc, _ := time.LoadLocation("Local") - tmp, _ := time.ParseInLocation(timeLayout, datetime, loc) - timestamp := tmp.Unix() - return strconv.FormatInt(timestamp, 10) -} - -func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 { - tm, _ := time.Parse(timeFormat, timeSrc) - return tm.Unix() -} - -func TimeStringToTime(timeString string) (time.Time, error) { - t, err := time.Parse("2006-01-02", timeString) - return t, err -} - -func TimeToString(t time.Time) string { - return t.Format("2006-01-02") -} diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go deleted file mode 100644 index babb548c8..000000000 --- a/pkg/utils/utils.go +++ /dev/null @@ -1,393 +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 utils - -import ( - "hash/crc32" - "math/rand" - "runtime" - "sort" - "strconv" - "strings" - "time" - - "github.com/jinzhu/copier" - "github.com/pkg/errors" - "google.golang.org/protobuf/proto" - - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant" - "github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/table/unrelation" - sdkws "github.com/OpenIMSDK/protocol/sdkws" -) - -// copy a by b b->a -func CopyStructFields(a interface{}, b interface{}, fields ...string) (err error) { - return copier.Copy(a, b) -} - -func Wrap1(err error) error { - return errors.Wrap(err, "==> "+printCallerNameAndLine()) -} - -func Wrap2[T any](a T, err error) (T, error) { - if err != nil { - return a, errors.Wrap(err, "==> "+printCallerNameAndLine()) - } - return a, nil -} - -func Wrap3[T any, V any](a T, b V, err error) (T, V, error) { - if err != nil { - return a, b, errors.Wrap(err, "==> "+printCallerNameAndLine()) - } - return a, b, nil -} - -func Wrap(err error, message string) error { - return errors.Wrap(err, "==> "+printCallerNameAndLine()+message) -} - -func WithMessage(err error, message string) error { - return errors.WithMessage(err, "==> "+printCallerNameAndLine()+message) -} - -func printCallerNameAndLine() string { - pc, _, line, _ := runtime.Caller(2) - return runtime.FuncForPC(pc).Name() + "()@" + strconv.Itoa(line) + ": " -} - -func GetSelfFuncName() string { - pc, _, _, _ := runtime.Caller(1) - return cleanUpFuncName(runtime.FuncForPC(pc).Name()) -} - -func GetFuncName(skips ...int) string { - skip := 1 - if len(skips) > 0 { - skip = skips[0] + 1 - } - pc, _, _, _ := runtime.Caller(skip) - return cleanUpFuncName(runtime.FuncForPC(pc).Name()) -} - -func cleanUpFuncName(funcName string) string { - end := strings.LastIndex(funcName, ".") - if end == -1 { - return "" - } - return funcName[end+1:] -} - -// Get the intersection of two slices -func Intersect(slice1, slice2 []int64) []int64 { - m := make(map[int64]bool) - n := make([]int64, 0) - for _, v := range slice1 { - m[v] = true - } - for _, v := range slice2 { - flag, _ := m[v] - if flag { - n = append(n, v) - } - } - return n -} - -// Get the diff of two slices -func Difference(slice1, slice2 []int64) []int64 { - m := make(map[int64]bool) - n := make([]int64, 0) - inter := Intersect(slice1, slice2) - for _, v := range inter { - m[v] = true - } - for _, v := range slice1 { - if !m[v] { - n = append(n, v) - } - } - - for _, v := range slice2 { - if !m[v] { - n = append(n, v) - } - } - return n -} - -// Get the intersection of two slices -func IntersectString(slice1, slice2 []string) []string { - m := make(map[string]bool) - n := make([]string, 0) - for _, v := range slice1 { - m[v] = true - } - for _, v := range slice2 { - flag, _ := m[v] - if flag { - n = append(n, v) - } - } - return n -} - -// Get the diff of two slices -func DifferenceString(slice1, slice2 []string) []string { - m := make(map[string]bool) - n := make([]string, 0) - inter := IntersectString(slice1, slice2) - for _, v := range inter { - m[v] = true - } - for _, v := range slice1 { - if !m[v] { - n = append(n, v) - } - } - - for _, v := range slice2 { - if !m[v] { - n = append(n, v) - } - } - return n -} - -func OperationIDGenerator() string { - return strconv.FormatInt(time.Now().UnixNano()+int64(rand.Uint32()), 10) -} - -func Pb2String(pb proto.Message) (string, error) { - s, err := proto.Marshal(pb) - if err != nil { - return "", err - } - return string(s), nil -} - -func String2Pb(s string, pb proto.Message) error { - return proto.Unmarshal([]byte(s), pb) -} - -func GetHashCode(s string) uint32 { - return crc32.ChecksumIEEE([]byte(s)) -} - -func GetNotificationConversationID(msg *sdkws.MsgData) string { - switch msg.SessionType { - case constant.SingleChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - return "n_" + strings.Join(l, "_") - case constant.GroupChatType: - return "n_" + msg.GroupID - case constant.SuperGroupChatType: - return "n_" + msg.GroupID - case constant.NotificationChatType: - return "n_" + msg.SendID + "_" + msg.RecvID - } - return "" -} - -func GetChatConversationIDByMsg(msg *sdkws.MsgData) string { - switch msg.SessionType { - case constant.SingleChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - return "si_" + strings.Join(l, "_") - case constant.GroupChatType: - return "g_" + msg.GroupID - case constant.SuperGroupChatType: - return "sg_" + msg.GroupID - case constant.NotificationChatType: - return "sn_" + msg.SendID + "_" + msg.RecvID - } - return "" -} - -func GenConversationIDForSingle(sendID, recvID string) string { - l := []string{sendID, recvID} - sort.Strings(l) - return "si_" + strings.Join(l, "_") -} - -func GenConversationUniqueKeyForGroup(groupID string) string { - return groupID -} - -func GenGroupConversationID(groupID string) string { - return "sg_" + groupID -} - -func GenConversationUniqueKeyForSingle(sendID, recvID string) string { - l := []string{sendID, recvID} - sort.Strings(l) - return strings.Join(l, "_") -} - -func GenConversationUniqueKey(msg *sdkws.MsgData) string { - switch msg.SessionType { - case constant.SingleChatType, constant.NotificationChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - return strings.Join(l, "_") - case constant.SuperGroupChatType: - return msg.GroupID - } - return "" -} - -func GetConversationIDByMsgModel(msg *unrelation.MsgDataModel) string { - options := Options(msg.Options) - switch msg.SessionType { - case constant.SingleChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - if !options.IsNotNotification() { - return "n_" + strings.Join(l, "_") - } - return "si_" + strings.Join(l, "_") // single chat - case constant.GroupChatType: - if !options.IsNotNotification() { - return "n_" + msg.GroupID // group chat - } - return "g_" + msg.GroupID // group chat - case constant.SuperGroupChatType: - if !options.IsNotNotification() { - return "n_" + msg.GroupID // super group chat - } - return "sg_" + msg.GroupID // super group chat - case constant.NotificationChatType: - if !options.IsNotNotification() { - return "n_" + msg.SendID + "_" + msg.RecvID // super group chat - } - return "sn_" + msg.SendID + "_" + msg.RecvID // server notification chat - } - return "" -} - -func GetConversationIDByMsg(msg *sdkws.MsgData) string { - options := Options(msg.Options) - switch msg.SessionType { - case constant.SingleChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - if !options.IsNotNotification() { - return "n_" + strings.Join(l, "_") - } - return "si_" + strings.Join(l, "_") // single chat - case constant.GroupChatType: - if !options.IsNotNotification() { - return "n_" + msg.GroupID // group chat - } - return "g_" + msg.GroupID // group chat - case constant.SuperGroupChatType: - if !options.IsNotNotification() { - return "n_" + msg.GroupID // super group chat - } - return "sg_" + msg.GroupID // super group chat - case constant.NotificationChatType: - if !options.IsNotNotification() { - return "n_" + msg.SendID + "_" + msg.RecvID // super group chat - } - return "sn_" + msg.SendID + "_" + msg.RecvID // server notification chat - } - return "" -} - -func GetConversationIDBySessionType(sessionType int, ids ...string) string { - sort.Strings(ids) - if len(ids) > 2 || len(ids) < 1 { - return "" - } - switch sessionType { - case constant.SingleChatType: - return "si_" + strings.Join(ids, "_") // single chat - case constant.GroupChatType: - return "g_" + ids[0] // group chat - case constant.SuperGroupChatType: - return "sg_" + ids[0] // super group chat - case constant.NotificationChatType: - return "sn_" + ids[0] // server notification chat - } - return "" -} - -func IsNotification(conversationID string) bool { - return strings.HasPrefix(conversationID, "n_") -} - -func IsNotificationByMsg(msg *sdkws.MsgData) bool { - return !Options(msg.Options).IsNotNotification() -} - -func ParseConversationID(msg *sdkws.MsgData) (isNotification bool, conversationID string) { - options := Options(msg.Options) - switch msg.SessionType { - case constant.SingleChatType: - l := []string{msg.SendID, msg.RecvID} - sort.Strings(l) - if !options.IsNotNotification() { - return true, "n_" + strings.Join(l, "_") - } - return false, "si_" + strings.Join(l, "_") // single chat - case constant.SuperGroupChatType: - if !options.IsNotNotification() { - return true, "n_" + msg.GroupID // super group chat - } - return false, "sg_" + msg.GroupID // super group chat - case constant.NotificationChatType: - if !options.IsNotNotification() { - return true, "n_" + msg.SendID + "_" + msg.RecvID // super group chat - } - return false, "sn_" + msg.SendID + "_" + msg.RecvID // server notification chat - } - return false, "" -} - -func GetNotificationConversationIDByConversationID(conversationID string) string { - l := strings.Split(conversationID, "_") - if len(l) > 1 { - l[0] = "n" - return strings.Join(l, "_") - } - return "" -} - -func GetSelfNotificationConversationID(userID string) string { - return "n_" + userID + "_" + userID -} - -func GetSeqsBeginEnd(seqs []int64) (int64, int64) { - if len(seqs) == 0 { - return 0, 0 - } - return seqs[0], seqs[len(seqs)-1] -} - -type MsgBySeq []*sdkws.MsgData - -func (s MsgBySeq) Len() int { - return len(s) -} - -func (s MsgBySeq) Less(i, j int) bool { - return s[i].Seq < s[j].Seq -} - -func (s MsgBySeq) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} diff --git a/pkg/utils/utils_v2.go b/pkg/utils/utils_v2.go deleted file mode 100644 index dc14fe4e8..000000000 --- a/pkg/utils/utils_v2.go +++ /dev/null @@ -1,557 +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 utils - -import ( - "encoding/json" - "sort" -) - -// SliceSub a中存在,b中不存在 (a-b) -func SliceSub[E comparable](a, b []E) []E { - k := make(map[E]struct{}) - for i := 0; i < len(b); i++ { - k[b[i]] = struct{}{} - } - t := make(map[E]struct{}) - rs := make([]E, 0, len(a)) - for i := 0; i < len(a); i++ { - e := a[i] - if _, ok := t[e]; ok { - continue - } - if _, ok := k[e]; ok { - continue - } - rs = append(rs, e) - t[e] = struct{}{} - } - return rs -} - -// SliceSubAny a中存在,b中不存在 (a-b) -func SliceSubAny[E comparable, T any](a []E, b []T, fn func(t T) E) []E { - return SliceSub(a, Slice(b, fn)) -} - -// SliceAnySub a中存在,b中不存在 (a-b) fn 返回的是uuid -func SliceAnySub[E any, T comparable](a, b []E, fn func(t E) T) []E { - m := make(map[T]E) - for i := 0; i < len(b); i++ { - v := b[i] - m[fn(v)] = v - } - var es []E - for i := 0; i < len(a); i++ { - v := a[i] - if _, ok := m[fn(v)]; !ok { - es = append(es, v) - } - } - return es -} - -// DistinctAny 去重 -func DistinctAny[E any, K comparable](es []E, fn func(e E) K) []E { - v := make([]E, 0, len(es)) - tmp := map[K]struct{}{} - for i := 0; i < len(es); i++ { - t := es[i] - k := fn(t) - if _, ok := tmp[k]; !ok { - tmp[k] = struct{}{} - v = append(v, t) - } - } - return v -} - -func DistinctAnyGetComparable[E any, K comparable](es []E, fn func(e E) K) []K { - v := make([]K, 0, len(es)) - tmp := map[K]struct{}{} - for i := 0; i < len(es); i++ { - t := es[i] - k := fn(t) - if _, ok := tmp[k]; !ok { - tmp[k] = struct{}{} - v = append(v, k) - } - } - return v -} - -// Distinct 去重 -func Distinct[T comparable](ts []T) []T { - if len(ts) < 2 { - return ts - } else if len(ts) == 2 { - if ts[0] == ts[1] { - return ts[:1] - } else { - return ts - } - } - return DistinctAny(ts, func(t T) T { - return t - }) -} - -// Delete 删除切片元素, 支持负数删除倒数第几个 -func Delete[E any](es []E, index ...int) []E { - switch len(index) { - case 0: - return es - case 1: - i := index[0] - if i < 0 { - i = len(es) + i - } - if len(es) <= i { - return es - } - return append(es[:i], es[i+1:]...) - default: - tmp := make(map[int]struct{}) - for _, i := range index { - if i < 0 { - i = len(es) + i - } - tmp[i] = struct{}{} - } - v := make([]E, 0, len(es)) - for i := 0; i < len(es); i++ { - if _, ok := tmp[i]; !ok { - v = append(v, es[i]) - } - } - return v - } -} - -// DeleteAt 删除切片元素, 支持负数删除倒数第几个 -func DeleteAt[E any](es *[]E, index ...int) []E { - v := Delete(*es, index...) - *es = v - return v -} - -// IndexAny get the index of the element -func IndexAny[E any, K comparable](e E, es []E, fn func(e E) K) int { - k := fn(e) - for i := 0; i < len(es); i++ { - if fn(es[i]) == k { - return i - } - } - return -1 -} - -// IndexOf get the index of the element -func IndexOf[E comparable](e E, es ...E) int { - return IndexAny(e, es, func(t E) E { - return t - }) -} - -// Contain 是否包含 -func Contain[E comparable](e E, es ...E) bool { - return IndexOf(e, es...) >= 0 -} - -// DuplicateAny 是否有重复的 -func DuplicateAny[E any, K comparable](es []E, fn func(e E) K) bool { - t := make(map[K]struct{}) - for _, e := range es { - k := fn(e) - if _, ok := t[k]; ok { - return true - } - t[k] = struct{}{} - } - return false -} - -// Duplicate 是否有重复的 -func Duplicate[E comparable](es []E) bool { - return DuplicateAny(es, func(e E) E { - return e - }) -} - -// SliceToMapOkAny slice to map (自定义类型, 筛选) -func SliceToMapOkAny[E any, K comparable, V any](es []E, fn func(e E) (K, V, bool)) map[K]V { - kv := make(map[K]V) - for i := 0; i < len(es); i++ { - t := es[i] - if k, v, ok := fn(t); ok { - kv[k] = v - } - } - return kv -} - -// SliceToMapAny slice to map (自定义类型) -func SliceToMapAny[E any, K comparable, V any](es []E, fn func(e E) (K, V)) map[K]V { - return SliceToMapOkAny(es, func(e E) (K, V, bool) { - k, v := fn(e) - return k, v, true - }) -} - -// SliceToMap slice to map -func SliceToMap[E any, K comparable](es []E, fn func(e E) K) map[K]E { - return SliceToMapOkAny(es, func(e E) (K, E, bool) { - k := fn(e) - return k, e, true - }) -} - -// SliceSetAny slice to map[K]struct{} -func SliceSetAny[E any, K comparable](es []E, fn func(e E) K) map[K]struct{} { - return SliceToMapAny(es, func(e E) (K, struct{}) { - return fn(e), struct{}{} - }) -} - -func Filter[E, T any](es []E, fn func(e E) (T, bool)) []T { - rs := make([]T, 0, len(es)) - for i := 0; i < len(es); i++ { - e := es[i] - if t, ok := fn(e); ok { - rs = append(rs, t) - } - } - return rs -} - -// Slice 批量转换切片类型 -func Slice[E any, T any](es []E, fn func(e E) T) []T { - v := make([]T, len(es)) - for i := 0; i < len(es); i++ { - v[i] = fn(es[i]) - } - return v -} - -// SliceSet slice to map[E]struct{} -func SliceSet[E comparable](es []E) map[E]struct{} { - return SliceSetAny(es, func(e E) E { - return e - }) -} - -// HasKey get whether the map contains key -func HasKey[K comparable, V any](m map[K]V, k K) bool { - if m == nil { - return false - } - _, ok := m[k] - return ok -} - -// Min get minimum value -func Min[E Ordered](e ...E) E { - v := e[0] - for _, t := range e[1:] { - if v > t { - v = t - } - } - return v -} - -// Max get maximum value -func Max[E Ordered](e ...E) E { - v := e[0] - for _, t := range e[1:] { - if v < t { - v = t - } - } - return v -} - -func Paginate[E any](es []E, pageNumber int, showNumber int) []E { - if pageNumber <= 0 { - return []E{} - } - if showNumber <= 0 { - return []E{} - } - start := (pageNumber - 1) * showNumber - end := start + showNumber - if start >= len(es) { - return []E{} - } - if end > len(es) { - end = len(es) - } - return es[start:end] -} - -// BothExistAny 获取切片中共同存在的元素(交集) -func BothExistAny[E any, K comparable](es [][]E, fn func(e E) K) []E { - if len(es) == 0 { - return []E{} - } - var idx int - ei := make([]map[K]E, len(es)) - for i := 0; i < len(ei); i++ { - e := es[i] - if len(e) == 0 { - return []E{} - } - kv := make(map[K]E) - for j := 0; j < len(e); j++ { - t := e[j] - k := fn(t) - kv[k] = t - } - ei[i] = kv - if len(kv) < len(ei[idx]) { - idx = i - } - } - v := make([]E, 0, len(ei[idx])) - for k := range ei[idx] { - all := true - for i := 0; i < len(ei); i++ { - if i == idx { - continue - } - if _, ok := ei[i][k]; !ok { - all = false - break - } - } - if !all { - continue - } - v = append(v, ei[idx][k]) - } - return v -} - -// BothExist 获取切片中共同存在的元素(交集) -func BothExist[E comparable](es ...[]E) []E { - return BothExistAny(es, func(e E) E { - return e - }) -} - -//// CompleteAny a中存在b的所有元素, 同时b中的所有元素a -//func CompleteAny[K comparable, E any](ks []K, es []E, fn func(e E) K) bool { -// if len(ks) == 0 && len(es) == 0 { -// return true -// } -// kn := make(map[K]uint8) -// for _, e := range Distinct(ks) { -// kn[e]++ -// } -// for k := range SliceSetAny(es, fn) { -// kn[k]++ -// } -// for _, n := range kn { -// if n != 2 { -// return false -// } -// } -// return true -//} - -// Complete a和b去重后是否相等(忽略顺序) -func Complete[E comparable](a []E, b []E) bool { - return len(Single(a, b)) == 0 -} - -// Keys get map keys -func Keys[K comparable, V any](kv map[K]V) []K { - ks := make([]K, 0, len(kv)) - for k := range kv { - ks = append(ks, k) - } - return ks -} - -// Values get map values -func Values[K comparable, V any](kv map[K]V) []V { - vs := make([]V, 0, len(kv)) - for k := range kv { - vs = append(vs, kv[k]) - } - return vs -} - -// Sort basic type sorting -func Sort[E Ordered](es []E, asc bool) []E { - SortAny(es, func(a, b E) bool { - if asc { - return a < b - } else { - return a > b - } - }) - return es -} - -// SortAny custom sort method -func SortAny[E any](es []E, fn func(a, b E) bool) { - sort.Sort(&sortSlice[E]{ - ts: es, - fn: fn, - }) -} - -// If true -> a, false -> b -func If[T any](isa bool, a, b T) T { - if isa { - return a - } - return b -} - -func ToPtr[T any](t T) *T { - return &t -} - -// Equal 比较切片是否相对(包括元素顺序) -func Equal[E comparable](a []E, b []E) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - return true -} - -// Single a中存在,b中不存在 或 b中存在,a中不存在 -func Single[E comparable](a, b []E) []E { - kn := make(map[E]uint8) - for _, e := range Distinct(a) { - kn[e]++ - } - for _, e := range Distinct(b) { - kn[e]++ - } - v := make([]E, 0, len(kn)) - for k, n := range kn { - if n == 1 { - v = append(v, k) - } - } - return v -} - -// Order 将ts按es排序 -func Order[E comparable, T any](es []E, ts []T, fn func(t T) E) []T { - if len(es) == 0 || len(ts) == 0 { - return ts - } - kv := make(map[E][]T) - for i := 0; i < len(ts); i++ { - t := ts[i] - k := fn(t) - kv[k] = append(kv[k], t) - } - rs := make([]T, 0, len(ts)) - for _, e := range es { - vs := kv[e] - delete(kv, e) - rs = append(rs, vs...) - } - for k := range kv { - rs = append(rs, kv[k]...) - } - return rs -} - -func OrderPtr[E comparable, T any](es []E, ts *[]T, fn func(t T) E) []T { - *ts = Order(es, *ts, fn) - return *ts -} - -func UniqueJoin(s ...string) string { - data, _ := json.Marshal(s) - return string(data) -} - -type sortSlice[E any] struct { - ts []E - fn func(a, b E) bool -} - -func (o *sortSlice[E]) Len() int { - return len(o.ts) -} - -func (o *sortSlice[E]) Less(i, j int) bool { - return o.fn(o.ts[i], o.ts[j]) -} - -func (o *sortSlice[E]) Swap(i, j int) { - o.ts[i], o.ts[j] = o.ts[j], o.ts[i] -} - -// Ordered types that can be sorted -type Ordered interface { - ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string -} - -func Unwrap(err error) error { - for err != nil { - unwrap, ok := err.(interface { - Unwrap() error - }) - if !ok { - break - } - err = unwrap.Unwrap() - } - return err -} - -// NotNilReplace 当new_不为空时, 将old设置为new_ -func NotNilReplace[T any](old, new_ *T) { - if new_ == nil { - return - } - *old = *new_ -} - -func Batch[T any, V any](fn func(T) V, ts []T) []V { - if ts == nil { - return nil - } - res := make([]V, 0, len(ts)) - for i := range ts { - res = append(res, fn(ts[i])) - } - return res -} - -func InitSlice[T any](val *[]T) { - if val != nil && *val == nil { - *val = []T{} - } -} - -func InitMap[K comparable, V any](val *map[K]V) { - if val != nil && *val == nil { - *val = map[K]V{} - } -} diff --git a/pkg/utils/utils_v2_test.go b/pkg/utils/utils_v2_test.go deleted file mode 100644 index ba55b8941..000000000 --- a/pkg/utils/utils_v2_test.go +++ /dev/null @@ -1,98 +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 utils - -import ( - "fmt" - "testing" -) - -func TestDistinct(t *testing.T) { - arr := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - fmt.Println(Distinct(arr)) -} - -func TestDeleteAt(t *testing.T) { - arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - fmt.Println(Delete(arr, 0, 1, -1, -2)) - fmt.Println(Delete(arr)) - fmt.Println(Delete(arr, 1)) -} - -func TestSliceToMap(t *testing.T) { - type Item struct { - ID string - Name string - } - list := []Item{ - {ID: "111", Name: "111"}, - {ID: "222", Name: "222"}, - {ID: "333", Name: "333"}, - } - - m := SliceToMap(list, func(t Item) string { - return t.ID - }) - - fmt.Printf("%+v\n", m) - -} - -func TestIndexOf(t *testing.T) { - arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - - fmt.Println(IndexOf(3, arr...)) - -} - -func TestSort(t *testing.T) { - arr := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - fmt.Println(Sort(arr, false)) -} - -func TestBothExist(t *testing.T) { - arr1 := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - arr2 := []int{6, 1, 3} - arr3 := []int{5, 1, 3, 6} - fmt.Println(BothExist(arr1, arr2, arr3)) -} - -func TestCompleteAny(t *testing.T) { - type Item struct { - ID int - Value string - } - - ids := []int{1, 2, 3, 4, 5, 6, 7, 8} - - var list []Item - - for _, id := range ids { - list = append(list, Item{ - ID: id, - Value: fmt.Sprintf("%d", id*1000), - }) - } - - DeleteAt(&list, -1) - DeleteAt(&ids, -1) - - ok := Complete(ids, Slice(list, func(t Item) int { - return t.ID - })) - - fmt.Printf("%+v\n", ok) - -}