91 lines
2.0 KiB
Go
Raw Normal View History

2018-02-28 23:06:03 +00:00
package notifications
import (
"net/http"
2018-10-17 00:31:15 +00:00
"sort"
2018-02-28 23:06:03 +00:00
"strconv"
"github.com/aerogo/aero"
2019-06-03 09:32:43 +00:00
"github.com/animenotifier/notify.moe/arn"
2019-06-01 04:55:49 +00:00
"github.com/animenotifier/notify.moe/assets"
2018-02-28 23:06:03 +00:00
"github.com/animenotifier/notify.moe/utils"
)
// CountUnseen sends the number of unseen notifications.
2019-06-01 04:55:49 +00:00
func CountUnseen(ctx aero.Context) error {
2018-02-28 23:06:03 +00:00
user := utils.GetUser(ctx)
if user == nil {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusBadRequest, "Not logged in")
2018-02-28 23:06:03 +00:00
}
2018-03-03 22:37:30 +00:00
unseen := user.Notifications().CountUnseen()
2018-02-28 23:06:03 +00:00
return ctx.Text(strconv.Itoa(unseen))
}
// MarkNotificationsAsSeen marks all notifications as seen.
2019-06-01 04:55:49 +00:00
func MarkNotificationsAsSeen(ctx aero.Context) error {
2018-02-28 23:06:03 +00:00
user := utils.GetUser(ctx)
if user == nil {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusBadRequest, "Not logged in")
2018-02-28 23:06:03 +00:00
}
notifications := user.Notifications().Notifications()
for _, notification := range notifications {
notification.Seen = arn.DateTimeUTC()
notification.Save()
}
// Update the counter on all clients
user.BroadcastEvent(&aero.Event{
Name: "notificationCount",
Data: 0,
})
2019-06-01 04:55:49 +00:00
return nil
2018-02-28 23:06:03 +00:00
}
2018-10-17 00:31:15 +00:00
// Latest returns the latest notifications.
2019-06-01 04:55:49 +00:00
func Latest(ctx aero.Context) error {
2018-10-17 00:31:15 +00:00
userID := ctx.Get("id")
user, err := arn.GetUser(userID)
if err != nil {
return ctx.Error(http.StatusBadRequest, "Invalid user ID")
}
notifications := user.Notifications().Notifications()
// Sort by date
sort.Slice(notifications, func(i, j int) bool {
return notifications[i].Created > notifications[j].Created
})
if len(notifications) > maxNotifications {
notifications = notifications[:maxNotifications]
}
return ctx.JSON(notifications)
}
2018-02-28 23:06:03 +00:00
// Test sends a test notification to the logged in user.
2019-06-01 04:55:49 +00:00
func Test(ctx aero.Context) error {
2018-02-28 23:06:03 +00:00
user := utils.GetUser(ctx)
if user == nil {
2018-07-07 03:42:00 +00:00
return ctx.Error(http.StatusBadRequest, "Not logged in")
2018-02-28 23:06:03 +00:00
}
user.SendNotification(&arn.PushNotification{
Title: "Anime Notifier",
Message: "Yay, it works!",
2019-06-01 04:55:49 +00:00
Icon: "https://" + assets.Domain + "/images/brand/220.png",
2018-02-28 23:06:03 +00:00
Type: arn.NotificationTypeTest,
})
2019-06-01 04:55:49 +00:00
return nil
2018-02-28 23:06:03 +00:00
}