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
|
|
|
)
|
|
|
|
|
2019-06-30 01:02:05 +03:00
|
|
|
// Library manages importing and retrieving video data.
|
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
|
|
|
|
}
|
|
|
|
|
2019-06-30 01:02:05 +03:00
|
|
|
// NewLibrary returns new instance of Library.
|
2019-06-26 22:02:31 +03:00
|
|
|
func NewLibrary() *Library {
|
|
|
|
lib := &Library{
|
|
|
|
Videos: make(map[string]*Video),
|
|
|
|
}
|
|
|
|
return lib
|
|
|
|
}
|
|
|
|
|
2019-06-30 01:02:05 +03:00
|
|
|
// Import adds all valid videos from a given path.
|
2019-06-26 22:02:31 +03:00
|
|
|
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-30 01:02:05 +03:00
|
|
|
// Add adds a single video from a given file path.
|
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
|
|
|
|
}
|
|
|
|
|
2019-06-30 01:02:05 +03:00
|
|
|
// Remove removes a single video from a given file path.
|
2019-06-29 01:20:52 +03:00
|
|
|
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-30 01:02:05 +03:00
|
|
|
// Playlist returns a sorted Playlist of all videos.
|
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-07-03 15:54:22 +03:00
|
|
|
pl := make(Playlist, len(lib.Videos))
|
|
|
|
i := 0
|
2019-06-26 22:02:31 +03:00
|
|
|
for _, v := range lib.Videos {
|
2019-07-03 15:54:22 +03:00
|
|
|
pl[i] = v
|
|
|
|
i++
|
2019-06-26 22:02:31 +03:00
|
|
|
}
|
|
|
|
sort.Sort(pl)
|
|
|
|
return pl
|
|
|
|
}
|