Add donation webhook

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2021-05-04 18:27:56 +02:00
parent aa20136f63
commit e4800c921f
Signed by: luzifer
GPG key ID: 0066F03ED215AD7D
3 changed files with 55 additions and 11 deletions

1
api.go
View file

@ -21,6 +21,7 @@ const (
msgTypeAlert string = "alert"
msgTypeBits string = "bits"
msgTypeCustom string = "custom"
msgTypeDonation string = "donation"
msgTypeFollow string = "follow"
msgTypeHost string = "host"
msgTypeRaid string = "raid"

View file

@ -4,18 +4,26 @@ import (
"compress/gzip"
"encoding/json"
"os"
"sort"
"sync"
"time"
"github.com/pkg/errors"
)
const storeMaxRecent = 25
const storeMaxRecent = 50
type subscriber struct {
Name string `json:"name"`
Months int64 `json:"months"`
}
type storedEvent struct {
Time time.Time
Type string
Message map[string]interface{}
}
type storage struct {
BitDonations struct {
LastDonator *string `json:"last_donator"`
@ -25,7 +33,6 @@ type storage struct {
Donations struct {
LastDonator *string `json:"last_donator"`
LastAmount float64 `json:"last_amount"`
TotalAmount float64 `json:"total_amount"`
} `json:"donations"`
Followers struct {
Last *string `json:"last"`
@ -39,6 +46,8 @@ type storage struct {
Recent []subscriber `json:"recent"`
} `json:"subs"`
Events []storedEvent
modLock sync.RWMutex
saveLock sync.Mutex
}
@ -82,6 +91,11 @@ func (s *storage) Save(to string) error {
s.Subs.Recent = s.Subs.Recent[:storeMaxRecent]
}
sort.Slice(s.Events, func(j, i int) bool { return s.Events[i].Time.Before(s.Events[j].Time) })
if len(s.Events) > storeMaxRecent {
s.Events = s.Events[:storeMaxRecent]
}
f, err := os.Create(to)
if err != nil {
return errors.Wrap(err, "create file")

View file

@ -63,6 +63,35 @@ func handleWebHookPush(w http.ResponseWriter, r *http.Request) {
}
switch hookType {
case "donation":
var payload struct {
Name string `json:"name"`
Amount float64 `json:"amount"`
Message string `json:"message"`
}
if err := json.NewDecoder(body).Decode(&payload); err != nil {
logger.WithError(err).Error("Unable to decode payload")
return
}
fields := map[string]interface{}{
"name": payload.Name,
"amount": payload.Amount,
"message": payload.Message,
}
if err := subscriptions.SendAllSockets(msgTypeDonation, fields); err != nil {
log.WithError(err).Error("Unable to send update to all sockets")
}
store.WithModLock(func() error {
store.Donations.LastAmount = payload.Amount
store.Donations.LastDonator = &payload.Name
return nil
})
case "follow":
var payload struct {
Data []struct {