summaryrefslogtreecommitdiff
path: root/ntfy
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-04-21 18:46:40 -0700
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-04-21 18:46:40 -0700
commitd14605d1388aaa7cc9ef1c230eae5ba14c9cef44 (patch)
tree59fcda0fae7899ca577eed1f72d89bff17d5ad5d /ntfy
downloadbackup-notify-d14605d1388aaa7cc9ef1c230eae5ba14c9cef44.tar.gz
backup-notify-d14605d1388aaa7cc9ef1c230eae5ba14c9cef44.zip
initial commit
Diffstat (limited to 'ntfy')
-rw-r--r--ntfy/watcher.go77
1 files changed, 77 insertions, 0 deletions
diff --git a/ntfy/watcher.go b/ntfy/watcher.go
new file mode 100644
index 0000000..af4dd55
--- /dev/null
+++ b/ntfy/watcher.go
@@ -0,0 +1,77 @@
+package ntfy
+
+import (
+ "bufio"
+ "log"
+ "net/http"
+ "net/url"
+ "path"
+ "time"
+)
+
+type Message struct {
+ Topic string
+ Text string
+}
+
+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
+
+ retry := 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)
+ retry()
+ continue
+ }
+
+ defer resp.Body.Close()
+ scanner := bufio.NewScanner(resp.Body)
+ for scanner.Scan() {
+ text := scanner.Text()
+ log.Println("received notification:", text)
+ notifications <- Message{Topic: topic, Text: text}
+ retries = retryCount // reset retries
+ }
+
+ if err := scanner.Err(); err != nil {
+ log.Println("error reading response body:", err)
+ retry()
+ }
+ }
+ }()
+ }
+
+ return notifications
+}
+
+func MakeNtfyWatcher(endpoint string, topics []string) *NtfyWatcher {
+ return &NtfyWatcher{
+ Endpoint: endpoint,
+ Topics: topics,
+ }
+}