SimpleCloudNotifier/server/firebase/firebase.go

88 lines
2.1 KiB
Go
Raw Normal View History

2022-11-19 14:57:45 +01:00
package firebase
import (
2022-11-19 15:13:47 +01:00
"blackforestbytes.com/simplecloudnotifier/models"
2022-11-19 14:57:45 +01:00
"context"
_ "embed"
fb "firebase.google.com/go"
"firebase.google.com/go/messaging"
"github.com/rs/zerolog/log"
2022-11-19 15:13:47 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2022-11-19 14:57:45 +01:00
"google.golang.org/api/option"
2022-11-19 15:13:47 +01:00
"strconv"
2022-11-19 14:57:45 +01:00
)
//go:embed scnserviceaccountkey.json
var scnserviceaccountkey []byte
type App struct {
app *fb.App
messaging *messaging.Client
}
func NewFirebaseApp() App {
opt := option.WithCredentialsJSON(scnserviceaccountkey)
app, err := fb.NewApp(context.Background(), nil, opt)
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,
}
}
type Notification struct {
Id string
Token string
Platform string
Title string
Body string
Priority int
}
2022-11-19 15:13:47 +01:00
func (fb App) SendNotification(ctx context.Context, client models.Client, msg models.Message) (string, error) {
2022-11-19 14:57:45 +01:00
n := messaging.Message{
Data: map[string]string{
"scn_msg_id": strconv.FormatInt(msg.SCNMessageID, 10),
"usr_msg_id": langext.Coalesce(msg.UserMessageID, ""),
2022-11-20 01:28:32 +01:00
"client_id": strconv.FormatInt(client.ClientID, 10),
"timestamp": strconv.FormatInt(msg.Timestamp().Unix(), 10),
"priority": strconv.Itoa(msg.Priority),
"trimmed": langext.Conditional(msg.NeedsTrim(), "true", "false"),
"title": msg.Title,
"body": langext.Coalesce(msg.TrimmedContent(), ""),
},
2022-11-19 14:57:45 +01:00
Notification: &messaging.Notification{
2022-11-19 15:13:47 +01:00
Title: msg.Title,
Body: msg.ShortContent(),
2022-11-19 14:57:45 +01:00
},
Android: nil,
APNS: nil,
Webpush: nil,
FCMOptions: nil,
2022-11-19 15:13:47 +01:00
Token: *client.FCMToken,
2022-11-19 14:57:45 +01:00
Topic: "",
Condition: "",
}
2022-11-19 15:13:47 +01:00
if client.Type == models.ClientTypeIOS {
2022-11-19 14:57:45 +01:00
n.APNS = nil
} else if client.Type == models.ClientTypeAndroid {
n.Notification = nil
n.Android = &messaging.AndroidConfig{Priority: "high"}
2022-11-19 14:57:45 +01:00
}
res, err := fb.messaging.Send(ctx, &n)
if err != nil {
log.Error().Err(err).Msg("failed to send push")
}
return res, err
}