tube/pkg/media/library.go

78 lines
1.2 KiB
Go
Raw Normal View History

2019-06-26 22:02:31 +03:00
package media
import (
"io/ioutil"
2019-06-29 01:20:52 +03:00
"log"
"path/filepath"
2019-06-26 22:02:31 +03:00
"sort"
"strings"
2019-06-29 01:20:52 +03:00
"sync"
2019-06-26 22:02:31 +03:00
)
type Library struct {
2019-06-29 01:20:52 +03:00
mu sync.RWMutex
2019-06-26 22:02:31 +03:00
Videos map[string]*Video
}
func NewLibrary() *Library {
lib := &Library{
Videos: make(map[string]*Video),
}
return lib
}
func (lib *Library) Import(path string) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, info := range files {
2019-06-29 01:20:52 +03:00
err = lib.Add(path + "/" + info.Name())
2019-06-26 22:02:31 +03:00
if err != nil {
// Ignore files that can't be parsed
continue
}
}
return nil
}
2019-06-29 01:20:52 +03:00
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
}
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)
}
}
2019-06-26 22:02:31 +03:00
func (lib *Library) Playlist() Playlist {
2019-06-29 01:20:52 +03:00
lib.mu.RLock()
defer lib.mu.RUnlock()
2019-06-26 22:02:31 +03:00
pl := make(Playlist, 0)
for _, v := range lib.Videos {
pl = append(pl, v)
}
sort.Sort(pl)
return pl
}