Debian Codegraph @

pkg/services/chat/xmpp/xmpp_service.go

raw
1 package xmpp
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net"
8 "net/url"
9 "strconv"
10 "time"
11
12 "github.com/nicholas-fedor/shoutrrr/pkg/format"
13 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
14 "github.com/nicholas-fedor/shoutrrr/pkg/types"
15 )
16
17 // Service sends fire-and-forget XMPP chat and MUC notifications.
18 type Service struct {
19 standard.Standard
20
21 // Config holds the parsed XMPP service settings.
22 Config *Config
23 // pkr applies URL query keys and Send params onto Config.
24 pkr format.PropKeyResolver
25 // dialContext, when set, is used instead of [net.Dialer] for the TCP dial.
26 dialContext types.DialContextFunc
27 // newSession constructs the XMPP session after the TCP dial succeeds.
28 newSession SessionFactory
29 }
30
31 // defaultTimeout bounds dial, session negotiation, and send.
32 const defaultTimeout = 30 * time.Second
33
34 var (
35 _ types.Service = (*Service)(nil)
36 _ types.ContextSender = (*Service)(nil)
37 _ types.DialContextSetter = (*Service)(nil)
38 )
39
40 // GetID returns the service identifier.
41 //
42 // Returns:
43 // - The scheme name [Scheme].
44 func (*Service) GetID() string {
45 return Scheme
46 }
47
48 // Initialize loads [Config] from serviceURL and sets logger for this [Service].
49 //
50 // Parameters:
51 // - serviceURL: The XMPP configuration URL.
52 // - logger: Logger used for service output ([types.StdLogger]).
53 //
54 // Returns:
55 // - An error if the configuration URL is invalid.
56 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
57 s.SetLogger(logger)
58 s.Config = &Config{}
59 s.pkr = format.NewPropKeyResolver(s.Config)
60
61 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
62 return fmt.Errorf("setting default props: %w", err)
63 }
64
65 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
66 return err
67 }
68
69 if s.newSession == nil {
70 s.newSession = newMelliumSession
71 }
72
73 return nil
74 }
75
76 // Send sends a notification message over XMPP.
77 //
78 // Parameters:
79 // - message: The notification body.
80 // - params: Optional runtime overrides for configuration fields ([types.Params]).
81 //
82 // Returns:
83 // - An error if configuration updates, connection, or delivery fail.
84 func (s *Service) Send(message string, params *types.Params) error {
85 return s.SendContext(context.Background(), message, params)
86 }
87
88 // SendContext sends a notification message over XMPP.
89 //
90 // It clones the service configuration, applies optional runtime params, dials
91 // the server, negotiates a session, and sends chat and MUC messages. Delivery
92 // continues after a per-target failure. The session is closed after the send.
93 //
94 // Parameters:
95 // - ctx: Parent context for cancellation and deadlines.
96 // - message: The notification body.
97 // - params: Optional runtime overrides for configuration fields ([types.Params]).
98 //
99 // Returns:
100 // - An aggregated error if any target delivery fails, or a setup error.
101 func (s *Service) SendContext(ctx context.Context, message string, params *types.Params) error {
102 config := s.Config.Clone()
103 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
104 return fmt.Errorf("updating config from params: %w", err)
105 }
106
107 config.To = compactStrings(config.To)
108 config.Rooms = compactStrings(config.Rooms)
109
110 if err := config.validate(); err != nil {
111 return err
112 }
113
114 if config.SkipTLSVerify {
115 s.Log("Warning: TLS verification is disabled, making connections insecure")
116 }
117
118 ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
119 defer cancel()
120
121 conn, err := s.dial(ctx, &config)
122 if err != nil {
123 return err
124 }
125
126 session, err := s.newSession(ctx, &config, conn)
127 if err != nil {
128 _ = conn.Close()
129
130 return err
131 }
132 defer func() { _ = session.Close() }()
133
134 body := composeMessage(config.Title, message)
135
136 var errs []error
137
138 for _, to := range config.To {
139 if err := session.SendChat(ctx, to, body); err != nil {
140 errs = append(errs, fmt.Errorf("sending chat to %s: %w", to, err))
141 }
142 }
143
144 nick := config.mucNick()
145 for _, room := range config.Rooms {
146 if err := session.SendToRoom(ctx, room, nick, config.RoomPassword, body); err != nil {
147 errs = append(errs, fmt.Errorf("sending groupchat to %s: %w", room, err))
148 }
149 }
150
151 return errors.Join(errs...)
152 }
153
154 // ServiceTimeout returns the session timeout used for an XMPP send.
155 //
156 // The budget is [defaultTimeout], which [Service.SendContext] applies to dial,
157 // negotiation, and send.
158 //
159 // Parameters:
160 // - params: Unused. The budget does not depend on send parameters.
161 //
162 // Returns:
163 // - [defaultTimeout].
164 func (*Service) ServiceTimeout(*types.Params) time.Duration {
165 return defaultTimeout
166 }
167
168 // SetDialContext sets a custom dial function for XMPP TCP connections.
169 //
170 // TLS wrapping for xmpps and STARTTLS still happens after the TCP dial.
171 // A nil dial restores the default [net.Dialer].
172 //
173 // Parameters:
174 // - dial: The dial function. Must be safe for concurrent use when non-nil.
175 func (s *Service) SetDialContext(dial types.DialContextFunc) {
176 s.dialContext = dial
177 }
178
179 // SetSessionFactory replaces the XMPP session constructor.
180 //
181 // Tests use this to inject a mock session. A nil factory restores the default.
182 //
183 // Parameters:
184 // - factory: The session factory. Must be safe for concurrent use when non-nil.
185 func (s *Service) SetSessionFactory(factory SessionFactory) {
186 if factory == nil {
187 s.newSession = newMelliumSession
188
189 return
190 }
191
192 s.newSession = factory
193 }
194
195 // dial opens a TCP connection to cfg.Host:cfg.Port.
196 //
197 // Parameters:
198 // - ctx: Parent context for the dial.
199 // - cfg: Configuration supplying the dial address.
200 //
201 // Returns:
202 // - The connected TCP socket.
203 // - An error if the dial fails.
204 func (s *Service) dial(ctx context.Context, cfg *Config) (net.Conn, error) {
205 addr := net.JoinHostPort(cfg.Host, strconvPort(cfg.Port))
206
207 dial := s.dialContext
208 if dial == nil {
209 var d net.Dialer
210
211 dial = d.DialContext
212 }
213
214 conn, err := dial(ctx, "tcp", addr)
215 if err != nil {
216 return nil, fmt.Errorf("dialing %s: %w", addr, err)
217 }
218
219 return conn, nil
220 }
221
222 // strconvPort formats port as a decimal string for [net.JoinHostPort].
223 //
224 // Parameters:
225 // - port: The TCP port.
226 //
227 // Returns:
228 // - The port as a decimal string.
229 func strconvPort(port uint16) string {
230 return strconv.FormatUint(uint64(port), 10)
231 }