package main
import (
"html/template"
"log"
"net/http"
"sync"
"git.sr.ht/~michalr/go-satel"
)
const (
NotificationPartitionIndex = 0
)
type Sender interface {
Send(msg GenericMessage, tpl *template.Template) error
}
type Sleeper interface {
Sleep(ch chan<- interface{})
}
func Consume(events <-chan GenericMessage) {
go func() {
for range events {
}
}()
}
func SendToTg(events <-chan GenericMessage, s Sender, wg *sync.WaitGroup, logger *log.Logger, tpl *template.Template) <-chan GenericMessage {
returnEvents := make(chan GenericMessage)
go func() {
wg.Add(1)
defer wg.Done()
for e := range events {
returnEvents <- e
err := s.Send(e, tpl)
if err != nil {
// TODO: handle it better
panic(err)
}
}
close(returnEvents)
}()
return returnEvents
}
func doHttpNotification(url string, logger *log.Logger, wg *sync.WaitGroup) {
wg.Add(1)
defer wg.Done()
if len(url) == 0 {
return
}
req, err := http.NewRequest(http.MethodPost, url, nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
logger.Print("Could not POST ", url, ": ", err)
return
}
logger.Print("Notified via HTTP with result ", res.StatusCode)
}
func notifyAllHttp(urls []string, logger *log.Logger, wg *sync.WaitGroup) {
for _, uri := range urls {
go doHttpNotification(uri, logger, wg)
}
}
func NotifyViaHTTP(events <-chan GenericMessage, config AppConfig, wg *sync.WaitGroup, logger *log.Logger) <-chan GenericMessage {
returnEvents := make(chan GenericMessage)
go func() {
wg.Add(1)
defer wg.Done()
for e := range events {
returnEvents <- e
inner_arm:
for _, basicElement := range e.Messages {
if (basicElement.Index == NotificationPartitionIndex) && (basicElement.Type == satel.ArmedPartition) {
if basicElement.Value == ArmedPartition_Armed {
notifyAllHttp(config.armCallbackUrls, logger, wg)
} else {
notifyAllHttp(config.disarmCallbackUrls, logger, wg)
}
break inner_arm
}
}
inner_alarm:
for _, basicElement := range e.Messages {
if basicElement.Type == satel.PartitionAlarm {
if basicElement.Value == PartitionAlarm_Alarm {
notifyAllHttp(config.alarmCallbackUrls, logger, wg)
break inner_alarm
}
}
}
}
close(returnEvents)
}()
return returnEvents
}