Debian Codegraph @

pkg/services/chat/zulip/zulip_service.go

raw
1 package zulip
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/url"
10 "regexp"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15
16 "github.com/nicholas-fedor/shoutrrr/pkg/format"
17 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
18 "github.com/nicholas-fedor/shoutrrr/pkg/types"
19 )
20
21 // HTTPClient defines the interface for HTTP operations.
22 type HTTPClient interface {
23 Do(req *http.Request) (*http.Response, error)
24 }
25
26 // DefaultHTTPClient is the default implementation using http.DefaultClient with timeout.
27 type DefaultHTTPClient struct {
28 client *http.Client
29 }
30
31 // registerResponse represents the relevant fields from the Zulip register endpoint.
32 type registerResponse struct {
33 MaxMessageLength int `json:"max_message_length"`
34 MaxTopicLength int `json:"max_topic_length"`
35 }
36
37 // Service sends notifications to a pre-configured Zulip channel or user.
38 type Service struct {
39 standard.Standard
40
41 Config *Config
42 pkr format.PropKeyResolver
43 HTTPClient HTTPClient
44
45 mu sync.Once
46 contentMaxSize int
47 topicMaxLength int
48 }
49
50 // defaultHTTPTimeout is the default timeout for HTTP requests to Zulip.
51 const defaultHTTPTimeout = 30 * time.Second
52
53 // contentMaxSize defines the default maximum allowed message size in bytes.
54 const contentMaxSize = 10000
55
56 // topicMaxLength defines the default maximum allowed topic length in characters.
57 const topicMaxLength = 60
58
59 // registerTimeout is the timeout for the register API call.
60 const registerTimeout = 10 * time.Second
61
62 // maxErrorBodySize limits how much of a non-OK response body we read to prevent
63 // memory exhaustion from huge error bodies returned by the server.
64 const maxErrorBodySize = 4 * 1024
65
66 // hostValidator ensures the host is a valid hostname or domain,
67 // optionally followed by a colon and port number (1-65535).
68 var hostValidator = regexp.MustCompile(
69 `^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$`,
70 )
71
72 // validateHost checks that the host string is a valid hostname with optional port (1-65535).
73 func validateHost(host string) error {
74 if !hostValidator.MatchString(host) {
75 return fmt.Errorf("%w: %q", ErrInvalidHost, host)
76 }
77
78 if _, portStr, ok := strings.Cut(host, ":"); ok && portStr != "" {
79 port, parseErr := strconv.Atoi(portStr)
80 if parseErr != nil || port < 1 || port > 65535 {
81 return fmt.Errorf("%w: %q", ErrInvalidHost, host)
82 }
83 }
84
85 return nil
86 }
87
88 func NewDefaultHTTPClient() *DefaultHTTPClient {
89 return &DefaultHTTPClient{
90 client: &http.Client{
91 Timeout: defaultHTTPTimeout,
92 },
93 }
94 }
95
96 // Do performs the HTTP request.
97 func (c *DefaultHTTPClient) Do(req *http.Request) (*http.Response, error) {
98 resp, err := c.client.Do(req)
99 if err != nil {
100 return nil, fmt.Errorf("performing HTTP request: %w", err)
101 }
102
103 return resp, nil
104 }
105
106 // GetID returns the identifier for this service.
107 func (s *Service) GetID() string {
108 return Scheme
109 }
110
111 // Initialize configures the service with a URL and logger.
112 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
113 s.SetLogger(logger)
114 s.Config = &Config{}
115 s.pkr = format.NewPropKeyResolver(s.Config)
116 s.HTTPClient = NewDefaultHTTPClient()
117 s.contentMaxSize = contentMaxSize
118 s.topicMaxLength = topicMaxLength
119
120 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
121 return fmt.Errorf("setting default properties: %w", err)
122 }
123
124 if err := s.Config.SetURL(serviceURL); err != nil {
125 return err
126 }
127
128 return nil
129 }
130
131 // Send delivers a notification message to Zulip.
132 func (s *Service) Send(message string, params *types.Params) error {
133 return s.SendWithContext(context.Background(), message, params)
134 }
135
136 // SendWithContext delivers a notification message to Zulip with context support.
137 func (s *Service) SendWithContext(ctx context.Context, message string, params *types.Params) error {
138 // Clone the config to avoid modifying the original for this send operation.
139 config := s.Config.Clone()
140
141 // Use PropKeyResolver for consistent param handling
142 if err := s.pkr.UpdateConfigFromParams(config, params); err != nil {
143 return fmt.Errorf("updating config from params: %w", err)
144 }
145
146 // If no topic is set, fall back to using the title as the topic
147 // for backward compatibility with tools that only provide a title.
148 if config.Topic == "" && config.Title != "" {
149 config.Topic = config.Title
150 config.Title = ""
151 }
152
153 if err := ValidateMessageType(config.Type); err != nil {
154 return err
155 }
156
157 if err := validateHost(config.Host); err != nil {
158 return err
159 }
160
161 s.mu.Do(func() { s.fetchLimits(ctx) })
162
163 topicLength := len([]rune(config.Topic))
164 if topicLength > s.topicMaxLength {
165 return fmt.Errorf(
166 "%w: %d characters, got %d",
167 ErrTopicTooLong,
168 s.topicMaxLength,
169 topicLength,
170 )
171 }
172
173 // Prepend title to message content when both topic and title are set.
174 if config.Title != "" {
175 message = fmt.Sprintf("%s\n\n%s", config.Title, message)
176 }
177
178 messageSize := len(message)
179 if messageSize > s.contentMaxSize {
180 return fmt.Errorf(
181 "%w: %d bytes, got %d bytes",
182 ErrMessageTooLong,
183 s.contentMaxSize,
184 messageSize,
185 )
186 }
187
188 if config.Type == MessageTypeDirect {
189 recipients := config.To
190 if recipients == "" && config.Stream != "" {
191 recipients = config.Stream
192 }
193
194 if recipients == "" {
195 return ErrMissingRecipient
196 }
197 } else if config.Stream == "" {
198 return ErrMissingRecipient
199 }
200
201 return s.doSend(ctx, config, message)
202 }
203
204 // doSend sends the notification to Zulip using the configured API URL.
205 func (s *Service) doSend(ctx context.Context, config *Config, message string) error {
206 apiURL := s.getAPIURL(config)
207
208 payload := CreatePayload(config, message)
209
210 req, err := http.NewRequestWithContext(
211 ctx,
212 http.MethodPost,
213 apiURL,
214 strings.NewReader(payload.Encode()),
215 )
216 if err != nil {
217 return fmt.Errorf("creating request: %w", err)
218 }
219
220 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
221
222 res, err := s.HTTPClient.Do(req)
223 if err != nil {
224 return fmt.Errorf("making HTTP POST request: %w", err)
225 }
226
227 defer func() { _ = res.Body.Close() }()
228
229 if res.StatusCode != http.StatusOK {
230 body, readErr := io.ReadAll(io.LimitReader(res.Body, maxErrorBodySize+1))
231 if readErr == nil && len(body) > 0 {
232 trunc := ""
233
234 if len(body) > maxErrorBodySize {
235 body = body[:maxErrorBodySize]
236 trunc = " [truncated]"
237 }
238
239 return fmt.Errorf("failed to send zulip message: %w: %d, body: %s%s", ErrResponseStatusFailure, res.StatusCode, string(body), trunc)
240 }
241
242 return fmt.Errorf("failed to send zulip message: %w: %d", ErrResponseStatusFailure, res.StatusCode)
243 }
244
245 return nil
246 }
247
248 // fetchLimits calls the Zulip register endpoint to fetch server-side size limits.
249 // Uses defaults if the call fails.
250 func (s *Service) fetchLimits(ctx context.Context) {
251 if err := validateHost(s.Config.Host); err != nil {
252 return
253 }
254
255 registerURL := s.getRegisterURL()
256
257 ctx, cancel := context.WithTimeout(ctx, registerTimeout)
258 defer cancel()
259
260 form := url.Values{}
261 form.Set("fetch_event_types", `["realm"]`)
262
263 req, err := http.NewRequestWithContext(ctx, http.MethodPost, registerURL, strings.NewReader(form.Encode()))
264 if err != nil {
265 return
266 }
267
268 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
269
270 res, err := s.HTTPClient.Do(req)
271 if err != nil {
272 return
273 }
274
275 defer func() { _ = res.Body.Close() }()
276
277 if res.StatusCode != http.StatusOK {
278 return
279 }
280
281 var reg registerResponse
282 if err := json.NewDecoder(res.Body).Decode(&reg); err != nil {
283 return
284 }
285
286 if reg.MaxMessageLength > 0 {
287 s.contentMaxSize = reg.MaxMessageLength
288 }
289
290 if reg.MaxTopicLength > 0 {
291 s.topicMaxLength = reg.MaxTopicLength
292 }
293 }
294
295 // getAPIURL constructs the API URL for Zulip based on the Config.
296 func (s *Service) getAPIURL(config *Config) string {
297 return (&url.URL{
298 User: url.UserPassword(config.BotMail, config.BotKey),
299 Host: config.Host,
300 Path: "/api/v1/messages",
301 Scheme: "https",
302 }).String()
303 }
304
305 // getRegisterURL constructs the register API URL from the service config.
306 func (s *Service) getRegisterURL() string {
307 return (&url.URL{
308 User: url.UserPassword(s.Config.BotMail, s.Config.BotKey),
309 Host: s.Config.Host,
310 Path: "/api/v1/register",
311 Scheme: "https",
312 }).String()
313 }