| 1 | package slack |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "time" |
| 12 | |
| 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 a pre-configured Slack channel or user. |
| 20 | type Service struct { |
| 21 | standard.Standard |
| 22 | |
| 23 | Config *Config |
| 24 | pkr format.PropKeyResolver |
| 25 | client *http.Client |
| 26 | httpClient types.HTTPClient |
| 27 | } |
| 28 | |
| 29 | // apiPostMessage is the Slack API endpoint for sending messages. |
| 30 | const ( |
| 31 | apiPostMessage = "https://slack.com/api/chat.postMessage" |
| 32 | defaultHTTPTimeout = 10 * time.Second // defaultHTTPTimeout is the default timeout for HTTP requests. |
| 33 | ) |
| 34 | |
| 35 | // GetID returns the service identifier. |
| 36 | func (s *Service) GetID() string { |
| 37 | return Scheme |
| 38 | } |
| 39 | |
| 40 | // Initialize configures the service with a URL and logger. |
| 41 | func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error { |
| 42 | s.SetLogger(logger) |
| 43 | s.Config = &Config{} |
| 44 | |
| 45 | s.pkr = format.NewPropKeyResolver(s.Config) |
| 46 | if s.client == nil { |
| 47 | s.client = &http.Client{ |
| 48 | Timeout: defaultHTTPTimeout, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return s.Config.setURL(&s.pkr, serviceURL) |
| 53 | } |
| 54 | |
| 55 | // Send delivers a notification message to Slack. |
| 56 | func (s *Service) Send(message string, params *types.Params) error { |
| 57 | config := s.Config |
| 58 | |
| 59 | if err := s.pkr.UpdateConfigFromParams(config, params); err != nil { |
| 60 | return fmt.Errorf("updating config from params: %w", err) |
| 61 | } |
| 62 | |
| 63 | payload := CreateJSONPayload(config, message) |
| 64 | |
| 65 | var err error |
| 66 | if config.Token.IsAPIToken() { |
| 67 | err = s.sendAPI(config, payload) |
| 68 | } else { |
| 69 | err = s.sendWebhook(config, payload) |
| 70 | } |
| 71 | |
| 72 | if err != nil { |
| 73 | return fmt.Errorf("failed to send slack notification: %w", err) |
| 74 | } |
| 75 | |
| 76 | return nil |
| 77 | } |
| 78 | |
| 79 | // SetHTTPClient sets a custom HTTP client for the service. |
| 80 | func (s *Service) SetHTTPClient(client types.HTTPClient) { |
| 81 | s.httpClient = client |
| 82 | } |
| 83 | |
| 84 | // httpClientOrDefault returns the injected client or the internal client. |
| 85 | func (s *Service) httpClientOrDefault() types.HTTPClient { |
| 86 | if s.httpClient != nil { |
| 87 | return s.httpClient |
| 88 | } |
| 89 | |
| 90 | return s.client |
| 91 | } |
| 92 | |
| 93 | // sendAPI sends a notification using the Slack API. |
| 94 | func (s *Service) sendAPI(config *Config, payload any) error { |
| 95 | response := APIResponse{} |
| 96 | jsonClient := jsonclient.NewWithHTTPClient(s.httpClientOrDefault()) |
| 97 | jsonClient.Headers().Set("Authorization", config.Token.Authorization()) |
| 98 | |
| 99 | if err := jsonClient.Post(apiPostMessage, payload, &response); err != nil { |
| 100 | return fmt.Errorf("posting to Slack API: %w", err) |
| 101 | } |
| 102 | |
| 103 | if !response.Ok { |
| 104 | if response.Error != "" { |
| 105 | return fmt.Errorf("%w: %v", ErrAPIResponseFailure, response.Error) |
| 106 | } |
| 107 | |
| 108 | return ErrUnknownAPIError |
| 109 | } |
| 110 | |
| 111 | if response.Warning != "" { |
| 112 | s.Logf("Slack API warning: %q", response.Warning) |
| 113 | } |
| 114 | |
| 115 | return nil |
| 116 | } |
| 117 | |
| 118 | // sendWebhook sends a notification using a Slack webhook. |
| 119 | func (s *Service) sendWebhook(config *Config, payload any) error { |
| 120 | payloadBytes, err := json.Marshal(payload) |
| 121 | if err != nil { |
| 122 | return fmt.Errorf("failed to marshal payload: %w", err) |
| 123 | } |
| 124 | |
| 125 | ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) |
| 126 | defer cancel() |
| 127 | |
| 128 | req, err := http.NewRequestWithContext( |
| 129 | ctx, |
| 130 | http.MethodPost, |
| 131 | config.Token.WebhookURL(), |
| 132 | bytes.NewBuffer(payloadBytes), |
| 133 | ) |
| 134 | if err != nil { |
| 135 | return fmt.Errorf("failed to create webhook request: %w", err) |
| 136 | } |
| 137 | |
| 138 | req.Header.Set("Content-Type", jsonclient.ContentType) |
| 139 | |
| 140 | client := s.httpClientOrDefault() |
| 141 | |
| 142 | res, err := client.Do(req) |
| 143 | if err != nil { |
| 144 | return fmt.Errorf("failed to invoke webhook: %w", err) |
| 145 | } |
| 146 | |
| 147 | defer func() { _ = res.Body.Close() }() |
| 148 | |
| 149 | resBytes, err := io.ReadAll(res.Body) |
| 150 | if err != nil { |
| 151 | return fmt.Errorf("failed to read response body: %w", err) |
| 152 | } |
| 153 | |
| 154 | response := string(resBytes) |
| 155 | |
| 156 | switch response { |
| 157 | case "": |
| 158 | if res.StatusCode != http.StatusOK { |
| 159 | return fmt.Errorf("%w: %v", ErrWebhookStatusFailure, res.Status) |
| 160 | } |
| 161 | |
| 162 | fallthrough |
| 163 | case "ok": |
| 164 | return nil |
| 165 | default: |
| 166 | return fmt.Errorf("%w: %v", ErrWebhookResponseFailure, response) |
| 167 | } |
| 168 | } |