Firebase is back

This commit is contained in:
2024-06-06 22:48:43 +08:00
parent f1ab0f203f
commit 6a37ee4487
8 changed files with 291 additions and 52 deletions

View File

@ -46,6 +46,9 @@ func main() {
}
// Connect other services
if err := services.SetupFirebase(); err != nil {
log.Error().Err(err).Msg("An error occurred when connecting firebase...")
}
if err := grpc.ConnectPaperclip(); err != nil {
log.Fatal().Err(err).Msg("An error occurred when connecting to paperclip...")
}

View File

@ -28,7 +28,7 @@ type NotificationLink struct {
}
const (
NotifySubscriberAPN = "apple"
NotifySubscriberFirebase = "firebase"
)
type NotificationSubscriber struct {

View File

@ -0,0 +1,22 @@
package services
import (
"context"
firebase "firebase.google.com/go"
"github.com/spf13/viper"
"google.golang.org/api/option"
)
var ExtFire *firebase.App
func SetupFirebase() error {
opt := option.WithCredentialsFile(viper.GetString("firebase_credentials"))
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return err
} else {
ExtFire = app
}
return nil
}

View File

@ -1,6 +1,8 @@
package services
import (
"context"
"firebase.google.com/go/messaging"
"reflect"
"git.solsynth.dev/hydrogen/passport/pkg/database"
@ -54,13 +56,20 @@ func NewNotification(notification models.Notification) error {
}
func PushNotification(notification models.Notification) error {
frontendAvailable := false
for conn := range wsConn[notification.RecipientID] {
frontendAvailable = true
_ = conn.WriteMessage(1, models.UnifiedCommand{
Action: "notifications.new",
Payload: notification,
}.Marshal())
}
// Skip push notification when frontend notify is available
if frontendAvailable {
return nil
}
var subscribers []models.NotificationSubscriber
if err := database.C.Where(&models.NotificationSubscriber{
AccountID: notification.RecipientID,
@ -70,7 +79,32 @@ func PushNotification(notification models.Notification) error {
for _, subscriber := range subscribers {
switch subscriber.Provider {
case models.NotifySubscriberAPN:
case models.NotifySubscriberFirebase:
if ExtFire != nil {
ctx := context.Background()
client, err := ExtFire.Messaging(ctx)
if err != nil {
log.Warn().Err(err).Msg("An error occurred when creating FCM client...")
break
}
message := &messaging.Message{
Notification: &messaging.Notification{
Title: notification.Subject,
Body: notification.Content,
},
Token: subscriber.DeviceToken,
}
if response, err := client.Send(ctx, message); err != nil {
log.Warn().Err(err).Msg("An error occurred when notify subscriber via FCM...")
} else {
log.Debug().
Str("response", response).
Int("subscriber", int(subscriber.ID)).
Msg("Notified subscriber via FCM.")
}
}
}
}