SimpleCloudNotifier/scnserver/push/firebase.go

134 lines
3.4 KiB
Go
Raw Normal View History

2022-11-23 19:32:23 +01:00
package push
2022-11-19 14:57:45 +01:00
import (
2022-11-20 17:19:11 +01:00
scn "blackforestbytes.com/simplecloudnotifier"
2022-11-19 15:13:47 +01:00
"blackforestbytes.com/simplecloudnotifier/models"
2022-11-20 17:19:11 +01:00
"bytes"
2022-11-19 14:57:45 +01:00
"context"
_ "embed"
2022-11-20 17:19:11 +01:00
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
2022-11-19 14:57:45 +01:00
"github.com/rs/zerolog/log"
2022-11-19 15:13:47 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2022-11-20 17:19:11 +01:00
"io"
"net/http"
2022-11-19 15:13:47 +01:00
"strconv"
2023-06-18 01:29:13 +02:00
"strings"
2022-11-20 17:19:11 +01:00
"time"
2022-11-19 14:57:45 +01:00
)
2022-11-20 17:19:11 +01:00
// https://firebase.google.com/docs/cloud-messaging/send-message#rest
// https://firebase.google.com/docs/cloud-messaging/auth-server
2022-11-19 14:57:45 +01:00
2022-11-23 19:32:23 +01:00
type FirebaseConnector struct {
2022-11-20 17:19:11 +01:00
fbProject string
client http.Client
2022-11-23 19:32:23 +01:00
auth *FirebaseOAuth2
2022-11-19 14:57:45 +01:00
}
2022-11-23 19:32:23 +01:00
func NewFirebaseConn(conf scn.Config) (NotificationClient, error) {
2022-11-20 17:19:11 +01:00
2023-06-18 01:29:13 +02:00
pkey := strings.ReplaceAll(conf.FirebasePrivateKey, "\\n", "\n")
fbauth, err := NewAuth(conf.FirebaseTokenURI, conf.FirebaseProjectID, conf.FirebaseClientMail, pkey)
2022-11-19 14:57:45 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
return nil, err
2022-11-19 14:57:45 +01:00
}
2022-11-20 17:19:11 +01:00
2022-11-23 19:32:23 +01:00
return &FirebaseConnector{
2022-11-20 17:19:11 +01:00
fbProject: conf.FirebaseProjectID,
client: http.Client{Timeout: 5 * time.Second},
auth: fbauth,
}, nil
2022-11-19 14:57:45 +01:00
}
type Notification struct {
Id string
Token string
Platform string
Title string
Body string
Priority int
}
func (fb FirebaseConnector) SendNotification(ctx context.Context, client models.Client, msg models.Message, compatTitleOverride *string, compatMsgIDOverride *string) (string, error) {
2022-11-20 17:19:11 +01:00
uri := "https://fcm.googleapis.com/v1/projects/" + fb.fbProject + "/messages:send"
2022-11-20 17:19:11 +01:00
jsonBody := gin.H{
"data": gin.H{
"scn_msg_id": langext.Coalesce(compatMsgIDOverride, msg.MessageID.String()),
"usr_msg_id": langext.Coalesce(msg.UserMessageID, ""),
2022-11-20 22:18:24 +01:00
"client_id": client.ClientID.String(),
"timestamp": strconv.FormatInt(msg.Timestamp().Unix(), 10),
"priority": strconv.Itoa(msg.Priority),
"trimmed": langext.Conditional(msg.NeedsTrim(), "true", "false"),
"title": langext.Coalesce(compatTitleOverride, msg.Title),
"body": langext.Coalesce(msg.TrimmedContent(), ""),
},
2023-05-28 23:25:18 +02:00
"token": client.FCMToken,
2022-11-20 17:19:11 +01:00
"android": gin.H{
"priority": "high",
2022-11-19 14:57:45 +01:00
},
2022-11-20 17:19:11 +01:00
"apns": gin.H{},
2022-11-19 14:57:45 +01:00
}
2022-11-19 15:13:47 +01:00
if client.Type == models.ClientTypeIOS {
2022-11-20 17:19:11 +01:00
jsonBody["notification"] = gin.H{
"title": msg.Title,
"body": msg.ShortContent(),
}
}
bytesBody, err := json.Marshal(gin.H{"message": jsonBody})
if err != nil {
return "", err
}
request, err := http.NewRequestWithContext(ctx, "POST", uri, bytes.NewBuffer(bytesBody))
if err != nil {
return "", err
2022-11-19 14:57:45 +01:00
}
2022-11-20 17:19:11 +01:00
tok, err := fb.auth.Token(ctx)
2022-11-19 14:57:45 +01:00
if err != nil {
2022-11-20 17:19:11 +01:00
log.Err(err).Msg("Refreshing FB token failed")
return "", err
2022-11-19 14:57:45 +01:00
}
2022-11-20 17:19:11 +01:00
request.Header.Set("Authorization", "Bearer "+tok)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
response, err := fb.client.Do(request)
if err != nil {
return "", err
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode < 200 || response.StatusCode >= 300 {
if bstr, err := io.ReadAll(response.Body); err == nil {
return "", errors.New(fmt.Sprintf("FCM-Request returned %d: %s", response.StatusCode, string(bstr)))
} else {
return "", errors.New(fmt.Sprintf("FCM-Request returned %d", response.StatusCode))
}
}
respBodyBin, err := io.ReadAll(response.Body)
if err != nil {
return "", err
}
var respBody struct {
Name string `json:"name"`
}
if err := json.Unmarshal(respBodyBin, &respBody); err != nil {
return "", err
}
2023-06-18 01:36:34 +02:00
log.Info().Msg(fmt.Sprintf("Sucessfully pushed notification %s", msg.MessageID))
2022-11-20 17:19:11 +01:00
return respBody.Name, nil
2022-11-19 14:57:45 +01:00
}