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