firebase via REST (less dependencies)
This commit is contained in:
@@ -1,40 +1,44 @@
|
||||
package firebase
|
||||
|
||||
import (
|
||||
scn "blackforestbytes.com/simplecloudnotifier"
|
||||
"blackforestbytes.com/simplecloudnotifier/models"
|
||||
"bytes"
|
||||
"context"
|
||||
_ "embed"
|
||||
fb "firebase.google.com/go"
|
||||
"firebase.google.com/go/messaging"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/rs/zerolog/log"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
"google.golang.org/api/option"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed scnserviceaccountkey.json
|
||||
var scnserviceaccountkey []byte
|
||||
// https://firebase.google.com/docs/cloud-messaging/send-message#rest
|
||||
// https://firebase.google.com/docs/cloud-messaging/auth-server
|
||||
|
||||
type App struct {
|
||||
app *fb.App
|
||||
messaging *messaging.Client
|
||||
type FBConnector struct {
|
||||
fbProject string
|
||||
client http.Client
|
||||
auth *FBOAuth2
|
||||
}
|
||||
|
||||
func NewFirebaseApp() App {
|
||||
opt := option.WithCredentialsJSON(scnserviceaccountkey)
|
||||
app, err := fb.NewApp(context.Background(), nil, opt)
|
||||
func NewFirebase(conf scn.Config) (*FBConnector, error) {
|
||||
|
||||
fbauth, err := NewAuth(conf.FirebaseTokenURI, conf.FirebaseProjectID, conf.FirebaseClientMail, conf.FirebasePrivateKey)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to init firebase app")
|
||||
}
|
||||
msg, err := app.Messaging(context.Background())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to init messaging client")
|
||||
}
|
||||
log.Info().Msg("Initialized Firebase")
|
||||
return App{
|
||||
app: app,
|
||||
messaging: msg,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FBConnector{
|
||||
fbProject: conf.FirebaseProjectID,
|
||||
client: http.Client{Timeout: 5 * time.Second},
|
||||
auth: fbauth,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
@@ -46,10 +50,12 @@ type Notification struct {
|
||||
Priority int
|
||||
}
|
||||
|
||||
func (fb App) SendNotification(ctx context.Context, client models.Client, msg models.Message) (string, error) {
|
||||
func (fb FBConnector) SendNotification(ctx context.Context, client models.Client, msg models.Message) (string, error) {
|
||||
|
||||
n := messaging.Message{
|
||||
Data: map[string]string{
|
||||
uri := "https://fcm.googleapis.com/v1/projects/" + fb.fbProject + "/messages:send"
|
||||
|
||||
jsonBody := gin.H{
|
||||
"data": gin.H{
|
||||
"scn_msg_id": strconv.FormatInt(msg.SCNMessageID, 10),
|
||||
"usr_msg_id": langext.Coalesce(msg.UserMessageID, ""),
|
||||
"client_id": strconv.FormatInt(client.ClientID, 10),
|
||||
@@ -59,29 +65,64 @@ func (fb App) SendNotification(ctx context.Context, client models.Client, msg mo
|
||||
"title": msg.Title,
|
||||
"body": langext.Coalesce(msg.TrimmedContent(), ""),
|
||||
},
|
||||
Notification: &messaging.Notification{
|
||||
Title: msg.Title,
|
||||
Body: msg.ShortContent(),
|
||||
"token": *client.FCMToken,
|
||||
"android": gin.H{
|
||||
"priority": "high",
|
||||
},
|
||||
Android: nil,
|
||||
APNS: nil,
|
||||
Webpush: nil,
|
||||
FCMOptions: nil,
|
||||
Token: *client.FCMToken,
|
||||
Topic: "",
|
||||
Condition: "",
|
||||
"apns": gin.H{},
|
||||
}
|
||||
|
||||
if client.Type == models.ClientTypeIOS {
|
||||
n.APNS = nil
|
||||
} else if client.Type == models.ClientTypeAndroid {
|
||||
n.Notification = nil
|
||||
n.Android = &messaging.AndroidConfig{Priority: "high"}
|
||||
jsonBody["notification"] = gin.H{
|
||||
"title": msg.Title,
|
||||
"body": msg.ShortContent(),
|
||||
}
|
||||
}
|
||||
|
||||
res, err := fb.messaging.Send(ctx, &n)
|
||||
bytesBody, err := json.Marshal(gin.H{"message": jsonBody})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to send push")
|
||||
return "", err
|
||||
}
|
||||
return res, err
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, "POST", uri, bytes.NewBuffer(bytesBody))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
tok, err := fb.auth.Token(ctx)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("Refreshing FB token failed")
|
||||
return "", err
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return respBody.Name, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user