This repository has been archived by the owner on Oct 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpushover.go
74 lines (65 loc) · 1.86 KB
/
pushover.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
package pushover
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/samber/lo"
"github.com/nam-truong-le/lambda-utils-go/v4/pkg/logger"
"github.com/vietnam-immigrations/vs2-utils-go/v2/pkg/db"
)
const (
pushoverURL = "https://api.pushover.net/1/messages.json"
)
func Send(ctx context.Context, title, message string) error {
log := logger.FromContext(ctx)
// send ios push notification
err := sendToIOSApp(ctx, title, message)
if err != nil {
log.Errorf("Failed to send to ios app: %s", err)
// will not return here, continue to send pushover
}
log.Infof("Pushover message [%s]", title)
cfg, err := db.GetConfig(ctx)
if err != nil {
log.Errorf("Failed to get global config: %s", err)
return err
}
users := lo.Map(strings.Split(cfg.PushoverUsers, ","), func(item string, _ int) string {
return strings.TrimSpace(item)
})
log.Infof("Pushover to users: %s", strings.Join(users, ", "))
httpClient := http.Client{
Timeout: 30 * time.Second,
}
errs := make([]error, 0)
for _, user := range users {
form := url.Values{
"token": []string{cfg.PushoverToken},
"user": []string{user},
"message": []string{message},
"title": []string{title},
"html": []string{"1"},
}
res, err := httpClient.PostForm(pushoverURL, form)
if err != nil {
log.Errorf("Failed to send http request to pushover [%s] to user [%s]: %s", title, user, err)
errs = append(errs, err)
continue
}
if res.StatusCode != 200 {
log.Errorf("Pushover [%s] to user [%s] returns [%d]", title, user, res.StatusCode)
errs = append(errs, err)
continue
}
log.Infof("Pushover succeeded [%s]: %s", user, title)
}
if len(errs) > 0 {
log.Errorf("Pushover error")
errMessages := lo.Map(errs, func(e error, _ int) string { return e.Error() })
return fmt.Errorf("pushover error: %s", strings.Join(errMessages, " | "))
}
return nil
}