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