Debian Codegraph @

pkg/services/chat/rocketchat/rocketchat.go

raw
1 package rocketchat
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "net"
9 "net/http"
10 "net/url"
11 "time"
12
13 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
14 "github.com/nicholas-fedor/shoutrrr/pkg/types"
15 )
16
17 // Service sends notifications to a pre-configured Rocket.Chat channel or user.
18 // It implements the types.Service interface for Rocket.Chat integration.
19 type Service struct {
20 standard.Standard
21
22 // Config holds the Rocket.Chat service configuration.
23 Config *Config
24 // Client is the HTTP client used for API requests.
25 Client *http.Client
26 }
27
28 // defaultHTTPTimeout is the default timeout for HTTP requests.
29 const defaultHTTPTimeout = 10 * time.Second
30
31 // GetID returns the service identifier.
32 func (s *Service) GetID() string {
33 return Scheme
34 }
35
36 // Initialize configures the service with a URL and logger.
37 //
38 // Params:
39 // - serviceURL: The configuration URL containing Rocket.Chat connection details
40 // - logger: The logger to use for this service
41 //
42 // Returns:
43 // - error: An error if configuration fails, nil otherwise
44 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
45 s.SetLogger(logger)
46
47 s.Config = &Config{}
48 if s.Client == nil {
49 s.Client = &http.Client{
50 Timeout: defaultHTTPTimeout, // Set a default timeout
51 }
52 }
53
54 if err := s.Config.SetURL(serviceURL); err != nil {
55 return err
56 }
57
58 return nil
59 }
60
61 // Send delivers a notification message to Rocket.Chat.
62 //
63 // Params:
64 // - message: The message text to send
65 // - params: Optional parameters that can override configuration (username, channel)
66 //
67 // Returns:
68 // - error: An error if sending fails, nil on success
69 func (s *Service) Send(message string, params *types.Params) error {
70 var res *http.Response
71
72 var err error
73
74 config := s.Config
75 serviceURL := buildURL(config)
76
77 json, err := CreateJSONPayload(config, message, params)
78 if err != nil {
79 return fmt.Errorf("creating JSON payload: %w", err)
80 }
81
82 ctx, cancel := context.WithTimeout(
83 context.Background(),
84 defaultHTTPTimeout,
85 )
86 defer cancel()
87
88 req, err := http.NewRequestWithContext(
89 ctx,
90 http.MethodPost,
91 serviceURL,
92 bytes.NewReader(json),
93 )
94 if err != nil {
95 return fmt.Errorf("creating request: %w", err)
96 }
97
98 req.Header.Set("Content-Type", "application/json")
99
100 res, err = s.Client.Do(req)
101 if err != nil {
102 return fmt.Errorf(
103 "posting to URL: %w\nHOST: %s\nPORT: %s",
104 err,
105 config.Host,
106 config.Port,
107 )
108 }
109
110 defer func() { _ = res.Body.Close() }()
111
112 if res.StatusCode != http.StatusOK {
113 resBody, err := io.ReadAll(res.Body)
114 if err != nil {
115 return fmt.Errorf(
116 "%w: %d",
117 ErrNotificationFailed,
118 res.StatusCode,
119 )
120 }
121
122 return fmt.Errorf("%w: %d %s",
123 ErrNotificationFailed,
124 res.StatusCode,
125 resBody,
126 )
127 }
128
129 return nil
130 }
131
132 // buildURL constructs the API URL for Rocket.Chat based on the Config.
133 //
134 // Params:
135 // - config: The configuration containing host, port, and token information
136 //
137 // Returns:
138 // - The complete Rocket.Chat webhook URL as a string
139 func buildURL(config *Config) string {
140 base := config.Host
141 if config.Port != "" {
142 base = net.JoinHostPort(config.Host, config.Port)
143 }
144
145 return fmt.Sprintf(
146 "https://%s/hooks/%s/%s",
147 base,
148 config.TokenA,
149 config.TokenB,
150 )
151 }