arlo-go/event_stream.go

206 lines
5.4 KiB
Go
Raw Normal View History

package arlo
import (
"bytes"
2020-05-27 08:49:40 +00:00
"context"
"encoding/json"
2020-05-27 08:49:40 +00:00
"fmt"
"net/http"
"sync"
"github.com/r3labs/sse"
2020-05-27 08:49:40 +00:00
log "github.com/sirupsen/logrus"
)
type eventStream struct {
2020-05-27 08:49:40 +00:00
SSEClient *sse.Client
Events chan *sse.Event
Error chan error
Verbose bool
2020-05-27 19:03:26 +00:00
disconnectedChan chan interface{}
2020-05-27 08:49:40 +00:00
once *sync.Once
isConnected bool
isConnectedMutex sync.RWMutex
2020-05-27 19:03:26 +00:00
transactionSubscribers map[string]chan *EventStreamResponse
transactionSubscribersMutex sync.RWMutex
resourceSubscribers map[string][]chan *EventStreamResponse
resourceSubscribersMutex sync.RWMutex
}
func newEventStream(url string, client *http.Client, authHeader string) *eventStream {
2020-05-27 08:49:40 +00:00
e := &eventStream{
2020-05-27 19:03:26 +00:00
Events: make(chan *sse.Event),
transactionSubscribers: make(map[string]chan *EventStreamResponse),
transactionSubscribersMutex: sync.RWMutex{},
resourceSubscribers: make(map[string][]chan *EventStreamResponse),
resourceSubscribersMutex: sync.RWMutex{},
2020-05-27 19:03:26 +00:00
disconnectedChan: make(chan interface{}),
once: new(sync.Once),
isConnected: false,
isConnectedMutex: sync.RWMutex{},
2020-05-27 08:49:40 +00:00
}
SSEClient := sse.NewClient(url)
SSEClient.Connection = client
SSEClient.Headers["Authorization"] = authHeader
2020-05-27 08:49:40 +00:00
SSEClient.OnDisconnect(func(c *sse.Client) {
e.disconnect()
})
e.SSEClient = SSEClient
return e
}
func (e *eventStream) disconnect() {
e.once.Do(func() {
log.Info("disconnect > close disconnectedChan")
2020-05-27 19:03:26 +00:00
close(e.disconnectedChan)
})
}
func (e *eventStream) listen(ctx context.Context) error {
log.Info("eventStream.listen > start")
2020-05-27 19:03:26 +00:00
2020-05-27 08:49:40 +00:00
err := e.SSEClient.SubscribeChanRaw(e.Events)
if err != nil {
return fmt.Errorf("failed to subscribe to seeclient")
2020-05-27 08:49:40 +00:00
}
go func() {
defer func() {
e.clearResourceSubscriptions()
e.clearTransactionSubscriptions()
log.Info("eventStream.listen > stop")
}()
for {
select {
2020-05-27 08:49:40 +00:00
case <-ctx.Done():
e.disconnect()
return
case event, ok := <-e.Events:
if !ok {
return
}
2020-05-27 08:49:40 +00:00
if event == nil || event.Data == nil {
log.Warn("EventStream > nil event or nil data in event")
continue
}
fmt.Printf("DATA : %s\n", event.Data)
var notifyResponse EventStreamResponse
err := json.NewDecoder(bytes.NewBuffer(event.Data)).Decode(&notifyResponse)
if err != nil {
log.Warnf("EventStream > failed to decode event: %s", event.Data)
continue
}
bytesProperties, err := json.Marshal(notifyResponse.EventStreamPayload.Properties)
if err != nil {
log.Warnf("EventStream > failed to marshal raw properties: %s", event.Data)
continue
}
notifyResponse.RawProperties = bytesProperties
if notifyResponse.Status == "connected" {
e.setIsConnected(true)
2020-05-27 08:49:40 +00:00
continue
}
if notifyResponse.Status == "disconnected" {
e.disconnect()
continue
}
if notifyResponse.Action == "logout" {
log.Warn("EventStream > logged out")
e.disconnect()
continue
}
2020-05-27 19:03:26 +00:00
e.transactionSubscribersMutex.RLock()
subscriber, ok := e.transactionSubscribers[notifyResponse.TransId]
e.transactionSubscribersMutex.RUnlock()
2020-05-27 08:49:40 +00:00
if ok {
subscriber <- &notifyResponse
e.removeTransactionSubscription(notifyResponse.TransId)
}
e.resourceSubscribersMutex.RLock()
subscribers, ok := e.resourceSubscribers[notifyResponse.Resource]
e.resourceSubscribersMutex.RUnlock()
if ok {
for _, s := range subscribers {
s <- &notifyResponse
}
2020-05-27 08:49:40 +00:00
}
2020-05-27 19:03:26 +00:00
case <-e.disconnectedChan:
log.Info("listen loop <- disconnectedchan")
e.setIsConnected(false)
return
}
}
}()
return nil
}
func (e *eventStream) GetIsConnected() bool {
e.isConnectedMutex.RLock()
defer e.isConnectedMutex.RUnlock()
return e.isConnected
}
func (e *eventStream) setIsConnected(isConnected bool) {
e.isConnectedMutex.Lock()
defer e.isConnectedMutex.Unlock()
e.isConnected = isConnected
}
func (e *eventStream) subscribeTransaction(transId string) chan *EventStreamResponse {
msgchan := make(chan *EventStreamResponse)
e.transactionSubscribersMutex.Lock()
e.transactionSubscribers[transId] = msgchan
e.transactionSubscribersMutex.Unlock()
return msgchan
}
func (e *eventStream) subscribeResource(resource string) chan *EventStreamResponse {
msgchan := make(chan *EventStreamResponse)
e.resourceSubscribersMutex.Lock()
e.resourceSubscribers[resource] = append(e.resourceSubscribers[resource], msgchan)
e.resourceSubscribersMutex.Unlock()
return msgchan
}
func (e *eventStream) removeTransactionSubscription(transId string) {
2020-05-27 19:03:26 +00:00
e.transactionSubscribersMutex.Lock()
defer e.transactionSubscribersMutex.Unlock()
subscriber, ok := e.transactionSubscribers[transId]
if ok {
close(subscriber)
2020-05-27 19:03:26 +00:00
delete(e.transactionSubscribers, transId)
}
}
func (e *eventStream) clearResourceSubscriptions() {
e.resourceSubscribersMutex.Lock()
defer e.resourceSubscribersMutex.Unlock()
for _, subscribers := range e.resourceSubscribers {
for _, subscriber := range subscribers {
close(subscriber)
}
}
e.resourceSubscribers = make(map[string][]chan *EventStreamResponse)
}
func (e *eventStream) clearTransactionSubscriptions() {
2020-05-27 19:03:26 +00:00
e.transactionSubscribersMutex.Lock()
defer e.transactionSubscribersMutex.Unlock()
for _, subscriber := range e.transactionSubscribers {
close(subscriber)
}
e.transactionSubscribers = make(map[string]chan *EventStreamResponse)
}