File: matrix_config.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.8.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 4,332 kB
  • sloc: sh: 61; makefile: 5
file content (68 lines) | stat: -rw-r--r-- 2,198 bytes parent folder | download | duplicates (2)
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
package matrix

import (
	"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"
)

// Config is the configuration for the matrix service.
type Config struct {
	standard.EnumlessConfig

	User       string   `desc:"Username or empty when using access token" optional:"" url:"user"`
	Password   string   `desc:"Password or access token"                              url:"password"`
	DisableTLS bool     `                                                                            default:"No" key:"disableTLS"`
	Host       string   `                                                             url:"host"`
	Rooms      []string `desc:"Room aliases, or with ! prefix, room IDs"  optional:""                             key:"rooms,room"`
	Title      string   `                                                                            default:""   key:"title"`
}

// GetURL returns a URL representation of it's current field values.
func (c *Config) GetURL() *url.URL {
	resolver := format.NewPropKeyResolver(c)

	return c.getURL(&resolver)
}

// SetURL updates a ServiceConfig from a URL representation of it's field values.
func (c *Config) SetURL(url *url.URL) error {
	resolver := format.NewPropKeyResolver(c)

	return c.setURL(&resolver, url)
}

func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
	return &url.URL{
		User:       url.UserPassword(c.User, c.Password),
		Host:       c.Host,
		Scheme:     Scheme,
		ForceQuery: true,
		RawQuery:   format.BuildQuery(resolver),
	}
}

func (c *Config) setURL(resolver types.ConfigQueryResolver, configURL *url.URL) error {
	c.User = configURL.User.Username()
	password, _ := configURL.User.Password()
	c.Password = password
	c.Host = configURL.Host

	for key, vals := range configURL.Query() {
		if err := resolver.Set(key, vals[0]); err != nil {
			return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
		}
	}

	for r, room := range c.Rooms {
		// If room does not begin with a '#' let's prepend it
		if room[0] != '#' && room[0] != '!' {
			c.Rooms[r] = "#" + room
		}
	}

	return nil
}