Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat push notifications #65

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions fcm/message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package fcm

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"

"golang.org/x/oauth2/google"
)

// TODO Fix log usage

const (
scopeURL = "https://www.googleapis.com/auth/firebase.messaging"
// Get file serviceaccount file from config
credFile = ""
)

type Message struct {
MessageContent `json:"message"`
}

type MessageContent struct {
Token string `json:"token"`
Notification *NotificationContent `json:"notification,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
}

type NotificationContent struct {
Title string `json:"title"`
Body string `json:"body"`
}

type MessageOption func(*MessageContent)

func WithData(data map[string]interface{}) MessageOption {
return func(m *MessageContent) {
m.Data = data
}
}

func WithNotification(title string, body string) MessageOption {
return func(m *MessageContent) {
m.Notification = &NotificationContent{
Title: title,
Body: body,
}
}
}

func NewMessage(token string, opts ...MessageOption) *Message {
if token == "" {
log.Fatalf("Token is mandatory for FCM message")
}

msg := &Message{
MessageContent: MessageContent{
Token: token,
},
}
for _, opt := range opts {
opt(&msg.MessageContent)
}
return msg
}

func Send(token string, msg *Message) error {
// TODO Parse project id from service-account json
projectId := ""
fcmEndpoint := fmt.Sprintf("https://fcm.googleapis.com/v1/projects/%s/messages:send", projectId)

// Convert the message to JSON
payload, err := json.Marshal(msg)
if err != nil {
return err
}

fmt.Println(string(payload))

// Create a new HTTP request
req, err := http.NewRequest("POST", fcmEndpoint, bytes.NewBuffer(payload))
if err != nil {
return err
}

// Set headers
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")

// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

// Check for errors in the response
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return errors.New(string(body))
}

return nil
}

func GetAccessToken() string {
data, err := os.ReadFile(credFile)
if err != nil {
log.Fatalf("Failed to read the credential file: %v", err)
}

conf, err := google.JWTConfigFromJSON(data, scopeURL)
if err != nil {
log.Fatalf("Failed to parse the credential file: %v", err)
}

token, err := conf.TokenSource(context.Background()).Token()
if err != nil {
log.Fatalf("Failed to get token: %v", err)
}

fmt.Println(token.AccessToken)
return token.AccessToken
}
7 changes: 7 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ require (
// replace github.com/blinklabs-io/gouroboros v0.52.0 => ../gouroboros

require (
cloud.google.com/go/compute v1.20.1 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
github.com/fxamacker/cbor/v2 v2.4.0 // indirect
github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
Expand All @@ -24,4 +26,9 @@ require (
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/crypto v0.12.0 // indirect
golang.org/x/sys v0.11.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/oauth2 v0.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect
)
22 changes: 19 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
github.com/blinklabs-io/gouroboros v0.52.0 h1:5abdw2PXHKHxve26BITukfAzz7OJoTPKWylbyth9Sxk=
github.com/blinklabs-io/gouroboros v0.52.0/go.mod h1:2wCCNNsHNYMT4gQB+bXS0Y99Oeu8+EM96hi7hW22C2w=
cloud.google.com/go/compute v1.20.1 h1:6aKEtlUiwEpJzM001l0yFkpXmUVXaN8W+fbkb2AZNbg=
cloud.google.com/go/compute v1.20.1/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM=
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/blinklabs-io/gouroboros v0.48.0 h1:A3mqNX1C8QtW/CoIoF3iyXfKPrKyfyWfbjzdnkwj6Jw=
github.com/blinklabs-io/gouroboros v0.48.0/go.mod h1:WBghLJF3Im3hXjMd8BFk929tfuSjcUZdn2zE2xtZJEo=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88=
github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo=
Expand Down Expand Up @@ -29,6 +34,17 @@ go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=
go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=
golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU=
golang.org/x/oauth2 v0.11.0/go.mod h1:LdF7O/8bLR/qWK9DrpXmbHLTouvRHK0SgJl0GmDBchk=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
1 change: 1 addition & 0 deletions output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ package output
import (
_ "github.com/blinklabs-io/snek/output/log"
_ "github.com/blinklabs-io/snek/output/notify"
_ "github.com/blinklabs-io/snek/output/push"
)
17 changes: 17 additions & 0 deletions output/push/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2023 Blink Labs, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package push

type PushOptionFunc func(*PushOutput)
36 changes: 36 additions & 0 deletions output/push/plugin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2023 Blink Labs, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package push

import (
"github.com/blinklabs-io/snek/plugin"
)

func init() {
plugin.Register(
plugin.PluginEntry{
Type: plugin.PluginTypeOutput,
Name: "push",
Description: "Send push notifications for events",
NewFromOptionsFunc: NewFromCmdlineOptions,
Options: []plugin.PluginOption{}, // Define any options if needed
},
)
}

func NewFromCmdlineOptions() plugin.Plugin {
p := New()
return p
}
143 changes: 143 additions & 0 deletions output/push/push.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Copyright 2023 Blink Labs, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package push

import (
"fmt"
"log"

"github.com/blinklabs-io/snek/event"
"github.com/blinklabs-io/snek/fcm"
"github.com/blinklabs-io/snek/input/chainsync"
)

type PushOutput struct {
errorChan chan error
eventChan chan event.Event
}

type Notification struct {
Tokens []string `json:"tokens"`
Platform int `json:"platform"`
Message string `json:"message"`
}

type PushPayload struct {
Notifications []Notification `json:"notifications"`
}

func New(options ...PushOptionFunc) *PushOutput {
p := &PushOutput{
errorChan: make(chan error),
eventChan: make(chan event.Event, 10),
}
for _, option := range options {
option(p)
}
return p
}

func (p *PushOutput) Start() error {
go func() {
for {
evt, ok := <-p.eventChan
// Channel has been closed, which means we're shutting down
if !ok {
return
}
switch evt.Type {
case "chainsync.block":
payload := evt.Payload
if payload == nil {
panic(fmt.Errorf("ERROR: %v", payload))
}

be := payload.(chainsync.BlockEvent)
fmt.Println("Snek")
fmt.Printf("New Block!\nBlockNumber: %d, SlotNumber: %d\nHash: %s",
be.BlockNumber,
be.SlotNumber,
be.BlockHash,
)
case "chainsync.rollback":
payload := evt.Payload
if payload == nil {
panic(fmt.Errorf("ERROR: %v", payload))
}

re := payload.(chainsync.RollbackEvent)
fmt.Println("Snek")
fmt.Printf("Rollback!\nSlotNumber: %d\nBlockHash: %s",
re.SlotNumber,
re.BlockHash,
)
case "chainsync.transaction":
payload := evt.Payload
if payload == nil {
panic(fmt.Errorf("ERROR: %v", payload))
}

te := payload.(chainsync.TransactionEvent)
accessToken := fcm.GetAccessToken()
// TODO define where tokens will be fetched from or we add this to topic
fcmToken := ""
title := "Snek"
body := fmt.Sprintf("New Transaction!\nBlockNumber: %d, SlotNumber: %d\nInputs: %d, Outputs: %d\nHash: %s",
te.BlockNumber,
te.SlotNumber,
len(te.Inputs),
len(te.Outputs),
te.TransactionHash,
)
msg := fcm.NewMessage(
fcmToken,
fcm.WithNotification(title, body),
)
err := fcm.Send(accessToken, msg)
if err != nil {
log.Fatalf("Failed to send message: %v", err)
}
fmt.Println("Message 1 sent successfully!")

default:
fmt.Println("Snek")
fmt.Printf("New Event!\nEvent: %v", evt)
}
}
}()
return nil
}

// Stop the embedded output
func (p *PushOutput) Stop() error {
close(p.eventChan)
close(p.errorChan)
return nil
}

// ErrorChan returns the input error channel
func (p *PushOutput) ErrorChan() chan error {
return p.errorChan
}

// InputChan returns the input event channel
func (p *PushOutput) InputChan() chan<- event.Event {
return p.eventChan
}

// OutputChan always returns nil
func (p *PushOutput) OutputChan() <-chan event.Event {
return nil
}
Loading