summaryrefslogtreecommitdiff
path: root/pkg/media/library.go
blob: 337907de6e4cc364672361ba7517783cb399a3ca (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
package media

import (
	"io/ioutil"
	"log"
	"path/filepath"
	"sort"
	"strings"
	"sync"
)

type Library struct {
	mu     sync.RWMutex
	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 {
		err = lib.Add(path + "/" + info.Name())
		if err != nil {
			// Ignore files that can't be parsed
			continue
		}
	}
	return nil
}

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)
	}
}

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
}