internal/mpv_playlist_test.go

444 lines · 13238 bytes

20 symbols in this file
  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 TestResolvePlaylistLeaveDefaultNeverRegressesOnRewind(t *testing.T) {
272	// Backward jump → never touch AniList/MAL, regardless of watch percentage.
273	if action := resolvePlaylistLeaveDefault(40, 39, 11, 85); action != playlistLeaveNone {
274		t.Fatalf("backward 11%% → %s want none", action)
275	}
276	if action := resolvePlaylistLeaveDefault(40, 39, 90, 85); action != playlistLeaveNone {
277		t.Fatalf("backward 90%% → %s want none", action)
278	}
279	if action := resolvePlaylistLeaveDefault(40, 1, 0, 85); action != playlistLeaveNone {
280		t.Fatalf("backward 0%% → %s want none", action)
281	}
282}
283
284func TestResolvePlaylistLeaveDefaultNeverPrompts(t *testing.T) {
285	// Same episode (mode toggle) → none.
286	if action := resolvePlaylistLeaveDefault(40, 40, 90, 85); action != playlistLeaveNone {
287		t.Fatalf("same ep → %s want none", action)
288	}
289	// Next +1 follows standard auto-mark behavior.
290	if action := resolvePlaylistLeaveDefault(40, 41, 11, 85); action != playlistLeaveNone {
291		t.Fatalf("forward early → %s want none", action)
292	}
293	if action := resolvePlaylistLeaveDefault(40, 41, 90, 85); action != playlistLeaveMarkLeft {
294		t.Fatalf("forward nearly-done → %s want mark", action)
295	}
296	// Forward skip (>+1) → none (deferred to session end).
297	if action := resolvePlaylistLeaveDefault(40, 45, 90, 85); action != playlistLeaveNone {
298		t.Fatalf("forward skip → %s want none", action)
299	}
300}
301
302func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) {
303	prev := promptSelectOrdered
304	t.Cleanup(func() { promptSelectOrdered = prev })
305
306	promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
307		return SelectionOption{Key: "cancel"}, nil
308	}
309	action, err := defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
310	if err != nil {
311		t.Fatal(err)
312	}
313	if action != playlistLeaveCancel {
314		t.Fatalf("cancel → %s", action)
315	}
316
317	promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
318		return SelectionOption{}, fmt.Errorf("tty busy")
319	}
320	action, err = defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
321	if err != nil {
322		t.Fatal(err)
323	}
324	if action != playlistLeaveNone {
325		t.Fatalf("prompt error → %s want none (still play target)", action)
326	}
327}
328
329func TestParsePlaylistEpisodeTitle(t *testing.T) {
330	ep, mode, ok := parsePlaylistEpisodeTitle("Bleach - Episode 39", "sub")
331	if !ok || ep != 39 || mode != "sub" {
332		t.Fatalf("got ep=%d mode=%s ok=%v", ep, mode, ok)
333	}
334	ep, mode, ok = parsePlaylistEpisodeTitle("Bleach - Episode 40 (DUB)", "sub")
335	if !ok || ep != 40 || mode != "dub" {
336		t.Fatalf("dub got ep=%d mode=%s ok=%v", ep, mode, ok)
337	}
338	_, _, ok = parsePlaylistEpisodeTitle("av://lavfi:color", "sub")
339	if ok {
340		t.Fatal("lavfi should not parse")
341	}
342}
343
344func TestMediaURLKeyStripsQuery(t *testing.T) {
345	a := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=abc")
346	b := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=xyz")
347	if a != b {
348		t.Fatalf("keys should match without query: %q vs %q", a, b)
349	}
350	if mediaURLKey("https://cdn.example/a/p.m3u8") == mediaURLKey("https://cdn.example/b/p.m3u8") {
351		t.Fatal("different paths should differ")
352	}
353}
354
355func TestEscapeMPVOptionValueQuotes(t *testing.T) {
356	got := escapeMPVOptionValue(`Show - Episode 1`)
357	if !strings.HasPrefix(got, `"`) || !strings.HasSuffix(got, `"`) {
358		t.Fatalf("expected quoted: %q", got)
359	}
360	got = escapeMPVOptionValue(`a"b`)
361	if !strings.Contains(got, `\"`) {
362		t.Fatalf("expected escaped quote: %q", got)
363	}
364}
365
366func TestFinalizePlaylistEpisodeChangeUpdatesLocalHistory(t *testing.T) {
367	dir := t.TempDir()
368	db := filepath.Join(dir, "curd_history.txt")
369	anime := &Anime{
370		AnilistId:    269,
371		ProviderId:   "269",
372		ProviderName: "senshi",
373		Title:        AnimeTitle{English: "Bleach"},
374		FillerEpisodes: []int{33},
375		Ep:           Episode{Number: 40},
376	}
377	c := &MPVPlaylistController{
378		config:        &CurdConfig{StoragePath: dir, SubOrDub: "sub"},
379		anime:         anime,
380		preferredMode: "sub",
381		socket:        "", // skip MPV title commands failures are fine
382	}
383
384	c.finalizePlaylistEpisodeChange(40, 39, "sub", playlistLeaveNone)
385
386	if anime.Ep.Number != 39 {
387		t.Fatalf("episode number=%d want 39", anime.Ep.Number)
388	}
389	if anime.Ep.IsFiller {
390		t.Fatal("ep 39 should not be filler")
391	}
392	// curd_id written
393	idRaw, err := os.ReadFile(filepath.Join(dir, "curd_id"))
394	if err != nil {
395		t.Fatal(err)
396	}
397	if strings.TrimSpace(string(idRaw)) != "269" {
398		t.Fatalf("curd_id=%q", idRaw)
399	}
400	// history row
401	list := LocalGetAllAnime(db)
402	found := LocalFindAnime(list, 269, "269")
403	if found == nil {
404		t.Fatal("expected history entry")
405	}
406	if found.Ep.Number != 39 {
407		t.Fatalf("history ep=%d want 39", found.Ep.Number)
408	}
409	if found.Ep.Player.PlaybackTime != 0 {
410		t.Fatalf("playback time should reset, got %d", found.Ep.Player.PlaybackTime)
411	}
412}
413
414func TestFinalizePlaylistMarksFillerFromList(t *testing.T) {
415	dir := t.TempDir()
416	anime := &Anime{
417		AnilistId:      1,
418		ProviderId:     "x",
419		ProviderName:   "senshi",
420		Title:          AnimeTitle{English: "Demo"},
421		FillerEpisodes: []int{5},
422		Ep:             Episode{Number: 1},
423	}
424	c := &MPVPlaylistController{
425		config: &CurdConfig{StoragePath: dir},
426		anime:  anime,
427	}
428	c.finalizePlaylistEpisodeChange(1, 5, "sub", playlistLeaveNone)
429	if !anime.Ep.IsFiller {
430		t.Fatal("expected filler flag for ep 5")
431	}
432	// silence unused if LocalGetAllAnime not needed
433	_ = strconv.Itoa(anime.Ep.Number)
434}
435
436func TestLocalHistoryPath(t *testing.T) {
437	if localHistoryPath("") != "" {
438		t.Fatal("empty storage")
439	}
440	got := localHistoryPath("/tmp/curd-test-store")
441	if !strings.HasSuffix(got, "curd_history.txt") {
442		t.Fatalf("got %q", got)
443	}
444}