File: join_config.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 4,432 kB
  • sloc: sh: 74; makefile: 5
file content (79 lines) | stat: -rw-r--r-- 2,220 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
69
70
71
72
73
74
75
76
77
78
79
package join

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

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

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

// ErrDevicesMissing indicates that no devices are specified in the configuration.
var (
	ErrDevicesMissing = errors.New("devices missing from config URL")
	ErrAPIKeyMissing  = errors.New("API key missing from config URL")
)

// Config holds settings for the Join notification service.
type Config struct {
	APIKey  string   `url:"pass"`
	Devices []string `           desc:"Comma separated list of device IDs" key:"devices"`
	Title   string   `           desc:"If set creates a notification"      key:"title"   optional:""`
	Icon    string   `           desc:"Icon URL"                           key:"icon"    optional:""`
}

// Enums returns the fields that should use an EnumFormatter for their values.
func (config *Config) Enums() map[string]types.EnumFormatter {
	return map[string]types.EnumFormatter{}
}

// GetURL generates a URL from the current configuration values.
func (config *Config) GetURL() *url.URL {
	resolver := format.NewPropKeyResolver(config)

	return config.getURL(&resolver)
}

// SetURL updates the configuration from a URL representation.
func (config *Config) SetURL(url *url.URL) error {
	resolver := format.NewPropKeyResolver(config)

	return config.setURL(&resolver, url)
}

func (config *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
	return &url.URL{
		User:       url.UserPassword("Token", config.APIKey),
		Host:       "join",
		Scheme:     Scheme,
		ForceQuery: true,
		RawQuery:   format.BuildQuery(resolver),
	}
}

func (config *Config) setURL(resolver types.ConfigQueryResolver, url *url.URL) error {
	password, _ := url.User.Password()
	config.APIKey = password

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

	if url.String() != "join://dummy@dummy.com" {
		if len(config.Devices) < 1 {
			return ErrDevicesMissing
		}

		if len(config.APIKey) < 1 {
			return ErrAPIKeyMissing
		}
	}

	return nil
}