summaryrefslogtreecommitdiff
path: root/template/ntfy/watcher.go
blob: d8959cdba85ab8ccd452dfcaaf57a16eab4a32fa (plain)
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
package ntfy

import (
	"bufio"
  "encoding/json"
	"log"
	"net/http"
	"net/url"
	"path"
	"time"
)

type Message struct {
  Id      string `json:"id"`
  Time    int    `json:"time"`
  Message string `json:"message"`
  Event   string `json:"event"`
}

type NtfyWatcher struct {
	Endpoint string
	Topics   []string
}

func (w *NtfyWatcher) Watch() chan Message {
	notifications := make(chan Message)

	for _, topic := range w.Topics {
		log.Println("subscribing to topic:", topic)

		go func() {
			retryCount := 5
			retryTime := 5 * time.Second
			retries := retryCount

			sleepAndDecrementRetry := func() {
				log.Println("waiting 5 seconds before reconnecting. retries left:", retries, "topic:", topic, "endpoint:", w.Endpoint)
				time.Sleep(retryTime)
				retries--
			}

			for true {
				if retries == 0 {
					log.Fatal("too many retries, exiting")
				}

				endpoint, _ := url.JoinPath(w.Endpoint, path.Join(topic, "json"))
				resp, err := http.Get(endpoint)
				if err != nil {
					log.Println("error connecting to endpoint:", err)
					sleepAndDecrementRetry()
					continue
				}

				defer resp.Body.Close()
				scanner := bufio.NewScanner(resp.Body)
				for scanner.Scan() {
					bytes := scanner.Bytes()
          var msg Message
          err := json.Unmarshal(bytes, &msg)
          if err != nil {
            log.Println("could not unmarshal message:", err)
            continue
          }

          if msg.Event == "keepalive" {
				  	log.Println("received keepalive message")
				  	continue
          }
          if msg.Event != "message" {
            log.Println("received unknown event:", msg.Event)
            continue
          }

					log.Println("received notification:", msg)
					notifications <- msg
					retries = retryCount // reset retries
				}

				if err := scanner.Err(); err != nil {
					log.Println("error reading response body:", err)
					sleepAndDecrementRetry()
				}
			}
		}()
	}

	return notifications
}

func MakeNtfyWatcher(endpoint string, topics []string) *NtfyWatcher {
	return &NtfyWatcher{
		Endpoint: endpoint,
		Topics:   topics,
	}
}