Debian Codegraph @

pkg/services/push/join/join.go

raw
1 package join
2
3 import (
4 "context"
5 "fmt"
6 "net/http"
7 "net/url"
8 "strings"
9
10 "github.com/nicholas-fedor/shoutrrr/pkg/format"
11 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
12 "github.com/nicholas-fedor/shoutrrr/pkg/types"
13 )
14
15 // Service sends notifications to Join devices.
16 type Service struct {
17 standard.Standard
18
19 Config *Config
20 pkr format.PropKeyResolver
21 }
22
23 const (
24 // hookURL defines the Join API endpoint for sending push notifications.
25 hookURL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush"
26 contentType = "text/plain"
27 )
28
29 // GetID returns the identifier for this service.
30 func (s *Service) GetID() string {
31 return Scheme
32 }
33
34 // Initialize configures the service with a URL and logger.
35 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
36 s.SetLogger(logger)
37 s.Config = &Config{}
38 s.pkr = format.NewPropKeyResolver(s.Config)
39
40 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
41 return err
42 }
43
44 return nil
45 }
46
47 // Send delivers a notification message to Join devices.
48 func (s *Service) Send(message string, params *types.Params) error {
49 config := s.Config
50
51 if params == nil {
52 params = &types.Params{}
53 }
54
55 title, found := (*params)["title"]
56 if !found {
57 title = config.Title
58 }
59
60 icon, found := (*params)["icon"]
61 if !found {
62 icon = config.Icon
63 }
64
65 devices := strings.Join(config.Devices, ",")
66
67 return s.sendToDevices(devices, message, title, icon)
68 }
69
70 func (s *Service) sendToDevices(devices, message, title, icon string) error {
71 config := s.Config
72
73 apiURL, err := url.Parse(hookURL)
74 if err != nil {
75 return fmt.Errorf("parsing Join API URL: %w", err)
76 }
77
78 data := url.Values{}
79 data.Set("deviceIds", devices)
80 data.Set("apikey", config.APIKey)
81 data.Set("text", message)
82
83 if title != "" {
84 data.Set("title", title)
85 }
86
87 if title != "" {
88 data.Set("icon", icon)
89 }
90
91 apiURL.RawQuery = data.Encode()
92
93 req, err := http.NewRequestWithContext(
94 context.Background(),
95 http.MethodPost,
96 apiURL.String(),
97 http.NoBody,
98 )
99 if err != nil {
100 return fmt.Errorf("creating HTTP request: %w", err)
101 }
102
103 req.Header.Set("Content-Type", contentType)
104
105 res, err := http.DefaultClient.Do(req)
106 if err != nil {
107 return fmt.Errorf("sending HTTP request to Join: %w", err)
108 }
109
110 defer func() { _ = res.Body.Close() }()
111
112 if res.StatusCode != http.StatusOK {
113 return fmt.Errorf(
114 "%w: %q, response status %q",
115 ErrSendFailed,
116 devices,
117 res.Status,
118 )
119 }
120
121 return nil
122 }