~gjabell/ko

ref: 3b82722bbda6 ko/media/store.go -rw-r--r-- 4.1 KiB
3b82722bGalen Abell mpv: Reset to unpaused when playing a new file 6 months ago
                                                                                
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
package media

import (
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"strings"

	"appliedgo.net/what"
	"git.sr.ht/~gjabell/ko/cfg"
)

var logger = log.New(os.Stderr, "[store] ", log.Ldate|log.Ltime|log.Lshortfile)

// TODO check file type by mime and not ending
var videoExtensions = map[string]int{".webm": 0, ".mkv": 0, ".flv": 0,
	".avi": 0, ".mov": 0, ".mp4": 0, ".m4v": 0, ".m2ts": 0}

type Store struct {
	MovieRootDir string
	ShowRootDir  string
	Movies       map[string]Movie
	Shows        map[string]Show
}

func NewStore(config *cfg.Config) (*Store, error) {
	store := &Store{}

	if movieConfig, ok := config.Collections["movies"]; ok {
		logger.Println("Loading movies")

		store.MovieRootDir = movieConfig.Path

		var err error
		if store.Movies, err = loadMovies(store.MovieRootDir); err != nil {
			return nil, err
		}
	}

	if showConfig, ok := config.Collections["shows"]; ok {
		logger.Println("Loading shows")

		store.ShowRootDir = showConfig.Path

		var err error
		if store.Shows, err = loadShows(store.ShowRootDir); err != nil {
			return nil, err
		}
	}

	logger.Printf("Loaded %d movies and %d shows", len(store.Movies), len(store.Shows))

	return store, nil
}

func loadMovies(rootDir string) (map[string]Movie, error) {
	mediaPaths, err := loadMediaPaths(rootDir)
	if err != nil {
		return nil, err
	}

	movies := make(map[string]Movie)
	for _, mediaPath := range mediaPaths {
		items := strings.Split(mediaPath, string(filepath.Separator))

		if len(items) != 2 {
			what.Happens("Skipping invalid movie path %s", mediaPath)
			continue
		}

		movieName := trimExt(items[1]) // ie "Inception (2010)"
		movie := makeMovie(movieName, mediaPath, rootDir)
		movies[movieName] = movie
	}

	what.Is(movies)
	return movies, nil
}

func makeMovie(name, relPath, rootDir string) Movie {
	return Movie{
		Name:   name,
		Poster: filepath.Join(rootDir, trimExt(relPath)+"-poster.jpg"),
		Path:   filepath.Join(rootDir, relPath),
	}
}

func loadShows(rootDir string) (map[string]Show, error) {
	mediaPaths, err := loadMediaPaths(rootDir)
	if err != nil {
		return nil, err
	}

	shows := make(map[string]Show)
	for _, mediaPath := range mediaPaths {
		parts := strings.Split(mediaPath, string(filepath.Separator))
		if len(parts) != 3 {
			what.Happens("Skipping invalid show path: %s", mediaPath)
			continue
		}

		showName := parts[0]    // ie "Futurama"
		seasonName := parts[1]  // ie "Season 01"
		episodeName := parts[2] // ie "Futurama - s01e01 - Space Pilot 3000"

		show, ok := shows[showName]
		if !ok {
			show = makeShow(showName, rootDir)
			shows[showName] = show
		}

		season, ok := show.Seasons[seasonName]
		if !ok {
			season = makeSeason(seasonName, showName, rootDir)
			show.Seasons[seasonName] = season
		}

		episode := makeEpisode(episodeName, mediaPath, rootDir)
		season.Episodes[episode.Name] = episode
	}

	what.Is(shows)
	return shows, nil
}

func makeShow(name, rootDir string) Show {
	return Show{
		Name:    name,
		Poster:  filepath.Join(rootDir, name, "poster.jpg"),
		Seasons: make(map[string]Season),
	}
}

func makeSeason(name, show, rootDir string) Season {
	posterName := strings.ReplaceAll(strings.ToLower(name), " ", "") + "-poster.jpg"

	return Season{
		Name:     name,
		Poster:   filepath.Join(rootDir, show, posterName),
		Episodes: make(map[string]Episode),
	}
}

func makeEpisode(name, relPath, rootDir string) Episode {
	name = trimExt(name)
	nameParts := strings.Split(name, " - ")

	return Episode{
		Name:        name,
		DisplayName: nameParts[len(nameParts)-1],
		Poster:      filepath.Join(rootDir, trimExt(relPath)+"-thumb.jpg"),
		Path:        filepath.Join(rootDir, relPath),
	}
}

func trimExt(filename string) string {
	return strings.TrimSuffix(filename, filepath.Ext(filename))
}

func loadMediaPaths(rootDir string) ([]string, error) {
	var media []string

	walkFunc := func(path string, d fs.DirEntry, err error) error {
		if d == nil {
			return nil
		}

		extension := filepath.Ext(d.Name())
		if _, ok := videoExtensions[extension]; ok {
			relPath, err := filepath.Rel(rootDir, path)
			if err != nil {
				return err
			}
			media = append(media, relPath)
		}

		return nil
	}

	return media, filepath.WalkDir(rootDir, walkFunc)
}