-
Notifications
You must be signed in to change notification settings - Fork 0
/
playlist.go
304 lines (262 loc) · 7.07 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package piplayer
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"regexp"
"strconv"
"github.com/fsnotify/fsnotify"
)
// Playlist stores the media items that can be played.
type Playlist struct {
Name string
Items []Item
Current *Item
watcher *fsnotify.Watcher
}
// Presentation is used to read the presentation.json file for added cues.
type Presentation struct {
Items []ItemString
}
// NewPlaylist creates a new playlist with media in the designated folder.
func NewPlaylist(p *Player, dir string) (*Playlist, error) {
pl := Playlist{Name: dir}
if err := p.conf.Mount.mount(); err != nil {
log.Println("NewServer: Error trying to mount folder:\n", err)
}
var err error
pl.watcher, err = fsnotify.NewWatcher()
if err != nil {
return &pl, err
}
go pl.watch(p)
if p.conf.Debug {
log.Println("starting directory watcher for dir:", dir)
}
err = pl.watcher.Add(dir)
return &pl, err
}
// Handles requests to the playlist api
func (p *Playlist) handleAPI(plr *Player, w http.ResponseWriter, h *http.Request) {
var m resMessage
switch plr.api.message.Method {
case "getCurrent":
if p.Current != nil {
m = resMessage{
Success: true,
Event: "current",
Message: p.Current.Name(),
}
} else {
m = resMessage{
Success: true,
Event: "noCurrent",
}
}
case "setCurrent":
if plr.api.message.Arguments == nil || len(plr.api.message.Arguments) == 0 {
m = resMessage{
Success: false,
Event: "noArgumentSupplied",
}
break
}
index, err := strconv.Atoi(plr.api.message.Arguments["index"])
if err != nil {
log.Printf("Error converting argument to int: playlist.HandleAPI.setCurrent\n%v", err)
}
if err != nil || index < 0 || index >= len(p.Items) {
m = resMessage{
Success: false,
Event: "argumentInvalid",
}
break
}
p.Current = &p.Items[index]
m = resMessage{
Success: true,
Event: "setCurrent",
Message: index,
}
// send update to the control page, if open.
if plr.ConnControl.isActive() {
m := wsMessage{
Success: true,
Event: "setCurrent",
Message: index,
}
send := plr.ConnControl.getChanSend()
send <- m
}
if plr.api.debug {
log.Println("set current item index to:", index)
}
case "getItems":
if err := p.fromFolder(plr, p.Name); err != nil {
log.Printf("Api call failed. Can't get items from folder %s\n%v", p.Name, err)
}
m = resMessage{
Success: true,
Event: "items",
Message: p.itemsString(),
}
default:
log.Printf("API call unsupported. Ignoring:\n%v\n", plr.api.message)
}
json.NewEncoder(w).Encode(m)
}
func (p *Playlist) fromFolder(plr *Player, dir string) error {
// Remove all items from the current playlist if there are any.
p.Items = []Item{}
p.Name = dir
// Read files from a certain folder into a playlist.
if !exists(dir) {
return fmt.Errorf("fromFolder: Can't read files from directory '%s' because it does not exist", dir)
}
files, err := ioutil.ReadDir(dir)
if err != nil {
return errors.New("fromFolder: Can't read folder for items: " + err.Error())
}
// Filter out all files except for supported ones.
for _, file := range files {
c := make(map[string]string)
e := path.Ext(file.Name())
if e == ".mp4" || e == ".webm" {
p.Items = append(p.Items, Item{Visual: file, Type: "video", Cues: c})
} else if e == ".jpg" || e == ".jpeg" || e == ".png" {
p.Items = append(p.Items, Item{Visual: file, Type: "image", Cues: c})
} else if e == ".html" {
p.Items = append(p.Items, Item{Visual: file, Type: "browser", Cues: c})
}
}
// scan for .mp3 files to see if any need to be attached to image files
for _, file := range files {
e := path.Ext(file.Name())
if e != ".mp3" && e != ".mp0" {
continue
}
audioBase := file.Name()[0 : len(file.Name())-len(e)]
for i, item := range p.Items {
visual := item.Visual.Name()
visualBase := visual[0 : len(visual)-len(path.Ext(visual))]
if audioBase == visualBase {
if e == ".mp3" {
p.Items[i].Audio = file
} else if e == ".mp0" {
p.Items[i].Cues["clear"] = "audio"
}
break
}
}
}
// look for presentation file for added cues.
file := path.Join(dir, "presentation.json")
if _, err := os.Stat(file); !os.IsNotExist(err) {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Printf("Error trying to read presentation file '%s': %v", file, err)
return nil
}
var presentation Presentation
json.Unmarshal(data, &presentation)
// Loop through presentation data and attach cues to items.
for _, presItem := range presentation.Items {
// Create regex to match on file names.
r, err := regexp.Compile(presItem.Visual)
if err != nil {
log.Printf("Could not compile regex with text '%s', comparing using visual name only.", presItem.Visual)
}
for _, playItem := range p.Items {
// If the regex can't compile, use the file name, otherwise use the regex.
if err != nil && presItem.Visual == playItem.Visual.Name() {
for k, v := range presItem.Cues {
playItem.Cues[k] = v
}
break
} else if err == nil && r.MatchString(playItem.Visual.Name()) {
for k, v := range presItem.Cues {
playItem.Cues[k] = v
}
}
}
}
}
return nil
}
// watch for changes in the supplied directory
func (p *Playlist) watch(plr *Player) {
defer p.watcher.Close()
send := plr.ConnControl.getChanSend()
for {
select {
case event, ok := <-p.watcher.Events:
// This means a file changed in the folder.
if !ok {
log.Println("issue getting file change event. Stopping watcher.")
return
}
if plr.conf.Debug {
log.Println("file change event:", event)
}
// Send a message to the viewer to get new items.
msg := wsMessage{
Component: "playlist",
Event: "newItems",
Message: "detected file change. Get new items.",
}
send <- msg
case err, ok := <-p.watcher.Errors:
if !ok {
log.Println("issue getting file change error. Stopping watcher.")
return
}
log.Println("error:", err)
}
}
}
// func (p *Playlist) getIndex(fileName string) int {
// for i, item := range p.Items {
// if item.Name() == fileName {
// return i
// }
// }
// return -1
// }
// func (p *Playlist) getNext() (*Item, error) {
// if p.Current == nil {
// return nil, errors.New("no current item, can't get next")
// }
// i := p.getIndex(p.Current.Name())
// if i == -1 {
// return nil, errors.New("can't find index of this item: " + p.Current.Name())
// }
// if i+1 > len(p.Items)-1 {
// return &p.Items[0], nil
// }
// return &p.Items[i+1], nil
// }
// func (p *Playlist) getPrevious() (*Item, error) {
// if p.Current == nil {
// return nil, errors.New("no current item, can't get previous")
// }
// i := p.getIndex(p.Current.Name())
// if i == -1 {
// return nil, errors.New("can't find index of this item: " + p.Current.Name())
// }
// if i-1 < 0 {
// return &p.Items[len(p.Items)-1], nil
// }
// return &p.Items[i-1], nil
// }
func (p *Playlist) itemsString() []ItemString {
var res []ItemString
for _, item := range p.Items {
res = append(res, item.String())
}
return res
}