|
| 1 | +package superChatEvent |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "github.com/eat-pray-ai/yutu/pkg/utils" |
| 7 | + "google.golang.org/api/youtube/v3" |
| 8 | + "log" |
| 9 | +) |
| 10 | + |
| 11 | +var ( |
| 12 | + service *youtube.Service |
| 13 | + errGetSuperChatEvent = errors.New("failed to get super chat event") |
| 14 | +) |
| 15 | + |
| 16 | +type superChatEvent struct { |
| 17 | + Hl string `yaml:"hl" json:"hl"` |
| 18 | + MaxResults int64 `yaml:"max_results" json:"max_results"` |
| 19 | +} |
| 20 | + |
| 21 | +type SuperChatEvent interface { |
| 22 | + get([]string) []*youtube.SuperChatEvent |
| 23 | + List([]string, string) |
| 24 | +} |
| 25 | + |
| 26 | +type Option func(*superChatEvent) |
| 27 | + |
| 28 | +func NewSuperChatEvent(opts ...Option) SuperChatEvent { |
| 29 | + s := &superChatEvent{} |
| 30 | + |
| 31 | + for _, opt := range opts { |
| 32 | + opt(s) |
| 33 | + } |
| 34 | + |
| 35 | + return s |
| 36 | +} |
| 37 | + |
| 38 | +func (s *superChatEvent) get(parts []string) []*youtube.SuperChatEvent { |
| 39 | + call := service.SuperChatEvents.List(parts) |
| 40 | + if s.Hl != "" { |
| 41 | + call = call.Hl(s.Hl) |
| 42 | + } |
| 43 | + if s.MaxResults <= 0 { |
| 44 | + s.MaxResults = 1 |
| 45 | + } |
| 46 | + call = call.MaxResults(s.MaxResults) |
| 47 | + |
| 48 | + res, err := call.Do() |
| 49 | + if err != nil { |
| 50 | + utils.PrintJSON(s) |
| 51 | + log.Fatalln(errors.Join(errGetSuperChatEvent, err)) |
| 52 | + } |
| 53 | + |
| 54 | + return res.Items |
| 55 | +} |
| 56 | + |
| 57 | +func (s *superChatEvent) List(parts []string, output string) { |
| 58 | + events := s.get(parts) |
| 59 | + switch output { |
| 60 | + case "json": |
| 61 | + utils.PrintJSON(events) |
| 62 | + case "yaml": |
| 63 | + utils.PrintYAML(events) |
| 64 | + default: |
| 65 | + fmt.Println("ID\tAmount") |
| 66 | + for _, event := range events { |
| 67 | + fmt.Printf("%v\t%v\n", event.Id, event.Snippet.AmountMicros) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +func WithHl(hl string) Option { |
| 73 | + return func(s *superChatEvent) { |
| 74 | + s.Hl = hl |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func WithMaxResults(maxResults int64) Option { |
| 79 | + return func(s *superChatEvent) { |
| 80 | + s.MaxResults = maxResults |
| 81 | + } |
| 82 | +} |
0 commit comments