| 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 | |
| 116 | s.pkr = format.NewPropKeyResolver(s.Config) |
| 117 | if s.HTTPClient == nil { |
| 118 | s.HTTPClient = NewDefaultHTTPClient() |
| 119 | } |
| 120 | |
| 121 | s.contentMaxSize = contentMaxSize |
| 122 | s.topicMaxLength = topicMaxLength |
| 123 | |
| 124 | if err := s.pkr.SetDefaultProps(s.Config); err != nil { |
| 125 | return fmt.Errorf("setting default properties: %w", err) |
| 126 | } |
| 127 | |
| 128 | if err := s.Config.SetURL(serviceURL); err != nil { |
| 129 | return err |
| 130 | } |
| 131 | |
| 132 | return nil |
| 133 | } |
| 134 | |
| 135 | // Send delivers a notification message to Zulip. |
| 136 | func (s *Service) Send(message string, params *types.Params) error { |
| 137 | return s.SendWithContext(context.Background(), message, params) |
| 138 | } |
| 139 | |
| 140 | // SendWithContext delivers a notification message to Zulip with context support. |
| 141 | func (s *Service) SendWithContext(ctx context.Context, message string, params *types.Params) error { |
| 142 | // Clone the config to avoid modifying the original for this send operation. |
| 143 | config := s.Config.Clone() |
| 144 | |
| 145 | // Use PropKeyResolver for consistent param handling |
| 146 | if err := s.pkr.UpdateConfigFromParams(config, params); err != nil { |
| 147 | return fmt.Errorf("updating config from params: %w", err) |
| 148 | } |
| 149 | |
| 150 | // If no topic is set, fall back to using the title as the topic |
| 151 | // for backward compatibility with tools that only provide a title. |
| 152 | if config.Topic == "" && config.Title != "" { |
| 153 | config.Topic = config.Title |
| 154 | config.Title = "" |
| 155 | } |
| 156 | |
| 157 | if err := ValidateMessageType(config.Type); err != nil { |
| 158 | return err |
| 159 | } |
| 160 | |
| 161 | if err := validateHost(config.Host); err != nil { |
| 162 | return err |
| 163 | } |
| 164 | |
| 165 | s.mu.Do(func() { s.fetchLimits(ctx) }) |
| 166 | |
| 167 | topicLength := len([]rune(config.Topic)) |
| 168 | if topicLength > s.topicMaxLength { |
| 169 | return fmt.Errorf( |
| 170 | "%w: %d characters, got %d", |
| 171 | ErrTopicTooLong, |
| 172 | s.topicMaxLength, |
| 173 | topicLength, |
| 174 | ) |
| 175 | } |
| 176 | |
| 177 | // Prepend title to message content when both topic and title are set. |
| 178 | if config.Title != "" { |
| 179 | message = fmt.Sprintf("%s\n\n%s", config.Title, message) |
| 180 | } |
| 181 | |
| 182 | messageSize := len(message) |
| 183 | if messageSize > s.contentMaxSize { |
| 184 | return fmt.Errorf( |
| 185 | "%w: %d bytes, got %d bytes", |
| 186 | ErrMessageTooLong, |
| 187 | s.contentMaxSize, |
| 188 | messageSize, |
| 189 | ) |
| 190 | } |
| 191 | |
| 192 | if config.Type == MessageTypeDirect { |
| 193 | recipients := config.To |
| 194 | if recipients == "" && config.Stream != "" { |
| 195 | recipients = config.Stream |
| 196 | } |
| 197 | |
| 198 | if recipients == "" { |
| 199 | return ErrMissingRecipient |
| 200 | } |
| 201 | } else if config.Stream == "" { |
| 202 | return ErrMissingRecipient |
| 203 | } |
| 204 | |
| 205 | return s.doSend(ctx, config, message) |
| 206 | } |
| 207 | |
| 208 | // SetHTTPClient sets a custom HTTP client for the service. |
| 209 | func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 210 | s.HTTPClient = client |
| 211 | } |
| 212 | |
| 213 | // doSend sends the notification to Zulip using the configured API URL. |
| 214 | func (s *Service) doSend(ctx context.Context, config *Config, message string) error { |
| 215 | apiURL := s.getAPIURL(config) |
| 216 | |
| 217 | payload := CreatePayload(config, message) |
| 218 | |
| 219 | req, err := http.NewRequestWithContext( |
| 220 | ctx, |
| 221 | http.MethodPost, |
| 222 | apiURL, |
| 223 | strings.NewReader(payload.Encode()), |
| 224 | ) |
| 225 | if err != nil { |
| 226 | return fmt.Errorf("creating request: %w", err) |
| 227 | } |
| 228 | |
| 229 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 230 | |
| 231 | res, err := s.HTTPClient.Do(req) |
| 232 | if err != nil { |
| 233 | return fmt.Errorf("making HTTP POST request: %w", err) |
| 234 | } |
| 235 | |
| 236 | defer func() { _ = res.Body.Close() }() |
| 237 | |
| 238 | if res.StatusCode != http.StatusOK { |
| 239 | body, readErr := io.ReadAll(io.LimitReader(res.Body, maxErrorBodySize+1)) |
| 240 | if readErr == nil && len(body) > 0 { |
| 241 | trunc := "" |
| 242 | |
| 243 | if len(body) > maxErrorBodySize { |
| 244 | body = body[:maxErrorBodySize] |
| 245 | trunc = " [truncated]" |
| 246 | } |
| 247 | |
| 248 | return fmt.Errorf("failed to send zulip message: %w: %d, body: %s%s", ErrResponseStatusFailure, res.StatusCode, string(body), trunc) |
| 249 | } |
| 250 | |
| 251 | return fmt.Errorf("failed to send zulip message: %w: %d", ErrResponseStatusFailure, res.StatusCode) |
| 252 | } |
| 253 | |
| 254 | return nil |
| 255 | } |
| 256 | |
| 257 | // fetchLimits calls the Zulip register endpoint to fetch server-side size limits. |
| 258 | // Uses defaults if the call fails. |
| 259 | func (s *Service) fetchLimits(ctx context.Context) { |
| 260 | if err := validateHost(s.Config.Host); err != nil { |
| 261 | return |
| 262 | } |
| 263 | |
| 264 | registerURL := s.getRegisterURL() |
| 265 | |
| 266 | ctx, cancel := context.WithTimeout(ctx, registerTimeout) |
| 267 | defer cancel() |
| 268 | |
| 269 | form := url.Values{} |
| 270 | form.Set("fetch_event_types", `["realm"]`) |
| 271 | |
| 272 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, registerURL, strings.NewReader(form.Encode())) |
| 273 | if err != nil { |
| 274 | return |
| 275 | } |
| 276 | |
| 277 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 278 | |
| 279 | res, err := s.HTTPClient.Do(req) |
| 280 | if err != nil { |
| 281 | return |
| 282 | } |
| 283 | |
| 284 | defer func() { _ = res.Body.Close() }() |
| 285 | |
| 286 | if res.StatusCode != http.StatusOK { |
| 287 | return |
| 288 | } |
| 289 | |
| 290 | var reg registerResponse |
| 291 | if err := json.NewDecoder(res.Body).Decode(®); err != nil { |
| 292 | return |
| 293 | } |
| 294 | |
| 295 | if reg.MaxMessageLength > 0 { |
| 296 | s.contentMaxSize = reg.MaxMessageLength |
| 297 | } |
| 298 | |
| 299 | if reg.MaxTopicLength > 0 { |
| 300 | s.topicMaxLength = reg.MaxTopicLength |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // getAPIURL constructs the API URL for Zulip based on the Config. |
| 305 | func (s *Service) getAPIURL(config *Config) string { |
| 306 | return (&url.URL{ |
| 307 | User: url.UserPassword(config.BotMail, config.BotKey), |
| 308 | Host: config.Host, |
| 309 | Path: "/api/v1/messages", |
| 310 | Scheme: "https", |
| 311 | }).String() |
| 312 | } |
| 313 | |
| 314 | // getRegisterURL constructs the register API URL from the service config. |
| 315 | func (s *Service) getRegisterURL() string { |
| 316 | return (&url.URL{ |
| 317 | User: url.UserPassword(s.Config.BotMail, s.Config.BotKey), |
| 318 | Host: s.Config.Host, |
| 319 | Path: "/api/v1/register", |
| 320 | Scheme: "https", |
| 321 | }).String() |
| 322 | } |