File: rocketchat.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,432 kB
  • sloc: sh: 74; makefile: 5
file content (103 lines) | stat: -rw-r--r-- 2,404 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
92
93
94
95
96
97
98
99
100
101
102
103
package rocketchat

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"time"

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

// defaultHTTPTimeout is the default timeout for HTTP requests.
const defaultHTTPTimeout = 10 * time.Second

// ErrNotificationFailed indicates a failure in sending the notification.
var ErrNotificationFailed = errors.New("notification failed")

// Service sends notifications to a pre-configured Rocket.Chat channel or user.
type Service struct {
	standard.Standard
	Config *Config
	Client *http.Client
}

// Initialize configures the service with a URL and logger.
func (service *Service) Initialize(configURL *url.URL, logger types.StdLogger) error {
	service.SetLogger(logger)

	service.Config = &Config{}
	if service.Client == nil {
		service.Client = &http.Client{
			Timeout: defaultHTTPTimeout, // Set a default timeout
		}
	}

	if err := service.Config.SetURL(configURL); err != nil {
		return err
	}

	return nil
}

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

// Send delivers a notification message to Rocket.Chat.
func (service *Service) Send(message string, params *types.Params) error {
	var res *http.Response

	var err error

	config := service.Config
	apiURL := buildURL(config)
	json, _ := CreateJSONPayload(config, message, params)

	ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(json))
	if err != nil {
		return fmt.Errorf("creating request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")

	res, err = service.Client.Do(req)
	if err != nil {
		return fmt.Errorf(
			"posting to URL: %w\nHOST: %s\nPORT: %s",
			err,
			config.Host,
			config.Port,
		)
	}

	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		resBody, _ := io.ReadAll(res.Body)

		return fmt.Errorf("%w: %d %s", ErrNotificationFailed, res.StatusCode, resBody)
	}

	return nil
}

// buildURL constructs the API URL for Rocket.Chat based on the Config.
func buildURL(config *Config) string {
	base := config.Host
	if config.Port != "" {
		base = net.JoinHostPort(config.Host, config.Port)
	}

	return fmt.Sprintf("https://%s/hooks/%s/%s", base, config.TokenA, config.TokenB)
}