SimpleCloudNotifier/server/api/handler/message.go

322 lines
12 KiB
Go
Raw Normal View History

2022-11-18 21:25:40 +01:00
package handler
import (
2022-11-19 15:13:47 +01:00
"blackforestbytes.com/simplecloudnotifier/api/apierr"
2022-11-18 21:25:40 +01:00
"blackforestbytes.com/simplecloudnotifier/common/ginresp"
2022-11-19 15:13:47 +01:00
"blackforestbytes.com/simplecloudnotifier/db"
2022-11-18 21:25:40 +01:00
"blackforestbytes.com/simplecloudnotifier/logic"
2022-11-20 22:18:24 +01:00
"blackforestbytes.com/simplecloudnotifier/models"
2022-11-19 15:13:47 +01:00
"database/sql"
"fmt"
2022-11-18 21:25:40 +01:00
"github.com/gin-gonic/gin"
2022-11-19 15:13:47 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/dataext"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"gogs.mikescher.com/BlackForestBytes/goext/mathext"
"gogs.mikescher.com/BlackForestBytes/goext/timeext"
"net/http"
"strings"
"time"
2022-11-18 21:25:40 +01:00
)
type MessageHandler struct {
2022-11-19 15:13:47 +01:00
app *logic.Application
database *db.Database
2022-11-18 21:25:40 +01:00
}
2022-11-19 15:13:47 +01:00
func NewMessageHandler(app *logic.Application) MessageHandler {
return MessageHandler{
app: app,
database: app.Database,
}
}
2022-11-20 03:06:08 +01:00
// SendMessageCompat swaggerdoc
//
// @Deprecated
//
// @Summary Send a new message (compatibility)
// @Description All parameter can be set via query-parameter or form-data body. Only UserID, UserKey and Title are required
//
// @Param query_data query handler.SendMessageCompat.query false " "
// @Param form_data formData handler.SendMessageCompat.form false " "
//
// @Success 200 {object} handler.sendMessageInternal.response
// @Failure 400 {object} ginresp.apiError
// @Failure 401 {object} ginresp.apiError
// @Failure 403 {object} ginresp.apiError
// @Failure 404 {object} ginresp.apiError
// @Failure 500 {object} ginresp.apiError
//
// @Router /send.php [POST]
func (h MessageHandler) SendMessageCompat(g *gin.Context) ginresp.HTTPResponse {
type query struct {
2022-11-20 22:18:24 +01:00
UserID *models.UserID `form:"user_id"`
UserKey *string `form:"user_key"`
Title *string `form:"title"`
Content *string `form:"content"`
Priority *int `form:"priority"`
UserMessageID *string `form:"msg_id"`
SendTimestamp *float64 `form:"timestamp"`
2022-11-20 03:06:08 +01:00
}
type form struct {
2022-11-20 22:18:24 +01:00
UserID *models.UserID `form:"user_id"`
UserKey *string `form:"user_key"`
Title *string `form:"title"`
Content *string `form:"content"`
Priority *int `form:"priority"`
UserMessageID *string `form:"msg_id"`
SendTimestamp *float64 `form:"timestamp"`
2022-11-20 03:06:08 +01:00
}
var f form
var q query
ctx, errResp := h.app.StartRequest(g, nil, &q, nil, &f)
if errResp != nil {
return *errResp
}
defer ctx.Cancel()
data := dataext.ObjectMerge(f, q)
2022-11-20 22:18:24 +01:00
return h.sendMessageInternal(g, ctx, data.UserID, data.UserKey, nil, nil, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp)
2022-11-20 03:06:08 +01:00
}
2022-11-19 15:13:47 +01:00
// SendMessage swaggerdoc
//
// @Summary Send a new message
// @Description All parameter can be set via query-parameter or the json body. Only UserID, UserKey and Title are required
//
// @Param query_data query handler.SendMessage.query false " "
// @Param post_body body handler.SendMessage.body false " "
2022-11-20 20:34:18 +01:00
// @Param form_body formData handler.SendMessage.body false " "
2022-11-19 15:13:47 +01:00
//
2022-11-20 03:06:08 +01:00
// @Success 200 {object} handler.sendMessageInternal.response
2022-11-19 15:13:47 +01:00
// @Failure 400 {object} ginresp.apiError
// @Failure 401 {object} ginresp.apiError
// @Failure 403 {object} ginresp.apiError
// @Failure 404 {object} ginresp.apiError
// @Failure 500 {object} ginresp.apiError
//
// @Router / [POST]
// @Router /send [POST]
2022-11-18 21:25:40 +01:00
func (h MessageHandler) SendMessage(g *gin.Context) ginresp.HTTPResponse {
2022-11-19 15:13:47 +01:00
type query struct {
2022-11-20 22:18:24 +01:00
UserID *models.UserID `form:"user_id"`
UserKey *string `form:"user_key"`
Channel *string `form:"channel"`
ChanKey *string `form:"chan_key"`
Title *string `form:"title"`
Content *string `form:"content"`
Priority *int `form:"priority"`
UserMessageID *string `form:"msg_id"`
SendTimestamp *float64 `form:"timestamp"`
2022-11-19 15:13:47 +01:00
}
type body struct {
2022-11-20 22:18:24 +01:00
UserID *models.UserID `json:"user_id"`
UserKey *string `json:"user_key"`
Channel *string `json:"channel"`
ChanKey *string `json:"chan_key"`
Title *string `json:"title"`
Content *string `json:"content"`
Priority *int `json:"priority"`
UserMessageID *string `json:"msg_id"`
SendTimestamp *float64 `json:"timestamp"`
2022-11-19 15:13:47 +01:00
}
2022-11-20 20:34:18 +01:00
type form struct {
2022-11-20 22:18:24 +01:00
UserID *models.UserID `form:"user_id"`
UserKey *string `form:"user_key"`
Channel *string `form:"channel"`
ChanKey *string `form:"chan_key"`
Title *string `form:"title"`
Content *string `form:"content"`
Priority *int `form:"priority"`
UserMessageID *string `form:"msg_id"`
SendTimestamp *float64 `form:"timestamp"`
2022-11-20 20:34:18 +01:00
}
2022-11-20 03:06:08 +01:00
var b body
var q query
2022-11-20 20:34:18 +01:00
var f form
ctx, errResp := h.app.StartRequest(g, nil, &q, &b, &f)
2022-11-20 03:06:08 +01:00
if errResp != nil {
return *errResp
}
defer ctx.Cancel()
2022-11-20 20:34:18 +01:00
data := dataext.ObjectMerge(dataext.ObjectMerge(b, f), q)
2022-11-20 03:06:08 +01:00
2022-11-20 17:19:11 +01:00
return h.sendMessageInternal(g, ctx, data.UserID, data.UserKey, data.Channel, data.ChanKey, data.Title, data.Content, data.Priority, data.UserMessageID, data.SendTimestamp)
2022-11-20 03:06:08 +01:00
}
2022-11-20 22:18:24 +01:00
func (h MessageHandler) sendMessageInternal(g *gin.Context, ctx *logic.AppContext, UserID *models.UserID, UserKey *string, Channel *string, ChanKey *string, Title *string, Content *string, Priority *int, UserMessageID *string, SendTimestamp *float64) ginresp.HTTPResponse {
2022-11-19 15:13:47 +01:00
type response struct {
2022-11-20 22:18:24 +01:00
Success bool `json:"success"`
ErrorID apierr.APIError `json:"error"`
ErrorHighlight int `json:"errhighlight"`
Message string `json:"message"`
SuppressSend bool `json:"suppress_send"`
MessageCount int `json:"messagecount"`
Quota int `json:"quota"`
IsPro bool `json:"is_pro"`
QuotaMax int `json:"quota_max"`
SCNMessageID models.SCNMessageID `json:"scn_msg_id"`
2022-11-19 15:13:47 +01:00
}
2022-11-20 12:59:43 +01:00
if Title != nil {
Title = langext.Ptr(strings.TrimSpace(*Title))
}
if UserMessageID != nil {
UserMessageID = langext.Ptr(strings.TrimSpace(*UserMessageID))
}
2022-11-20 03:06:08 +01:00
if UserID == nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.MISSING_UID, 101, "Missing parameter [[user_id]]", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
if UserKey == nil {
2022-11-20 20:34:18 +01:00
return ginresp.SendAPIError(g, 400, apierr.MISSING_TOK, 102, "Missing parameter [[user_token]]", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
if Title == nil {
2022-11-20 20:34:18 +01:00
return ginresp.SendAPIError(g, 400, apierr.MISSING_TITLE, 103, "Missing parameter [[title]]", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
if SendTimestamp != nil && mathext.Abs(*SendTimestamp-float64(time.Now().Unix())) > (24*time.Hour).Seconds() {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.TIMESTAMP_OUT_OF_RANGE, -1, "The timestamp mus be within 24 hours of now()", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
if Priority != nil && (*Priority != 0 && *Priority != 1 && *Priority != 2) {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.INVALID_PRIO, 105, "Invalid priority", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 12:59:43 +01:00
if len(*Title) == 0 {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.NO_TITLE, 103, "No title specified", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 12:59:43 +01:00
if UserMessageID != nil && len(*UserMessageID) > 64 {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.USR_MSG_ID_TOO_LONG, -1, "MessageID too long (64 characters)", nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
user, err := h.database.GetUser(ctx, *UserID)
2022-11-19 15:13:47 +01:00
if err == sql.ErrNoRows {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.USER_NOT_FOUND, -1, "User not found", nil)
2022-11-19 15:13:47 +01:00
}
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to query user", err)
2022-11-19 15:13:47 +01:00
}
2022-11-20 22:18:24 +01:00
channelName := user.DefaultChannel()
if Channel != nil {
channelName = h.app.NormalizeChannelName(*Channel)
}
2022-11-20 20:34:18 +01:00
if len(*Title) > user.MaxTitleLength() {
return ginresp.SendAPIError(g, 400, apierr.TITLE_TOO_LONG, 103, fmt.Sprintf("Title too long (max %d characters)", user.MaxTitleLength()), nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 12:59:43 +01:00
if Content != nil && len(*Content) > user.MaxContentLength() {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 400, apierr.CONTENT_TOO_LONG, 104, fmt.Sprintf("Content too long (%d characters; max := %d characters)", len(*Content), user.MaxContentLength()), nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
if UserMessageID != nil {
msg, err := h.database.GetMessageByUserMessageID(ctx, *UserMessageID)
2022-11-19 15:13:47 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to query existing message", err)
2022-11-19 15:13:47 +01:00
}
if msg != nil {
2022-11-20 03:06:08 +01:00
return ctx.FinishSuccess(ginresp.JSON(http.StatusOK, response{
2022-11-19 15:13:47 +01:00
Success: true,
ErrorID: apierr.NO_ERROR,
ErrorHighlight: -1,
2022-11-19 15:13:47 +01:00
Message: "Message already sent",
SuppressSend: true,
MessageCount: user.MessagesSent,
Quota: user.QuotaUsedToday(),
IsPro: user.IsPro,
QuotaMax: user.QuotaPerDay(),
SCNMessageID: msg.SCNMessageID,
2022-11-20 03:06:08 +01:00
}))
2022-11-19 15:13:47 +01:00
}
}
if user.QuotaRemainingToday() <= 0 {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 403, apierr.QUOTA_REACHED, -1, fmt.Sprintf("Daily quota reached (%d)", user.QuotaPerDay()), nil)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
channel, err := h.app.GetOrCreateChannel(ctx, *UserID, channelName)
2022-11-19 15:13:47 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to query/create channel", err)
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
selfChanAdmin := *UserID == channel.OwnerUserID && *UserKey == user.AdminKey
selfChanSend := *UserID == channel.OwnerUserID && *UserKey == user.SendKey
forgChanSend := *UserID != channel.OwnerUserID && ChanKey != nil && *ChanKey == channel.SendKey
2022-11-19 15:13:47 +01:00
if !selfChanAdmin && !selfChanSend && !forgChanSend {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 401, apierr.USER_AUTH_FAILED, 102, fmt.Sprintf("Daily quota reached (%d)", user.QuotaPerDay()), nil)
2022-11-19 15:13:47 +01:00
}
var sendTimestamp *time.Time = nil
2022-11-20 03:06:08 +01:00
if SendTimestamp != nil {
sendTimestamp = langext.Ptr(timeext.UnixFloatSeconds(*SendTimestamp))
2022-11-19 15:13:47 +01:00
}
2022-11-20 03:06:08 +01:00
priority := langext.Coalesce(Priority, 1)
2022-11-19 15:13:47 +01:00
2022-11-20 03:06:08 +01:00
msg, err := h.database.CreateMessage(ctx, *UserID, channel, sendTimestamp, *Title, Content, priority, UserMessageID)
2022-11-19 15:13:47 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to create message in db", err)
2022-11-19 15:13:47 +01:00
}
subscriptions, err := h.database.ListSubscriptionsByChannel(ctx, channel.ChannelID)
2022-11-19 15:13:47 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to query subscriptions", err)
2022-11-19 15:13:47 +01:00
}
err = h.database.IncUserMessageCounter(ctx, user)
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to inc user msg-counter", err)
}
err = h.database.IncChannelMessageCounter(ctx, channel)
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to inc channel msg-counter", err)
}
2022-11-19 15:13:47 +01:00
for _, sub := range subscriptions {
clients, err := h.database.ListClients(ctx, sub.SubscriberUserID)
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to query clients", err)
2022-11-19 15:13:47 +01:00
}
if !sub.Confirmed {
continue
}
2022-11-19 15:13:47 +01:00
for _, client := range clients {
2022-11-20 15:40:19 +01:00
fcmDelivID, err := h.app.DeliverMessage(ctx, client, msg)
2022-11-19 15:13:47 +01:00
if err != nil {
_, err = h.database.CreateRetryDelivery(ctx, client, msg)
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to create delivery", err)
2022-11-19 15:13:47 +01:00
}
} else {
_, err = h.database.CreateSuccessDelivery(ctx, client, msg, *fcmDelivID)
if err != nil {
2022-11-20 17:19:11 +01:00
return ginresp.SendAPIError(g, 500, apierr.DATABASE_ERROR, -1, "Failed to create delivery", err)
2022-11-19 15:13:47 +01:00
}
}
}
}
2022-11-20 03:06:08 +01:00
return ctx.FinishSuccess(ginresp.JSON(http.StatusOK, response{
Success: true,
ErrorID: apierr.NO_ERROR,
ErrorHighlight: -1,
Message: "Message sent",
SuppressSend: false,
MessageCount: user.MessagesSent + 1,
Quota: user.QuotaUsedToday() + 1,
IsPro: user.IsPro,
QuotaMax: user.QuotaPerDay(),
SCNMessageID: msg.SCNMessageID,
2022-11-20 03:06:08 +01:00
}))
2022-11-18 21:25:40 +01:00
}