feat: add openim optimize commit code

pull/1906/head
Xinwei Xiong (cubxxw) 2 years ago
parent e0dc9f71a1
commit 8a81768b56

@ -16,6 +16,7 @@ package fcm
import ( import (
"context" "context"
"fmt"
"path/filepath" "path/filepath"
firebase "firebase.google.com/go" firebase "firebase.google.com/go"
@ -39,23 +40,36 @@ type Fcm struct {
cache cache.MsgModel cache cache.MsgModel
} }
func NewClient(cache cache.MsgModel) *Fcm { // NewClient initializes a new FCM client using the Firebase Admin SDK.
projectRoot := config.GetProjectRoot() // It requires the FCM service account credentials file located within the project's configuration directory.
credentialsFilePath := filepath.Join(projectRoot, "config", config.Config.Push.Fcm.ServiceAccount) // The function returns an Fcm pointer on success, or nil and an error if initialization fails.
opt := option.WithCredentialsFile(credentialsFilePath) func NewClient(cache cache.MsgModel) (*Fcm, error) {
fcmApp, err := firebase.NewApp(context.Background(), nil, opt) // Attempt to get the project root directory.
if err != nil { projectRoot, err := config.GetProjectRoot()
return nil if err != nil {
} return nil, fmt.Errorf("failed to get project root: %w", err)
}
ctx := context.Background() credentialsFilePath := filepath.Join(projectRoot, "config", config.Config.Push.Fcm.ServiceAccount)
fcmMsgClient, err := fcmApp.Messaging(ctx) opt := option.WithCredentialsFile(credentialsFilePath)
if err != nil {
return nil // Initialize the Firebase app with the specified service account credentials.
} fcmApp, err := firebase.NewApp(context.Background(), nil, opt)
return &Fcm{fcmMsgCli: fcmMsgClient, cache: cache} if err != nil {
return nil, fmt.Errorf("failed to initialize Firebase app: %w", err)
}
// Obtain the messaging client from the Firebase app.
ctx := context.Background()
fcmMsgClient, err := fcmApp.Messaging(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get Firebase messaging client: %w", err)
}
return &Fcm{fcmMsgCli: fcmMsgClient, cache: cache}, nil
} }
func (f *Fcm) Push(ctx context.Context, userIDs []string, title, content string, opts *offlinepush.Opts) error { func (f *Fcm) Push(ctx context.Context, userIDs []string, title, content string, opts *offlinepush.Opts) error {
// accounts->registrationToken // accounts->registrationToken
allTokens := make(map[string][]string, 0) allTokens := make(map[string][]string, 0)

@ -82,7 +82,7 @@ func NewOfflinePusher(cache cache.MsgModel) offlinepush.OfflinePusher {
case "getui": case "getui":
offlinePusher = getui.NewClient(cache) offlinePusher = getui.NewClient(cache)
case "fcm": case "fcm":
offlinePusher = fcm.NewClient(cache) offlinePusher, _ = fcm.NewClient(cache)
case "jpush": case "jpush":
offlinePusher = jpush.NewClient() offlinePusher = jpush.NewClient()
default: default:

@ -32,17 +32,29 @@ func NewApiCmd() *ApiCmd {
return ret return ret
} }
// AddApi configures the API command to run with specified ports for the API and Prometheus monitoring.
// It ensures error handling for port retrieval and only proceeds if both port numbers are successfully obtained.
func (a *ApiCmd) AddApi(f func(port int, promPort int) error) { func (a *ApiCmd) AddApi(f func(port int, promPort int) error) {
a.Command.RunE = func(cmd *cobra.Command, args []string) error { a.Command.RunE = func(cmd *cobra.Command, args []string) error {
return f(a.getPortFlag(cmd), a.getPrometheusPortFlag(cmd)) port, err := a.getPortFlag(cmd)
if err != nil {
return err
}
promPort, err := a.getPrometheusPortFlag(cmd)
if err != nil {
return err
}
return f(port, promPort)
} }
} }
func (a *ApiCmd) GetPortFromConfig(portType string) (int, error) { func (a *ApiCmd) GetPortFromConfig(portType string) (int,) {
if portType == constant.FlagPort { if portType == constant.FlagPort {
return config2.Config.Api.OpenImApiPort[0], nil return config2.Config.Api.OpenImApiPort[0]
} else if portType == constant.FlagPrometheusPort { } else if portType == constant.FlagPrometheusPort {
return config2.Config.Prometheus.ApiPrometheusPort[0], nil return config2.Config.Prometheus.ApiPrometheusPort[0]
} }
return 0, nil return 0
} }

@ -44,7 +44,7 @@ func TestMsgGatewayCmd_GetPortFromConfig(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.portType, func(t *testing.T) { t.Run(tt.portType, func(t *testing.T) {
got := msgGatewayCmd.GetPortFromConfig(tt.portType) got, _ := msgGatewayCmd.GetPortFromConfig(tt.portType)
assert.Equal(t, tt.want, got) assert.Equal(t, tt.want, got)
}) })
} }

@ -54,6 +54,23 @@ func GetDefaultConfigPath() (string, error) {
return configPath, nil return configPath, nil
} }
// GetProjectRoot returns the absolute path of the project root directory by navigating up from the directory
// containing the executable. It provides a detailed error if the path cannot be determined.
func GetProjectRoot() (string, error) {
executablePath, err := os.Executable()
if err != nil {
return "", errs.Wrap(err, "failed to retrieve executable path")
}
// Attempt to compute the project root by navigating up from the executable's directory
projectRoot, err := genutil.OutDir(filepath.Join(filepath.Dir(executablePath), "../../../../.."))
if err != nil {
return "", errs.Wrap(err, "failed to determine project root directory")
}
return projectRoot, nil
}
func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options { func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options {
opts := msgprocessor.NewOptions() opts := msgprocessor.NewOptions()
@ -73,25 +90,36 @@ func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options {
return opts return opts
} }
// initConfig loads configuration from a specified path into the provided config structure.
// If the specified config file does not exist, it attempts to load from the project's default "config" directory.
// It logs informative messages regarding the configuration path being used.
func initConfig(config any, configName, configFolderPath string) error { func initConfig(config any, configName, configFolderPath string) error {
configFolderPath = filepath.Join(configFolderPath, configName) configFilePath := filepath.Join(configFolderPath, configName)
_, err := os.Stat(configFolderPath) _, err := os.Stat(configFilePath)
if err != nil { if err != nil {
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
return errs.Wrap(err, "stat config path error") return errs.Wrap(err, fmt.Sprintf("failed to check existence of config file at path: %s", configFilePath))
} }
configFolderPath = filepath.Join(GetProjectRoot(), "config", configName) projectRoot, err := GetProjectRoot()
fmt.Println("flag's path,enviment's path,default path all is not exist,using project path:", configFolderPath) if err != nil {
return err
}
configFilePath = filepath.Join(projectRoot, "config", configName)
fmt.Printf("Configuration file not found at specified path. Falling back to project path: %s\n", configFilePath)
} }
data, err := os.ReadFile(configFolderPath)
data, err := os.ReadFile(configFilePath)
if err != nil { if err != nil {
return errs.Wrap(err, "read file error") // Wrap and return the error if reading the configuration file fails.
return errs.Wrap(err, fmt.Sprintf("failed to read configuration file at path: %s", configFilePath))
} }
if err = yaml.Unmarshal(data, config); err != nil { if err = yaml.Unmarshal(data, config); err != nil {
return errs.Wrap(err, "unmarshal yaml error") // Wrap and return the error if unmarshalling the YAML configuration fails.
return errs.Wrap(err, "failed to unmarshal YAML configuration")
} }
fmt.Println("The path of the configuration file to start the process:", configFolderPath)
fmt.Printf("Configuration file loaded successfully from path: %s\n", configFilePath)
return nil return nil
} }
@ -107,7 +135,6 @@ func InitConfig(configFolderPath string) error {
var err error var err error
configFolderPath, err = GetDefaultConfigPath() configFolderPath, err = GetDefaultConfigPath()
if err != nil { if err != nil {
// Wrap and return the error if getting the default config path fails
return err return err
} }
} }

