复制项目
This commit is contained in:
150
internal/push/callback.go
Normal file
150
internal/push/callback.go
Normal file
@@ -0,0 +1,150 @@
|
||||
// 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 push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/webhook"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/callbackstruct"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"git.imall.cloud/openim/protocol/constant"
|
||||
"git.imall.cloud/openim/protocol/sdkws"
|
||||
"github.com/openimsdk/tools/mcontext"
|
||||
)
|
||||
|
||||
func (c *ConsumerHandler) webhookBeforeOfflinePush(ctx context.Context, before *config.BeforeConfig, userIDs []string, msg *sdkws.MsgData, offlinePushUserIDs *[]string) error {
|
||||
return webhook.WithCondition(ctx, before, func(ctx context.Context) error {
|
||||
if msg.ContentType == constant.Typing {
|
||||
return nil
|
||||
}
|
||||
req := &callbackstruct.CallbackBeforePushReq{
|
||||
UserStatusBatchCallbackReq: callbackstruct.UserStatusBatchCallbackReq{
|
||||
UserStatusBaseCallback: callbackstruct.UserStatusBaseCallback{
|
||||
CallbackCommand: callbackstruct.CallbackBeforeOfflinePushCommand,
|
||||
OperationID: mcontext.GetOperationID(ctx),
|
||||
PlatformID: int(msg.SenderPlatformID),
|
||||
Platform: constant.PlatformIDToName(int(msg.SenderPlatformID)),
|
||||
},
|
||||
UserIDList: userIDs,
|
||||
},
|
||||
OfflinePushInfo: msg.OfflinePushInfo,
|
||||
ClientMsgID: msg.ClientMsgID,
|
||||
SendID: msg.SendID,
|
||||
GroupID: msg.GroupID,
|
||||
ContentType: msg.ContentType,
|
||||
SessionType: msg.SessionType,
|
||||
AtUserIDs: msg.AtUserIDList,
|
||||
Content: GetContent(msg),
|
||||
}
|
||||
|
||||
resp := &callbackstruct.CallbackBeforePushResp{}
|
||||
|
||||
if err := c.webhookClient.SyncPost(ctx, req.GetCallbackCommand(), req, resp, before); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(resp.UserIDs) != 0 {
|
||||
*offlinePushUserIDs = resp.UserIDs
|
||||
}
|
||||
if resp.OfflinePushInfo != nil {
|
||||
msg.OfflinePushInfo = resp.OfflinePushInfo
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) webhookBeforeOnlinePush(ctx context.Context, before *config.BeforeConfig, userIDs []string, msg *sdkws.MsgData) error {
|
||||
return webhook.WithCondition(ctx, before, func(ctx context.Context) error {
|
||||
if msg.ContentType == constant.Typing {
|
||||
return nil
|
||||
}
|
||||
req := callbackstruct.CallbackBeforePushReq{
|
||||
UserStatusBatchCallbackReq: callbackstruct.UserStatusBatchCallbackReq{
|
||||
UserStatusBaseCallback: callbackstruct.UserStatusBaseCallback{
|
||||
CallbackCommand: callbackstruct.CallbackBeforeOnlinePushCommand,
|
||||
OperationID: mcontext.GetOperationID(ctx),
|
||||
PlatformID: int(msg.SenderPlatformID),
|
||||
Platform: constant.PlatformIDToName(int(msg.SenderPlatformID)),
|
||||
},
|
||||
UserIDList: userIDs,
|
||||
},
|
||||
ClientMsgID: msg.ClientMsgID,
|
||||
SendID: msg.SendID,
|
||||
GroupID: msg.GroupID,
|
||||
ContentType: msg.ContentType,
|
||||
SessionType: msg.SessionType,
|
||||
AtUserIDs: msg.AtUserIDList,
|
||||
Content: GetContent(msg),
|
||||
}
|
||||
resp := &callbackstruct.CallbackBeforePushResp{}
|
||||
if err := c.webhookClient.SyncPost(ctx, req.GetCallbackCommand(), req, resp, before); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) webhookBeforeGroupOnlinePush(
|
||||
ctx context.Context,
|
||||
before *config.BeforeConfig,
|
||||
groupID string,
|
||||
msg *sdkws.MsgData,
|
||||
pushToUserIDs *[]string,
|
||||
) error {
|
||||
return webhook.WithCondition(ctx, before, func(ctx context.Context) error {
|
||||
if msg.ContentType == constant.Typing {
|
||||
return nil
|
||||
}
|
||||
req := callbackstruct.CallbackBeforeSuperGroupOnlinePushReq{
|
||||
UserStatusBaseCallback: callbackstruct.UserStatusBaseCallback{
|
||||
CallbackCommand: callbackstruct.CallbackBeforeGroupOnlinePushCommand,
|
||||
OperationID: mcontext.GetOperationID(ctx),
|
||||
PlatformID: int(msg.SenderPlatformID),
|
||||
Platform: constant.PlatformIDToName(int(msg.SenderPlatformID)),
|
||||
},
|
||||
ClientMsgID: msg.ClientMsgID,
|
||||
SendID: msg.SendID,
|
||||
GroupID: groupID,
|
||||
ContentType: msg.ContentType,
|
||||
SessionType: msg.SessionType,
|
||||
AtUserIDs: msg.AtUserIDList,
|
||||
Content: GetContent(msg),
|
||||
Seq: msg.Seq,
|
||||
}
|
||||
resp := &callbackstruct.CallbackBeforeSuperGroupOnlinePushResp{}
|
||||
if err := c.webhookClient.SyncPost(ctx, req.GetCallbackCommand(), req, resp, before); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(resp.UserIDs) != 0 {
|
||||
*pushToUserIDs = resp.UserIDs
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func GetContent(msg *sdkws.MsgData) string {
|
||||
if msg.ContentType >= constant.NotificationBegin && msg.ContentType <= constant.NotificationEnd {
|
||||
var notification sdkws.NotificationElem
|
||||
if err := json.Unmarshal(msg.Content, ¬ification); err != nil {
|
||||
return ""
|
||||
}
|
||||
return notification.Detail
|
||||
} else {
|
||||
return string(msg.Content)
|
||||
}
|
||||
}
|
||||
38
internal/push/offlinepush/dummy/push.go
Normal file
38
internal/push/offlinepush/dummy/push.go
Normal file
@@ -0,0 +1,38 @@
|
||||
// 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 dummy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"github.com/openimsdk/tools/log"
|
||||
)
|
||||
|
||||
func NewClient() *Dummy {
|
||||
return &Dummy{}
|
||||
}
|
||||
|
||||
type Dummy struct {
|
||||
v atomic.Bool
|
||||
}
|
||||
|
||||
func (d *Dummy) Push(ctx context.Context, userIDs []string, title, content string, opts *options.Opts) error {
|
||||
if d.v.CompareAndSwap(false, true) {
|
||||
log.ZWarn(ctx, "dummy push", nil, "ps", "the offline push is not configured. to configure it, please go to config/openim-push.yml")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
172
internal/push/offlinepush/fcm/push.go
Normal file
172
internal/push/offlinepush/fcm/push.go
Normal file
@@ -0,0 +1,172 @@
|
||||
// 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 fcm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"github.com/openimsdk/tools/utils/httputil"
|
||||
|
||||
firebase "firebase.google.com/go/v4"
|
||||
"firebase.google.com/go/v4/messaging"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache"
|
||||
"git.imall.cloud/openim/protocol/constant"
|
||||
"github.com/openimsdk/tools/errs"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"google.golang.org/api/option"
|
||||
)
|
||||
|
||||
const SinglePushCountLimit = 400
|
||||
|
||||
var Terminal = []int{constant.IOSPlatformID, constant.AndroidPlatformID, constant.WebPlatformID}
|
||||
|
||||
type Fcm struct {
|
||||
fcmMsgCli *messaging.Client
|
||||
cache cache.ThirdCache
|
||||
}
|
||||
|
||||
// NewClient initializes a new FCM client using the Firebase Admin SDK.
|
||||
// It requires the FCM service account credentials file located within the project's configuration directory.
|
||||
func NewClient(pushConf *config.Push, cache cache.ThirdCache, fcmConfigPath string) (*Fcm, error) {
|
||||
var opt option.ClientOption
|
||||
switch {
|
||||
case len(pushConf.FCM.FilePath) != 0:
|
||||
// with file path
|
||||
credentialsFilePath := filepath.Join(fcmConfigPath, pushConf.FCM.FilePath)
|
||||
opt = option.WithCredentialsFile(credentialsFilePath)
|
||||
case len(pushConf.FCM.AuthURL) != 0:
|
||||
// with authentication URL
|
||||
client := httputil.NewHTTPClient(httputil.NewClientConfig())
|
||||
resp, err := client.Get(pushConf.FCM.AuthURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt = option.WithCredentialsJSON(resp)
|
||||
default:
|
||||
return nil, errs.New("no FCM config").Wrap()
|
||||
}
|
||||
|
||||
fcmApp, err := firebase.NewApp(context.Background(), nil, opt)
|
||||
if err != nil {
|
||||
return nil, errs.Wrap(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
fcmMsgClient, err := fcmApp.Messaging(ctx)
|
||||
if err != nil {
|
||||
return nil, errs.Wrap(err)
|
||||
}
|
||||
return &Fcm{fcmMsgCli: fcmMsgClient, cache: cache}, nil
|
||||
}
|
||||
|
||||
func (f *Fcm) Push(ctx context.Context, userIDs []string, title, content string, opts *options.Opts) error {
|
||||
// accounts->registrationToken
|
||||
allTokens := make(map[string][]string, 0)
|
||||
for _, account := range userIDs {
|
||||
var personTokens []string
|
||||
for _, v := range Terminal {
|
||||
Token, err := f.cache.GetFcmToken(ctx, account, v)
|
||||
if err == nil {
|
||||
personTokens = append(personTokens, Token)
|
||||
}
|
||||
}
|
||||
allTokens[account] = personTokens
|
||||
}
|
||||
Success := 0
|
||||
Fail := 0
|
||||
notification := &messaging.Notification{}
|
||||
notification.Body = content
|
||||
notification.Title = title
|
||||
var messages []*messaging.Message
|
||||
var sendErrBuilder strings.Builder
|
||||
var msgErrBuilder strings.Builder
|
||||
for userID, personTokens := range allTokens {
|
||||
apns := &messaging.APNSConfig{Payload: &messaging.APNSPayload{Aps: &messaging.Aps{Sound: opts.IOSPushSound}}}
|
||||
messageCount := len(messages)
|
||||
if messageCount >= SinglePushCountLimit {
|
||||
response, err := f.fcmMsgCli.SendEach(ctx, messages)
|
||||
if err != nil {
|
||||
Fail = Fail + messageCount
|
||||
// Record push error
|
||||
sendErrBuilder.WriteString(err.Error())
|
||||
sendErrBuilder.WriteByte('.')
|
||||
} else {
|
||||
Success = Success + response.SuccessCount
|
||||
Fail = Fail + response.FailureCount
|
||||
if response.FailureCount != 0 {
|
||||
// Record message error
|
||||
for i := range response.Responses {
|
||||
if !response.Responses[i].Success {
|
||||
msgErrBuilder.WriteString(response.Responses[i].Error.Error())
|
||||
msgErrBuilder.WriteByte('.')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
messages = messages[0:0]
|
||||
}
|
||||
if opts.IOSBadgeCount {
|
||||
unreadCountSum, err := f.cache.IncrUserBadgeUnreadCountSum(ctx, userID)
|
||||
if err == nil {
|
||||
apns.Payload.Aps.Badge = &unreadCountSum
|
||||
} else {
|
||||
// log.Error(operationID, "IncrUserBadgeUnreadCountSum redis err", err.Error(), uid)
|
||||
Fail++
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
unreadCountSum, err := f.cache.GetUserBadgeUnreadCountSum(ctx, userID)
|
||||
if err == nil && unreadCountSum != 0 {
|
||||
apns.Payload.Aps.Badge = &unreadCountSum
|
||||
} else if errors.Is(err, redis.Nil) || unreadCountSum == 0 {
|
||||
zero := 1
|
||||
apns.Payload.Aps.Badge = &zero
|
||||
} else {
|
||||
// log.Error(operationID, "GetUserBadgeUnreadCountSum redis err", err.Error(), uid)
|
||||
Fail++
|
||||
continue
|
||||
}
|
||||
}
|
||||
for _, token := range personTokens {
|
||||
temp := &messaging.Message{
|
||||
Data: map[string]string{"ex": opts.Ex},
|
||||
Token: token,
|
||||
Notification: notification,
|
||||
APNS: apns,
|
||||
}
|
||||
messages = append(messages, temp)
|
||||
}
|
||||
}
|
||||
messageCount := len(messages)
|
||||
if messageCount > 0 {
|
||||
response, err := f.fcmMsgCli.SendEach(ctx, messages)
|
||||
if err != nil {
|
||||
Fail = Fail + messageCount
|
||||
} else {
|
||||
Success = Success + response.SuccessCount
|
||||
Fail = Fail + response.FailureCount
|
||||
}
|
||||
}
|
||||
if Fail != 0 {
|
||||
return errs.New(fmt.Sprintf("%d message send failed;send err:%s;message err:%s",
|
||||
Fail, sendErrBuilder.String(), msgErrBuilder.String())).Wrap()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
219
internal/push/offlinepush/getui/body.go
Normal file
219
internal/push/offlinepush/getui/body.go
Normal file
@@ -0,0 +1,219 @@
|
||||
// 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 getui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"github.com/openimsdk/tools/utils/datautil"
|
||||
)
|
||||
|
||||
var (
|
||||
incOne = datautil.ToPtr("+1")
|
||||
addNum = "1"
|
||||
defaultStrategy = strategy{
|
||||
Default: 1,
|
||||
}
|
||||
msgCategory = "CATEGORY_MESSAGE"
|
||||
)
|
||||
|
||||
type Resp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
func (r *Resp) parseError() (err error) {
|
||||
switch r.Code {
|
||||
case tokenExpireCode:
|
||||
err = ErrTokenExpire
|
||||
case 0:
|
||||
err = nil
|
||||
default:
|
||||
err = fmt.Errorf("code %d, msg %s", r.Code, r.Msg)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type RespI interface {
|
||||
parseError() error
|
||||
}
|
||||
|
||||
type AuthReq struct {
|
||||
Sign string `json:"sign"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
AppKey string `json:"appkey"`
|
||||
}
|
||||
|
||||
type AuthResp struct {
|
||||
ExpireTime string `json:"expire_time"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
type TaskResp struct {
|
||||
TaskID string `json:"taskID"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
TTL *int64 `json:"ttl"`
|
||||
Strategy strategy `json:"strategy"`
|
||||
}
|
||||
|
||||
type strategy struct {
|
||||
Default int64 `json:"default"`
|
||||
//IOS int64 `json:"ios"`
|
||||
//St int64 `json:"st"`
|
||||
//Hw int64 `json:"hw"`
|
||||
//Ho int64 `json:"ho"`
|
||||
//XM int64 `json:"xm"`
|
||||
//XMG int64 `json:"xmg"`
|
||||
//VV int64 `json:"vv"`
|
||||
//Op int64 `json:"op"`
|
||||
//OpG int64 `json:"opg"`
|
||||
//MZ int64 `json:"mz"`
|
||||
//HosHw int64 `json:"hoshw"`
|
||||
//WX int64 `json:"wx"`
|
||||
}
|
||||
|
||||
type Audience struct {
|
||||
Alias []string `json:"alias"`
|
||||
}
|
||||
|
||||
type PushMessage struct {
|
||||
Notification *Notification `json:"notification,omitempty"`
|
||||
Transmission *string `json:"transmission,omitempty"`
|
||||
}
|
||||
|
||||
type PushChannel struct {
|
||||
Ios *Ios `json:"ios"`
|
||||
Android *Android `json:"android"`
|
||||
}
|
||||
|
||||
type PushReq struct {
|
||||
RequestID *string `json:"request_id"`
|
||||
Settings *Settings `json:"settings"`
|
||||
Audience *Audience `json:"audience"`
|
||||
PushMessage *PushMessage `json:"push_message"`
|
||||
PushChannel *PushChannel `json:"push_channel"`
|
||||
IsAsync *bool `json:"is_async"`
|
||||
TaskID *string `json:"taskid"`
|
||||
}
|
||||
|
||||
type Ios struct {
|
||||
NotificationType *string `json:"type"`
|
||||
AutoBadge *string `json:"auto_badge"`
|
||||
Aps struct {
|
||||
Sound string `json:"sound"`
|
||||
Alert Alert `json:"alert"`
|
||||
} `json:"aps"`
|
||||
}
|
||||
|
||||
type Alert struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
type Android struct {
|
||||
Ups struct {
|
||||
Notification Notification `json:"notification"`
|
||||
Options Options `json:"options"`
|
||||
} `json:"ups"`
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
ChannelID string `json:"channelID"`
|
||||
ChannelName string `json:"ChannelName"`
|
||||
ClickType string `json:"click_type"`
|
||||
BadgeAddNum string `json:"badge_add_num"`
|
||||
Category string `json:"category"`
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
HW struct {
|
||||
DefaultSound bool `json:"/message/android/notification/default_sound"`
|
||||
ChannelID string `json:"/message/android/notification/channel_id"`
|
||||
Sound string `json:"/message/android/notification/sound"`
|
||||
Importance string `json:"/message/android/notification/importance"`
|
||||
Category string `json:"/message/android/category"`
|
||||
} `json:"HW"`
|
||||
XM struct {
|
||||
ChannelID string `json:"/extra.channel_id"`
|
||||
} `json:"XM"`
|
||||
VV struct {
|
||||
Classification int `json:"/classification"`
|
||||
} `json:"VV"`
|
||||
}
|
||||
|
||||
type Payload struct {
|
||||
IsSignal bool `json:"isSignal"`
|
||||
}
|
||||
|
||||
func newPushReq(pushConf *config.Push, title, content string) PushReq {
|
||||
pushReq := PushReq{PushMessage: &PushMessage{Notification: &Notification{
|
||||
Title: title,
|
||||
Body: content,
|
||||
ClickType: "startapp",
|
||||
ChannelID: pushConf.GeTui.ChannelID,
|
||||
ChannelName: pushConf.GeTui.ChannelName,
|
||||
BadgeAddNum: addNum,
|
||||
Category: msgCategory,
|
||||
}}}
|
||||
return pushReq
|
||||
}
|
||||
|
||||
func newBatchPushReq(userIDs []string, taskID string) PushReq {
|
||||
IsAsync := true
|
||||
return PushReq{Audience: &Audience{Alias: userIDs}, IsAsync: &IsAsync, TaskID: &taskID}
|
||||
}
|
||||
|
||||
func (pushReq *PushReq) setPushChannel(title string, body string) {
|
||||
pushReq.PushChannel = &PushChannel{}
|
||||
// autoBadge := "+1"
|
||||
pushReq.PushChannel.Ios = &Ios{}
|
||||
notify := "notify"
|
||||
pushReq.PushChannel.Ios.NotificationType = ¬ify
|
||||
pushReq.PushChannel.Ios.Aps.Sound = "default"
|
||||
pushReq.PushChannel.Ios.AutoBadge = incOne
|
||||
pushReq.PushChannel.Ios.Aps.Alert = Alert{
|
||||
Title: title,
|
||||
Body: body,
|
||||
}
|
||||
pushReq.PushChannel.Android = &Android{}
|
||||
pushReq.PushChannel.Android.Ups.Notification = Notification{
|
||||
Title: title,
|
||||
Body: body,
|
||||
ClickType: "startapp",
|
||||
}
|
||||
pushReq.PushChannel.Android.Ups.Options = Options{
|
||||
HW: struct {
|
||||
DefaultSound bool `json:"/message/android/notification/default_sound"`
|
||||
ChannelID string `json:"/message/android/notification/channel_id"`
|
||||
Sound string `json:"/message/android/notification/sound"`
|
||||
Importance string `json:"/message/android/notification/importance"`
|
||||
Category string `json:"/message/android/category"`
|
||||
}{ChannelID: "RingRing4", Sound: "/raw/ring001", Importance: "NORMAL", Category: "IM"},
|
||||
XM: struct {
|
||||
ChannelID string `json:"/extra.channel_id"`
|
||||
}{ChannelID: "high_system"},
|
||||
VV: struct {
|
||||
Classification int "json:\"/classification\""
|
||||
}{
|
||||
Classification: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
219
internal/push/offlinepush/getui/push.go
Normal file
219
internal/push/offlinepush/getui/push.go
Normal file
@@ -0,0 +1,219 @@
|
||||
// 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 getui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache"
|
||||
"github.com/openimsdk/tools/errs"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"github.com/openimsdk/tools/mcontext"
|
||||
"github.com/openimsdk/tools/utils/httputil"
|
||||
"github.com/openimsdk/tools/utils/splitter"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrTokenExpire = errs.New("token expire")
|
||||
ErrUserIDEmpty = errs.New("userIDs is empty")
|
||||
)
|
||||
|
||||
const (
|
||||
pushURL = "/push/single/alias"
|
||||
authURL = "/auth"
|
||||
taskURL = "/push/list/message"
|
||||
batchPushURL = "/push/list/alias"
|
||||
|
||||
// Codes.
|
||||
tokenExpireCode = 10001
|
||||
tokenExpireTime = 60 * 60 * 23
|
||||
taskIDTTL = 1000 * 60 * 60 * 24
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
cache cache.ThirdCache
|
||||
tokenExpireTime int64
|
||||
taskIDTTL int64
|
||||
pushConf *config.Push
|
||||
httpClient *httputil.HTTPClient
|
||||
}
|
||||
|
||||
func NewClient(pushConf *config.Push, cache cache.ThirdCache) *Client {
|
||||
return &Client{cache: cache,
|
||||
tokenExpireTime: tokenExpireTime,
|
||||
taskIDTTL: taskIDTTL,
|
||||
pushConf: pushConf,
|
||||
httpClient: httputil.NewHTTPClient(httputil.NewClientConfig()),
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Client) Push(ctx context.Context, userIDs []string, title, content string, opts *options.Opts) error {
|
||||
token, err := g.cache.GetGetuiToken(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
log.ZDebug(ctx, "getui token not exist in redis")
|
||||
token, err = g.getTokenAndSave2Redis(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
pushReq := newPushReq(g.pushConf, title, content)
|
||||
pushReq.setPushChannel(title, content)
|
||||
if len(userIDs) > 1 {
|
||||
maxNum := 999
|
||||
if len(userIDs) > maxNum {
|
||||
s := splitter.NewSplitter(maxNum, userIDs)
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(s.GetSplitResult()))
|
||||
for i, v := range s.GetSplitResult() {
|
||||
go func(index int, userIDs []string) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < len(userIDs); i += maxNum {
|
||||
end := i + maxNum
|
||||
if end > len(userIDs) {
|
||||
end = len(userIDs)
|
||||
}
|
||||
if err = g.batchPush(ctx, token, userIDs[i:end], pushReq); err != nil {
|
||||
log.ZError(ctx, "batchPush failed", err, "index", index, "token", token, "req", pushReq)
|
||||
}
|
||||
}
|
||||
if err = g.batchPush(ctx, token, userIDs, pushReq); err != nil {
|
||||
log.ZError(ctx, "batchPush failed", err, "index", index, "token", token, "req", pushReq)
|
||||
}
|
||||
}(i, v.Item)
|
||||
}
|
||||
wg.Wait()
|
||||
} else {
|
||||
err = g.batchPush(ctx, token, userIDs, pushReq)
|
||||
}
|
||||
} else if len(userIDs) == 1 {
|
||||
err = g.singlePush(ctx, token, userIDs[0], pushReq)
|
||||
} else {
|
||||
return ErrUserIDEmpty
|
||||
}
|
||||
switch err {
|
||||
case ErrTokenExpire:
|
||||
token, err = g.getTokenAndSave2Redis(ctx)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (g *Client) Auth(ctx context.Context, timeStamp int64) (token string, expireTime int64, err error) {
|
||||
h := sha256.New()
|
||||
h.Write(
|
||||
[]byte(g.pushConf.GeTui.AppKey + strconv.Itoa(int(timeStamp)) + g.pushConf.GeTui.MasterSecret),
|
||||
)
|
||||
sign := hex.EncodeToString(h.Sum(nil))
|
||||
reqAuth := AuthReq{
|
||||
Sign: sign,
|
||||
Timestamp: strconv.Itoa(int(timeStamp)),
|
||||
AppKey: g.pushConf.GeTui.AppKey,
|
||||
}
|
||||
respAuth := AuthResp{}
|
||||
err = g.request(ctx, authURL, reqAuth, "", &respAuth)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
expire, err := strconv.Atoi(respAuth.ExpireTime)
|
||||
return respAuth.Token, int64(expire), err
|
||||
}
|
||||
|
||||
func (g *Client) GetTaskID(ctx context.Context, token string, pushReq PushReq) (string, error) {
|
||||
respTask := TaskResp{}
|
||||
ttl := int64(1000 * 60 * 5)
|
||||
pushReq.Settings = &Settings{TTL: &ttl, Strategy: defaultStrategy}
|
||||
err := g.request(ctx, taskURL, pushReq, token, &respTask)
|
||||
if err != nil {
|
||||
return "", errs.Wrap(err)
|
||||
}
|
||||
return respTask.TaskID, nil
|
||||
}
|
||||
|
||||
// max num is 999.
|
||||
func (g *Client) batchPush(ctx context.Context, token string, userIDs []string, pushReq PushReq) error {
|
||||
taskID, err := g.GetTaskID(ctx, token, pushReq)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pushReq = newBatchPushReq(userIDs, taskID)
|
||||
return g.request(ctx, batchPushURL, pushReq, token, nil)
|
||||
}
|
||||
|
||||
func (g *Client) singlePush(ctx context.Context, token, userID string, pushReq PushReq) error {
|
||||
operationID := mcontext.GetOperationID(ctx)
|
||||
pushReq.RequestID = &operationID
|
||||
pushReq.Audience = &Audience{Alias: []string{userID}}
|
||||
return g.request(ctx, pushURL, pushReq, token, nil)
|
||||
}
|
||||
|
||||
func (g *Client) request(ctx context.Context, url string, input any, token string, output any) error {
|
||||
header := map[string]string{"token": token}
|
||||
resp := &Resp{}
|
||||
resp.Data = output
|
||||
return g.postReturn(ctx, g.pushConf.GeTui.PushUrl+url, header, input, resp, 3)
|
||||
}
|
||||
|
||||
func (g *Client) postReturn(
|
||||
ctx context.Context,
|
||||
url string,
|
||||
header map[string]string,
|
||||
input any,
|
||||
output RespI,
|
||||
timeout int,
|
||||
) error {
|
||||
err := g.httpClient.PostReturn(ctx, url, header, input, output, timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, "postReturn", "url", url, "header", header, "input", input, "timeout", timeout, "output", output)
|
||||
return output.parseError()
|
||||
}
|
||||
|
||||
func (g *Client) getTokenAndSave2Redis(ctx context.Context) (token string, err error) {
|
||||
token, _, err = g.Auth(ctx, time.Now().UnixNano()/1e6)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = g.cache.SetGetuiToken(ctx, token, 60*60*23)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (g *Client) GetTaskIDAndSave2Redis(ctx context.Context, token string, pushReq PushReq) (taskID string, err error) {
|
||||
pushReq.Settings = &Settings{TTL: &g.taskIDTTL, Strategy: defaultStrategy}
|
||||
taskID, err = g.GetTaskID(ctx, token, pushReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = g.cache.SetGetuiTaskID(ctx, taskID, g.tokenExpireTime)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
64
internal/push/offlinepush/jpush/body/audience.go
Normal file
64
internal/push/offlinepush/jpush/body/audience.go
Normal file
@@ -0,0 +1,64 @@
|
||||
// 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 body
|
||||
|
||||
const (
|
||||
TAG = "tag"
|
||||
TAGAND = "tag_and"
|
||||
TAGNOT = "tag_not"
|
||||
ALIAS = "alias"
|
||||
REGISTRATIONID = "registration_id"
|
||||
)
|
||||
|
||||
type Audience struct {
|
||||
Object any
|
||||
audience map[string][]string
|
||||
}
|
||||
|
||||
func (a *Audience) set(key string, v []string) {
|
||||
if a.audience == nil {
|
||||
a.audience = make(map[string][]string)
|
||||
a.Object = a.audience
|
||||
}
|
||||
// v, ok = this.audience[key]
|
||||
// if ok {
|
||||
// return
|
||||
//}
|
||||
a.audience[key] = v
|
||||
}
|
||||
|
||||
func (a *Audience) SetTag(tags []string) {
|
||||
a.set(TAG, tags)
|
||||
}
|
||||
|
||||
func (a *Audience) SetTagAnd(tags []string) {
|
||||
a.set(TAGAND, tags)
|
||||
}
|
||||
|
||||
func (a *Audience) SetTagNot(tags []string) {
|
||||
a.set(TAGNOT, tags)
|
||||
}
|
||||
|
||||
func (a *Audience) SetAlias(alias []string) {
|
||||
a.set(ALIAS, alias)
|
||||
}
|
||||
|
||||
func (a *Audience) SetRegistrationId(ids []string) {
|
||||
a.set(REGISTRATIONID, ids)
|
||||
}
|
||||
|
||||
func (a *Audience) SetAll() {
|
||||
a.Object = "all"
|
||||
}
|
||||
41
internal/push/offlinepush/jpush/body/message.go
Normal file
41
internal/push/offlinepush/jpush/body/message.go
Normal file
@@ -0,0 +1,41 @@
|
||||
// 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 body
|
||||
|
||||
type Message struct {
|
||||
MsgContent string `json:"msg_content"`
|
||||
Title string `json:"title,omitempty"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
Extras map[string]any `json:"extras,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Message) SetMsgContent(c string) {
|
||||
m.MsgContent = c
|
||||
}
|
||||
|
||||
func (m *Message) SetTitle(t string) {
|
||||
m.Title = t
|
||||
}
|
||||
|
||||
func (m *Message) SetContentType(c string) {
|
||||
m.ContentType = c
|
||||
}
|
||||
|
||||
func (m *Message) SetExtras(key string, value any) {
|
||||
if m.Extras == nil {
|
||||
m.Extras = make(map[string]any)
|
||||
}
|
||||
m.Extras[key] = value
|
||||
}
|
||||
72
internal/push/offlinepush/jpush/body/notification.go
Normal file
72
internal/push/offlinepush/jpush/body/notification.go
Normal file
@@ -0,0 +1,72 @@
|
||||
// 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 body
|
||||
|
||||
import (
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
)
|
||||
|
||||
type Notification struct {
|
||||
Alert string `json:"alert,omitempty"`
|
||||
Android Android `json:"android,omitempty"`
|
||||
IOS Ios `json:"ios,omitempty"`
|
||||
}
|
||||
|
||||
type Android struct {
|
||||
Alert string `json:"alert,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Intent struct {
|
||||
URL string `json:"url,omitempty"`
|
||||
} `json:"intent,omitempty"`
|
||||
Extras map[string]string `json:"extras,omitempty"`
|
||||
}
|
||||
type Ios struct {
|
||||
Alert IosAlert `json:"alert,omitempty"`
|
||||
Sound string `json:"sound,omitempty"`
|
||||
Badge string `json:"badge,omitempty"`
|
||||
Extras map[string]string `json:"extras,omitempty"`
|
||||
MutableContent bool `json:"mutable-content"`
|
||||
}
|
||||
|
||||
type IosAlert struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Body string `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
func (n *Notification) SetAlert(alert string, title string, opts *options.Opts) {
|
||||
n.Alert = alert
|
||||
n.Android.Alert = alert
|
||||
n.Android.Title = title
|
||||
n.IOS.Alert.Body = alert
|
||||
n.IOS.Alert.Title = title
|
||||
n.IOS.Sound = opts.IOSPushSound
|
||||
if opts.IOSBadgeCount {
|
||||
n.IOS.Badge = "+1"
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Notification) SetExtras(extras map[string]string) {
|
||||
n.IOS.Extras = extras
|
||||
n.Android.Extras = extras
|
||||
}
|
||||
|
||||
func (n *Notification) SetAndroidIntent(pushConf *config.Push) {
|
||||
n.Android.Intent.URL = pushConf.JPush.PushIntent
|
||||
}
|
||||
|
||||
func (n *Notification) IOSEnableMutableContent() {
|
||||
n.IOS.MutableContent = true
|
||||
}
|
||||
23
internal/push/offlinepush/jpush/body/options.go
Normal file
23
internal/push/offlinepush/jpush/body/options.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// 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 body
|
||||
|
||||
type Options struct {
|
||||
ApnsProduction bool `json:"apns_production"`
|
||||
}
|
||||
|
||||
func (o *Options) SetApnsProduction(c bool) {
|
||||
o.ApnsProduction = c
|
||||
}
|
||||
99
internal/push/offlinepush/jpush/body/platform.go
Normal file
99
internal/push/offlinepush/jpush/body/platform.go
Normal file
@@ -0,0 +1,99 @@
|
||||
// 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 body
|
||||
|
||||
import (
|
||||
"github.com/openimsdk/tools/errs"
|
||||
|
||||
"git.imall.cloud/openim/protocol/constant"
|
||||
)
|
||||
|
||||
const (
|
||||
ANDROID = "android"
|
||||
IOS = "ios"
|
||||
QUICKAPP = "quickapp"
|
||||
WINDOWSPHONE = "winphone"
|
||||
ALL = "all"
|
||||
)
|
||||
|
||||
type Platform struct {
|
||||
Os any
|
||||
osArry []string
|
||||
}
|
||||
|
||||
func (p *Platform) Set(os string) error {
|
||||
if p.Os == nil {
|
||||
p.osArry = make([]string, 0, 4)
|
||||
} else {
|
||||
switch p.Os.(type) {
|
||||
case string:
|
||||
return errs.New("platform is all")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range p.osArry {
|
||||
if os == value {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
switch os {
|
||||
case IOS:
|
||||
fallthrough
|
||||
case ANDROID:
|
||||
fallthrough
|
||||
case QUICKAPP:
|
||||
fallthrough
|
||||
case WINDOWSPHONE:
|
||||
p.osArry = append(p.osArry, os)
|
||||
p.Os = p.osArry
|
||||
default:
|
||||
return errs.New("unknow platform")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Platform) SetPlatform(platform string) error {
|
||||
switch platform {
|
||||
case constant.AndroidPlatformStr:
|
||||
return p.SetAndroid()
|
||||
case constant.IOSPlatformStr:
|
||||
return p.SetIOS()
|
||||
default:
|
||||
return errs.New("platform err")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Platform) SetIOS() error {
|
||||
return p.Set(IOS)
|
||||
}
|
||||
|
||||
func (p *Platform) SetAndroid() error {
|
||||
return p.Set(ANDROID)
|
||||
}
|
||||
|
||||
func (p *Platform) SetQuickApp() error {
|
||||
return p.Set(QUICKAPP)
|
||||
}
|
||||
|
||||
func (p *Platform) SetWindowsPhone() error {
|
||||
return p.Set(WINDOWSPHONE)
|
||||
}
|
||||
|
||||
func (p *Platform) SetAll() {
|
||||
p.Os = ALL
|
||||
}
|
||||
43
internal/push/offlinepush/jpush/body/pushobj.go
Normal file
43
internal/push/offlinepush/jpush/body/pushobj.go
Normal file
@@ -0,0 +1,43 @@
|
||||
// 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 body
|
||||
|
||||
type PushObj struct {
|
||||
Platform any `json:"platform"`
|
||||
Audience any `json:"audience"`
|
||||
Notification any `json:"notification,omitempty"`
|
||||
Message any `json:"message,omitempty"`
|
||||
Options any `json:"options,omitempty"`
|
||||
}
|
||||
|
||||
func (p *PushObj) SetPlatform(pf *Platform) {
|
||||
p.Platform = pf.Os
|
||||
}
|
||||
|
||||
func (p *PushObj) SetAudience(ad *Audience) {
|
||||
p.Audience = ad.Object
|
||||
}
|
||||
|
||||
func (p *PushObj) SetNotification(no *Notification) {
|
||||
p.Notification = no
|
||||
}
|
||||
|
||||
func (p *PushObj) SetMessage(m *Message) {
|
||||
p.Message = m
|
||||
}
|
||||
|
||||
func (p *PushObj) SetOptions(o *Options) {
|
||||
p.Options = o
|
||||
}
|
||||
107
internal/push/offlinepush/jpush/push.go
Normal file
107
internal/push/offlinepush/jpush/push.go
Normal file
@@ -0,0 +1,107 @@
|
||||
// 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 jpush
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/jpush/body"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"github.com/openimsdk/tools/utils/httputil"
|
||||
)
|
||||
|
||||
type JPush struct {
|
||||
pushConf *config.Push
|
||||
httpClient *httputil.HTTPClient
|
||||
}
|
||||
|
||||
func NewClient(pushConf *config.Push) *JPush {
|
||||
return &JPush{pushConf: pushConf,
|
||||
httpClient: httputil.NewHTTPClient(httputil.NewClientConfig()),
|
||||
}
|
||||
}
|
||||
|
||||
func (j *JPush) Auth(apiKey, secretKey string, timeStamp int64) (token string, err error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (j *JPush) SetAlias(cid, alias string) (resp string, err error) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (j *JPush) getAuthorization(appKey string, masterSecret string) string {
|
||||
str := fmt.Sprintf("%s:%s", appKey, masterSecret)
|
||||
buf := []byte(str)
|
||||
Authorization := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(buf))
|
||||
return Authorization
|
||||
}
|
||||
|
||||
func (j *JPush) Push(ctx context.Context, userIDs []string, title, content string, opts *options.Opts) error {
|
||||
var pf body.Platform
|
||||
pf.SetAll()
|
||||
var au body.Audience
|
||||
au.SetAlias(userIDs)
|
||||
var no body.Notification
|
||||
extras := make(map[string]string)
|
||||
extras["ex"] = opts.Ex
|
||||
if opts.Signal.ClientMsgID != "" {
|
||||
extras["ClientMsgID"] = opts.Signal.ClientMsgID
|
||||
}
|
||||
no.IOSEnableMutableContent()
|
||||
no.SetExtras(extras)
|
||||
no.SetAlert(content, title, opts)
|
||||
no.SetAndroidIntent(j.pushConf)
|
||||
|
||||
var msg body.Message
|
||||
msg.SetMsgContent(content)
|
||||
msg.SetTitle(title)
|
||||
if opts.Signal.ClientMsgID != "" {
|
||||
msg.SetExtras("ClientMsgID", opts.Signal.ClientMsgID)
|
||||
}
|
||||
msg.SetExtras("ex", opts.Ex)
|
||||
var opt body.Options
|
||||
opt.SetApnsProduction(j.pushConf.IOSPush.Production)
|
||||
var pushObj body.PushObj
|
||||
pushObj.SetPlatform(&pf)
|
||||
pushObj.SetAudience(&au)
|
||||
pushObj.SetNotification(&no)
|
||||
pushObj.SetMessage(&msg)
|
||||
pushObj.SetOptions(&opt)
|
||||
var resp map[string]any
|
||||
return j.request(ctx, pushObj, &resp, 5)
|
||||
}
|
||||
|
||||
func (j *JPush) request(ctx context.Context, po body.PushObj, resp *map[string]any, timeout int) error {
|
||||
err := j.httpClient.PostReturn(
|
||||
ctx,
|
||||
j.pushConf.JPush.PushURL,
|
||||
map[string]string{
|
||||
"Authorization": j.getAuthorization(j.pushConf.JPush.AppKey, j.pushConf.JPush.MasterSecret),
|
||||
},
|
||||
po,
|
||||
resp,
|
||||
timeout,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if (*resp)["sendno"] != "0" {
|
||||
return fmt.Errorf("jpush push failed %v", resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
55
internal/push/offlinepush/offlinepusher.go
Normal file
55
internal/push/offlinepush/offlinepusher.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// 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 offlinepush
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/dummy"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/fcm"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/getui"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/jpush"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache"
|
||||
)
|
||||
|
||||
const (
|
||||
geTUI = "getui"
|
||||
firebase = "fcm"
|
||||
jPush = "jpush"
|
||||
)
|
||||
|
||||
// OfflinePusher Offline Pusher.
|
||||
type OfflinePusher interface {
|
||||
Push(ctx context.Context, userIDs []string, title, content string, opts *options.Opts) error
|
||||
}
|
||||
|
||||
func NewOfflinePusher(pushConf *config.Push, cache cache.ThirdCache, fcmConfigPath string) (OfflinePusher, error) {
|
||||
var offlinePusher OfflinePusher
|
||||
pushConf.Enable = strings.ToLower(pushConf.Enable)
|
||||
switch pushConf.Enable {
|
||||
case geTUI:
|
||||
offlinePusher = getui.NewClient(pushConf, cache)
|
||||
case firebase:
|
||||
return fcm.NewClient(pushConf, cache, fcmConfigPath)
|
||||
case jPush:
|
||||
offlinePusher = jpush.NewClient(pushConf)
|
||||
default:
|
||||
offlinePusher = dummy.NewClient()
|
||||
}
|
||||
return offlinePusher, nil
|
||||
}
|
||||
14
internal/push/offlinepush/options/options.go
Normal file
14
internal/push/offlinepush/options/options.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package options
|
||||
|
||||
// Opts opts.
|
||||
type Opts struct {
|
||||
Signal *Signal
|
||||
IOSPushSound string
|
||||
IOSBadgeCount bool
|
||||
Ex string
|
||||
}
|
||||
|
||||
// Signal message id.
|
||||
type Signal struct {
|
||||
ClientMsgID string
|
||||
}
|
||||
105
internal/push/offlinepush_handler.go
Normal file
105
internal/push/offlinepush_handler.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/prommetrics"
|
||||
"git.imall.cloud/openim/protocol/constant"
|
||||
pbpush "git.imall.cloud/openim/protocol/push"
|
||||
"git.imall.cloud/openim/protocol/sdkws"
|
||||
"github.com/openimsdk/tools/errs"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"github.com/openimsdk/tools/utils/jsonutil"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type OfflinePushConsumerHandler struct {
|
||||
offlinePusher offlinepush.OfflinePusher
|
||||
}
|
||||
|
||||
func NewOfflinePushConsumerHandler(offlinePusher offlinepush.OfflinePusher) *OfflinePushConsumerHandler {
|
||||
return &OfflinePushConsumerHandler{
|
||||
offlinePusher: offlinePusher,
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OfflinePushConsumerHandler) HandleMsg2OfflinePush(ctx context.Context, msg []byte) {
|
||||
offlinePushMsg := pbpush.PushMsgReq{}
|
||||
if err := proto.Unmarshal(msg, &offlinePushMsg); err != nil {
|
||||
log.ZError(ctx, "offline push Unmarshal msg err", err, "msg", string(msg))
|
||||
return
|
||||
}
|
||||
if offlinePushMsg.MsgData == nil || offlinePushMsg.UserIDs == nil {
|
||||
log.ZError(ctx, "offline push msg is empty", errs.New("offlinePushMsg is empty"), "userIDs", offlinePushMsg.UserIDs, "msg", offlinePushMsg.MsgData)
|
||||
return
|
||||
}
|
||||
if offlinePushMsg.MsgData.Status == constant.MsgStatusSending {
|
||||
offlinePushMsg.MsgData.Status = constant.MsgStatusSendSuccess
|
||||
}
|
||||
log.ZInfo(ctx, "receive to OfflinePush MQ", "userIDs", offlinePushMsg.UserIDs, "msg", offlinePushMsg.MsgData)
|
||||
|
||||
err := o.offlinePushMsg(ctx, offlinePushMsg.MsgData, offlinePushMsg.UserIDs)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, "offline push failed", err, "msg", offlinePushMsg.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OfflinePushConsumerHandler) getOfflinePushInfos(msg *sdkws.MsgData) (title, content string, opts *options.Opts, err error) {
|
||||
type AtTextElem struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
AtUserList []string `json:"atUserList,omitempty"`
|
||||
IsAtSelf bool `json:"isAtSelf"`
|
||||
}
|
||||
|
||||
opts = &options.Opts{Signal: &options.Signal{ClientMsgID: msg.ClientMsgID}}
|
||||
if msg.OfflinePushInfo != nil {
|
||||
opts.IOSBadgeCount = msg.OfflinePushInfo.IOSBadgeCount
|
||||
opts.IOSPushSound = msg.OfflinePushInfo.IOSPushSound
|
||||
opts.Ex = msg.OfflinePushInfo.Ex
|
||||
}
|
||||
|
||||
if msg.OfflinePushInfo != nil {
|
||||
title = msg.OfflinePushInfo.Title
|
||||
content = msg.OfflinePushInfo.Desc
|
||||
}
|
||||
if title == "" {
|
||||
switch msg.ContentType {
|
||||
case constant.Text:
|
||||
fallthrough
|
||||
case constant.Picture:
|
||||
fallthrough
|
||||
case constant.Voice:
|
||||
fallthrough
|
||||
case constant.Video:
|
||||
fallthrough
|
||||
case constant.File:
|
||||
title = constant.ContentType2PushContent[int64(msg.ContentType)]
|
||||
case constant.AtText:
|
||||
ac := AtTextElem{}
|
||||
_ = jsonutil.JsonStringToStruct(string(msg.Content), &ac)
|
||||
case constant.SignalingNotification:
|
||||
title = constant.ContentType2PushContent[constant.SignalMsg]
|
||||
default:
|
||||
title = constant.ContentType2PushContent[constant.Common]
|
||||
}
|
||||
}
|
||||
if content == "" {
|
||||
content = title
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (o *OfflinePushConsumerHandler) offlinePushMsg(ctx context.Context, msg *sdkws.MsgData, offlinePushUserIDs []string) error {
|
||||
title, content, opts, err := o.getOfflinePushInfos(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = o.offlinePusher.Push(ctx, offlinePushUserIDs, title, content, opts)
|
||||
if err != nil {
|
||||
prommetrics.MsgOfflinePushFailedCounter.Inc()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
214
internal/push/onlinepusher.go
Normal file
214
internal/push/onlinepusher.go
Normal file
@@ -0,0 +1,214 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"git.imall.cloud/openim/protocol/msggateway"
|
||||
"git.imall.cloud/openim/protocol/sdkws"
|
||||
"github.com/openimsdk/tools/discovery"
|
||||
"github.com/openimsdk/tools/errs"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"github.com/openimsdk/tools/utils/datautil"
|
||||
"github.com/openimsdk/tools/utils/runtimeenv"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
conf "git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
)
|
||||
|
||||
type OnlinePusher interface {
|
||||
GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
|
||||
pushToUserIDs []string) (wsResults []*msggateway.SingleMsgToUserResults, err error)
|
||||
GetOnlinePushFailedUserIDs(ctx context.Context, msg *sdkws.MsgData, wsResults []*msggateway.SingleMsgToUserResults,
|
||||
pushToUserIDs *[]string) []string
|
||||
}
|
||||
|
||||
type emptyOnlinePusher struct{}
|
||||
|
||||
func newEmptyOnlinePusher() *emptyOnlinePusher {
|
||||
return &emptyOnlinePusher{}
|
||||
}
|
||||
|
||||
func (emptyOnlinePusher) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData, pushToUserIDs []string) (wsResults []*msggateway.SingleMsgToUserResults, err error) {
|
||||
log.ZInfo(ctx, "emptyOnlinePusher GetConnsAndOnlinePush", nil)
|
||||
return nil, nil
|
||||
}
|
||||
func (u emptyOnlinePusher) GetOnlinePushFailedUserIDs(ctx context.Context, msg *sdkws.MsgData, wsResults []*msggateway.SingleMsgToUserResults, pushToUserIDs *[]string) []string {
|
||||
log.ZInfo(ctx, "emptyOnlinePusher GetOnlinePushFailedUserIDs", nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewOnlinePusher(disCov discovery.Conn, config *Config) (OnlinePusher, error) {
|
||||
if conf.Standalone() {
|
||||
return NewDefaultAllNode(disCov, config), nil
|
||||
}
|
||||
if runtimeenv.RuntimeEnvironment() == conf.KUBERNETES {
|
||||
return NewDefaultAllNode(disCov, config), nil
|
||||
}
|
||||
switch config.Discovery.Enable {
|
||||
case conf.ETCD:
|
||||
return NewDefaultAllNode(disCov, config), nil
|
||||
default:
|
||||
return nil, errs.New(fmt.Sprintf("unsupported discovery type %s", config.Discovery.Enable))
|
||||
}
|
||||
}
|
||||
|
||||
type DefaultAllNode struct {
|
||||
disCov discovery.Conn
|
||||
config *Config
|
||||
}
|
||||
|
||||
func NewDefaultAllNode(disCov discovery.Conn, config *Config) *DefaultAllNode {
|
||||
return &DefaultAllNode{disCov: disCov, config: config}
|
||||
}
|
||||
|
||||
func (d *DefaultAllNode) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
|
||||
pushToUserIDs []string) (wsResults []*msggateway.SingleMsgToUserResults, err error) {
|
||||
conns, err := d.disCov.GetConns(ctx, d.config.Discovery.RpcService.MessageGateway)
|
||||
if len(conns) == 0 {
|
||||
log.ZWarn(ctx, "get gateway conn 0 ", nil)
|
||||
} else {
|
||||
log.ZDebug(ctx, "get gateway conn", "conn length", len(conns))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
wg = errgroup.Group{}
|
||||
input = &msggateway.OnlineBatchPushOneMsgReq{MsgData: msg, PushToUserIDs: pushToUserIDs}
|
||||
maxWorkers = d.config.RpcConfig.MaxConcurrentWorkers
|
||||
)
|
||||
|
||||
if maxWorkers < 3 {
|
||||
maxWorkers = 3
|
||||
}
|
||||
|
||||
wg.SetLimit(maxWorkers)
|
||||
|
||||
// Online push message
|
||||
for _, conn := range conns {
|
||||
conn := conn // loop var safe
|
||||
ctx := ctx
|
||||
wg.Go(func() error {
|
||||
msgClient := msggateway.NewMsgGatewayClient(conn)
|
||||
reply, err := msgClient.SuperGroupOnlineBatchPushOneMsg(ctx, input)
|
||||
if err != nil {
|
||||
log.ZError(ctx, "SuperGroupOnlineBatchPushOneMsg ", err, "req:", input.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
log.ZDebug(ctx, "push result", "reply", reply)
|
||||
if reply != nil && reply.SinglePushResult != nil {
|
||||
mu.Lock()
|
||||
wsResults = append(wsResults, reply.SinglePushResult...)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
_ = wg.Wait()
|
||||
|
||||
// always return nil
|
||||
return wsResults, nil
|
||||
}
|
||||
|
||||
func (d *DefaultAllNode) GetOnlinePushFailedUserIDs(_ context.Context, msg *sdkws.MsgData,
|
||||
wsResults []*msggateway.SingleMsgToUserResults, pushToUserIDs *[]string) []string {
|
||||
|
||||
onlineSuccessUserIDs := []string{msg.SendID}
|
||||
for _, v := range wsResults {
|
||||
//message sender do not need offline push
|
||||
if msg.SendID == v.UserID {
|
||||
continue
|
||||
}
|
||||
// mobile online push success
|
||||
if v.OnlinePush {
|
||||
onlineSuccessUserIDs = append(onlineSuccessUserIDs, v.UserID)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return datautil.SliceSub(*pushToUserIDs, onlineSuccessUserIDs)
|
||||
}
|
||||
|
||||
type K8sStaticConsistentHash struct {
|
||||
disCov discovery.SvcDiscoveryRegistry
|
||||
config *Config
|
||||
}
|
||||
|
||||
func NewK8sStaticConsistentHash(disCov discovery.SvcDiscoveryRegistry, config *Config) *K8sStaticConsistentHash {
|
||||
return &K8sStaticConsistentHash{disCov: disCov, config: config}
|
||||
}
|
||||
|
||||
func (k *K8sStaticConsistentHash) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData,
|
||||
pushToUserIDs []string) (wsResults []*msggateway.SingleMsgToUserResults, err error) {
|
||||
|
||||
var usersHost = make(map[string][]string)
|
||||
for _, v := range pushToUserIDs {
|
||||
tHost, err := k.disCov.GetUserIdHashGatewayHost(ctx, v)
|
||||
if err != nil {
|
||||
log.ZError(ctx, "get msg gateway hash error", err)
|
||||
return nil, err
|
||||
}
|
||||
tUsers, tbl := usersHost[tHost]
|
||||
if tbl {
|
||||
tUsers = append(tUsers, v)
|
||||
usersHost[tHost] = tUsers
|
||||
} else {
|
||||
usersHost[tHost] = []string{v}
|
||||
}
|
||||
}
|
||||
log.ZDebug(ctx, "genUsers send hosts struct:", "usersHost", usersHost)
|
||||
var usersConns = make(map[grpc.ClientConnInterface][]string)
|
||||
for host, userIds := range usersHost {
|
||||
tconn, _ := k.disCov.GetConn(ctx, host)
|
||||
usersConns[tconn] = userIds
|
||||
}
|
||||
var (
|
||||
mu sync.Mutex
|
||||
wg = errgroup.Group{}
|
||||
maxWorkers = k.config.RpcConfig.MaxConcurrentWorkers
|
||||
)
|
||||
if maxWorkers < 3 {
|
||||
maxWorkers = 3
|
||||
}
|
||||
wg.SetLimit(maxWorkers)
|
||||
for conn, userIds := range usersConns {
|
||||
tcon := conn
|
||||
tuserIds := userIds
|
||||
wg.Go(func() error {
|
||||
input := &msggateway.OnlineBatchPushOneMsgReq{MsgData: msg, PushToUserIDs: tuserIds}
|
||||
msgClient := msggateway.NewMsgGatewayClient(tcon)
|
||||
reply, err := msgClient.SuperGroupOnlineBatchPushOneMsg(ctx, input)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
log.ZDebug(ctx, "push result", "reply", reply)
|
||||
if reply != nil && reply.SinglePushResult != nil {
|
||||
mu.Lock()
|
||||
wsResults = append(wsResults, reply.SinglePushResult...)
|
||||
mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
_ = wg.Wait()
|
||||
return wsResults, nil
|
||||
}
|
||||
func (k *K8sStaticConsistentHash) GetOnlinePushFailedUserIDs(_ context.Context, _ *sdkws.MsgData,
|
||||
wsResults []*msggateway.SingleMsgToUserResults, _ *[]string) []string {
|
||||
var needOfflinePushUserIDs []string
|
||||
for _, v := range wsResults {
|
||||
if !v.OnlinePush {
|
||||
needOfflinePushUserIDs = append(needOfflinePushUserIDs, v.UserID)
|
||||
}
|
||||
}
|
||||
return needOfflinePushUserIDs
|
||||
}
|
||||
163
internal/push/push.go
Normal file
163
internal/push/push.go
Normal file
@@ -0,0 +1,163 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/openimsdk/tools/mq"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/authverify"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/config"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache/mcache"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/cache/redis"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/controller"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/database/mgo"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/dbbuild"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/mqbuild"
|
||||
pbpush "git.imall.cloud/openim/protocol/push"
|
||||
"github.com/openimsdk/tools/discovery"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"github.com/openimsdk/tools/mcontext"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type pushServer struct {
|
||||
pbpush.UnimplementedPushMsgServiceServer
|
||||
database controller.PushDatabase
|
||||
disCov discovery.Conn
|
||||
offlinePusher offlinepush.OfflinePusher
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
RpcConfig config.Push
|
||||
RedisConfig config.Redis
|
||||
MongoConfig config.Mongo
|
||||
KafkaConfig config.Kafka
|
||||
NotificationConfig config.Notification
|
||||
Share config.Share
|
||||
WebhooksConfig config.Webhooks
|
||||
LocalCacheConfig config.LocalCache
|
||||
Discovery config.Discovery
|
||||
FcmConfigPath config.Path
|
||||
}
|
||||
|
||||
func (p pushServer) DelUserPushToken(ctx context.Context,
|
||||
req *pbpush.DelUserPushTokenReq) (resp *pbpush.DelUserPushTokenResp, err error) {
|
||||
if err = p.database.DelFcmToken(ctx, req.UserID, int(req.PlatformID)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbpush.DelUserPushTokenResp{}, nil
|
||||
}
|
||||
|
||||
func Start(ctx context.Context, config *Config, client discovery.SvcDiscoveryRegistry, server grpc.ServiceRegistrar) error {
|
||||
dbb := dbbuild.NewBuilder(&config.MongoConfig, &config.RedisConfig)
|
||||
rdb, err := dbb.Redis(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var cacheModel cache.ThirdCache
|
||||
if rdb == nil {
|
||||
mdb, err := dbb.Mongo(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mc, err := mgo.NewCacheMgo(mdb.GetDB())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cacheModel = mcache.NewThirdCache(mc)
|
||||
} else {
|
||||
cacheModel = redis.NewThirdCache(rdb)
|
||||
}
|
||||
offlinePusher, err := offlinepush.NewOfflinePusher(&config.RpcConfig, cacheModel, string(config.FcmConfigPath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
builder := mqbuild.NewBuilder(&config.KafkaConfig)
|
||||
|
||||
offlinePushProducer, err := builder.GetTopicProducer(ctx, config.KafkaConfig.ToOfflinePushTopic)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
database := controller.NewPushDatabase(cacheModel, offlinePushProducer)
|
||||
|
||||
pushConsumer, err := builder.GetTopicConsumer(ctx, config.KafkaConfig.ToPushTopic)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
offlinePushConsumer, err := builder.GetTopicConsumer(ctx, config.KafkaConfig.ToOfflinePushTopic)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pushHandler, err := NewConsumerHandler(ctx, config, database, offlinePusher, rdb, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
offlineHandler := NewOfflinePushConsumerHandler(offlinePusher)
|
||||
|
||||
pbpush.RegisterPushMsgServiceServer(server, &pushServer{
|
||||
database: database,
|
||||
disCov: client,
|
||||
offlinePusher: offlinePusher,
|
||||
})
|
||||
|
||||
go func() {
|
||||
consumerCtx := mcontext.SetOperationID(context.Background(), "push_"+strconv.Itoa(int(rand.Uint32())))
|
||||
waitDone := make(chan struct{})
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.ZError(consumerCtx, "WaitCache panic", nil, "panic", r)
|
||||
}
|
||||
close(waitDone)
|
||||
}()
|
||||
pushHandler.WaitCache()
|
||||
}()
|
||||
select {
|
||||
case <-waitDone:
|
||||
log.ZInfo(consumerCtx, "WaitCache completed successfully")
|
||||
case <-time.After(30 * time.Second):
|
||||
log.ZWarn(consumerCtx, "WaitCache timeout after 30s, will start subscribe anyway", nil)
|
||||
}
|
||||
fn := func(msg mq.Message) error {
|
||||
pushHandler.HandleMs2PsChat(authverify.WithTempAdmin(msg.Context()), msg.Value())
|
||||
return nil
|
||||
}
|
||||
log.ZInfo(consumerCtx, "begin consume messages")
|
||||
for {
|
||||
if err := pushConsumer.Subscribe(consumerCtx, fn); err != nil {
|
||||
log.ZError(consumerCtx, "subscribe err, will retry in 5 seconds", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
// Subscribe returned normally (possibly due to context cancellation), retry immediately
|
||||
log.ZWarn(consumerCtx, "Subscribe returned normally, will retry immediately", nil)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
fn := func(msg mq.Message) error {
|
||||
offlineHandler.HandleMsg2OfflinePush(msg.Context(), msg.Value())
|
||||
return nil
|
||||
}
|
||||
consumerCtx := mcontext.SetOperationID(context.Background(), "push_"+strconv.Itoa(int(rand.Uint32())))
|
||||
log.ZInfo(consumerCtx, "begin consume messages")
|
||||
for {
|
||||
if err := offlinePushConsumer.Subscribe(consumerCtx, fn); err != nil {
|
||||
log.ZError(consumerCtx, "subscribe err, will retry in 5 seconds", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
// Subscribe returned normally (possibly due to context cancellation), retry immediately
|
||||
log.ZWarn(consumerCtx, "Subscribe returned normally, will retry immediately", nil)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
615
internal/push/push_handler.go
Normal file
615
internal/push/push_handler.go
Normal file
@@ -0,0 +1,615 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/internal/push/offlinepush/options"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/prommetrics"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/controller"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/common/webhook"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/msgprocessor"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/rpccache"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/rpcli"
|
||||
"git.imall.cloud/openim/open-im-server-deploy/pkg/util/conversationutil"
|
||||
"git.imall.cloud/openim/protocol/constant"
|
||||
"git.imall.cloud/openim/protocol/msggateway"
|
||||
pbpush "git.imall.cloud/openim/protocol/push"
|
||||
"git.imall.cloud/openim/protocol/sdkws"
|
||||
"github.com/openimsdk/tools/discovery"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"github.com/openimsdk/tools/mcontext"
|
||||
"github.com/openimsdk/tools/utils/datautil"
|
||||
"github.com/openimsdk/tools/utils/jsonutil"
|
||||
"github.com/openimsdk/tools/utils/timeutil"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type ConsumerHandler struct {
|
||||
//pushConsumerGroup mq.Consumer
|
||||
offlinePusher offlinepush.OfflinePusher
|
||||
onlinePusher OnlinePusher
|
||||
pushDatabase controller.PushDatabase
|
||||
onlineCache rpccache.OnlineCache
|
||||
groupLocalCache *rpccache.GroupLocalCache
|
||||
conversationLocalCache *rpccache.ConversationLocalCache
|
||||
webhookClient *webhook.Client
|
||||
config *Config
|
||||
userClient *rpcli.UserClient
|
||||
groupClient *rpcli.GroupClient
|
||||
msgClient *rpcli.MsgClient
|
||||
conversationClient *rpcli.ConversationClient
|
||||
}
|
||||
|
||||
func NewConsumerHandler(ctx context.Context, config *Config, database controller.PushDatabase, offlinePusher offlinepush.OfflinePusher, rdb redis.UniversalClient, client discovery.Conn) (*ConsumerHandler, error) {
|
||||
userConn, err := client.GetConn(ctx, config.Discovery.RpcService.User)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
groupConn, err := client.GetConn(ctx, config.Discovery.RpcService.Group)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgConn, err := client.GetConn(ctx, config.Discovery.RpcService.Msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conversationConn, err := client.GetConn(ctx, config.Discovery.RpcService.Conversation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
onlinePusher, err := NewOnlinePusher(client, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var consumerHandler ConsumerHandler
|
||||
consumerHandler.userClient = rpcli.NewUserClient(userConn)
|
||||
consumerHandler.groupClient = rpcli.NewGroupClient(groupConn)
|
||||
consumerHandler.msgClient = rpcli.NewMsgClient(msgConn)
|
||||
consumerHandler.conversationClient = rpcli.NewConversationClient(conversationConn)
|
||||
|
||||
consumerHandler.offlinePusher = offlinePusher
|
||||
consumerHandler.onlinePusher = onlinePusher
|
||||
consumerHandler.groupLocalCache = rpccache.NewGroupLocalCache(consumerHandler.groupClient, &config.LocalCacheConfig, rdb)
|
||||
consumerHandler.conversationLocalCache = rpccache.NewConversationLocalCache(consumerHandler.conversationClient, &config.LocalCacheConfig, rdb)
|
||||
consumerHandler.webhookClient = webhook.NewWebhookClient(config.WebhooksConfig.URL)
|
||||
consumerHandler.config = config
|
||||
consumerHandler.pushDatabase = database
|
||||
consumerHandler.onlineCache, err = rpccache.NewOnlineCache(consumerHandler.userClient, consumerHandler.groupLocalCache, rdb, config.RpcConfig.FullUserCache, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &consumerHandler, nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) HandleMs2PsChat(ctx context.Context, msg []byte) {
|
||||
msgFromMQ := pbpush.PushMsgReq{}
|
||||
if err := proto.Unmarshal(msg, &msgFromMQ); err != nil {
|
||||
log.ZError(ctx, "push Unmarshal msg err", err, "msg", string(msg))
|
||||
return
|
||||
}
|
||||
|
||||
sec := msgFromMQ.MsgData.SendTime / 1000
|
||||
nowSec := timeutil.GetCurrentTimestampBySecond()
|
||||
|
||||
if nowSec-sec > 10 {
|
||||
prommetrics.MsgLoneTimePushCounter.Inc()
|
||||
log.ZWarn(ctx, "it’s been a while since the message was sent", nil, "msg", msgFromMQ.String(), "sec", sec, "nowSec", nowSec, "nowSec-sec", nowSec-sec)
|
||||
}
|
||||
var err error
|
||||
|
||||
switch msgFromMQ.MsgData.SessionType {
|
||||
case constant.ReadGroupChatType:
|
||||
err = c.Push2Group(ctx, msgFromMQ.MsgData.GroupID, msgFromMQ.MsgData)
|
||||
default:
|
||||
var pushUserIDList []string
|
||||
isSenderSync := datautil.GetSwitchFromOptions(msgFromMQ.MsgData.Options, constant.IsSenderSync)
|
||||
if !isSenderSync || msgFromMQ.MsgData.SendID == msgFromMQ.MsgData.RecvID {
|
||||
pushUserIDList = append(pushUserIDList, msgFromMQ.MsgData.RecvID)
|
||||
} else {
|
||||
pushUserIDList = append(pushUserIDList, msgFromMQ.MsgData.RecvID, msgFromMQ.MsgData.SendID)
|
||||
}
|
||||
err = c.Push2User(ctx, pushUserIDList, msgFromMQ.MsgData)
|
||||
}
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, "push failed", err, "msg", msgFromMQ.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) WaitCache() {
|
||||
c.onlineCache.WaitCache()
|
||||
}
|
||||
|
||||
// Push2User Suitable for two types of conversations, one is SingleChatType and the other is NotificationChatType.
|
||||
func (c *ConsumerHandler) Push2User(ctx context.Context, userIDs []string, msg *sdkws.MsgData) (err error) {
|
||||
log.ZInfo(ctx, "Get msg from msg_transfer And push msg", "userIDs", userIDs, "msg", msg.String())
|
||||
defer func(duration time.Time) {
|
||||
t := time.Since(duration)
|
||||
log.ZInfo(ctx, "Get msg from msg_transfer And push msg end", "msg", msg.String(), "time cost", t)
|
||||
}(time.Now())
|
||||
if err := c.webhookBeforeOnlinePush(ctx, &c.config.WebhooksConfig.BeforeOnlinePush, userIDs, msg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
wsResults, err := c.GetConnsAndOnlinePush(ctx, msg, userIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.ZDebug(ctx, "single and notification push result", "result", wsResults, "msg", msg, "push_to_userID", userIDs)
|
||||
log.ZInfo(ctx, "single and notification push end")
|
||||
|
||||
if !c.shouldPushOffline(ctx, msg) {
|
||||
return nil
|
||||
}
|
||||
log.ZInfo(ctx, "pushOffline start")
|
||||
|
||||
for _, v := range wsResults {
|
||||
//message sender do not need offline push
|
||||
if msg.SendID == v.UserID {
|
||||
continue
|
||||
}
|
||||
//receiver online push success
|
||||
if v.OnlinePush {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
needOfflinePushUserID := []string{msg.RecvID}
|
||||
var offlinePushUserID []string
|
||||
|
||||
//receiver offline push
|
||||
if err = c.webhookBeforeOfflinePush(ctx, &c.config.WebhooksConfig.BeforeOfflinePush, needOfflinePushUserID, msg, &offlinePushUserID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(offlinePushUserID) > 0 {
|
||||
needOfflinePushUserID = offlinePushUserID
|
||||
}
|
||||
err = c.offlinePushMsg(ctx, msg, needOfflinePushUserID)
|
||||
if err != nil {
|
||||
log.ZDebug(ctx, "offlinePushMsg failed", err, "needOfflinePushUserID", needOfflinePushUserID, "msg", msg)
|
||||
log.ZWarn(ctx, "offlinePushMsg failed", err, "needOfflinePushUserID length", len(needOfflinePushUserID), "msg", msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) shouldPushOffline(_ context.Context, msg *sdkws.MsgData) bool {
|
||||
isOfflinePush := datautil.GetSwitchFromOptions(msg.Options, constant.IsOfflinePush)
|
||||
if !isOfflinePush {
|
||||
return false
|
||||
}
|
||||
switch msg.ContentType {
|
||||
case constant.RoomParticipantsConnectedNotification:
|
||||
return false
|
||||
case constant.RoomParticipantsDisconnectedNotification:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) GetConnsAndOnlinePush(ctx context.Context, msg *sdkws.MsgData, pushToUserIDs []string) ([]*msggateway.SingleMsgToUserResults, error) {
|
||||
if msg != nil && msg.Status == constant.MsgStatusSending {
|
||||
msg.Status = constant.MsgStatusSendSuccess
|
||||
}
|
||||
onlineUserIDs, offlineUserIDs, err := c.onlineCache.GetUsersOnline(ctx, pushToUserIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.ZDebug(ctx, "GetConnsAndOnlinePush online cache", "sendID", msg.SendID, "recvID", msg.RecvID, "groupID", msg.GroupID, "sessionType", msg.SessionType, "clientMsgID", msg.ClientMsgID, "serverMsgID", msg.ServerMsgID, "offlineUserIDs", offlineUserIDs, "onlineUserIDs", onlineUserIDs)
|
||||
var result []*msggateway.SingleMsgToUserResults
|
||||
if len(onlineUserIDs) > 0 {
|
||||
var err error
|
||||
result, err = c.onlinePusher.GetConnsAndOnlinePush(ctx, msg, onlineUserIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, userID := range offlineUserIDs {
|
||||
result = append(result, &msggateway.SingleMsgToUserResults{
|
||||
UserID: userID,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) Push2Group(ctx context.Context, groupID string, msg *sdkws.MsgData) (err error) {
|
||||
log.ZInfo(ctx, "Get group msg from msg_transfer and push msg", "msg", msg.String(), "groupID", groupID, "contentType", msg.ContentType)
|
||||
defer func(duration time.Time) {
|
||||
t := time.Since(duration)
|
||||
log.ZInfo(ctx, "Get group msg from msg_transfer and push msg end", "msg", msg.String(), "groupID", groupID, "time cost", t)
|
||||
}(time.Now())
|
||||
var pushToUserIDs []string
|
||||
if err = c.webhookBeforeGroupOnlinePush(ctx, &c.config.WebhooksConfig.BeforeGroupOnlinePush, groupID, msg,
|
||||
&pushToUserIDs); err != nil {
|
||||
log.ZWarn(ctx, "Push2Group webhookBeforeGroupOnlinePush failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, "Push2Group after webhook", "groupID", groupID, "pushToUserIDsFromWebhook", pushToUserIDs, "count", len(pushToUserIDs))
|
||||
|
||||
err = c.groupMessagesHandler(ctx, groupID, &pushToUserIDs, msg)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, "Push2Group groupMessagesHandler failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, "Push2Group after groupMessagesHandler", "groupID", groupID, "pushToUserIDs", pushToUserIDs, "count", len(pushToUserIDs))
|
||||
|
||||
wsResults, err := c.GetConnsAndOnlinePush(ctx, msg, pushToUserIDs)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, "Push2Group GetConnsAndOnlinePush failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, "Push2Group online push completed", "groupID", groupID, "wsResultsCount", len(wsResults))
|
||||
|
||||
log.ZDebug(ctx, "group push result", "result", wsResults, "msg", msg)
|
||||
log.ZInfo(ctx, "online group push end")
|
||||
|
||||
if !c.shouldPushOffline(ctx, msg) {
|
||||
return nil
|
||||
}
|
||||
needOfflinePushUserIDs := c.onlinePusher.GetOnlinePushFailedUserIDs(ctx, msg, wsResults, &pushToUserIDs)
|
||||
//filter some user, like don not disturb or don't need offline push etc.
|
||||
needOfflinePushUserIDs, err = c.filterGroupMessageOfflinePush(ctx, groupID, msg, needOfflinePushUserIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.ZInfo(ctx, "filterGroupMessageOfflinePush end")
|
||||
|
||||
// Use offline push messaging
|
||||
if len(needOfflinePushUserIDs) > 0 {
|
||||
c.asyncOfflinePush(ctx, needOfflinePushUserIDs, msg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) asyncOfflinePush(ctx context.Context, needOfflinePushUserIDs []string, msg *sdkws.MsgData) {
|
||||
var offlinePushUserIDs []string
|
||||
err := c.webhookBeforeOfflinePush(ctx, &c.config.WebhooksConfig.BeforeOfflinePush, needOfflinePushUserIDs, msg, &offlinePushUserIDs)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, "webhookBeforeOfflinePush failed", err, "msg", msg)
|
||||
return
|
||||
}
|
||||
|
||||
if len(offlinePushUserIDs) > 0 {
|
||||
needOfflinePushUserIDs = offlinePushUserIDs
|
||||
}
|
||||
if err := c.pushDatabase.MsgToOfflinePushMQ(ctx, conversationutil.GenConversationUniqueKeyForSingle(msg.SendID, msg.RecvID), needOfflinePushUserIDs, msg); err != nil {
|
||||
log.ZDebug(ctx, "Msg To OfflinePush MQ error", err, "needOfflinePushUserIDs",
|
||||
needOfflinePushUserIDs, "msg", msg)
|
||||
log.ZWarn(ctx, "Msg To OfflinePush MQ error", err, "needOfflinePushUserIDs length",
|
||||
len(needOfflinePushUserIDs), "msg", msg)
|
||||
prommetrics.GroupChatMsgProcessFailedCounter.Inc()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) groupMessagesHandler(ctx context.Context, groupID string, pushToUserIDs *[]string, msg *sdkws.MsgData) (err error) {
|
||||
if len(*pushToUserIDs) == 0 {
|
||||
*pushToUserIDs, err = c.groupLocalCache.GetGroupMemberIDs(ctx, groupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch msg.ContentType {
|
||||
case constant.MemberQuitNotification:
|
||||
var tips sdkws.MemberQuitTips
|
||||
if unmarshalNotificationElem(msg.Content, &tips) != nil {
|
||||
return err
|
||||
}
|
||||
if err = c.DeleteMemberAndSetConversationSeq(ctx, groupID, []string{tips.QuitUser.UserID}); err != nil {
|
||||
log.ZError(ctx, "MemberQuitNotification DeleteMemberAndSetConversationSeq", err, "groupID", groupID, "userID", tips.QuitUser.UserID)
|
||||
}
|
||||
// 退出群聊通知只通知群主和管理员,不通知退出者本人
|
||||
case constant.MemberKickedNotification:
|
||||
var tips sdkws.MemberKickedTips
|
||||
if unmarshalNotificationElem(msg.Content, &tips) != nil {
|
||||
return err
|
||||
}
|
||||
kickedUsers := datautil.Slice(tips.KickedUserList, func(e *sdkws.GroupMemberFullInfo) string { return e.UserID })
|
||||
if err = c.DeleteMemberAndSetConversationSeq(ctx, groupID, kickedUsers); err != nil {
|
||||
log.ZError(ctx, "MemberKickedNotification DeleteMemberAndSetConversationSeq", err, "groupID", groupID, "userIDs", kickedUsers)
|
||||
}
|
||||
// 被踢出群聊通知只通知群主和管理员,不通知被踢出的用户本人
|
||||
case constant.GroupDismissedNotification:
|
||||
if msgprocessor.IsNotification(msgprocessor.GetConversationIDByMsg(msg)) {
|
||||
var tips sdkws.GroupDismissedTips
|
||||
if unmarshalNotificationElem(msg.Content, &tips) != nil {
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, "GroupDismissedNotificationInfo****", "groupID", groupID, "num", len(*pushToUserIDs), "list", pushToUserIDs)
|
||||
if len(c.config.Share.IMAdminUser.UserIDs) > 0 {
|
||||
ctx = mcontext.WithOpUserIDContext(ctx, c.config.Share.IMAdminUser.UserIDs[0])
|
||||
}
|
||||
defer func(groupID string) {
|
||||
if err := c.groupClient.DismissGroup(ctx, groupID, true); err != nil {
|
||||
log.ZError(ctx, "DismissGroup Notification clear members", err, "groupID", groupID)
|
||||
}
|
||||
}(groupID)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 过滤通知消息,只通知群主、管理员和相关成员本人
|
||||
switch msg.ContentType {
|
||||
case constant.GroupMemberMutedNotification, constant.GroupMemberCancelMutedNotification:
|
||||
// 禁言和取消禁言:通知群主、管理员和本人
|
||||
if err := c.filterNotificationWithUser(ctx, groupID, pushToUserIDs, msg, true); err != nil {
|
||||
return err
|
||||
}
|
||||
case constant.MemberQuitNotification, constant.MemberEnterNotification, constant.GroupMemberInfoSetNotification:
|
||||
// 退出、进入、成员信息设置:只通知群主和管理员
|
||||
if err := c.filterNotificationWithUser(ctx, groupID, pushToUserIDs, msg, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case constant.MemberKickedNotification:
|
||||
// 被踢出:通知群主、管理员和本人
|
||||
if err := c.filterNotificationWithUser(ctx, groupID, pushToUserIDs, msg, true); err != nil {
|
||||
return err
|
||||
}
|
||||
case constant.MemberInvitedNotification:
|
||||
// 被邀请:通知群主、管理员和被邀请的本人
|
||||
if err := c.filterNotificationWithUser(ctx, groupID, pushToUserIDs, msg, true); err != nil {
|
||||
return err
|
||||
}
|
||||
case constant.GroupMemberSetToAdminNotification, constant.GroupMemberSetToOrdinaryUserNotification:
|
||||
// 设置为管理员/普通用户:通知群主、管理员和本人
|
||||
if err := c.filterNotificationWithUser(ctx, groupID, pushToUserIDs, msg, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// filterNotificationWithUser 过滤通知消息,只通知群主、管理员,可选是否包含相关用户本人
|
||||
// includeUser: true 表示包含相关用户本人,false 表示排除相关用户
|
||||
func (c *ConsumerHandler) filterNotificationWithUser(ctx context.Context, groupID string, pushToUserIDs *[]string, msg *sdkws.MsgData, includeUser bool) error {
|
||||
notificationName := getNotificationName(msg.ContentType)
|
||||
log.ZInfo(ctx, notificationName+" push filter start", "groupID", groupID, "originalPushToUserIDs", *pushToUserIDs, "originalCount", len(*pushToUserIDs), "includeUser", includeUser)
|
||||
|
||||
// 解析通知内容,提取相关用户ID
|
||||
var relatedUserIDs []string
|
||||
var excludeUserIDs []string
|
||||
switch msg.ContentType {
|
||||
case constant.GroupMemberMutedNotification:
|
||||
var tips sdkws.GroupMemberMutedTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
if includeUser {
|
||||
relatedUserIDs = append(relatedUserIDs, tips.MutedUser.UserID)
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "mutedUserID", tips.MutedUser.UserID, "opUserID", tips.OpUser.UserID)
|
||||
case constant.GroupMemberCancelMutedNotification:
|
||||
var tips sdkws.GroupMemberCancelMutedTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
if includeUser {
|
||||
relatedUserIDs = append(relatedUserIDs, tips.MutedUser.UserID)
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "cancelMutedUserID", tips.MutedUser.UserID, "opUserID", tips.OpUser.UserID)
|
||||
case constant.MemberQuitNotification:
|
||||
var tips sdkws.MemberQuitTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
excludeUserIDs = append(excludeUserIDs, tips.QuitUser.UserID)
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "quitUserID", tips.QuitUser.UserID)
|
||||
case constant.MemberInvitedNotification:
|
||||
var tips sdkws.MemberInvitedTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
invitedUserIDs := datautil.Slice(tips.InvitedUserList, func(e *sdkws.GroupMemberFullInfo) string { return e.UserID })
|
||||
if includeUser {
|
||||
relatedUserIDs = append(relatedUserIDs, invitedUserIDs...)
|
||||
} else {
|
||||
excludeUserIDs = append(excludeUserIDs, invitedUserIDs...)
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "invitedUserIDs", invitedUserIDs, "opUserID", tips.OpUser.UserID)
|
||||
case constant.MemberEnterNotification:
|
||||
var tips sdkws.MemberEnterTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
excludeUserIDs = append(excludeUserIDs, tips.EntrantUser.UserID)
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "entrantUserID", tips.EntrantUser.UserID)
|
||||
case constant.MemberKickedNotification:
|
||||
var tips sdkws.MemberKickedTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
kickedUserIDs := datautil.Slice(tips.KickedUserList, func(e *sdkws.GroupMemberFullInfo) string { return e.UserID })
|
||||
if includeUser {
|
||||
relatedUserIDs = append(relatedUserIDs, kickedUserIDs...)
|
||||
} else {
|
||||
excludeUserIDs = append(excludeUserIDs, kickedUserIDs...)
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "kickedUserIDs", kickedUserIDs, "opUserID", tips.OpUser.UserID)
|
||||
case constant.GroupMemberInfoSetNotification, constant.GroupMemberSetToAdminNotification, constant.GroupMemberSetToOrdinaryUserNotification:
|
||||
var tips sdkws.GroupMemberInfoSetTips
|
||||
if err := unmarshalNotificationElem(msg.Content, &tips); err != nil {
|
||||
log.ZWarn(ctx, notificationName+" unmarshalNotificationElem failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
if includeUser {
|
||||
relatedUserIDs = append(relatedUserIDs, tips.ChangedUser.UserID)
|
||||
} else {
|
||||
excludeUserIDs = append(excludeUserIDs, tips.ChangedUser.UserID)
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" parsed tips", "changedUserID", tips.ChangedUser.UserID, "opUserID", tips.OpUser.UserID)
|
||||
default:
|
||||
log.ZWarn(ctx, notificationName+" unsupported notification type", nil, "contentType", msg.ContentType)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取所有群成员信息(如果还没有获取)
|
||||
allMemberIDs := *pushToUserIDs
|
||||
if len(allMemberIDs) == 0 {
|
||||
var err error
|
||||
allMemberIDs, err = c.groupLocalCache.GetGroupMemberIDs(ctx, groupID)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, notificationName+" GetGroupMemberIDs failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" fetched all member IDs", "groupID", groupID, "memberCount", len(allMemberIDs))
|
||||
}
|
||||
|
||||
members, err := c.groupLocalCache.GetGroupMembers(ctx, groupID, allMemberIDs)
|
||||
if err != nil {
|
||||
log.ZWarn(ctx, notificationName+" GetGroupMembers failed", err, "groupID", groupID)
|
||||
return err
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" got members", "groupID", groupID, "memberCount", len(members))
|
||||
|
||||
// 筛选群主和管理员
|
||||
var targetUserIDs []string
|
||||
var ownerUserIDs []string
|
||||
var adminUserIDs []string
|
||||
for _, member := range members {
|
||||
// 排除相关用户
|
||||
if len(excludeUserIDs) > 0 && datautil.Contain(member.UserID, excludeUserIDs...) {
|
||||
continue
|
||||
}
|
||||
if member.RoleLevel == constant.GroupOwner {
|
||||
targetUserIDs = append(targetUserIDs, member.UserID)
|
||||
ownerUserIDs = append(ownerUserIDs, member.UserID)
|
||||
} else if member.RoleLevel == constant.GroupAdmin {
|
||||
targetUserIDs = append(targetUserIDs, member.UserID)
|
||||
adminUserIDs = append(adminUserIDs, member.UserID)
|
||||
}
|
||||
}
|
||||
log.ZDebug(ctx, notificationName+" filtered owners and admins", "ownerCount", len(ownerUserIDs), "ownerIDs", ownerUserIDs, "adminCount", len(adminUserIDs), "adminIDs", adminUserIDs)
|
||||
|
||||
// 添加相关用户本人(如果需要)
|
||||
if includeUser && len(relatedUserIDs) > 0 {
|
||||
targetUserIDs = append(targetUserIDs, relatedUserIDs...)
|
||||
log.ZDebug(ctx, notificationName+" added related users", "relatedUserIDs", relatedUserIDs, "targetCountBeforeDistinct", len(targetUserIDs))
|
||||
}
|
||||
|
||||
// 去重并更新推送列表
|
||||
*pushToUserIDs = datautil.Distinct(targetUserIDs)
|
||||
log.ZInfo(ctx, notificationName+" push filter completed", "groupID", groupID, "finalPushToUserIDs", *pushToUserIDs, "finalCount", len(*pushToUserIDs), "filteredFrom", len(allMemberIDs))
|
||||
return nil
|
||||
}
|
||||
|
||||
// getNotificationName 根据通知类型获取通知名称
|
||||
func getNotificationName(contentType int32) string {
|
||||
switch contentType {
|
||||
case constant.GroupMemberMutedNotification:
|
||||
return "GroupMemberMutedNotification"
|
||||
case constant.GroupMemberCancelMutedNotification:
|
||||
return "GroupMemberCancelMutedNotification"
|
||||
case constant.MemberQuitNotification:
|
||||
return "MemberQuitNotification"
|
||||
case constant.MemberInvitedNotification:
|
||||
return "MemberInvitedNotification"
|
||||
case constant.MemberEnterNotification:
|
||||
return "MemberEnterNotification"
|
||||
case constant.MemberKickedNotification:
|
||||
return "MemberKickedNotification"
|
||||
case constant.GroupMemberInfoSetNotification:
|
||||
return "GroupMemberInfoSetNotification"
|
||||
case constant.GroupMemberSetToAdminNotification:
|
||||
return "GroupMemberSetToAdminNotification"
|
||||
case constant.GroupMemberSetToOrdinaryUserNotification:
|
||||
return "GroupMemberSetToOrdinaryUserNotification"
|
||||
default:
|
||||
return "UnknownNotification"
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) offlinePushMsg(ctx context.Context, msg *sdkws.MsgData, offlinePushUserIDs []string) error {
|
||||
title, content, opts, err := c.getOfflinePushInfos(msg)
|
||||
if err != nil {
|
||||
log.ZError(ctx, "getOfflinePushInfos failed", err, "msg", msg)
|
||||
return err
|
||||
}
|
||||
err = c.offlinePusher.Push(ctx, offlinePushUserIDs, title, content, opts)
|
||||
if err != nil {
|
||||
prommetrics.MsgOfflinePushFailedCounter.Inc()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) filterGroupMessageOfflinePush(ctx context.Context, groupID string, msg *sdkws.MsgData,
|
||||
offlinePushUserIDs []string) (userIDs []string, err error) {
|
||||
needOfflinePushUserIDs, err := c.conversationClient.GetConversationOfflinePushUserIDs(ctx, conversationutil.GenGroupConversationID(groupID), offlinePushUserIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return needOfflinePushUserIDs, nil
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) getOfflinePushInfos(msg *sdkws.MsgData) (title, content string, opts *options.Opts, err error) {
|
||||
type AtTextElem struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
AtUserList []string `json:"atUserList,omitempty"`
|
||||
IsAtSelf bool `json:"isAtSelf"`
|
||||
}
|
||||
|
||||
opts = &options.Opts{Signal: &options.Signal{ClientMsgID: msg.ClientMsgID}}
|
||||
if msg.OfflinePushInfo != nil {
|
||||
opts.IOSBadgeCount = msg.OfflinePushInfo.IOSBadgeCount
|
||||
opts.IOSPushSound = msg.OfflinePushInfo.IOSPushSound
|
||||
opts.Ex = msg.OfflinePushInfo.Ex
|
||||
}
|
||||
|
||||
if msg.OfflinePushInfo != nil {
|
||||
title = msg.OfflinePushInfo.Title
|
||||
content = msg.OfflinePushInfo.Desc
|
||||
}
|
||||
if title == "" {
|
||||
switch msg.ContentType {
|
||||
case constant.Text:
|
||||
fallthrough
|
||||
case constant.Picture:
|
||||
fallthrough
|
||||
case constant.Voice:
|
||||
fallthrough
|
||||
case constant.Video:
|
||||
fallthrough
|
||||
case constant.File:
|
||||
title = constant.ContentType2PushContent[int64(msg.ContentType)]
|
||||
case constant.AtText:
|
||||
ac := AtTextElem{}
|
||||
_ = jsonutil.JsonStringToStruct(string(msg.Content), &ac)
|
||||
case constant.SignalingNotification:
|
||||
title = constant.ContentType2PushContent[constant.SignalMsg]
|
||||
default:
|
||||
title = constant.ContentType2PushContent[constant.Common]
|
||||
}
|
||||
}
|
||||
if content == "" {
|
||||
content = title
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *ConsumerHandler) DeleteMemberAndSetConversationSeq(ctx context.Context, groupID string, userIDs []string) error {
|
||||
conversationID := msgprocessor.GetConversationIDBySessionType(constant.ReadGroupChatType, groupID)
|
||||
maxSeq, err := c.msgClient.GetConversationMaxSeq(ctx, conversationID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.conversationClient.SetConversationMaxSeq(ctx, conversationID, userIDs, maxSeq)
|
||||
}
|
||||
|
||||
func unmarshalNotificationElem(bytes []byte, t any) error {
|
||||
var notification sdkws.NotificationElem
|
||||
if err := json.Unmarshal(bytes, ¬ification); err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal([]byte(notification.Detail), t)
|
||||
}
|
||||
Reference in New Issue
Block a user