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 // SetDialContext sets a custom dial function for XMPP TCP connections.
155 //
156 // TLS wrapping for xmpps and STARTTLS still happens after the TCP dial.
157 // A nil dial restores the default [net.Dialer].
158 //
159 // Parameters:
160 // - dial: The dial function. Must be safe for concurrent use when non-nil.
161 func (s *Service) SetDialContext(dial types.DialContextFunc) {
162 s.dialContext = dial
163 }
164
165 // SetSessionFactory replaces the XMPP session constructor.
166 //
167 // Tests use this to inject a mock session. A nil factory restores the default.
168 //
169 // Parameters:
170 // - factory: The session factory. Must be safe for concurrent use when non-nil.
171 func (s *Service) SetSessionFactory(factory SessionFactory) {
172 if factory == nil {
173 s.newSession = newMelliumSession
174
175 return
176 }
177
178 s.newSession = factory
179 }
180
181 // dial opens a TCP connection to cfg.Host:cfg.Port.
182 //
183 // Parameters:
184 // - ctx: Parent context for the dial.
185 // - cfg: Configuration supplying the dial address.
186 //
187 // Returns:
188 // - The connected TCP socket.
189 // - An error if the dial fails.
190 func (s *Service) dial(ctx context.Context, cfg *Config) (net.Conn, error) {
191 addr := net.JoinHostPort(cfg.Host, strconvPort(cfg.Port))
192
193 dial := s.dialContext
194 if dial == nil {
195 var d net.Dialer
196
197 dial = d.DialContext
198 }
199
200 conn, err := dial(ctx, "tcp", addr)
201 if err != nil {
202 return nil, fmt.Errorf("dialing %s: %w", addr, err)
203 }
204
205 return conn, nil
206 }
207
208 // strconvPort formats port as a decimal string for [net.JoinHostPort].
209 //
210 // Parameters:
211 // - port: The TCP port.
212 //
213 // Returns:
214 // - The port as a decimal string.
215 func strconvPort(port uint16) string {
216 return strconv.FormatUint(uint64(port), 10)
217 }