SmsHook/smshook/smshook.go

110 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-06-16 14:49:15 +02:00
package smshook
import (
"encoding/json"
"net/http"
"sync"
2024-06-16 15:27:46 +02:00
"time"
2024-06-16 14:49:15 +02:00
2024-06-16 15:38:28 +02:00
"git.directme.in/Joren/SmsHook/ringbuffer"
2024-06-16 14:49:15 +02:00
)
type WebhookServer struct {
buffer *ringbuffer.RingBuffer
cond *sync.Cond
mux *http.ServeMux
}
type WebhookPayload struct {
Content string `json:"content"`
}
func NewWebhookServer(bufferSize int) *WebhookServer {
mutex := sync.Mutex{}
server := &WebhookServer{
buffer: ringbuffer.NewRingBuffer(bufferSize),
cond: sync.NewCond(&mutex),
mux: http.NewServeMux(),
}
server.mux.HandleFunc("/webhook", server.webhookHandler)
return server
}
func (s *WebhookServer) webhookHandler(w http.ResponseWriter, r *http.Request) {
var payload WebhookPayload
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.buffer.Add(payload.Content)
s.cond.Broadcast()
}
func (s *WebhookServer) GetLastItem() (string, int) {
return s.buffer.GetLast()
}
func (s *WebhookServer) WaitForNewItem() string {
s.cond.L.Lock()
s.cond.Wait()
newItem := s.buffer.WaitForNewItem()
s.cond.L.Unlock()
return newItem
}
2024-06-16 15:27:46 +02:00
func (s *WebhookServer) WaitForNewItemWithTimeout(timeout time.Duration) (string, bool) {
s.cond.L.Lock()
defer s.cond.L.Unlock()
initialPos := s.buffer.GetLastPosition()
timedOut := false
timer := time.AfterFunc(timeout, func() {
s.cond.Broadcast()
timedOut = true
})
for s.buffer.GetLastPosition() == initialPos {
if timedOut {
return "", false
}
s.cond.Wait()
}
timer.Stop()
newItem := s.buffer.WaitForNewItem()
return newItem, true
}
2024-06-16 14:49:15 +02:00
func (s *WebhookServer) Start(address string) error {
return http.ListenAndServe(address, s.mux)
}
2024-06-16 15:27:46 +02:00
var Server *WebhookServer
2024-06-16 14:49:15 +02:00
func Init(bufferSize int, address string) {
2024-06-16 15:27:46 +02:00
Server = NewWebhookServer(bufferSize)
2024-06-16 14:49:15 +02:00
go func() {
2024-06-16 15:27:46 +02:00
if err := Server.Start(address); err != nil {
2024-06-16 14:49:15 +02:00
panic(err)
}
}()
}
func GetLast() (string, int) {
2024-06-16 15:27:46 +02:00
return Server.GetLastItem()
2024-06-16 14:49:15 +02:00
}
func WaitForNew() string {
2024-06-16 15:27:46 +02:00
return Server.WaitForNewItem()
}
func WaitForNewWithTimeout(timeout time.Duration) (string, bool) {
return Server.WaitForNewItemWithTimeout(timeout)
2024-06-16 14:49:15 +02:00
}