90 lines
2.6 KiB
Go
90 lines
2.6 KiB
Go
package notify
|
|
|
|
import (
|
|
"encoding/json"
|
|
"nCovTrack-Backend/global"
|
|
"nCovTrack-Backend/models"
|
|
"nCovTrack-Backend/utils"
|
|
)
|
|
|
|
type NotifyFunc func([]string, models.BackNotification)
|
|
|
|
const (
|
|
NOTIFY_KEY = "notification_"
|
|
NOTIFY_DEL_VALUE = "notify_del"
|
|
)
|
|
|
|
var (
|
|
NOTIFY_CHANNEL_FUNC_ARR = []NotifyFunc{notifyNotification, emailNotification}
|
|
)
|
|
|
|
//emailNotification send email
|
|
func emailNotification(regions []string, notification models.BackNotification) {
|
|
queryMap := []map[string]interface{}{{"region": regions, "role": global.ROLE_ID_MAP["ADMIN"]}}
|
|
observations := models.ListField[models.BackUser](queryMap, false, "email")
|
|
var emails []string
|
|
for _, observation := range *observations {
|
|
emails = append(emails, observation["email"].(string))
|
|
}
|
|
utils.SendEmail(notification.Kind+"通知邮件", notification.Content, emails...)
|
|
}
|
|
|
|
//notifyNotification add to notify system
|
|
func notifyNotification(regions []string, notification models.BackNotification) {
|
|
valueByte, _ := json.Marshal(notification)
|
|
pipe := global.Redis.TxPipeline()
|
|
for _, region := range regions {
|
|
pipe.RPush(NOTIFY_KEY+region, valueByte)
|
|
}
|
|
pipe.Exec()
|
|
}
|
|
|
|
//DeleteNotification delete notify by id
|
|
func DeleteNotification(region string, index int) {
|
|
key := NOTIFY_KEY + region
|
|
pipe := global.Redis.TxPipeline()
|
|
pipe.LSet(key, int64(index), NOTIFY_DEL_VALUE)
|
|
pipe.LRem(key, 2, NOTIFY_DEL_VALUE)
|
|
pipe.Exec()
|
|
}
|
|
|
|
//CleanNotification delete all notify
|
|
func CleanNotification(region string) {
|
|
key := NOTIFY_KEY + region
|
|
global.Redis.Del(key)
|
|
}
|
|
|
|
//QueryNotificationLen query the count notification
|
|
func QueryNotificationLen(region string) int {
|
|
key := NOTIFY_KEY + region
|
|
return int(global.Redis.LLen(key).Val())
|
|
}
|
|
|
|
//ListNotifycation list the notifications ny range
|
|
func ListNotifycation(region string, start, end int) []models.BackNotification {
|
|
key := NOTIFY_KEY + region
|
|
var notifications []models.BackNotification
|
|
notificationStrArr := global.Redis.LRange(key, int64(start), int64(end)).Val()
|
|
for _, notificationStr := range notificationStrArr {
|
|
var notification models.BackNotification
|
|
json.Unmarshal([]byte(notificationStr), ¬ification)
|
|
notifications = append(notifications, notification)
|
|
}
|
|
return notifications
|
|
}
|
|
|
|
//SendNotify send notify to kafka
|
|
func SendNotify(send models.SendInfo) {
|
|
sendInfo, _ := json.Marshal(send)
|
|
global.KafkaProducerChan <- sendInfo
|
|
}
|
|
|
|
//HandleKafkaNotify handle kafka info
|
|
func HandleKafkaNotify(sendInfoByte []byte) {
|
|
var sendInfo models.SendInfo
|
|
json.Unmarshal(sendInfoByte, &sendInfo)
|
|
for _, channel := range sendInfo.Channel {
|
|
NOTIFY_CHANNEL_FUNC_ARR[channel](sendInfo.Region, sendInfo.Notification)
|
|
}
|
|
}
|