From f33497d0029c63257790cd1d4829b9fc5d889fbc Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Wed, 25 Dec 2024 00:25:32 +0800 Subject: [PATCH] :sparkles: Notify all users endpoint --- pkg/internal/http/api/index.go | 1 + pkg/internal/http/api/notify_api.go | 57 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/pkg/internal/http/api/index.go b/pkg/internal/http/api/index.go index 55fdbeb..586a997 100644 --- a/pkg/internal/http/api/index.go +++ b/pkg/internal/http/api/index.go @@ -139,6 +139,7 @@ func MapAPIs(app *fiber.App, baseURL string) { developers := api.Group("/dev").Name("Developers API") { developers.Post("/notify", notifyUser) + developers.Post("/notify/all", notifyAllUser) bots := developers.Group("/bots").Name("Bots") { diff --git a/pkg/internal/http/api/notify_api.go b/pkg/internal/http/api/notify_api.go index 6462180..6d2c912 100644 --- a/pkg/internal/http/api/notify_api.go +++ b/pkg/internal/http/api/notify_api.go @@ -4,6 +4,7 @@ import ( "fmt" "git.solsynth.dev/hypernet/passport/pkg/authkit/models" + "git.solsynth.dev/hypernet/passport/pkg/internal/database" "git.solsynth.dev/hypernet/passport/pkg/internal/http/exts" "git.solsynth.dev/hypernet/passport/pkg/internal/services" "github.com/gofiber/fiber/v2" @@ -65,3 +66,59 @@ func notifyUser(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) } + +func notifyAllUser(c *fiber.Ctx) error { + if err := exts.EnsureGrantedPerm(c, "DevNotifyAllUser", true); err != nil { + return err + } + user := c.Locals("user").(models.Account) + + var data struct { + ClientID string `json:"client_id" validate:"required"` + Topic string `json:"type" validate:"required"` + Title string `json:"subject" validate:"required,max=1024"` + Subtitle string `json:"subtitle" validate:"max=1024"` + Body string `json:"content" validate:"required,max=4096"` + Metadata map[string]any `json:"metadata"` + Priority int `json:"priority"` + IsRealtime bool `json:"is_realtime"` + } + + if err := exts.BindAndValidate(c, &data); err != nil { + return err + } + + client, err := services.GetThirdClientWithUser(data.ClientID, user.ID) + if err != nil { + return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to get client: %v", err)) + } + + var accounts []models.Account + if err := database.C.Find(&accounts).Error; err != nil { + return fiber.NewError(fiber.StatusBadRequest, err.Error()) + } + + var notifications []models.Notification + for _, account := range accounts { + notification := models.Notification{ + Topic: data.Topic, + Subtitle: data.Subtitle, + Title: data.Title, + Body: data.Body, + Metadata: data.Metadata, + Priority: data.Priority, + Account: account, + AccountID: account.ID, + SenderID: &client.ID, + } + notifications = append(notifications, notification) + } + + if data.IsRealtime { + go services.PushNotificationBatch(notifications) + } else { + go services.NewNotificationBatch(notifications) + } + + return c.SendStatus(fiber.StatusOK) +}