-
Notifications
You must be signed in to change notification settings - Fork 1
/
playlist.go
77 lines (63 loc) · 1.4 KB
/
playlist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"errors"
"fmt"
"io"
"math/rand"
"net/http"
)
const (
ORDER_ITERATE = iota
ORDER_RANDOM
)
type PlaylistItem struct {
location string
author string
description string
code []byte
}
type Playlist struct {
order int
items []PlaylistItem
previous int
}
func NewPlaylist() *Playlist {
return &Playlist{
order: ORDER_ITERATE,
items: []PlaylistItem{},
previous: -1,
}
}
func (p *Playlist) getNext() (*PlaylistItem, error) {
if len(p.items) == 0 {
return nil, errors.New("Playlist is empty")
}
var iItemToPlay int = 0
if p.order == ORDER_ITERATE {
iItemToPlay = (p.previous + 1) % len(p.items)
} else { // Random
// #TODO: ensure no repeats
iItemToPlay = rand.Intn(len(p.items))
}
item := p.items[iItemToPlay]
p.previous = iItemToPlay
if item.code != nil {
// fmt.Printf("Cached: %s\n", item.location)
return &item, nil
}
// fmt.Printf("Loading: %s\n", item.location)
respLua, err := http.Get(item.location)
if err != nil {
return nil, err
}
defer respLua.Body.Close()
if respLua.StatusCode != http.StatusOK {
return nil, errors.New(fmt.Sprintf("ERR write: Status Code = %d", respLua.StatusCode))
}
data, err := io.ReadAll(respLua.Body)
if err != nil {
return nil, err
}
p.items[iItemToPlay].code = data
return &p.items[iItemToPlay], nil
}