blob: c0d79eb6b55de969b16de29def5c53d69a0cc4f8 (
plain)
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
|
package media
import (
"io/ioutil"
"log"
"path/filepath"
"sort"
"strings"
"sync"
)
// Library manages importing and retrieving video data.
type Library struct {
mu sync.RWMutex
Videos map[string]*Video
}
// NewLibrary returns new instance of Library.
func NewLibrary() *Library {
lib := &Library{
Videos: make(map[string]*Video),
}
return lib
}
// Import adds all valid videos from a given path.
func (lib *Library) Import(path string) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, info := range files {
err = lib.Add(path + "/" + info.Name())
if err != nil {
// Ignore files that can't be parsed
continue
}
}
return nil
}
// Add adds a single video from a given file path.
func (lib *Library) Add(path string) error {
v, err := ParseVideo(path)
if err != nil {
return err
}
lib.mu.Lock()
defer lib.mu.Unlock()
lib.Videos[v.ID] = v
log.Println("Added:", path)
return nil
}
// Remove removes a single video from a given file path.
func (lib *Library) Remove(path string) {
name := filepath.Base(path)
// ID is name without extension
idx := strings.LastIndex(name, ".")
if idx == -1 {
idx = len(name)
}
id := name[:idx]
lib.mu.Lock()
defer lib.mu.Unlock()
_, ok := lib.Videos[id]
if ok {
delete(lib.Videos, id)
log.Println("Removed:", path)
}
}
// Playlist returns a sorted Playlist of all videos.
func (lib *Library) Playlist() Playlist {
lib.mu.RLock()
defer lib.mu.RUnlock()
pl := make(Playlist, 0)
for _, v := range lib.Videos {
pl = append(pl, v)
}
sort.Sort(pl)
return pl
}
|