90 lines
1.9 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"
"github.com/animenotifier/arn"
"github.com/animenotifier/notify.moe/utils"
)
// CountUnseen sends the number of unseen notifications.
func CountUnseen(ctx *aero.Context) string {
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.
func MarkNotificationsAsSeen(ctx *aero.Context) string {
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,
})
2018-02-28 23:06:03 +00:00
return "ok"
}
2018-10-17 00:31:15 +00:00
// Latest returns the latest notifications.
func Latest(ctx *aero.Context) string {
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.
func Test(ctx *aero.Context) string {
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!",
Icon: "https://" + ctx.App.Config.Domain + "/images/brand/220.png",
Type: arn.NotificationTypeTest,
})
return "ok"
}