internal/mpv_playlist_test.go
413 lines · 11849 bytes
1package internal
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strconv"
8 "strings"
9 "testing"
10)
11
12func TestEpisodeLabelMarksCurrentAndFiller(t *testing.T) {
13 c := &MPVPlaylistController{
14 anime: &Anime{
15 Title: AnimeTitle{English: "Demo"},
16 FillerEpisodes: []int{3, 5},
17 Ep: Episode{Number: 2},
18 },
19 preferredMode: "sub",
20 currentPlaying: 2,
21 currentMode: "sub",
22 }
23 label := c.episodeLabel(2, "sub")
24 if !strings.Contains(label, "Episode 2") || !strings.Contains(label, "◀") {
25 t.Fatalf("current ep label: %q", label)
26 }
27 if !strings.Contains(label, "Demo") {
28 t.Fatalf("expected show name in label: %q", label)
29 }
30 filler := c.episodeLabel(3, "sub")
31 if !strings.Contains(filler, "Filler") {
32 t.Fatalf("expected filler mark, got %q", filler)
33 }
34 dub := c.episodeLabel(2, "dub")
35 if !strings.Contains(strings.ToUpper(dub), "DUB") {
36 t.Fatalf("expected dub mark, got %q", dub)
37 }
38 // Preferred dub should not spam DUB on every preferred row.
39 c.preferredMode = "dub"
40 c.currentMode = "dub"
41 preferredDub := c.episodeLabel(1, "dub")
42 if strings.Contains(preferredDub, "(DUB)") {
43 t.Fatalf("preferred dub row should not add (DUB): %q", preferredDub)
44 }
45}
46
47func TestEpisodeIndexFindsAlternateModeSlot(t *testing.T) {
48 c := &MPVPlaylistController{
49 slots: []playlistSlot{
50 {Episode: 1, Mode: "sub"},
51 {Episode: 2, Mode: "sub"},
52 {Episode: 2, Mode: "dub"},
53 {Episode: 3, Mode: "sub"},
54 },
55 }
56 if got := c.episodeIndex(2, "dub"); got != 2 {
57 t.Fatalf("dub slot index=%d want 2", got)
58 }
59 if got := c.episodeIndex(2, "sub"); got != 1 {
60 t.Fatalf("sub slot index=%d want 1", got)
61 }
62 if got := c.episodeIndex(9, "sub"); got != 8 {
63 t.Fatalf("fallback index for ep9=%d want 8", got)
64 }
65}
66
67func TestIsEpisodeFillerHelper(t *testing.T) {
68 if !IsEpisodeFiller([]int{1, 4, 7}, 4) {
69 t.Fatal("expected filler")
70 }
71 if IsEpisodeFiller([]int{1, 4, 7}, 3) {
72 t.Fatal("expected non-filler")
73 }
74}
75
76func TestParseEpisodeNumberListDedupesAndSorts(t *testing.T) {
77 got := parseEpisodeNumberList([]string{"3", "1", "2", "2", " 12.0 ", "bad", "0", "-1"})
78 want := []int{1, 2, 3, 12}
79 if len(got) != len(want) {
80 t.Fatalf("got %v want %v", got, want)
81 }
82 for i := range want {
83 if got[i] != want[i] {
84 t.Fatalf("got %v want %v", got, want)
85 }
86 }
87}
88
89func TestWritePlaceholderM3UHasEXTINFTitles(t *testing.T) {
90 c := &MPVPlaylistController{
91 config: &CurdConfig{StoragePath: t.TempDir()},
92 anime: &Anime{Title: AnimeTitle{English: "Demo"}},
93 }
94 slots := []playlistSlot{
95 {Episode: 1, Mode: "sub", Label: "Demo - Episode 1"},
96 {Episode: 2, Mode: "sub", Label: "Demo - Episode 2 [Filler]"},
97 }
98 path, err := c.writePlaceholderM3U(slots)
99 if err != nil {
100 t.Fatal(err)
101 }
102 defer os.Remove(path)
103
104 raw, err := os.ReadFile(path)
105 if err != nil {
106 t.Fatal(err)
107 }
108 body := string(raw)
109 if !strings.HasPrefix(body, "#EXTM3U\n") {
110 t.Fatalf("missing EXTM3U header: %q", body)
111 }
112 if !strings.Contains(body, "#EXTINF:-1,Demo - Episode 1\n") {
113 t.Fatalf("missing titled entry 1: %q", body)
114 }
115 if !strings.Contains(body, "#EXTINF:-1,Demo - Episode 2 [Filler]\n") {
116 t.Fatalf("missing titled entry 2: %q", body)
117 }
118 if !strings.Contains(body, placeholderURL(1)) || !strings.Contains(body, placeholderURL(2)) {
119 t.Fatalf("missing unique placeholder urls: %q", body)
120 }
121 // Must not leave bare lavfi as the only human-visible line without EXTINF.
122 lines := strings.Split(strings.TrimSpace(body), "\n")
123 for i, line := range lines {
124 if strings.HasPrefix(line, "av://") && i > 0 && !strings.HasPrefix(lines[i-1], "#EXTINF:") {
125 t.Fatalf("placeholder without preceding EXTINF at line %d", i)
126 }
127 }
128}
129
130func TestSanitizeM3UTitleStripsNewlines(t *testing.T) {
131 got := sanitizeM3UTitle("Foo\nBar\rBaz")
132 if strings.ContainsAny(got, "\n\r") {
133 t.Fatalf("newlines remain: %q", got)
134 }
135 if got == "" {
136 t.Fatal("empty after sanitize")
137 }
138}
139
140func TestMPVPlaylistSwitchingFlag(t *testing.T) {
141 endMPVPlaylistSwitch()
142 if MPVPlaylistIsSwitching() {
143 t.Fatal("expected switch flag clear")
144 }
145 beginMPVPlaylistSwitch()
146 if !MPVPlaylistIsSwitching() {
147 t.Fatal("expected switch flag set")
148 }
149 endMPVPlaylistSwitch()
150 if MPVPlaylistIsSwitching() {
151 t.Fatal("expected switch flag clear after end")
152 }
153}
154
155func TestClassifyPlaybackLossDoesNotExitWhileMPVAlive(t *testing.T) {
156 endMPVPlaylistSwitch()
157 // Incomplete watch + empty socket (IsMPVRunning false) → exit
158 if got := ClassifyPlaybackLoss("", true, 11, 85); got != PlaybackLossExit {
159 t.Fatalf("empty socket incomplete: got %d want Exit", got)
160 }
161 // Complete threshold → complete regardless of socket
162 if got := ClassifyPlaybackLoss("", true, 90, 85); got != PlaybackLossComplete {
163 t.Fatalf("complete: got %d want Complete", got)
164 }
165 // Switching flag forces wait
166 beginMPVPlaylistSwitch()
167 if got := ClassifyPlaybackLoss("", true, 11, 85); got != PlaybackLossWait {
168 t.Fatalf("switching: got %d want Wait", got)
169 }
170 endMPVPlaylistSwitch()
171 // Not started → wait
172 if got := ClassifyPlaybackLoss("", false, 0, 85); got != PlaybackLossWait {
173 t.Fatalf("not started: got %d want Wait", got)
174 }
175}
176
177func TestPlaceholderIsLongLivedAndUniquePerEpisode(t *testing.T) {
178 a := placeholderURL(39)
179 b := placeholderURL(40)
180 if a == b {
181 t.Fatal("placeholder URLs must differ per episode")
182 }
183 if !strings.Contains(a, "d=86400") {
184 t.Fatalf("placeholder should be long-lived: %q", a)
185 }
186 // Fragments break lavfi in mpv — ensure we never emit them.
187 if strings.Contains(a, "#") {
188 t.Fatalf("must not use URL fragments: %q", a)
189 }
190 for _, ep := range []int{1, 39, 40, 366, 1000} {
191 url := placeholderURL(ep)
192 got, ok := parseEpisodeFromPlaceholder(url)
193 if !ok || got != ep {
194 t.Fatalf("ep %d: url=%q parsed=%d ok=%v", ep, url, got, ok)
195 }
196 }
197}
198
199func TestPromptPlaylistPlusOneAutoNoMenu(t *testing.T) {
200 prev := promptSelectOrdered
201 t.Cleanup(func() { promptSelectOrdered = prev })
202 called := false
203 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
204 called = true
205 return options[0], nil
206 }
207
208 // +1 early → no remote mark, no menu
209 action, err := defaultPromptPlaylistEpisodeLeave(40, 41, 11, 85)
210 if err != nil {
211 t.Fatal(err)
212 }
213 if action != playlistLeaveNone {
214 t.Fatalf("+1 early → %s want none", action)
215 }
216 if called {
217 t.Fatal("+1 must not open a menu")
218 }
219
220 // +1 nearly done → auto mark left
221 action, err = defaultPromptPlaylistEpisodeLeave(40, 41, 90, 85)
222 if err != nil {
223 t.Fatal(err)
224 }
225 if action != playlistLeaveMarkLeft {
226 t.Fatalf("+1 nearly done → %s want mark", action)
227 }
228}
229
230func TestPromptPlaylistJumpOffersUpstreamOptions(t *testing.T) {
231 prev := promptSelectOrdered
232 t.Cleanup(func() { promptSelectOrdered = prev })
233
234 var keys []string
235 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
236 keys = nil
237 for _, o := range options {
238 keys = append(keys, o.Key)
239 }
240 return options[0], nil
241 }
242
243 action, err := defaultPromptPlaylistEpisodeLeave(40, 39, 11, 85)
244 if err != nil {
245 t.Fatal(err)
246 }
247 if action != playlistLeaveNone { // first option for early jump
248 t.Fatalf("jump early default=%s want none", action)
249 }
250 want := map[string]bool{"none": true, "mark": true, "setwatch": true, "cancel": true}
251 for _, k := range keys {
252 delete(want, k)
253 }
254 if len(want) != 0 {
255 t.Fatalf("missing options %v (got %v)", want, keys)
256 }
257
258 // Nearly done jump leads with mark
259 action, err = defaultPromptPlaylistEpisodeLeave(40, 10, 90, 85)
260 if err != nil {
261 t.Fatal(err)
262 }
263 if action != playlistLeaveMarkLeft {
264 t.Fatalf("jump nearly-done default=%s want mark", action)
265 }
266 if keys[0] != "mark" {
267 t.Fatalf("first option=%s want mark", keys[0])
268 }
269}
270
271func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) {
272 prev := promptSelectOrdered
273 t.Cleanup(func() { promptSelectOrdered = prev })
274
275 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
276 return SelectionOption{Key: "cancel"}, nil
277 }
278 action, err := defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
279 if err != nil {
280 t.Fatal(err)
281 }
282 if action != playlistLeaveCancel {
283 t.Fatalf("cancel → %s", action)
284 }
285
286 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
287 return SelectionOption{}, fmt.Errorf("tty busy")
288 }
289 action, err = defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
290 if err != nil {
291 t.Fatal(err)
292 }
293 if action != playlistLeaveNone {
294 t.Fatalf("prompt error → %s want none (still play target)", action)
295 }
296}
297
298func TestParsePlaylistEpisodeTitle(t *testing.T) {
299 ep, mode, ok := parsePlaylistEpisodeTitle("Bleach - Episode 39", "sub")
300 if !ok || ep != 39 || mode != "sub" {
301 t.Fatalf("got ep=%d mode=%s ok=%v", ep, mode, ok)
302 }
303 ep, mode, ok = parsePlaylistEpisodeTitle("Bleach - Episode 40 (DUB)", "sub")
304 if !ok || ep != 40 || mode != "dub" {
305 t.Fatalf("dub got ep=%d mode=%s ok=%v", ep, mode, ok)
306 }
307 _, _, ok = parsePlaylistEpisodeTitle("av://lavfi:color", "sub")
308 if ok {
309 t.Fatal("lavfi should not parse")
310 }
311}
312
313func TestMediaURLKeyStripsQuery(t *testing.T) {
314 a := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=abc")
315 b := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=xyz")
316 if a != b {
317 t.Fatalf("keys should match without query: %q vs %q", a, b)
318 }
319 if mediaURLKey("https://cdn.example/a/p.m3u8") == mediaURLKey("https://cdn.example/b/p.m3u8") {
320 t.Fatal("different paths should differ")
321 }
322}
323
324func TestEscapeMPVOptionValueQuotes(t *testing.T) {
325 got := escapeMPVOptionValue(`Show - Episode 1`)
326 if !strings.HasPrefix(got, `"`) || !strings.HasSuffix(got, `"`) {
327 t.Fatalf("expected quoted: %q", got)
328 }
329 got = escapeMPVOptionValue(`a"b`)
330 if !strings.Contains(got, `\"`) {
331 t.Fatalf("expected escaped quote: %q", got)
332 }
333}
334
335func TestFinalizePlaylistEpisodeChangeUpdatesLocalHistory(t *testing.T) {
336 dir := t.TempDir()
337 db := filepath.Join(dir, "curd_history.txt")
338 anime := &Anime{
339 AnilistId: 269,
340 ProviderId: "269",
341 ProviderName: "senshi",
342 Title: AnimeTitle{English: "Bleach"},
343 FillerEpisodes: []int{33},
344 Ep: Episode{Number: 40},
345 }
346 c := &MPVPlaylistController{
347 config: &CurdConfig{StoragePath: dir, SubOrDub: "sub"},
348 anime: anime,
349 preferredMode: "sub",
350 socket: "", // skip MPV title commands failures are fine
351 }
352
353 c.finalizePlaylistEpisodeChange(40, 39, "sub", playlistLeaveNone)
354
355 if anime.Ep.Number != 39 {
356 t.Fatalf("episode number=%d want 39", anime.Ep.Number)
357 }
358 if anime.Ep.IsFiller {
359 t.Fatal("ep 39 should not be filler")
360 }
361 // curd_id written
362 idRaw, err := os.ReadFile(filepath.Join(dir, "curd_id"))
363 if err != nil {
364 t.Fatal(err)
365 }
366 if strings.TrimSpace(string(idRaw)) != "269" {
367 t.Fatalf("curd_id=%q", idRaw)
368 }
369 // history row
370 list := LocalGetAllAnime(db)
371 found := LocalFindAnime(list, 269, "269")
372 if found == nil {
373 t.Fatal("expected history entry")
374 }
375 if found.Ep.Number != 39 {
376 t.Fatalf("history ep=%d want 39", found.Ep.Number)
377 }
378 if found.Ep.Player.PlaybackTime != 0 {
379 t.Fatalf("playback time should reset, got %d", found.Ep.Player.PlaybackTime)
380 }
381}
382
383func TestFinalizePlaylistMarksFillerFromList(t *testing.T) {
384 dir := t.TempDir()
385 anime := &Anime{
386 AnilistId: 1,
387 ProviderId: "x",
388 ProviderName: "senshi",
389 Title: AnimeTitle{English: "Demo"},
390 FillerEpisodes: []int{5},
391 Ep: Episode{Number: 1},
392 }
393 c := &MPVPlaylistController{
394 config: &CurdConfig{StoragePath: dir},
395 anime: anime,
396 }
397 c.finalizePlaylistEpisodeChange(1, 5, "sub", playlistLeaveNone)
398 if !anime.Ep.IsFiller {
399 t.Fatal("expected filler flag for ep 5")
400 }
401 // silence unused if LocalGetAllAnime not needed
402 _ = strconv.Itoa(anime.Ep.Number)
403}
404
405func TestLocalHistoryPath(t *testing.T) {
406 if localHistoryPath("") != "" {
407 t.Fatal("empty storage")
408 }
409 got := localHistoryPath("/tmp/curd-test-store")
410 if !strings.HasSuffix(got, "curd_history.txt") {
411 t.Fatalf("got %q", got)
412 }
413}