go_dreamfactory/modules/timer/chat.go
2022-12-19 16:25:22 +08:00

104 lines
2.8 KiB
Go

package timer
import (
"context"
"fmt"
"go_dreamfactory/comm"
"go_dreamfactory/modules"
"go_dreamfactory/pb"
"go_dreamfactory/sys/configure"
cfg "go_dreamfactory/sys/configure/structs"
"go_dreamfactory/lego/core"
"go_dreamfactory/lego/sys/cron"
"go_dreamfactory/lego/sys/log"
"google.golang.org/protobuf/types/known/anypb"
)
var (
game_chatsystem = "game_chatsystem.json"
)
/*
聊天系统 推送系统公告
*/
type ChatComp struct {
modules.MCompConfigure
service core.IService
module *Timer
takes []cron.EntryID
}
//组件初始化接口
func (this *ChatComp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
this.MCompConfigure.Init(service, module, comp, options)
this.service = service
this.module = module.(*Timer)
this.takes = make([]cron.EntryID, 0)
return
}
func (this *ChatComp) Start() (err error) {
err = this.MCompConfigure.Start()
configure.RegisterConfigure(game_chatsystem, cfg.NewGameChatSystem, func() {
for _, v := range this.takes { //移除前面的定时任务
cron.Remove(v)
}
if v, err := this.GetConfigure(game_chatsystem); err != nil {
this.module.Errorf("err:%v", err)
return
} else {
var id cron.EntryID
this.takes = make([]cron.EntryID, 0)
confs := v.(*cfg.GameChatSystem)
for _, v1 := range confs.GetDataMap() {
if v1.Type == int32(comm.ChatSystem1) { //处理定时任务
weekStr := ""
for _, w := range v1.Week {
weekStr += fmt.Sprintf("%d,", w)
}
if len(v1.Week) > 0 && len(v1.Week) < 7 {
weekStr = weekStr[0 : len(weekStr)-1]
} else {
weekStr = "*"
}
cronStr := fmt.Sprintf("0 %d %d ? * %s", v1.TimeM, v1.TimeH, weekStr)
this.module.Debug("注册Chat广播公告消息", log.Field{Key: "cronStr", Value: cronStr}, log.Field{Key: "text", Value: v1.Text})
if id, err = cron.AddFunc(cronStr, this.chatNoticen(v1)); err != nil {
this.module.Errorf("cron.AddFunc:%s err:%v", cronStr, err)
continue
}
this.takes = append(this.takes, id)
}
}
}
})
return
}
func (this *ChatComp) chatNoticen(sys *cfg.GameChatSystemData) func() {
return func() {
msg := &pb.DBChat{
Channel: pb.ChatChannel_System,
Stag: this.service.GetTag(),
Ctime: configure.Now().Unix(),
Content: "",
Display: sys.Display,
AppendInt: int64(sys.Key),
}
data, _ := anypb.New(&pb.ChatMessagePush{Chat: msg})
this.module.Debug("广播公告消息", log.Field{Key: "chat", Value: sys.Text})
if err := this.module.service.RpcBroadcast(context.Background(), comm.Service_Gateway, string(comm.Rpc_GatewaySendRadioMsg), pb.UserMessage{
MainType: string(comm.ModuleChat),
SubType: "message",
Data: data,
}, nil); err != nil {
this.module.Errorf("err:%v", err)
}
}
}