Skip to content

Commit

Permalink
Add SendDataNotification method (#1352)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro Pombeiro authored and mandrigin committed Jan 18, 2019
1 parent cfa9368 commit 2e44491
Show file tree
Hide file tree
Showing 10 changed files with 110 additions and 77 deletions.
6 changes: 3 additions & 3 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
name = "github.com/golang/protobuf"
version = "1.1.0"

[[constraint]]
name = "github.com/NaySoftware/go-fcm"
revision = "024ca6a2c5444c93980f558f91c35a2defebd362"
source = "github.com/status-im/go-fcm"

# * * * * * `go-ethereum` dependencies * * * * *
# Pinned down SHAs from `go-ethereum/vendor/vendor.json`
# When upgrading upstream, upgrade these values too.
Expand Down
21 changes: 16 additions & 5 deletions api/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math/big"
"sync"

fcmlib "github.com/NaySoftware/go-fcm"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
Expand Down Expand Up @@ -463,11 +462,23 @@ func (b *StatusBackend) SelectAccount(address, password string) error {
return nil
}

// NotifyUsers sends push notifications to users.
func (b *StatusBackend) NotifyUsers(message string, payload fcmlib.NotificationPayload, tokens ...string) error {
err := b.newNotification().Send(message, payload, tokens...)
// SendDataNotification sends data push notifications to users.
// dataPayloadJSON is a JSON string that looks like this:
// {
// "data": {
// "msg-v2": {
// "from": "0x2cea3bd5", // hash of sender (first 10 characters/4 bytes of sha3 hash)
// "to": "0xb1f89744", // hash of recipient (first 10 characters/4 bytes of sha3 hash)
// "id": "0x872653ad", // message ID hash (first 10 characters/4 bytes of sha3 hash)
// }
// }
// }
func (b *StatusBackend) SendDataNotification(dataPayloadJSON string, tokens ...string) error {
log.Debug("sending data push notification")

err := b.newNotification().Send(dataPayloadJSON, tokens...)
if err != nil {
b.log.Error("Notify failed", "error", err)
b.log.Error("SendDataNotification failed", "dataPayloadJSON", dataPayloadJSON, "error", err)
}

return err
Expand Down
30 changes: 16 additions & 14 deletions lib/library.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"os"
"unsafe"

"github.com/NaySoftware/go-fcm"
"github.com/ethereum/go-ethereum/log"
"github.com/status-im/status-go/api"
"github.com/status-im/status-go/logutils"
Expand Down Expand Up @@ -421,24 +420,34 @@ func makeJSONResponse(err error) *C.char {
return C.CString(string(outBytes))
}

// NotifyUsers sends push notifications by given tokens.
//export NotifyUsers
func NotifyUsers(message, payloadJSON, tokensArray *C.char) (outCBytes *C.char) {
// SendDataNotification sends push notifications by given tokens.
// dataPayloadJSON is a JSON string that looks like this:
// {
// "data": {
// "msg-v2": {
// "from": "0x2cea3bd5", // hash of sender (first 10 characters/4 bytes of sha3 hash)
// "to": "0xb1f89744", // hash of recipient (first 10 characters/4 bytes of sha3 hash)
// "id": "0x872653ad", // message ID hash (first 10 characters/4 bytes of sha3 hash)
// }
// }
// }
//export SendDataNotification
func SendDataNotification(dataPayloadJSON, tokensArray *C.char) (outCBytes *C.char) {
var (
err error
outBytes []byte
)
errString := ""

defer func() {
out := NotifyResult{
out := SendDataNotificationResult{
Status: err == nil,
Error: errString,
}

outBytes, err = json.Marshal(out)
if err != nil {
logger.Error("failed to marshal Notify output", "error", err)
logger.Error("failed to marshal SendDataNotification output", "error", err)
outCBytes = makeJSONResponse(err)
return
}
Expand All @@ -452,14 +461,7 @@ func NotifyUsers(message, payloadJSON, tokensArray *C.char) (outCBytes *C.char)
return
}

var payload fcm.NotificationPayload
err = json.Unmarshal([]byte(C.GoString(payloadJSON)), &payload)
if err != nil {
errString = err.Error()
return
}

err = statusBackend.NotifyUsers(C.GoString(message), payload, tokens...)
err = statusBackend.SendDataNotification(C.GoString(dataPayloadJSON), tokens...)
if err != nil {
errString = err.Error()
return
Expand Down
4 changes: 2 additions & 2 deletions lib/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ type AccountInfo struct {
Error string `json:"error"`
}

// NotifyResult is a JSON returned from notify message.
type NotifyResult struct {
// SendDataNotificationResult is a JSON returned from notify message.
type SendDataNotificationResult struct {
Status bool `json:"status"`
Error string `json:"error,omitempty"`
}
1 change: 0 additions & 1 deletion notifications/push/fcm/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ import (
type FirebaseClient interface {
NewFcmRegIdsMsg(tokens []string, body interface{}) *gofcm.FcmClient
Send() (*gofcm.FcmResponseStatus, error)
SetNotificationPayload(payload *gofcm.NotificationPayload) *gofcm.FcmClient
}
14 changes: 2 additions & 12 deletions notifications/push/fcm/client_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 17 additions & 16 deletions notifications/push/fcm/notification.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package fcm

import (
"encoding/json"
"fmt"

"github.com/NaySoftware/go-fcm"
)

// Notifier manages Push Notifications.
type Notifier interface {
Send(body string, payload fcm.NotificationPayload, tokens ...string) error
Send(dataPayloadJSON string, tokens ...string) error
}

// NotificationConstructor returns constructor of configured instance Notifier interface.
Expand All @@ -25,30 +26,30 @@ func NewNotification(key string) NotificationConstructor {
client := fcm.NewFcmClient(key).
SetDelayWhileIdle(true).
SetContentAvailable(true).
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)
SetTimeToLive(fcm.MAX_TTL)

return &Notification{client}
}
}

// Send send to the tokens list.
func (n *Notification) Send(body string, payload fcm.NotificationPayload, tokens ...string) error {
data := map[string]string{
"msg": body,
// 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
}

if payload.Title == "" {
payload.Title = "Status"
n.client.NewFcmRegIdsMsg(tokens, dataPayload)
resp, err := n.client.Send()
if err != nil {
return err
}
if payload.Body == "" {
payload.Body = "You have a new message"
}

fmt.Println(payload.Title, payload.Body)

n.client.NewFcmRegIdsMsg(tokens, data)
n.client.SetNotificationPayload(&payload)
_, err := n.client.Send()
if resp != nil && !resp.Ok {
return fmt.Errorf("FCM error sending message, code=%d err=%s", resp.StatusCode, resp.Err)
}

return err
return nil
}
57 changes: 33 additions & 24 deletions notifications/push/fcm/notification_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package fcm

import (
"encoding/json"
"errors"
"testing"

"github.com/NaySoftware/go-fcm"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/suite"
)
Expand All @@ -29,43 +29,52 @@ func (s *NotifierTestSuite) TearDownTest() {
s.fcmClientMockCtrl.Finish()
}

func (s *NotifierTestSuite) TestNotifySuccess() {
fcmPayload := getPayload()
func (s *NotifierTestSuite) TestSendSuccess() {
ids := []string{"1"}
payload := fcmPayload
msg := make(map[string]string)
body := "body1"
msg["msg"] = body

s.fcmClientMock.EXPECT().SetNotificationPayload(&fcmPayload).Times(1)
s.fcmClientMock.EXPECT().NewFcmRegIdsMsg(ids, msg).Times(1)
dataPayload := make(map[string]string)
dataPayload["from"] = "a"
dataPayload["to"] = "b"
dataPayloadByteArray, err := json.Marshal(dataPayload)
s.Require().NoError(err)
dataPayloadJSON := string(dataPayloadByteArray)

s.fcmClientMock.EXPECT().NewFcmRegIdsMsg(ids, dataPayload).Times(1)
s.fcmClientMock.EXPECT().Send().Return(nil, nil).Times(1)
fcmClient := Notification{s.fcmClientMock}

err := fcmClient.Send(body, payload, ids...)
err = fcmClient.Send(dataPayloadJSON, ids...)

s.NoError(err)
}

func (s *NotifierTestSuite) TestNotifyError() {
func (s *NotifierTestSuite) TestSendError() {
expectedError := errors.New("error")
fcmPayload := getPayload()
ids := []string{"1"}
payload := fcmPayload
msg := make(map[string]string)
body := "body2"
msg["msg"] = body

s.fcmClientMock.EXPECT().SetNotificationPayload(&fcmPayload).Times(1)
s.fcmClientMock.EXPECT().NewFcmRegIdsMsg(ids, msg).Times(1)
ids := []string{"2"}
dataPayload := make(map[string]string)
dataPayload["from"] = "c"
dataPayload["to"] = "d"
dataPayloadByteArray, err := json.Marshal(dataPayload)
s.Require().NoError(err)
dataPayloadJSON := string(dataPayloadByteArray)

s.fcmClientMock.EXPECT().NewFcmRegIdsMsg(ids, dataPayload).Times(1)
s.fcmClientMock.EXPECT().Send().Return(nil, expectedError).Times(1)
fcmClient := Notification{s.fcmClientMock}

err := fcmClient.Send(body, payload, ids...)
err = fcmClient.Send(dataPayloadJSON, ids...)

s.Equal(expectedError, err)
}

func getPayload() fcm.NotificationPayload {
return fcm.NotificationPayload{Title: "Status - new message", Body: "sum"}
func (s *NotifierTestSuite) TestSendWithInvalidJSON() {
ids := []string{"3"}
dataPayloadJSON := "{a=b}"

fcmClient := Notification{s.fcmClientMock}

err := fcmClient.Send(dataPayloadJSON, ids...)
s.Require().Error(err)

_, ok := err.(*json.SyntaxError)
s.True(ok)
}
16 changes: 16 additions & 0 deletions vendor/github.com/NaySoftware/go-fcm/fcm.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 2e44491

Please sign in to comment.