78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
package notifications
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
|
|
firebase "firebase.google.com/go/v4"
|
|
"firebase.google.com/go/v4/messaging"
|
|
"google.golang.org/api/option"
|
|
)
|
|
|
|
type FCMService struct {
|
|
app *firebase.App
|
|
client *messaging.Client
|
|
}
|
|
|
|
func NewFCMService(serviceAccountJSON []byte) (*FCMService, error) {
|
|
ctx := context.Background()
|
|
opt := option.WithCredentialsJSON(serviceAccountJSON)
|
|
|
|
app, err := firebase.NewApp(ctx, nil, opt)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error initializing firebase app: %w", err)
|
|
}
|
|
|
|
client, err := app.Messaging(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error getting messaging client: %w", err)
|
|
}
|
|
|
|
return &FCMService{
|
|
app: app,
|
|
client: client,
|
|
}, nil
|
|
}
|
|
|
|
func (s *FCMService) SendPush(ctx context.Context, token, title, body string, data map[string]string) error {
|
|
message := &messaging.Message{
|
|
Token: token,
|
|
Notification: &messaging.Notification{
|
|
Title: title,
|
|
Body: body,
|
|
},
|
|
Data: data,
|
|
}
|
|
|
|
response, err := s.client.Send(ctx, message)
|
|
if err != nil {
|
|
return fmt.Errorf("error sending fcm message: %w", err)
|
|
}
|
|
|
|
log.Printf("Successfully sent fcm message: %s", response)
|
|
return nil
|
|
}
|
|
|
|
func (s *FCMService) SendMulticast(ctx context.Context, tokens []string, title, body string, data map[string]string) error {
|
|
if len(tokens) == 0 {
|
|
return nil
|
|
}
|
|
|
|
message := &messaging.MulticastMessage{
|
|
Tokens: tokens,
|
|
Notification: &messaging.Notification{
|
|
Title: title,
|
|
Body: body,
|
|
},
|
|
Data: data,
|
|
}
|
|
|
|
br, err := s.client.SendEachForMulticast(ctx, message)
|
|
if err != nil {
|
|
return fmt.Errorf("error sending multicast message: %w", err)
|
|
}
|
|
|
|
log.Printf("Multicast results: %d successes, %d failures", br.SuccessCount, br.FailureCount)
|
|
return nil
|
|
}
|