-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessages.go
90 lines (77 loc) · 2.09 KB
/
messages.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package notella
import (
"encoding/json"
"fmt"
"sync"
"time"
ll "github.com/gwennlbh/label-logger-go"
)
func (msg Message) ShouldRun() bool {
return time.Now().After(msg.SendAt)
}
func (msg Message) Run() error {
subs, users, err := msg.ShouldSendTo()
if err != nil {
return fmt.Errorf("could not determine what subscriptions to send the notification to: %w", err)
}
if len(subs) == 0 {
ll.Warn("no subscriptions to send notification [dim]%s[reset] ([bold]%s on %s[reset]) to", msg.Id, msg.Event, msg.ChurrosObjectId)
return nil
}
group, err := msg.Group()
if err != nil {
return fmt.Errorf("could not get churros responsible group for %s: %w", msg.ChurrosObjectId, err)
}
ll.Log("Sending", "green", "notification for %s on %s to %d users (%d subscriptions)", msg.Event, msg.ChurrosObjectId, len(users), len(subs))
// Separate native and webpush subscriptions
nativeSubs := make([]Subscription, 0, len(subs))
webpushSubs := make([]Subscription, 0, len(subs))
for _, sub := range subs {
if sub.IsNative() {
nativeSubs = append(nativeSubs, sub)
} else if sub.IsWebpush() {
webpushSubs = append(webpushSubs, sub)
} else {
ll.Warn("invalid subscription %#v", sub)
}
}
var wg sync.WaitGroup
wg.Add(3)
go func(wg *sync.WaitGroup) {
defer wg.Done()
msg.CreateInDatabaseNotifications(group, subs)
}(&wg)
go func(wg *sync.WaitGroup) {
defer wg.Done()
err := msg.SendToFirebase(group, nativeSubs)
if err != nil {
ll.ErrorDisplay("could not send notification via firebase", err)
}
}(&wg)
go func(wg *sync.WaitGroup) {
defer wg.Done()
err := msg.SendWebPush(group, webpushSubs)
if err != nil {
ll.ErrorDisplay("could not send notification via webpush", err)
}
}(&wg)
wg.Wait()
return nil
}
func (msg Message) JSONString() string {
out, err := json.Marshal(msg)
if err != nil {
return ""
}
return string(out)
}
func (msg Message) JSONBytes() []byte {
out, err := json.Marshal(msg)
if err != nil {
return nil
}
return out
}
func (msg Message) String() string {
return fmt.Sprintf("%-10s | %-10s on %s", msg.Id, msg.Event, msg.ChurrosObjectId)
}