service/library/middleware/notif_sender.go

100 lines
2.6 KiB
Go

package middleware
import (
"fmt"
"service/apollostruct"
"service/app/mix/service"
"service/app/mix/service/logic"
"service/dbstruct"
"service/library/apollo"
"service/library/logger"
"service/api/consts"
notificationproto "service/api/proto/notification/proto"
goproto "google.golang.org/protobuf/proto"
"github.com/gin-gonic/gin"
)
var (
DefaultNotifSender gin.HandlerFunc
)
func InitNotifSender(_DefaultNotification *logic.Notification, _DefaultNotifBcstCenter service.NotifBcstCenter) {
DefaultNotifSender = func(ctx *gin.Context) {
// 获取通知builder
notifBuildersObj, ok := ctx.Get("notif_builders")
if !ok {
ctx.Next()
}
notifBuilders := notifBuildersObj.([]*dbstruct.NotifBuilder)
for _, notifBuilder := range notifBuilders {
notification := &dbstruct.Notification{}
notification.SubMid = goproto.Int64(0)
// 从模板Id拿到模板信息
key := fmt.Sprint(notifBuilder.TemplateId)
cfg := apollostruct.NotifTemplateCfg{}
err := apollo.GetJson(key, &cfg, apollo.ApolloOpts().SetNamespace("notif_template"))
if err != nil {
logger.Error("Apollo read failed : %v", err)
continue
}
// 通知接收人mids不为空则默认认为是自定义发送
if len(notifBuilder.ObjMids) > 0 {
notification.ObjType = goproto.Int64(consts.Notification_ObjType_Customized)
} else {
notification.ObjType = goproto.Int64(notifBuilder.ObjType)
}
// 消息类型
notification.NType = goproto.Int64(cfg.NType)
notification.NDesc = goproto.String(consts.NotifDescMap[cfg.NType])
// 拼装通知信息
msg := fmt.Sprintf(cfg.NotifTemplate, notifBuilder.TemplateParams...)
notification.Message = goproto.String(msg)
// 链接信息
if cfg.Action != "" {
linkText := fmt.Sprintf(cfg.LinkTextTemplate, notifBuilder.LinkTextTemplateParams...)
notification.LinkText = goproto.String(linkText)
notification.Action = goproto.String(cfg.Action)
notification.Params = goproto.String(notifBuilder.Params)
}
// 推送时间
notification.PushTime = goproto.Int64(notifBuilder.PushTime)
// 创建通知
err = _DefaultNotification.OpCreate(ctx, &notificationproto.OpCreateReq{
Notification: notification,
})
if err != nil {
logger.Error("通知创建失败:%v", err)
ctx.Next()
}
nids := make([]int64, 0)
nids = append(nids, notification.GetId())
// 广播通知
err = _DefaultNotifBcstCenter.BcstNotifs(ctx, nids, notification.GetObjType(), notification.ObjMids)
if err != nil {
logger.Error("通知广播失败:%v", err)
continue
}
}
ctx.Next()
}
}
func NotifSender() gin.HandlerFunc {
return DefaultNotifSender
}