Passport/pkg/server/notifications_api.go

100 lines
2.5 KiB
Go
Raw Normal View History

2024-02-01 07:58:28 +00:00
package server
import (
2024-04-20 14:50:09 +00:00
"git.solsynth.dev/hydrogen/passport/pkg/utils"
2024-03-16 04:28:50 +00:00
"time"
2024-04-13 05:48:19 +00:00
"git.solsynth.dev/hydrogen/passport/pkg/database"
"git.solsynth.dev/hydrogen/passport/pkg/models"
"git.solsynth.dev/hydrogen/passport/pkg/services"
2024-02-01 07:58:28 +00:00
"github.com/gofiber/fiber/v2"
"github.com/samber/lo"
)
func getNotifications(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
2024-03-16 04:28:50 +00:00
only_unread := !c.QueryBool("past", false)
2024-02-28 15:30:29 +00:00
tx := database.C.Where(&models.Notification{RecipientID: user.ID}).Model(&models.Notification{})
if only_unread {
tx = tx.Where("read_at IS NULL")
}
2024-02-01 07:58:28 +00:00
var count int64
var notifications []models.Notification
2024-02-28 15:30:29 +00:00
if err := tx.
2024-02-01 07:58:28 +00:00
Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
2024-02-28 15:30:29 +00:00
if err := tx.
2024-02-01 07:58:28 +00:00
Limit(take).
Offset(offset).
Order("read_at desc").
Find(&notifications).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(fiber.Map{
"count": count,
"data": notifications,
})
}
func markNotificationRead(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
id, _ := c.ParamsInt("notificationId", 0)
var data models.Notification
if err := database.C.Where(&models.Notification{
BaseModel: models.BaseModel{ID: uint(id)},
RecipientID: user.ID,
}).First(&data).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
data.ReadAt = lo.ToPtr(time.Now())
if err := database.C.Save(&data).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
return c.SendStatus(fiber.StatusOK)
}
}
2024-02-07 15:15:16 +00:00
func addNotifySubscriber(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
var data struct {
Provider string `json:"provider" validate:"required"`
DeviceID string `json:"device_id" validate:"required"`
}
2024-04-20 14:50:09 +00:00
if err := utils.BindAndValidate(c, &data); err != nil {
2024-02-07 15:15:16 +00:00
return err
}
2024-02-08 03:08:29 +00:00
var count int64
if err := database.C.Where(&models.NotificationSubscriber{
DeviceID: data.DeviceID,
AccountID: user.ID,
}).Model(&models.NotificationSubscriber{}).Count(&count).Error; err != nil || count > 0 {
return c.SendStatus(fiber.StatusOK)
}
2024-02-07 15:15:16 +00:00
subscriber, err := services.AddNotifySubscriber(
user,
data.Provider,
data.DeviceID,
c.Get(fiber.HeaderUserAgent),
)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(subscriber)
}