@ -17,7 +17,7 @@ package convert
import ( import (
"time" "time"
"github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/sdkws"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
) )

@ -46,11 +46,7 @@ type BlackCacheRedis struct {
blackDB relationtb.BlackModelInterface blackDB relationtb.BlackModelInterface
} }
func NewBlackCacheRedis( func NewBlackCacheRedis(rdb redis.UniversalClient, blackDB relationtb.BlackModelInterface, options rockscache.Options) BlackCache {
rdb redis.UniversalClient,
blackDB relationtb.BlackModelInterface,
options rockscache.Options,
) BlackCache {
rcClient := rockscache.NewClient(rdb, options) rcClient := rockscache.NewClient(rdb, options)
return &BlackCacheRedis{ return &BlackCacheRedis{

@ -24,8 +24,6 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/msgprocessor" "github.com/openimsdk/open-im-server/v3/pkg/msgprocessor"
"github.com/OpenIMSDK/tools/errs"
"github.com/gogo/protobuf/jsonpb" "github.com/gogo/protobuf/jsonpb"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
@ -443,7 +441,7 @@ func (c *msgCache) PipeSetMessageToCache(ctx context.Context, conversationID str
results, err := pipe.Exec(ctx) results, err := pipe.Exec(ctx)
if err != nil { if err != nil {
return 0, errs.Warp(err) return 0, errs.Wrap(err)
} }
for _, res := range results { for _, res := range results {

@ -23,12 +23,13 @@ import (
"github.com/OpenIMSDK/tools/discoveryregistry" "github.com/OpenIMSDK/tools/discoveryregistry"
"github.com/openimsdk/open-im-server/v3/pkg/common/config" "github.com/openimsdk/open-im-server/v3/pkg/common/config"
util "github.com/openimsdk/open-im-server/v3/pkg/util/genutil"
) )
func NewAuth(discov discoveryregistry.SvcDiscoveryRegistry) *Auth { func NewAuth(discov discoveryregistry.SvcDiscoveryRegistry) *Auth {
conn, err := discov.GetConn(context.Background(), config.Config.RpcRegisterName.OpenImAuthName) conn, err := discov.GetConn(context.Background(), config.Config.RpcRegisterName.OpenImAuthName)
if err != nil { if err != nil {
panic(err) util.ExitWithError(err)
} }
client := auth.NewAuthClient(conn) client := auth.NewAuthClient(conn)
return &Auth{discov: discov, conn: conn, Client: client} return &Auth{discov: discov, conn: conn, Client: client}

@ -116,11 +116,7 @@ func (c *ConversationRpcClient) GetConversationsByConversationID(ctx context.Con
return resp.Conversations, nil return resp.Conversations, nil
} }
func (c *ConversationRpcClient) GetConversations( func (c *ConversationRpcClient) GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*pbconversation.Conversation, error) {
ctx context.Context,
ownerUserID string,
conversationIDs []string,
) ([]*pbconversation.Conversation, error) {
if len(conversationIDs) == 0 { if len(conversationIDs) == 0 {
return nil, nil return nil, nil
} }

Loading…
Cancel
Save