Skip to content

Commit

Permalink
✨ Add super chat event service
Browse files Browse the repository at this point in the history
  • Loading branch information
OpenWaygate committed Aug 31, 2024
1 parent 53ffe81 commit 6c22e93
Show file tree
Hide file tree
Showing 2 changed files with 122 additions and 0 deletions.
82 changes: 82 additions & 0 deletions pkg/superChatEvent/superChatEvent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package superChatEvent

import (
"errors"
"fmt"
"github.com/eat-pray-ai/yutu/pkg/utils"
"google.golang.org/api/youtube/v3"
"log"
)

var (
service *youtube.Service
errGetSuperChatEvent = errors.New("failed to get super chat event")
)

type superChatEvent struct {
Hl string `yaml:"hl" json:"hl"`
MaxResults int64 `yaml:"max_results" json:"max_results"`
}

type SuperChatEvent interface {
get([]string) []*youtube.SuperChatEvent
List([]string, string)
}

type Option func(*superChatEvent)

func NewSuperChatEvent(opts ...Option) SuperChatEvent {
s := &superChatEvent{}

for _, opt := range opts {
opt(s)
}

return s
}

func (s *superChatEvent) get(parts []string) []*youtube.SuperChatEvent {
call := service.SuperChatEvents.List(parts)
if s.Hl != "" {
call = call.Hl(s.Hl)
}
if s.MaxResults <= 0 {
s.MaxResults = 1
}
call = call.MaxResults(s.MaxResults)

res, err := call.Do()
if err != nil {
utils.PrintJSON(s)
log.Fatalln(errors.Join(errGetSuperChatEvent, err))
}

return res.Items
}

func (s *superChatEvent) List(parts []string, output string) {
events := s.get(parts)
switch output {
case "json":
utils.PrintJSON(events)
case "yaml":
utils.PrintYAML(events)
default:
fmt.Println("ID\tAmount")
for _, event := range events {
fmt.Printf("%v\t%v\n", event.Id, event.Snippet.AmountMicros)
}
}
}

func WithHl(hl string) Option {
return func(s *superChatEvent) {
s.Hl = hl
}
}

func WithMaxResults(maxResults int64) Option {
return func(s *superChatEvent) {
s.MaxResults = maxResults
}
}
40 changes: 40 additions & 0 deletions pkg/superChatEvent/superChatEvent_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package superChatEvent

import (
"reflect"
"testing"
)

func TestNewSuperChatEvent(t *testing.T) {
type args struct {
opts []Option
}
tests := []struct {
name string
args args
want SuperChatEvent
}{
{
name: "TestNewSuperChatEvent",
args: args{
opts: []Option{
WithHl("hl"),
WithMaxResults(1),
},
},
want: &superChatEvent{
Hl: "hl",
MaxResults: 1,
},
},
}
for _, tt := range tests {
t.Run(
tt.name, func(t *testing.T) {
if got := NewSuperChatEvent(tt.args.opts...); !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewSuperChatEvent() = %v, want %v", got, tt.want)
}
},
)
}
}

0 comments on commit 6c22e93

Please # to comment.