1
0
Fork 0
forked from mirrors/ntfy
ntfy/server/server_firebase.go

90 lines
2.4 KiB
Go
Raw Normal View History

2022-02-01 01:06:48 +00:00
package server
import (
"context"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
"fmt"
"google.golang.org/api/option"
"heckel.io/ntfy/auth"
"strings"
)
2022-02-01 01:12:47 +00:00
func createFirebaseSubscriber(credentialsFile string, auther auth.Auther) (subscriber, error) {
fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(credentialsFile))
2022-02-01 01:06:48 +00:00
if err != nil {
return nil, err
}
msg, err := fb.Messaging(context.Background())
if err != nil {
return nil, err
}
2022-02-01 01:12:47 +00:00
return func(m *message) error {
fbm, err := toFirebaseMessage(m, auther)
if err != nil {
return err
}
_, err = msg.Send(context.Background(), fbm)
2022-02-01 01:06:48 +00:00
return err
}, nil
}
2022-02-01 01:12:47 +00:00
func toFirebaseMessage(m *message, auther auth.Auther) (*messaging.Message, error) {
var data map[string]string // Mostly matches https://ntfy.sh/docs/subscribe/api/#json-message-format
switch m.Event {
case keepaliveEvent, openEvent:
data = map[string]string{
"id": m.ID,
"time": fmt.Sprintf("%d", m.Time),
"event": m.Event,
"topic": m.Topic,
}
case messageEvent:
allowForward := true
if auther != nil {
allowForward = auther.Authorize(nil, m.Topic, auth.PermissionRead) == nil
}
if allowForward {
data = map[string]string{
"id": m.ID,
"time": fmt.Sprintf("%d", m.Time),
"event": m.Event,
"topic": m.Topic,
"priority": fmt.Sprintf("%d", m.Priority),
"tags": strings.Join(m.Tags, ","),
"click": m.Click,
"title": m.Title,
"message": m.Message,
"encoding": m.Encoding,
}
if m.Attachment != nil {
data["attachment_name"] = m.Attachment.Name
data["attachment_type"] = m.Attachment.Type
data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
data["attachment_url"] = m.Attachment.URL
}
} else {
// If anonymous read for a topic is not allowed, we cannot send the message along
// via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
2022-02-01 01:06:48 +00:00
data = map[string]string{
"id": m.ID,
"time": fmt.Sprintf("%d", m.Time),
2022-02-01 01:12:47 +00:00
"event": pollRequestEvent,
2022-02-01 01:06:48 +00:00
"topic": m.Topic,
}
}
2022-02-01 01:12:47 +00:00
}
var androidConfig *messaging.AndroidConfig
if m.Priority >= 4 {
androidConfig = &messaging.AndroidConfig{
Priority: "high",
2022-02-01 01:06:48 +00:00
}
2022-02-01 01:12:47 +00:00
}
return maybeTruncateFCMMessage(&messaging.Message{
Topic: m.Topic,
Data: data,
Android: androidConfig,
}), nil
2022-02-01 01:06:48 +00:00
}