Просмотр исходного кода

use SubscribePush IDs for all subscription dispatch

DESKTOP-HN5QP3V\Administrator 1 месяц назад
Родитель
Сommit
20515ac6f9

+ 7 - 13
app/service/subscribe.go

@@ -111,14 +111,14 @@ func (this *SubscribeCheckService) Check() ([]int, error) {
 }
 
 type SubscribeSendService struct {
-	Module string   `json:"module"`
+	Module int      `json:"module"`
 	Data   []string `json:"data"`
 }
 
 func (this *SubscribeSendService) Send() error {
 	row, ok := sender.SubscribePushConfig(this.Module)
 	if !ok {
-		return errors.New("unknown module")
+		return errors.New("unknown SubscribePush ID")
 	}
 	if !sender.SubscribePushActive(this.Module) {
 		return nil
@@ -128,7 +128,7 @@ func (this *SubscribeSendService) Send() error {
 	// data 应该是个json对象
 	filter := bson.M{"settings": row.ID, "open_id": bson.M{"$exists": true, "$ne": ""}}
 
-	if this.Module != "alliance" {
+	if len(this.Data) > 0 {
 		filter["device_id"] = bson.M{"$in": this.Data}
 	}
 
@@ -151,22 +151,16 @@ func (this *SubscribeSendService) Send() error {
 
 type SubscribeTaskService struct {
 	DeviceId  string `json:"device_id"`
-	Module    string `json:"module"`
+	Module    int    `json:"module"`
 	Timestamp int64  `json:"timestamp"`
 	Status    bool   `json:"status"`
 }
 
 func (this *SubscribeTaskService) Task() error {
-	var key string
-
-	switch this.Module {
-	case "hangup":
-		key = fmt.Sprintf("%s_hangup", this.DeviceId)
-	case "autofight":
-		key = fmt.Sprintf("%s_autofight", this.DeviceId)
-	default:
-		return errors.New("unknown module")
+	if this.DeviceId == "" || !sender.SubscribePushConfigByID(this.Module) {
+		return errors.New("device_id is empty or unknown SubscribePush ID")
 	}
+	key := fmt.Sprintf("%s_%d", this.DeviceId, this.Module)
 
 	if this.Status {
 		if !sender.SubscribePushActive(this.Module) {

+ 2 - 2
app/service/subscribe_test.go

@@ -64,11 +64,11 @@ func TestDisabledPushIsNotQueued(t *testing.T) {
 	}); err != nil {
 		t.Fatal(err)
 	}
-	request := SubscribeTaskService{DeviceId: "device", Module: "hangup", Timestamp: 123, Status: true}
+	request := SubscribeTaskService{DeviceId: "device", Module: 101, Timestamp: 123, Status: true}
 	if err := request.Task(); err != nil {
 		t.Fatal(err)
 	}
-	if err := (&SubscribeSendService{Module: "hangup"}).Send(); err != nil {
+	if err := (&SubscribeSendService{Module: 101}).Send(); err != nil {
 		t.Fatal(err)
 	}
 }

+ 5 - 5
app/task/subscribe.go

@@ -13,8 +13,8 @@ var SubscribeTask *Subscribe
 type PushItem struct {
 	Key       string // 玩家设备id
 	DeviceId  string
-	Module    string // 推送类型
-	Timestamp int64  // 时间戳
+	Module    int   // SubscribePush 配置 ID
+	Timestamp int64 // 时间戳
 }
 
 type Subscribe struct {
@@ -47,7 +47,7 @@ func (this *Subscribe) Exec() {
 	this.Unlock()
 
 	for _, item := range needPush {
-		logger.Info("Subscribe exec neePush module %s, device id %s", item.Module, item.DeviceId)
+		logger.Info("Subscribe exec neePush module %d, device id %s", item.Module, item.DeviceId)
 		this.sender.Send(&sender.SubscribeSend{
 			DeviceId: item.DeviceId,
 			Module:   item.Module,
@@ -55,7 +55,7 @@ func (this *Subscribe) Exec() {
 	}
 }
 
-func (this *Subscribe) Append(key string, deviceId string, timestamp int64, module string) {
+func (this *Subscribe) Append(key string, deviceId string, timestamp int64, module int) {
 	this.Lock()
 	defer this.Unlock()
 
@@ -70,7 +70,7 @@ func (this *Subscribe) Remove(key string) {
 	delete(this.waiting, key)
 }
 
-func (this *Subscribe) Send(openIds []string, module string) {
+func (this *Subscribe) Send(openIds []string, module int) {
 	this.sender.Send(&sender.SubscribeSend{
 		OpenIds: openIds,
 		Module:  module,

+ 2 - 2
main-subscribe/README.md

@@ -5,6 +5,6 @@
 - `GM_SUBSCRIBE_PUSH_URL`:GM 内网接口的完整 URL,例如 `http://<gm-host>:<port>/internal/subscribe_push/config`。
 - `GM_INTERNAL_SECRET`:与 GM `config.admin` 相同的内部签名密钥。
 
-进程启动时向 GM 发起一次签名 POST,读取以配置 ID 为键的 SubscribePush 表对象(例如 `{"101":{"id":101,...}}`);当前实现要求包含 101–105,读取或校验失败则启动失败。运行期间不再轮询 GM。微信模板 ID 仍按 `CHANNEL` 从 `config/subscribe_template.yaml` 选择,但所有场景使用同一个 `general` 模板。部署时需先上线 GM 接口,再重启订阅进程。
+进程启动时向 GM 发起一次签名 POST,读取以配置 ID 为键的 SubscribePush 表对象(例如 `{"101":{"id":101,...}}`);读取或校验失败则启动失败。运行期间不再轮询 GM。微信模板 ID 仍按 `CHANNEL` 从 `config/subscribe_template.yaml` 选择,但所有场景使用同一个 `general` 模板。部署时需先上线 GM 接口,再重启订阅进程。
 
-玩家订阅记录使用 `settings: [101, 103, ...]` 保存已开启的配置 ID。`/subscribe/v1/open` 和 `/subscribe/v1/close` 的 `module` 均为配置 ID 数组(例如 `[101,102]`),一次请求批量加入或移除;开启请求还需 `device_id`、`open_id`,关闭请求需 `device_id`。`/check` 返回数组。发送和任务接口的 `module` 仍使用原英文模块名。服务端推送和排队只使用配置的 `is_open`、`title1`、`desc`;`is_set`、`set_initialize` 等设置字段由客户端处理。此结构不读取旧版 `modules` 字段,部署前需按运营计划重置旧订阅表。进程启动时会创建 `device_id` 唯一索引。
+玩家订阅记录使用 `settings: [101, 103, ...]` 保存已开启的配置 ID。`/subscribe/v1/open` 和 `/subscribe/v1/close` 的 `module` 均为配置 ID 数组(例如 `[101,102]`),一次请求批量加入或移除;开启请求还需 `device_id`、`open_id`,关闭请求需 `device_id`。`/check` 返回数组。`/send` 和 `/task` 的 `module` 则是单个数字配置 ID(例如 `101`)。`/send` 的 `data` 是设备 ID 数组,为空时发送给全部开启该项的设备。服务端推送和排队只使用配置的 `is_open`、`title1`、`desc`;`is_set`、`set_initialize` 等设置字段由客户端处理。此结构不读取旧版 `modules` 字段,部署前需按运营计划重置旧订阅表。进程启动时会创建 `device_id` 唯一索引。

+ 22 - 65
pkg/sender/subscribe.go

@@ -24,7 +24,7 @@ var (
 type SubscribeSend struct {
 	DeviceId string
 	OpenIds  []string
-	Module   string
+	Module   int
 }
 
 type SubscribeSender struct {
@@ -57,7 +57,7 @@ func (this *SubscribeSender) Start() {
 
 func (this *SubscribeSender) worker(id int) {
 	for task := range this.queue {
-		logger.Info("Subscribe worker(%d) do safe send module %s, openid_len %d device id %s", id, task.Module, len(task.OpenIds), task.DeviceId)
+		logger.Info("Subscribe worker(%d) do safe send module %d, openid_len %d device id %s", id, task.Module, len(task.OpenIds), task.DeviceId)
 		this.safeSend(task)
 	}
 }
@@ -66,79 +66,36 @@ func (this *SubscribeSender) safeSend(send *SubscribeSend) {
 	defer func() {
 		if r := recover(); r != nil {
 			log.Printf("send subscribe panic: %v", r)
-			logger.Info("[订阅推送] 发送订阅消息异常, module=%s, device_id=%s, err=%v", send.Module, send.DeviceId, r)
+			logger.Info("[订阅推送] 发送订阅消息异常, module=%d, device_id=%s, err=%v", send.Module, send.DeviceId, r)
 		}
 	}()
 
-	switch send.Module {
-	case "hangup":
-		this.SendHangupSubscribe(send.DeviceId)
-	case "autofight":
-		this.SendAutoFightSubscribe(send.DeviceId)
-	case "guildgame":
-		this.SendGuildGameSubscribe(send.OpenIds)
-	case "alliance":
-		this.SendAllianceSubscribe(send.OpenIds)
-	case "warheavens":
-		this.SendWarHeavensSubscribe(send.OpenIds)
-	default:
-		logger.Info("[push] unknown type=%s, openId=%s",
-			send.Module, send.DeviceId)
-	}
-}
-
-func (this *SubscribeSender) SendHangupSubscribe(deviceId string) {
-	row, ok := SubscribePushConfig("hangup")
-	if !ok || !SubscribePushActive("hangup") {
-		return
-	}
-	subscribeOne := new(subscribe.Subscribe)
-	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": deviceId, "open_id": bson.M{"$exists": true, "$ne": ""}, "settings": row.ID}, subscribeOne)
-	if err != nil {
-		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "hangup", deviceId, err)
-		return
-	}
-
-	this.sendWechatSubscribe(subscribeOne.OpenId, "hangup")
-}
-
-func (this *SubscribeSender) SendAutoFightSubscribe(deviceId string) {
-	row, ok := SubscribePushConfig("autofight")
-	if !ok || !SubscribePushActive("autofight") {
-		return
-	}
-	subscribeOne := new(subscribe.Subscribe)
-	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": deviceId, "open_id": bson.M{"$exists": true, "$ne": ""}, "settings": row.ID}, subscribeOne)
-	if err != nil {
-		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "autofight", deviceId, err)
+	row, ok := SubscribePushConfig(send.Module)
+	if !ok || !SubscribePushActive(send.Module) {
+		logger.Info("[订阅推送] 模块未启用或配置缺失, module=%d", send.Module)
 		return
 	}
-
-	this.sendWechatSubscribe(subscribeOne.OpenId, "autofight")
-}
-
-func (this *SubscribeSender) SendGuildGameSubscribe(openIds []string) {
-	for _, openId := range openIds {
-		this.sendWechatSubscribe(openId, "guildgame")
-	}
-}
-
-func (this *SubscribeSender) SendAllianceSubscribe(openIds []string) {
-	for _, openId := range openIds {
-		this.sendWechatSubscribe(openId, "alliance")
+	openIDs := send.OpenIds
+	if send.DeviceId != "" {
+		subscribeOne := new(subscribe.Subscribe)
+		filter := bson.M{"device_id": send.DeviceId, "open_id": bson.M{"$exists": true, "$ne": ""}, "settings": row.ID}
+		if err := mgm.Coll(&subscribe.Subscribe{}).First(filter, subscribeOne); err != nil {
+			logger.Info("[订阅推送] 查询订阅记录失败, module=%d, device_id=%s, err=%v", send.Module, send.DeviceId, err)
+			return
+		}
+		openIDs = []string{subscribeOne.OpenId}
 	}
-}
-
-func (this *SubscribeSender) SendWarHeavensSubscribe(openIds []string) {
-	for _, openId := range openIds {
-		this.sendWechatSubscribe(openId, "warheavens")
+	for _, openID := range openIDs {
+		if openID != "" {
+			this.sendWechatSubscribe(openID, send.Module)
+		}
 	}
 }
 
-func (this *SubscribeSender) sendWechatSubscribe(openId string, module string) {
+func (this *SubscribeSender) sendWechatSubscribe(openId string, module int) {
 	configured, ok := subscribePushMessage(module)
 	if !ok {
-		logger.Info("[订阅推送] 模块未启用或配置缺失, module=%s", module)
+		logger.Info("[订阅推送] 模块未启用或配置缺失, module=%d", module)
 		return
 	}
 	msg := map[string]map[string]string{
@@ -147,7 +104,7 @@ func (this *SubscribeSender) sendWechatSubscribe(openId string, module string) {
 	}
 	templateID := subscribeTemplateID()
 	if templateID == "" {
-		logger.Info("[push] subscribe template id not configured, channel=%s, module=%s", os.Getenv("CHANNEL"), module)
+		logger.Info("[push] subscribe template id not configured, channel=%s, module=%d", os.Getenv("CHANNEL"), module)
 		return
 	}
 

+ 7 - 24
pkg/sender/subscribe_push_config.go

@@ -19,14 +19,6 @@ type subscribeMessage struct {
 	Description string
 }
 
-var moduleConfigID = map[string]int{
-	"hangup":     101,
-	"autofight":  102,
-	"guildgame":  103,
-	"alliance":   104,
-	"warheavens": 105,
-}
-
 var subscribePushRows atomic.Value // map[int]SubscribePushRow
 
 // ConfigureSubscribePush installs the one-time startup snapshot fetched from GM.
@@ -44,33 +36,24 @@ func ConfigureSubscribePush(rows []SubscribePushRow) error {
 		}
 		byID[row.ID] = row
 	}
-	for module, id := range moduleConfigID {
-		if _, ok := byID[id]; !ok {
-			return fmt.Errorf("SubscribePush row %d for %s is missing", id, module)
-		}
-	}
 	subscribePushRows.Store(byID)
 	return nil
 }
 
-func subscribePushMessage(module string) (subscribeMessage, bool) {
-	row, ok := SubscribePushConfig(module)
-	if !ok || !SubscribePushActive(module) {
+func subscribePushMessage(id int) (subscribeMessage, bool) {
+	row, ok := SubscribePushConfig(id)
+	if !ok || !SubscribePushActive(id) {
 		return subscribeMessage{}, false
 	}
 	return subscribeMessage{Title: row.Title1, Description: row.Desc}, true
 }
 
-func SubscribePushActive(module string) bool {
-	row, ok := SubscribePushConfig(module)
+func SubscribePushActive(id int) bool {
+	row, ok := SubscribePushConfig(id)
 	return ok && row.IsOpen != 0 && strings.TrimSpace(row.Title1) != "" && strings.TrimSpace(row.Desc) != ""
 }
 
-func SubscribePushConfig(module string) (SubscribePushRow, bool) {
-	id, ok := moduleConfigID[module]
-	if !ok {
-		return SubscribePushRow{}, false
-	}
+func SubscribePushConfig(id int) (SubscribePushRow, bool) {
 	value := subscribePushRows.Load()
 	if value == nil {
 		return SubscribePushRow{}, false
@@ -85,6 +68,6 @@ func SubscribePushConfigByID(id int) bool {
 	if value == nil {
 		return false
 	}
-	_, ok := value.(map[int]SubscribePushRow)[id]
+	_, ok := SubscribePushConfig(id)
 	return ok
 }

+ 10 - 4
pkg/sender/subscribe_push_config_test.go

@@ -22,16 +22,22 @@ func TestConfigureSubscribePushUsesGMTextAndOpenSwitch(t *testing.T) {
 	if err := ConfigureSubscribePush(rows); err != nil {
 		t.Fatal(err)
 	}
-	got, ok := subscribePushMessage("hangup")
+	got, ok := subscribePushMessage(101)
 	if !ok || got.Title != "挂机标题" || got.Description != "挂机内容" {
 		t.Fatalf("hangup message = %+v, enabled = %v", got, ok)
 	}
-	if _, ok := subscribePushMessage("autofight"); ok {
+	if _, ok := subscribePushMessage(102); ok {
 		t.Fatal("disabled config must suppress push")
 	}
-	if _, ok := subscribePushMessage("unknown"); ok {
+	if _, ok := subscribePushMessage(999); ok {
 		t.Fatal("unknown module must not be sent")
 	}
+	if err := ConfigureSubscribePush([]SubscribePushRow{{ID: 112, Title1: "新通知", Desc: "新内容", IsOpen: 1}}); err != nil {
+		t.Fatal("config IDs must not require a hard-coded module list:", err)
+	}
+	if got, ok := subscribePushMessage(112); !ok || got.Title != "新通知" {
+		t.Fatalf("config ID 112 message = %+v, enabled = %v", got, ok)
+	}
 }
 
 func TestLoadSubscribePushFromGM(t *testing.T) {
@@ -69,7 +75,7 @@ func TestLoadSubscribePushFromGM(t *testing.T) {
 	if err := LoadSubscribePushFromGM(context.Background(), server.URL+"/internal/subscribe_push/config", secret); err != nil {
 		t.Fatal(err)
 	}
-	got, ok := subscribePushMessage("hangup")
+	got, ok := subscribePushMessage(101)
 	if !ok || got.Title != "配置标题" || got.Description != "配置文案" {
 		t.Fatalf("loaded message = %+v, enabled = %v", got, ok)
 	}