go-twitch/eventsub/eventsub.go

75 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-02-27 22:13:57 -05:00
package eventsub
import (
"context"
2024-02-27 22:13:57 -05:00
"go.fifitido.net/twitch/api"
"go.fifitido.net/twitch/api/eventsub"
)
type EventSub struct {
api *api.API
2024-03-05 12:14:18 -05:00
transport Transport
2024-02-27 22:13:57 -05:00
subscriptions map[string]*eventsub.Subscription
}
2024-03-05 12:14:18 -05:00
func New(api *api.API, trans Transport) *EventSub {
2024-02-27 22:13:57 -05:00
return &EventSub{
api: api,
transport: trans,
}
}
func (e *EventSub) Subscribe(ctx context.Context, subType eventsub.SubscriptionType, cond eventsub.Condition) error {
res, err := e.api.EventSub.CreateEventSubSubscription(ctx, &eventsub.CreateEventSubSubscriptionRequest{
2024-02-27 22:13:57 -05:00
SubscriptionType: subType,
Condition: cond,
2024-03-05 12:14:18 -05:00
Transport: e.transport.ApiTransport(),
2024-02-27 22:13:57 -05:00
})
if err != nil {
return err
}
for _, sub := range res.Data {
e.subscriptions[sub.ID] = sub
}
return nil
}
2024-03-05 12:14:18 -05:00
func (e *EventSub) Unsubscribe(ctx context.Context, subType eventsub.SubscriptionType) error {
for _, sub := range e.subscriptions {
if sub.SubType() == subType {
if err := e.api.EventSub.DeleteEventSubSubscription(ctx, sub.ID); err != nil {
return err
}
}
}
return nil
}
func (e *EventSub) Run() error {
return e.transport.Run()
}
func (e *EventSub) Start() {
e.transport.Start()
}
2024-02-27 22:13:57 -05:00
func (e *EventSub) Close() error {
for _, sub := range e.subscriptions {
if err := e.api.EventSub.DeleteEventSubSubscription(context.Background(), sub.ID); err != nil {
2024-02-27 22:13:57 -05:00
return err
}
}
2024-03-05 12:14:18 -05:00
if err := e.transport.Close(); err != nil {
return err
}
2024-02-27 22:13:57 -05:00
return nil
}