| 1 |
package router |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"net/url" |
| 7 |
"strings" |
| 8 |
"time" |
| 9 |
|
| 10 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 11 |
) |
| 12 |
|
| 13 |
// ServiceRouter is responsible for routing a message to a specific notification service using the notification URL. |
| 14 |
type ServiceRouter struct { |
| 15 |
logger types.StdLogger |
| 16 |
services []types.Service |
| 17 |
queue []string |
| 18 |
Timeout time.Duration |
| 19 |
} |
| 20 |
|
| 21 |
// DefaultTimeout is the default duration for service operation timeouts. |
| 22 |
const DefaultTimeout = 10 * time.Second |
| 23 |
|
| 24 |
var ( |
| 25 |
ErrNoSenders = errors.New("error sending message: no senders") |
| 26 |
ErrServiceTimeout = errors.New("failed to send: timed out") |
| 27 |
ErrCustomURLsNotSupported = errors.New("custom URLs are not supported by service") |
| 28 |
ErrUnknownService = errors.New("unknown service") |
| 29 |
ErrParseURLFailed = errors.New("failed to parse URL") |
| 30 |
ErrSendFailed = errors.New("failed to send message") |
| 31 |
ErrCustomURLConversion = errors.New("failed to convert custom URL") |
| 32 |
ErrInitializeFailed = errors.New("failed to initialize service") |
| 33 |
) |
| 34 |
|
| 35 |
// AddService initializes the specified service from its URL, and adds it if no errors occur. |
| 36 |
func (r *ServiceRouter) AddService(serviceURL string) error { |
| 37 |
service, err := r.initService(serviceURL) |
| 38 |
if err == nil { |
| 39 |
r.services = append(r.services, service) |
| 40 |
} |
| 41 |
|
| 42 |
return err |
| 43 |
} |
| 44 |
|
| 45 |
// Enqueue adds the message to an internal queue and sends it when Flush is invoked. |
| 46 |
func (r *ServiceRouter) Enqueue(message string, v ...any) { |
| 47 |
if len(v) > 0 { |
| 48 |
message = fmt.Sprintf(message, v...) |
| 49 |
} |
| 50 |
|
| 51 |
r.queue = append(r.queue, message) |
| 52 |
} |
| 53 |
|
| 54 |
// ExtractServiceName from a service URL. |
| 55 |
func (r *ServiceRouter) ExtractServiceName(rawURL string) (string, *url.URL, error) { |
| 56 |
serviceURL, err := url.Parse(rawURL) |
| 57 |
if err != nil { |
| 58 |
return "", &url.URL{}, fmt.Errorf("%s: %w", rawURL, ErrParseURLFailed) |
| 59 |
} |
| 60 |
|
| 61 |
scheme := serviceURL.Scheme |
| 62 |
schemeParts := strings.Split(scheme, "+") |
| 63 |
|
| 64 |
if len(schemeParts) > 1 { |
| 65 |
scheme = schemeParts[0] |
| 66 |
} |
| 67 |
|
| 68 |
return scheme, serviceURL, nil |
| 69 |
} |
| 70 |
|
| 71 |
// Flush sends all messages that have been queued up as a combined message. |
| 72 |
func (r *ServiceRouter) Flush(params *types.Params) { |
| 73 |
// Since this method is supposed to be deferred we just have to ignore errors |
| 74 |
_ = r.Send(strings.Join(r.queue, "\n"), params) |
| 75 |
r.queue = []string{} |
| 76 |
} |
| 77 |
|
| 78 |
// ListServices returns the available services. |
| 79 |
func (r *ServiceRouter) ListServices() []string { |
| 80 |
services := make([]string, len(serviceMap)) |
| 81 |
|
| 82 |
i := 0 |
| 83 |
|
| 84 |
for key := range serviceMap { |
| 85 |
services[i] = key |
| 86 |
i++ |
| 87 |
} |
| 88 |
|
| 89 |
return services |
| 90 |
} |
| 91 |
|
| 92 |
// Locate returns the service implementation that corresponds to the given service URL. |
| 93 |
func (r *ServiceRouter) Locate(rawURL string) (types.Service, error) { |
| 94 |
service, err := r.initService(rawURL) |
| 95 |
|
| 96 |
return service, err |
| 97 |
} |
| 98 |
|
| 99 |
// NewService returns a new uninitialized service instance. |
| 100 |
func (*ServiceRouter) NewService(serviceScheme string) (types.Service, error) { |
| 101 |
return newService(serviceScheme) |
| 102 |
} |
| 103 |
|
| 104 |
// Route a message to a specific notification service using the notification URL. |
| 105 |
func (r *ServiceRouter) Route(rawURL, message string) error { |
| 106 |
service, err := r.Locate(rawURL) |
| 107 |
if err != nil { |
| 108 |
return err |
| 109 |
} |
| 110 |
|
| 111 |
if err := service.Send(message, nil); err != nil { |
| 112 |
return fmt.Errorf("%s: %w", service.GetID(), ErrSendFailed) |
| 113 |
} |
| 114 |
|
| 115 |
return nil |
| 116 |
} |
| 117 |
|
| 118 |
// Send sends the specified message using the routers underlying services. |
| 119 |
func (r *ServiceRouter) Send(message string, params *types.Params) []error { |
| 120 |
if r == nil { |
| 121 |
return []error{ErrNoSenders} |
| 122 |
} |
| 123 |
|
| 124 |
serviceCount := len(r.services) |
| 125 |
errs := make([]error, serviceCount) |
| 126 |
results := r.SendAsync(message, params) |
| 127 |
|
| 128 |
for i := range r.services { |
| 129 |
errs[i] = <-results |
| 130 |
} |
| 131 |
|
| 132 |
return errs |
| 133 |
} |
| 134 |
|
| 135 |
// SendAsync sends the specified message using the routers underlying services. |
| 136 |
func (r *ServiceRouter) SendAsync(message string, params *types.Params) chan error { |
| 137 |
serviceCount := len(r.services) |
| 138 |
proxy := make(chan error, serviceCount) |
| 139 |
errs := make(chan error, serviceCount) |
| 140 |
|
| 141 |
if params == nil { |
| 142 |
params = &types.Params{} |
| 143 |
} |
| 144 |
|
| 145 |
for _, service := range r.services { |
| 146 |
go sendToService(service, proxy, r.Timeout, message, *params) |
| 147 |
} |
| 148 |
|
| 149 |
go func() { |
| 150 |
for range serviceCount { |
| 151 |
errs <- <-proxy |
| 152 |
} |
| 153 |
|
| 154 |
close(errs) |
| 155 |
}() |
| 156 |
|
| 157 |
return errs |
| 158 |
} |
| 159 |
|
| 160 |
// SendItems sends the specified message items using the routers underlying services. |
| 161 |
func (r *ServiceRouter) SendItems(items []types.MessageItem, params types.Params) []error { |
| 162 |
if r == nil { |
| 163 |
return []error{ErrNoSenders} |
| 164 |
} |
| 165 |
|
| 166 |
// Fallback using old API for now |
| 167 |
message := strings.Builder{} |
| 168 |
for _, item := range items { |
| 169 |
message.WriteString(item.Text) |
| 170 |
} |
| 171 |
|
| 172 |
serviceCount := len(r.services) |
| 173 |
errs := make([]error, serviceCount) |
| 174 |
results := r.SendAsync(message.String(), ¶ms) |
| 175 |
|
| 176 |
for i := range r.services { |
| 177 |
errs[i] = <-results |
| 178 |
} |
| 179 |
|
| 180 |
return errs |
| 181 |
} |
| 182 |
|
| 183 |
// SetLogger sets the logger that the services will use to write progress logs. |
| 184 |
func (r *ServiceRouter) SetLogger(logger types.StdLogger) { |
| 185 |
r.logger = logger |
| 186 |
for _, service := range r.services { |
| 187 |
service.SetLogger(logger) |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
func (r *ServiceRouter) initService(rawURL string) (types.Service, error) { |
| 192 |
scheme, serviceURL, err := r.ExtractServiceName(rawURL) |
| 193 |
if err != nil { |
| 194 |
return nil, err |
| 195 |
} |
| 196 |
|
| 197 |
service, err := newService(scheme) |
| 198 |
if err != nil { |
| 199 |
return nil, err |
| 200 |
} |
| 201 |
|
| 202 |
if serviceURL.Scheme != scheme { |
| 203 |
r.log("Got custom URL:", serviceURL.String()) |
| 204 |
|
| 205 |
customURLService, ok := service.(types.CustomURLService) |
| 206 |
if !ok { |
| 207 |
return nil, fmt.Errorf("%w: '%s' service", ErrCustomURLsNotSupported, scheme) |
| 208 |
} |
| 209 |
|
| 210 |
serviceURL, err = customURLService.GetServiceURLFromCustom(serviceURL) |
| 211 |
if err != nil { |
| 212 |
return nil, fmt.Errorf("%s: %w", serviceURL.String(), ErrCustomURLConversion) |
| 213 |
} |
| 214 |
|
| 215 |
r.log("Converted service URL:", serviceURL.String()) |
| 216 |
} |
| 217 |
|
| 218 |
err = service.Initialize(serviceURL, r.logger) |
| 219 |
if err != nil { |
| 220 |
return service, fmt.Errorf("%s: %w", scheme, ErrInitializeFailed) |
| 221 |
} |
| 222 |
|
| 223 |
return service, nil |
| 224 |
} |
| 225 |
|
| 226 |
func (r *ServiceRouter) log(v ...any) { |
| 227 |
if r.logger == nil { |
| 228 |
return |
| 229 |
} |
| 230 |
|
| 231 |
r.logger.Println(v...) |
| 232 |
} |
| 233 |
|
| 234 |
// New creates a new service router using the specified logger and service URLs. |
| 235 |
func New(logger types.StdLogger, serviceURLs ...string) (*ServiceRouter, error) { |
| 236 |
router := ServiceRouter{ |
| 237 |
logger: logger, |
| 238 |
services: nil, |
| 239 |
queue: nil, |
| 240 |
Timeout: DefaultTimeout, |
| 241 |
} |
| 242 |
|
| 243 |
for _, serviceURL := range serviceURLs { |
| 244 |
if err := router.AddService(serviceURL); err != nil { |
| 245 |
return nil, fmt.Errorf("error initializing router services: %w", err) |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
return &router, nil |
| 250 |
} |
| 251 |
|
| 252 |
// newService returns a new uninitialized service instance. |
| 253 |
func newService(serviceScheme string) (types.Service, error) { |
| 254 |
serviceFactory, valid := serviceMap[strings.ToLower(serviceScheme)] |
| 255 |
if !valid { |
| 256 |
return nil, fmt.Errorf("%w: %q", ErrUnknownService, serviceScheme) |
| 257 |
} |
| 258 |
|
| 259 |
return serviceFactory(), nil |
| 260 |
} |
| 261 |
|
| 262 |
func sendToService( |
| 263 |
service types.Service, |
| 264 |
results chan error, |
| 265 |
timeout time.Duration, |
| 266 |
message string, |
| 267 |
params types.Params, |
| 268 |
) { |
| 269 |
result := make(chan error) |
| 270 |
|
| 271 |
serviceID := service.GetID() |
| 272 |
|
| 273 |
go func() { result <- service.Send(message, ¶ms) }() |
| 274 |
|
| 275 |
select { |
| 276 |
case res := <-result: |
| 277 |
results <- res |
| 278 |
case <-time.After(timeout): |
| 279 |
results <- fmt.Errorf("%w: using %v", ErrServiceTimeout, serviceID) |
| 280 |
} |
| 281 |
} |