Pārlūkot izejas kodu

refactor subscribe push settings to config ID arrays

DESKTOP-HN5QP3V\Administrator 1 mēnesi atpakaļ
vecāks
revīzija
77e84b57f2

+ 2 - 2
app/api/v1/subscribe.go

@@ -40,10 +40,10 @@ func Check(c *gin.Context) {
 	var appG = app.Gin{C: c}
 	var appG = app.Gin{C: c}
 	service := service.SubscribeCheckService{}
 	service := service.SubscribeCheckService{}
 	if err := c.ShouldBind(&service); err == nil {
 	if err := c.ShouldBind(&service); err == nil {
-		if err := service.Check(); err != nil {
+		if settings, err := service.Check(); err != nil {
 			appG.Response(http.StatusOK, e.INVALID_PARAMS, err.Error())
 			appG.Response(http.StatusOK, e.INVALID_PARAMS, err.Error())
 		} else {
 		} else {
-			appG.Response(http.StatusOK, e.SUCCESS, nil)
+			appG.Response(http.StatusOK, e.SUCCESS, settings)
 		}
 		}
 	} else {
 	} else {
 		appG.Response(http.StatusOK, e.INVALID_PARAMS, err.Error())
 		appG.Response(http.StatusOK, e.INVALID_PARAMS, err.Error())

+ 78 - 72
app/service/subscribe.go

@@ -5,6 +5,7 @@ import (
 	"dsbqj-admin/app/task"
 	"dsbqj-admin/app/task"
 	"dsbqj-admin/model/mongo/subscribe"
 	"dsbqj-admin/model/mongo/subscribe"
 	"dsbqj-admin/pkg/logger"
 	"dsbqj-admin/pkg/logger"
+	"dsbqj-admin/pkg/sender"
 	"dsbqj-admin/pkg/util"
 	"dsbqj-admin/pkg/util"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
@@ -12,104 +13,101 @@ import (
 	"go.mongodb.org/mongo-driver/bson"
 	"go.mongodb.org/mongo-driver/bson"
 	"go.mongodb.org/mongo-driver/mongo"
 	"go.mongodb.org/mongo-driver/mongo"
 	"go.mongodb.org/mongo-driver/mongo/options"
 	"go.mongodb.org/mongo-driver/mongo/options"
+	"time"
 )
 )
 
 
 type SubscribeOpenService struct {
 type SubscribeOpenService struct {
 	DeviceId string `json:"device_id"`
 	DeviceId string `json:"device_id"`
 	OpenId   string `json:"open_id"`
 	OpenId   string `json:"open_id"`
-	Module   string `json:"module"`
+	Module   []int  `json:"module"`
 }
 }
 
 
-func (s *SubscribeOpenService) createSubscribe(deviceId, openId, module string) error {
-	sub := &subscribe.Subscribe{
-		OpenId:   openId,
-		DeviceId: deviceId,
-		Modules:  make(map[string]*subscribe.ModuleSubscribe),
+func updateSubscribeSetting(deviceId, openId string, modules []int, enabled bool) error {
+	if deviceId == "" || (enabled && openId == "") {
+		return errors.New("device_id or open_id is empty")
 	}
 	}
-
-	sub.Modules[module] = &subscribe.ModuleSubscribe{
-		Enabled: true,
-		OpenAt:  util.GetNowSecond(),
+	ids, err := subscribeSettingIDs(modules)
+	if err != nil {
+		return err
 	}
 	}
-
-	return mgm.Coll(sub).Create(sub)
-}
-
-func (this *SubscribeOpenService) updateSubscribe(deviceId string, openId string, module string) error {
 	now := util.GetNowSecond()
 	now := util.GetNowSecond()
-
-	filter := bson.M{"device_id": deviceId}
-
-	update := bson.M{
-		"$set": bson.M{
-			"device_id": deviceId,
-			"open_id":   openId,
-			"modules." + module: bson.M{
-				"enabled": true,
-				"open_at": now,
-			},
-			"updated_at": now,
-		},
+	update := subscribeSettingUpdate(ids, openId, enabled, now)
+	if enabled {
+		_, err = mgm.Coll(&subscribe.Subscribe{}).UpdateOne(
+			context.Background(),
+			bson.M{"device_id": deviceId},
+			update,
+			options.Update().SetUpsert(true),
+		)
+		return err
 	}
 	}
-
-	opts := options.Update().SetUpsert(true)
-
-	_, err := mgm.Coll(&subscribe.Subscribe{}).
-		UpdateOne(context.Background(), filter, update, opts)
-
+	_, err = mgm.Coll(&subscribe.Subscribe{}).UpdateOne(
+		context.Background(), bson.M{"device_id": deviceId}, update,
+	)
 	return err
 	return err
 }
 }
 
 
-func (this *SubscribeOpenService) Open() error {
-	subscribeOne := new(subscribe.Subscribe)
-	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": this.DeviceId}, subscribeOne)
-	if err != nil {
-		// 1️⃣ 没有记录
-		if err == mongo.ErrNoDocuments {
-			// 走创建逻辑
-			return this.createSubscribe(this.DeviceId, this.OpenId, this.Module)
+func subscribeSettingIDs(modules []int) ([]int, error) {
+	if len(modules) == 0 {
+		return nil, errors.New("module must contain at least one SubscribePush ID")
+	}
+	ids := make([]int, 0, len(modules))
+	seen := make(map[int]bool, len(modules))
+	for _, id := range modules {
+		if id <= 0 || !sender.SubscribePushConfigByID(id) {
+			return nil, fmt.Errorf("unknown SubscribePush ID %d", id)
+		}
+		if !seen[id] {
+			ids = append(ids, id)
+			seen[id] = true
 		}
 		}
+	}
+	return ids, nil
+}
 
 
-		// 2️⃣ 其他错误
-		return err
+func subscribeSettingUpdate(ids []int, openId string, enabled bool, now int64) bson.M {
+	set := bson.M{"updated_at": now}
+	update := bson.M{"$set": set}
+	if enabled {
+		set["open_id"] = openId
+		update["$addToSet"] = bson.M{"settings": bson.M{"$each": ids}}
+		update["$setOnInsert"] = bson.M{"created_at": time.Now()}
+		return update
 	}
 	}
-	return this.updateSubscribe(this.DeviceId, this.OpenId, this.Module)
+	update["$pull"] = bson.M{"settings": bson.M{"$in": ids}}
+	return update
+}
+
+func (this *SubscribeOpenService) Open() error {
+	return updateSubscribeSetting(this.DeviceId, this.OpenId, this.Module, true)
 }
 }
 
 
 type SubscribeCloseService struct {
 type SubscribeCloseService struct {
 	DeviceId string `json:"device_id"`
 	DeviceId string `json:"device_id"`
-	Module   string `json:"module"`
+	Module   []int  `json:"module"`
 }
 }
 
 
 func (this *SubscribeCloseService) Close() error {
 func (this *SubscribeCloseService) Close() error {
-	now := util.GetNowSecond()
-
-	filter := bson.M{
-		"device_id":                           this.DeviceId,
-		"modules." + this.Module + ".enabled": true,
-	}
-
-	update := bson.M{
-		"$set": bson.M{
-			"modules." + this.Module + ".enabled":  false,
-			"modules." + this.Module + ".close_at": now,
-			"updated_at":                           now,
-		},
-	}
-
-	_, err := mgm.Coll(&subscribe.Subscribe{}).
-		UpdateOne(context.Background(), filter, update)
-
-	return err
+	return updateSubscribeSetting(this.DeviceId, "", this.Module, false)
 }
 }
 
 
 type SubscribeCheckService struct {
 type SubscribeCheckService struct {
 	DeviceId string `json:"device_id"`
 	DeviceId string `json:"device_id"`
 }
 }
 
 
-func (this *SubscribeCheckService) Check() error {
-
-	return nil
+func (this *SubscribeCheckService) Check() ([]int, error) {
+	if this.DeviceId == "" {
+		return nil, errors.New("device_id is empty")
+	}
+	player := new(subscribe.Subscribe)
+	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": this.DeviceId}, player)
+	if err != nil && err != mongo.ErrNoDocuments {
+		return nil, err
+	}
+	if player.Settings == nil {
+		return []int{}, nil
+	}
+	return player.Settings, nil
 }
 }
 
 
 type SubscribeSendService struct {
 type SubscribeSendService struct {
@@ -118,12 +116,17 @@ type SubscribeSendService struct {
 }
 }
 
 
 func (this *SubscribeSendService) Send() error {
 func (this *SubscribeSendService) Send() error {
+	row, ok := sender.SubscribePushConfig(this.Module)
+	if !ok {
+		return errors.New("unknown module")
+	}
+	if !sender.SubscribePushActive(this.Module) {
+		return nil
+	}
 	var list = make([]*subscribe.Subscribe, 0)
 	var list = make([]*subscribe.Subscribe, 0)
 	// 更具deviceId 和 module 获取 需要推送的用户openid 列表
 	// 更具deviceId 和 module 获取 需要推送的用户openid 列表
 	// data 应该是个json对象
 	// data 应该是个json对象
-	filter := bson.M{
-		"modules." + this.Module + ".enabled": true,
-	}
+	filter := bson.M{"settings": row.ID, "open_id": bson.M{"$exists": true, "$ne": ""}}
 
 
 	if this.Module != "alliance" {
 	if this.Module != "alliance" {
 		filter["device_id"] = bson.M{"$in": this.Data}
 		filter["device_id"] = bson.M{"$in": this.Data}
@@ -164,8 +167,11 @@ func (this *SubscribeTaskService) Task() error {
 	default:
 	default:
 		return errors.New("unknown module")
 		return errors.New("unknown module")
 	}
 	}
-	
+
 	if this.Status {
 	if this.Status {
+		if !sender.SubscribePushActive(this.Module) {
+			return nil
+		}
 		logger.Info("Subscribe task append key %s, device id %s timestamp %d, task_time %s", key, this.DeviceId, this.Timestamp, util.TimeStr2DateTime(this.Timestamp, util.TimeLayout))
 		logger.Info("Subscribe task append key %s, device id %s timestamp %d, task_time %s", key, this.DeviceId, this.Timestamp, util.TimeStr2DateTime(this.Timestamp, util.TimeLayout))
 		task.SubscribeTask.Append(key, this.DeviceId, this.Timestamp, this.Module)
 		task.SubscribeTask.Append(key, this.DeviceId, this.Timestamp, this.Module)
 	} else {
 	} else {

+ 74 - 0
app/service/subscribe_test.go

@@ -0,0 +1,74 @@
+package service
+
+import (
+	"dsbqj-admin/pkg/sender"
+	"testing"
+
+	"go.mongodb.org/mongo-driver/bson"
+)
+
+func TestSubscribeSettingUpdateUsesIDArray(t *testing.T) {
+	open := subscribeSettingUpdate([]int{101, 102}, "openid", true, 123)
+	if got := open["$addToSet"].(bson.M)["settings"].(bson.M)["$each"]; !equalIDs(got.([]int), []int{101, 102}) {
+		t.Fatalf("open must add both IDs, got %v", got)
+	}
+	if _, exists := open["$set"].(bson.M)["settings"]; exists {
+		t.Fatal("open must not overwrite the settings array")
+	}
+	close := subscribeSettingUpdate([]int{101, 102}, "", false, 124)
+	if got := close["$pull"].(bson.M)["settings"].(bson.M)["$in"]; !equalIDs(got.([]int), []int{101, 102}) {
+		t.Fatalf("close must remove both IDs, got %v", got)
+	}
+	if _, exists := close["$setOnInsert"]; exists {
+		t.Fatal("close must not create a player record")
+	}
+}
+
+func equalIDs(a, b []int) bool {
+	if len(a) != len(b) {
+		return false
+	}
+	for i := range a {
+		if a[i] != b[i] {
+			return false
+		}
+	}
+	return true
+}
+
+func TestSubscribeSettingIDsValidation(t *testing.T) {
+	if err := sender.ConfigureSubscribePush([]sender.SubscribePushRow{
+		{ID: 101}, {ID: 102}, {ID: 103}, {ID: 104}, {ID: 105}, {ID: 112},
+	}); err != nil {
+		t.Fatal(err)
+	}
+	ids, err := subscribeSettingIDs([]int{101, 112, 101})
+	if err != nil || !equalIDs(ids, []int{101, 112}) {
+		t.Fatalf("dedup failed: %v, %v", ids, err)
+	}
+	if _, err := subscribeSettingIDs([]int{101, 999}); err == nil {
+		t.Fatal("unknown ID must fail before Mongo update")
+	}
+	if _, err := subscribeSettingIDs(nil); err == nil {
+		t.Fatal("empty IDs must fail")
+	}
+}
+
+func TestDisabledPushIsNotQueued(t *testing.T) {
+	if err := sender.ConfigureSubscribePush([]sender.SubscribePushRow{
+		{ID: 101, IsOpen: 0},
+		{ID: 102, Title1: "a", Desc: "a", IsOpen: 1},
+		{ID: 103, Title1: "b", Desc: "b", IsOpen: 1},
+		{ID: 104, Title1: "c", Desc: "c", IsOpen: 1},
+		{ID: 105, Title1: "d", Desc: "d", IsOpen: 1},
+	}); err != nil {
+		t.Fatal(err)
+	}
+	request := SubscribeTaskService{DeviceId: "device", Module: "hangup", Timestamp: 123, Status: true}
+	if err := request.Task(); err != nil {
+		t.Fatal(err)
+	}
+	if err := (&SubscribeSendService{Module: "hangup"}).Send(); err != nil {
+		t.Fatal(err)
+	}
+}

+ 3 - 1
main-subscribe/README.md

@@ -5,4 +5,6 @@
 - `GM_SUBSCRIBE_PUSH_URL`:GM 内网接口的完整 URL,例如 `http://<gm-host>:<port>/internal/subscribe_push/config`。
 - `GM_SUBSCRIBE_PUSH_URL`:GM 内网接口的完整 URL,例如 `http://<gm-host>:<port>/internal/subscribe_push/config`。
 - `GM_INTERNAL_SECRET`:与 GM `config.admin` 相同的内部签名密钥。
 - `GM_INTERNAL_SECRET`:与 GM `config.admin` 相同的内部签名密钥。
 
 
-进程启动时向 GM 发起一次签名 POST,读取 SubscribePush 的 101–105 配置快照;读取或校验失败则启动失败。运行期间不再轮询 GM。微信模板 ID 仍按 `CHANNEL` 从 `config/subscribe_template.yaml` 选择,但所有场景使用同一个 `general` 模板。部署时需先上线 GM 接口,再重启订阅进程。
+进程启动时向 GM 发起一次签名 POST,读取以配置 ID 为键的 SubscribePush 表对象(例如 `{"101":{"id":101,...}}`);当前实现要求包含 101–105,读取或校验失败则启动失败。运行期间不再轮询 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` 唯一索引。

+ 4 - 0
main-subscribe/main.go

@@ -5,6 +5,7 @@ import (
 	"dsbqj-admin/app/router"
 	"dsbqj-admin/app/router"
 	"dsbqj-admin/app/task"
 	"dsbqj-admin/app/task"
 	"dsbqj-admin/model/mongo"
 	"dsbqj-admin/model/mongo"
+	"dsbqj-admin/model/mongo/subscribe"
 	"dsbqj-admin/pkg/cache"
 	"dsbqj-admin/pkg/cache"
 	"dsbqj-admin/pkg/logger"
 	"dsbqj-admin/pkg/logger"
 	"dsbqj-admin/pkg/sender"
 	"dsbqj-admin/pkg/sender"
@@ -45,6 +46,9 @@ func main() {
 	// 连接数据库
 	// 连接数据库
 	//mysql.Database(os.Getenv("MYSQL_DSN"))
 	//mysql.Database(os.Getenv("MYSQL_DSN"))
 	mongo.Database(os.Getenv("MONGO_DSN"))
 	mongo.Database(os.Getenv("MONGO_DSN"))
+	if err := subscribe.EnsureDeviceIndex(); err != nil {
+		log.Fatalf("ensure subscribe device index: %v", err)
+	}
 	// GM 配置仅在进程启动时读取一次,避免每条推送访问 GM。
 	// GM 配置仅在进程启动时读取一次,避免每条推送访问 GM。
 	if err := sender.LoadSubscribePushFromGM(context.Background(), os.Getenv("GM_SUBSCRIBE_PUSH_URL"), os.Getenv("GM_INTERNAL_SECRET")); err != nil {
 	if err := sender.LoadSubscribePushFromGM(context.Background(), os.Getenv("GM_SUBSCRIBE_PUSH_URL"), os.Getenv("GM_INTERNAL_SECRET")); err != nil {
 		log.Fatalf("load SubscribePush configuration: %v", err)
 		log.Fatalf("load SubscribePush configuration: %v", err)

+ 18 - 10
model/mongo/subscribe/subscribe.go

@@ -1,17 +1,14 @@
 package subscribe
 package subscribe
 
 
 import (
 import (
+	"context"
+
 	"github.com/kamva/mgm/v3"
 	"github.com/kamva/mgm/v3"
+	"go.mongodb.org/mongo-driver/bson"
+	"go.mongodb.org/mongo-driver/mongo"
+	"go.mongodb.org/mongo-driver/mongo/options"
 )
 )
 
 
-type ModuleSubscribe struct {
-	Enabled bool `bson:"enabled" json:"enabled"`
-
-	// 最近一次开启 / 关闭时间
-	OpenAt  int64 `bson:"open_at,omitempty"  json:"open_at,omitempty"`
-	CloseAt int64 `bson:"close_at,omitempty" json:"close_at,omitempty"`
-}
-
 type Subscribe struct {
 type Subscribe struct {
 	mgm.DefaultModel `bson:",inline"`
 	mgm.DefaultModel `bson:",inline"`
 
 
@@ -19,6 +16,17 @@ type Subscribe struct {
 	OpenId   string `bson:"open_id"   json:"open_id"`
 	OpenId   string `bson:"open_id"   json:"open_id"`
 	DeviceId string `bson:"device_id" json:"device_id"`
 	DeviceId string `bson:"device_id" json:"device_id"`
 
 
-	// 订阅状态集合:key = module, value = 订阅信息
-	Modules map[string]*ModuleSubscribe `bson:"modules" json:"modules"`
+	// 已开启的 SubscribePush 配置 ID。
+	Settings []int `bson:"settings" json:"settings"`
+}
+
+func EnsureDeviceIndex() error {
+	_, err := mgm.Coll(&Subscribe{}).Indexes().CreateOne(
+		context.Background(),
+		mongo.IndexModel{
+			Keys:    bson.D{{Key: "device_id", Value: 1}},
+			Options: options.Index().SetUnique(true),
+		},
+	)
+	return err
 }
 }

+ 10 - 2
pkg/sender/subscribe.go

@@ -88,8 +88,12 @@ func (this *SubscribeSender) safeSend(send *SubscribeSend) {
 }
 }
 
 
 func (this *SubscribeSender) SendHangupSubscribe(deviceId string) {
 func (this *SubscribeSender) SendHangupSubscribe(deviceId string) {
+	row, ok := SubscribePushConfig("hangup")
+	if !ok || !SubscribePushActive("hangup") {
+		return
+	}
 	subscribeOne := new(subscribe.Subscribe)
 	subscribeOne := new(subscribe.Subscribe)
-	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": deviceId, "modules.hangup.enabled": true}, subscribeOne)
+	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 {
 	if err != nil {
 		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "hangup", deviceId, err)
 		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "hangup", deviceId, err)
 		return
 		return
@@ -99,8 +103,12 @@ func (this *SubscribeSender) SendHangupSubscribe(deviceId string) {
 }
 }
 
 
 func (this *SubscribeSender) SendAutoFightSubscribe(deviceId string) {
 func (this *SubscribeSender) SendAutoFightSubscribe(deviceId string) {
+	row, ok := SubscribePushConfig("autofight")
+	if !ok || !SubscribePushActive("autofight") {
+		return
+	}
 	subscribeOne := new(subscribe.Subscribe)
 	subscribeOne := new(subscribe.Subscribe)
-	err := mgm.Coll(&subscribe.Subscribe{}).First(bson.M{"device_id": deviceId, "modules.autofight.enabled": true}, subscribeOne)
+	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 {
 	if err != nil {
 		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "autofight", deviceId, err)
 		logger.Info("[订阅推送] 查询订阅记录失败, module=%s, device_id=%s, err=%v", "autofight", deviceId, err)
 		return
 		return

+ 29 - 11
pkg/sender/subscribe_push_config.go

@@ -8,12 +8,10 @@ import (
 
 
 // SubscribePushRow is the GM SubscribePush table entry needed by the sender.
 // SubscribePushRow is the GM SubscribePush table entry needed by the sender.
 type SubscribePushRow struct {
 type SubscribePushRow struct {
-	ID            int    `json:"id"`
-	Title1        string `json:"title1"`
-	Desc          string `json:"desc"`
-	IsOpen        int    `json:"is_open"`
-	IsSet         int    `json:"is_set"`
-	SetInitialize int    `json:"set_initialize"`
+	ID     int    `json:"id"`
+	Title1 string `json:"title1"`
+	Desc   string `json:"desc"`
+	IsOpen int    `json:"is_open"`
 }
 }
 
 
 type subscribeMessage struct {
 type subscribeMessage struct {
@@ -56,17 +54,37 @@ func ConfigureSubscribePush(rows []SubscribePushRow) error {
 }
 }
 
 
 func subscribePushMessage(module string) (subscribeMessage, bool) {
 func subscribePushMessage(module string) (subscribeMessage, bool) {
+	row, ok := SubscribePushConfig(module)
+	if !ok || !SubscribePushActive(module) {
+		return subscribeMessage{}, false
+	}
+	return subscribeMessage{Title: row.Title1, Description: row.Desc}, true
+}
+
+func SubscribePushActive(module string) bool {
+	row, ok := SubscribePushConfig(module)
+	return ok && row.IsOpen != 0 && strings.TrimSpace(row.Title1) != "" && strings.TrimSpace(row.Desc) != ""
+}
+
+func SubscribePushConfig(module string) (SubscribePushRow, bool) {
 	id, ok := moduleConfigID[module]
 	id, ok := moduleConfigID[module]
 	if !ok {
 	if !ok {
-		return subscribeMessage{}, false
+		return SubscribePushRow{}, false
 	}
 	}
 	value := subscribePushRows.Load()
 	value := subscribePushRows.Load()
 	if value == nil {
 	if value == nil {
-		return subscribeMessage{}, false
+		return SubscribePushRow{}, false
 	}
 	}
 	row, ok := value.(map[int]SubscribePushRow)[id]
 	row, ok := value.(map[int]SubscribePushRow)[id]
-	if !ok || row.IsOpen == 0 {
-		return subscribeMessage{}, false
+	return row, ok
+}
+
+// SubscribePushConfigByID reports whether an ID exists in the GM startup snapshot.
+func SubscribePushConfigByID(id int) bool {
+	value := subscribePushRows.Load()
+	if value == nil {
+		return false
 	}
 	}
-	return subscribeMessage{Title: row.Title1, Description: row.Desc}, true
+	_, ok := value.(map[int]SubscribePushRow)[id]
+	return ok
 }
 }

+ 8 - 7
pkg/sender/subscribe_push_config_test.go

@@ -55,13 +55,14 @@ func TestLoadSubscribePushFromGM(t *testing.T) {
 			w.WriteHeader(http.StatusForbidden)
 			w.WriteHeader(http.StatusForbidden)
 			return
 			return
 		}
 		}
-		_ = json.NewEncoder(w).Encode(map[string]any{"list": []SubscribePushRow{
-			{ID: 101, Title1: "配置标题", Desc: "配置文案", IsOpen: 1},
-			{ID: 102, IsOpen: 0},
-			{ID: 103, IsOpen: 0},
-			{ID: 104, IsOpen: 0},
-			{ID: 105, IsOpen: 0},
-		}})
+		_ = json.NewEncoder(w).Encode(map[string]any{
+			"101": map[string]any{"id": 101, "title1": "配置标题", "desc": "配置文案", "is_open": 1, "is_set": 0},
+			"102": map[string]any{"id": 102, "is_open": 0},
+			"103": map[string]any{"id": 103, "is_open": 0},
+			"104": map[string]any{"id": 104, "is_open": 0},
+			"105": map[string]any{"id": 105, "is_open": 0},
+			"112": map[string]any{"id": 112, "is_open": 0},
+		})
 	}))
 	}))
 	defer server.Close()
 	defer server.Close()
 
 

+ 12 - 7
pkg/sender/subscribe_push_gm.go

@@ -10,14 +10,11 @@ import (
 	"fmt"
 	"fmt"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
+	"strconv"
 	"strings"
 	"strings"
 	"time"
 	"time"
 )
 )
 
 
-type subscribePushGMResponse struct {
-	List []SubscribePushRow `json:"list"`
-}
-
 // LoadSubscribePushFromGM fetches one startup snapshot. GM verifies token as
 // LoadSubscribePushFromGM fetches one startup snapshot. GM verifies token as
 // HMAC-SHA256(base64) over JSON.stringify(body without token).
 // HMAC-SHA256(base64) over JSON.stringify(body without token).
 func LoadSubscribePushFromGM(ctx context.Context, endpoint, secret string) error {
 func LoadSubscribePushFromGM(ctx context.Context, endpoint, secret string) error {
@@ -51,9 +48,17 @@ func LoadSubscribePushFromGM(ctx context.Context, endpoint, secret string) error
 	if response.StatusCode != http.StatusOK {
 	if response.StatusCode != http.StatusOK {
 		return fmt.Errorf("fetch SubscribePush from GM: HTTP %d", response.StatusCode)
 		return fmt.Errorf("fetch SubscribePush from GM: HTTP %d", response.StatusCode)
 	}
 	}
-	var payload subscribePushGMResponse
-	if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
+	var table map[string]SubscribePushRow
+	if err := json.NewDecoder(response.Body).Decode(&table); err != nil {
 		return fmt.Errorf("decode SubscribePush from GM: %w", err)
 		return fmt.Errorf("decode SubscribePush from GM: %w", err)
 	}
 	}
-	return ConfigureSubscribePush(payload.List)
+	rows := make([]SubscribePushRow, 0, len(table))
+	for key, row := range table {
+		id, err := strconv.Atoi(key)
+		if err != nil || id <= 0 || row.ID != id {
+			return fmt.Errorf("SubscribePush row ID does not match table key %q", key)
+		}
+		rows = append(rows, row)
+	}
+	return ConfigureSubscribePush(rows)
 }
 }