File: matrix.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,680 kB
  • sloc: sh: 74; makefile: 58
file content (79 lines) | stat: -rw-r--r-- 1,954 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package matrix

import (
	"errors"
	"fmt"
	"net/url"

	"github.com/nicholas-fedor/shoutrrr/pkg/format"
	"github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
	"github.com/nicholas-fedor/shoutrrr/pkg/types"
)

// Scheme identifies this service in configuration URLs.
const Scheme = "matrix"

// ErrClientNotInitialized indicates that the client is not initialized for sending messages.
var ErrClientNotInitialized = errors.New("client not initialized; cannot send message")

// Service sends notifications via the Matrix protocol.
type Service struct {
	standard.Standard
	Config *Config
	client *client
	pkr    format.PropKeyResolver
}

// Initialize configures the service with a URL and logger.
func (s *Service) Initialize(configURL *url.URL, logger types.StdLogger) error {
	s.SetLogger(logger)
	s.Config = &Config{}
	s.pkr = format.NewPropKeyResolver(s.Config)

	if err := s.Config.setURL(&s.pkr, configURL); err != nil {
		return err
	}

	if configURL.String() != "matrix://dummy@dummy.com" {
		s.client = newClient(s.Config.Host, s.Config.DisableTLS, logger)
		if s.Config.User != "" {
			return s.client.login(s.Config.User, s.Config.Password)
		}

		s.client.useToken(s.Config.Password)
	}

	return nil
}

// GetID returns the identifier for this service.
func (s *Service) GetID() string {
	return Scheme
}

// Send delivers a notification message to Matrix rooms.
func (s *Service) Send(message string, params *types.Params) error {
	config := *s.Config
	if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
		return fmt.Errorf("updating config from params: %w", err)
	}

	if s.client == nil {
		return ErrClientNotInitialized
	}

	errors := s.client.sendMessage(message, s.Config.Rooms)
	if len(errors) > 0 {
		for _, err := range errors {
			s.Logf("error sending message: %w", err)
		}

		return fmt.Errorf(
			"%v error(s) sending message, with initial error: %w",
			len(errors),
			errors[0],
		)
	}

	return nil
}