2017-10-11 13:51:43 +00:00
package fcm
import (
2019-01-18 13:03:32 +00:00
"encoding/json"
2017-10-23 15:46:51 +00:00
"fmt"
2017-10-11 13:51:43 +00:00
"github.com/NaySoftware/go-fcm"
)
2018-03-23 08:55:05 +00:00
// Notifier manages Push Notifications.
type Notifier interface {
2019-01-18 13:03:32 +00:00
Send ( dataPayloadJSON string , tokens ... string ) error
2018-03-23 08:55:05 +00:00
}
// NotificationConstructor returns constructor of configured instance Notifier interface.
type NotificationConstructor func ( ) Notifier
2017-10-18 20:56:39 +00:00
// Notification represents messaging provider for notifications.
type Notification struct {
2018-04-05 13:14:47 +00:00
client FirebaseClient
2017-10-11 13:51:43 +00:00
}
2017-10-18 20:56:39 +00:00
// NewNotification Firebase Cloud Messaging client constructor.
2018-03-23 08:55:05 +00:00
func NewNotification ( key string ) NotificationConstructor {
return func ( ) Notifier {
2017-10-23 15:46:51 +00:00
client := fcm . NewFcmClient ( key ) .
SetDelayWhileIdle ( true ) .
SetContentAvailable ( true ) .
2019-01-18 13:03:32 +00:00
SetPriority ( fcm . Priority_HIGH ) . // Message needs to be marked as high-priority so that background task in an Android's recipient device can be invoked (https://github.com/invertase/react-native-firebase/blob/d13f0af53f1c8f20db8bc8d4b6f8c6d210e108b9/android/src/main/java/io/invertase/firebase/messaging/RNFirebaseMessagingService.java#L56)
2017-10-23 15:46:51 +00:00
SetTimeToLive ( fcm . MAX_TTL )
return & Notification { client }
2017-10-12 14:31:14 +00:00
}
2017-10-11 13:51:43 +00:00
}
2019-01-18 13:03:32 +00:00
// Send sends a push notification to the tokens list.
func ( n * Notification ) Send ( dataPayloadJSON string , tokens ... string ) error {
var dataPayload map [ string ] string
err := json . Unmarshal ( [ ] byte ( dataPayloadJSON ) , & dataPayload )
if err != nil {
return err
2017-10-23 15:46:51 +00:00
}
2017-10-11 13:51:43 +00:00
2019-01-18 13:03:32 +00:00
n . client . NewFcmRegIdsMsg ( tokens , dataPayload )
resp , err := n . client . Send ( )
if err != nil {
return err
2017-10-23 15:46:51 +00:00
}
2019-01-14 12:09:51 +00:00
2019-01-18 13:03:32 +00:00
if resp != nil && ! resp . Ok {
return fmt . Errorf ( "FCM error sending message, code=%d err=%s" , resp . StatusCode , resp . Err )
}
2019-01-14 12:09:51 +00:00
2019-01-18 13:03:32 +00:00
return nil
2017-10-11 13:51:43 +00:00
}