2022-09-10 11:39:07 +00:00
|
|
|
package overlays
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2023-11-27 23:09:27 +00:00
|
|
|
"gorm.io/gorm"
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2023-11-27 23:09:27 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v3/internal/helpers"
|
2022-11-02 21:38:14 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v3/pkg/database"
|
|
|
|
"github.com/Luzifer/twitch-bot/v3/plugins"
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
type (
|
|
|
|
overlaysEvent struct {
|
2023-11-25 19:23:34 +00:00
|
|
|
ID uint64 `gorm:"primaryKey"`
|
2022-10-22 22:08:02 +00:00
|
|
|
Channel string `gorm:"not null;index:overlays_events_sort_idx"`
|
|
|
|
CreatedAt time.Time `gorm:"index:overlays_events_sort_idx"`
|
|
|
|
EventType string
|
|
|
|
Fields string
|
|
|
|
}
|
|
|
|
)
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func AddChannelEvent(db database.Connector, channel string, evt SocketMessage) error {
|
2022-09-10 11:39:07 +00:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if err := json.NewEncoder(buf).Encode(evt.Fields); err != nil {
|
|
|
|
return errors.Wrap(err, "encoding fields")
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
return errors.Wrap(
|
2023-11-27 23:09:27 +00:00
|
|
|
helpers.RetryTransaction(db.DB(), func(tx *gorm.DB) error {
|
|
|
|
return tx.Create(&overlaysEvent{
|
|
|
|
Channel: channel,
|
|
|
|
CreatedAt: evt.Time.UTC(),
|
|
|
|
EventType: evt.Type,
|
|
|
|
Fields: strings.TrimSpace(buf.String()),
|
|
|
|
}).Error
|
|
|
|
}),
|
2022-10-22 22:08:02 +00:00
|
|
|
"storing event to database",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func GetChannelEvents(db database.Connector, channel string) ([]SocketMessage, error) {
|
|
|
|
var evts []overlaysEvent
|
|
|
|
|
2023-11-27 23:09:27 +00:00
|
|
|
if err := helpers.Retry(func() error {
|
|
|
|
return db.DB().Where("channel = ?", channel).Order("created_at").Find(&evts).Error
|
|
|
|
}); err != nil {
|
2022-09-10 11:39:07 +00:00
|
|
|
return nil, errors.Wrap(err, "querying channel events")
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
var out []SocketMessage
|
|
|
|
for _, e := range evts {
|
2022-09-10 11:39:07 +00:00
|
|
|
fields := new(plugins.FieldCollection)
|
2022-10-22 22:08:02 +00:00
|
|
|
if err := json.NewDecoder(strings.NewReader(e.Fields)).Decode(fields); err != nil {
|
2022-09-10 11:39:07 +00:00
|
|
|
return nil, errors.Wrap(err, "decoding fields")
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
out = append(out, SocketMessage{
|
2022-09-10 11:39:07 +00:00
|
|
|
IsLive: false,
|
2022-10-22 22:08:02 +00:00
|
|
|
Time: e.CreatedAt,
|
|
|
|
Type: e.EventType,
|
2022-09-10 11:39:07 +00:00
|
|
|
Fields: fields,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
return out, nil
|
2022-09-10 11:39:07 +00:00
|
|
|
}
|