website/pkg/worker/barertc.go

93 lines
2.1 KiB
Go

package worker
import (
"encoding/json"
"io/ioutil"
"net/http"
"sync"
"time"
"code.nonshy.com/nonshy/website/pkg/config"
"code.nonshy.com/nonshy/website/pkg/log"
)
// ChatStatistics is the json result of the BareRTC /api/statistics endpoint.
type ChatStatistics struct {
UserCount int
Usernames []string
}
// GetChatStatistics returns the latest (cached) chat statistics.
func GetChatStatistics() ChatStatistics {
chatStatisticsMu.RLock()
defer chatStatisticsMu.RUnlock()
if cachedChatStatistics != nil {
return *cachedChatStatistics
}
return ChatStatistics{
Usernames: []string{},
}
}
var (
cachedChatStatistics *ChatStatistics
chatStatisticsMu sync.RWMutex
)
// WatchBareRTC is a worker goroutine that caches the current online chatters in the chat room.
func WatchBareRTC() {
if config.Current.BareRTC.JWTSecret == "" || config.Current.BareRTC.URL == "" {
log.Error("Worker (WatchBareRTC): chat room is not configured, will not watch chat room status")
return
}
// Check it immediately.
DoCheckBareRTC()
// And on an interval forever.
ticker := time.NewTicker(config.ChatStatusRefreshInterval)
for range ticker.C {
DoCheckBareRTC()
}
}
// DoCheckBareRTC invokes the attempt to refresh data from the chat server about who's online.
func DoCheckBareRTC() {
log.Info("Refresh BareRTC")
req, err := http.NewRequest(http.MethodGet, config.Current.BareRTC.URL+"/api/statistics", nil)
// Lock the cached statistics.
chatStatisticsMu.Lock()
defer chatStatisticsMu.Unlock()
if err != nil {
log.Error("WatchBareRTC: couldn't make request: %s", err)
cachedChatStatistics = nil
return
}
client := http.Client{
Timeout: 30 * time.Second,
}
res, err := client.Do(req)
if err != nil {
log.Error("WatchBareRTC: request error: %s", err)
cachedChatStatistics = nil
return
}
if res.StatusCode == http.StatusOK {
var cs ChatStatistics
body, _ := ioutil.ReadAll(res.Body)
res.Body.Close()
if err = json.Unmarshal(body, &cs); err != nil {
log.Error("WatchBareRTC: json decode error: %s", err)
return
}
cachedChatStatistics = &cs
}
}