File: rocketchat_config.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 (91 lines) | stat: -rw-r--r-- 2,215 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
80
81
82
83
84
85
86
87
88
89
90
91
package rocketchat

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

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

// Scheme is the identifying part of this service's configuration URL.
const Scheme = "rocketchat"

// Constants for URL path length checks.
const (
	MinPathParts = 3 // Minimum number of path parts required (including empty first slash)
	TokenBIndex  = 2 // Index for TokenB in path
	ChannelIndex = 3 // Index for Channel in path
)

// Static errors for configuration validation.
var (
	ErrNotEnoughArguments = errors.New("the apiURL does not include enough arguments")
)

// Config for the Rocket.Chat service.
type Config struct {
	standard.EnumlessConfig
	UserName string `optional:"" url:"user"`
	Host     string `            url:"host"`
	Port     string `            url:"port"`
	TokenA   string `            url:"path1"`
	Channel  string `            url:"path3"`
	TokenB   string `            url:"path2"`
}

// GetURL returns a URL representation of the Config's current field values.
func (config *Config) GetURL() *url.URL {
	host := config.Host
	if config.Port != "" {
		host = fmt.Sprintf("%s:%s", config.Host, config.Port)
	}

	url := &url.URL{
		Host:       host,
		Path:       fmt.Sprintf("%s/%s", config.TokenA, config.TokenB),
		Scheme:     Scheme,
		ForceQuery: false,
	}

	return url
}

// SetURL updates the Config from a URL representation of its field values.
func (config *Config) SetURL(serviceURL *url.URL) error {
	userName := serviceURL.User.Username()
	host := serviceURL.Hostname()

	path := strings.Split(serviceURL.Path, "/")
	if serviceURL.String() != "rocketchat://dummy@dummy.com" {
		if len(path) < MinPathParts {
			return ErrNotEnoughArguments
		}
	}

	config.Port = serviceURL.Port()
	config.UserName = userName
	config.Host = host

	if len(path) > 1 {
		config.TokenA = path[1]
	}

	if len(path) > TokenBIndex {
		config.TokenB = path[TokenBIndex]
	}

	if len(path) > ChannelIndex {
		switch {
		case serviceURL.Fragment != "":
			config.Channel = "#" + serviceURL.Fragment
		case !strings.HasPrefix(path[ChannelIndex], "@"):
			config.Channel = "#" + path[ChannelIndex]
		default:
			config.Channel = path[ChannelIndex]
		}
	}

	return nil
}