SimpleCloudNotifier/server/firebase/firebase.go

78 lines
1.7 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{
2022-11-19 15:13:47 +01:00
Data: map[string]string{"scn_msg_id": strconv.FormatInt(msg.SCNMessageID, 10)},
2022-11-19 14:57:45 +01:00
Notification: &messaging.Notification{
2022-11-19 15:13:47 +01:00
Title: msg.Title,
Body: langext.Coalesce(msg.Content, ""),
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
}
2022-11-19 15:13:47 +01:00
if client.Type == models.ClientTypeAndroid {
2022-11-19 14:57:45 +01:00
n.Android = nil
}
res, err := fb.messaging.Send(ctx, &n)
if err != nil {
log.Error().Err(err).Msg("failed to send push")
}
return res, err
}