Debian Codegraph @

pkg/services/push/ntfy/ntfy.go

raw symbols SCIP
1 package ntfy
2
3 import (
4 "crypto/tls"
5 "encoding/base64"
6 "fmt"
7 "net/http"
8 "net/url"
9 "strings"
10 "time"
11
12 "github.com/nicholas-fedor/shoutrrr/internal/meta"
13 "github.com/nicholas-fedor/shoutrrr/pkg/format"
14 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
15 "github.com/nicholas-fedor/shoutrrr/pkg/types"
16 "github.com/nicholas-fedor/shoutrrr/pkg/util/jsonclient"
17 )
18
19 // Service sends notifications to ntfy.
20 type Service struct {
21 standard.Standard
22
23 Config *Config
24 pkr format.PropKeyResolver
25 httpClient types.HTTPClient
26 client jsonclient.Client
27 }
28
29 // HTTPTimeout defines the HTTP client timeout in seconds.
30 const HTTPTimeout = 10
31
32 // GetID returns the service identifier.
33 func (s *Service) GetID() string {
34 return Scheme
35 }
36
37 // Initialize configures the service with a URL and logger.
38 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
39 s.SetLogger(logger)
40 s.Config = &Config{}
41 s.pkr = format.NewPropKeyResolver(s.Config)
42
43 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
44 return fmt.Errorf("setting default props: %w", err)
45 }
46
47 err := s.Config.setURL(&s.pkr, serviceURL)
48 if err != nil {
49 return err
50 }
51
52 // Force HTTP scheme when DisableTLS is true
53 if s.Config.DisableTLS {
54 s.Config.Scheme = "http"
55 }
56
57 // Configure HTTP transport: skip TLS verification if disabled, enforce TLS 1.2 minimum
58 if s.Config.DisableTLSVerification {
59 if s.httpClient == nil {
60 s.httpClient = &http.Client{
61 Timeout: HTTPTimeout * time.Second,
62 Transport: &http.Transport{
63 TLSClientConfig: &tls.Config{
64 InsecureSkipVerify: true,
65 MinVersion: tls.VersionTLS12,
66 },
67 },
68 }
69 s.Log("Warning: TLS verification is disabled, making connections insecure")
70 }
71 } else {
72 if s.httpClient == nil {
73 s.httpClient = &http.Client{
74 Timeout: HTTPTimeout * time.Second,
75 Transport: &http.Transport{
76 TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
77 },
78 }
79 }
80 }
81
82 s.client = jsonclient.NewWithHTTPClient(s.httpClient)
83
84 return nil
85 }
86
87 // Send delivers a notification message to ntfy.
88 func (s *Service) Send(message string, params *types.Params) error {
89 config := s.Config
90
91 // Update config with runtime parameters
92 if err := s.pkr.UpdateConfigFromParams(config, params); err != nil {
93 return fmt.Errorf("updating config from params: %w", err)
94 }
95
96 // Execute the API request to send the notification
97 if err := s.sendAPI(config, message); err != nil {
98 return fmt.Errorf("failed to send ntfy notification: %w", err)
99 }
100
101 return nil
102 }
103
104 // SetHTTPClient sets a custom HTTP client for the service.
105 func (s *Service) SetHTTPClient(client types.HTTPClient) {
106 s.httpClient = client
107 if client != nil {
108 s.client = jsonclient.NewWithHTTPClient(client)
109 }
110 }
111
112 // sendAPI sends a notification to the ntfy API.
113 func (s *Service) sendAPI(config *Config, message string) error {
114 response := apiResponseError{}
115 request := message
116
117 // Prepare request headers
118 headers := s.client.Headers()
119 if config.Markdown {
120 headers.Set("Content-Type", "text/markdown")
121 } else {
122 headers.Set("Content-Type", "text/plain; charset=utf-8")
123 }
124
125 headers.Set("User-Agent", "shoutrrr/"+meta.Version)
126 addHeaderIfNotEmpty(&headers, "Title", config.Title)
127 addHeaderIfNotEmpty(&headers, "Priority", config.Priority.String())
128 addHeaderIfNotEmpty(&headers, "Tags", strings.Join(config.Tags, ","))
129 addHeaderIfNotEmpty(&headers, "Delay", config.Delay)
130 addHeaderIfNotEmpty(&headers, "Actions", strings.Join(config.Actions, ";"))
131 addHeaderIfNotEmpty(&headers, "Click", config.Click)
132 addHeaderIfNotEmpty(&headers, "Attach", config.Attach)
133 addHeaderIfNotEmpty(&headers, "X-Icon", config.Icon)
134 addHeaderIfNotEmpty(&headers, "Filename", config.Filename)
135 addHeaderIfNotEmpty(&headers, "Email", config.Email)
136
137 if !config.Cache {
138 headers.Add("Cache", "no")
139 }
140
141 if !config.Firebase {
142 headers.Add("Firebase", "no")
143 }
144
145 // Add Basic Auth header if username or password is provided
146 if config.Username != "" || config.Password != "" {
147 headers.Set(
148 "Authorization",
149 "Basic "+base64.StdEncoding.EncodeToString([]byte(config.Username+":"+config.Password)),
150 )
151 }
152
153 // Send the HTTP request
154 if err := s.client.Post(config.GetAPIURL(), request, &response); err != nil {
155 s.Logf("NTFY API request failed with error: %v", err)
156 // Attempt to parse structured error response from API
157 if s.client.ErrorResponse(err, &response) {
158 return &response
159 }
160
161 return fmt.Errorf("posting to ntfy API: %w", err)
162 }
163
164 s.Logf("NTFY API request succeeded")
165
166 return nil
167 }
168
169 // addHeaderIfNotEmpty adds a header to the request if the value is non-empty.
170 func addHeaderIfNotEmpty(headers *http.Header, key, value string) {
171 if value != "" {
172 headers.Add(key, value)
173 }
174 }