internal/provider_stack_test.go

730 lines · 24704 bytes

  1package internal
  2
  3import (
  4	"errors"
  5	"os"
  6	"path/filepath"
  7	"strings"
  8	"testing"
  9
 10	"github.com/wraient/curd/internal/providers"
 11)
 12
 13type stackStubProvider struct {
 14	name           string
 15	searchResults  map[string][]SelectionOption
 16	episodeResults map[string]map[string][]string
 17	episodeErrors  map[string]map[string]error
 18	searchCalls    []string
 19	calls          []string
 20}
 21
 22func (s *stackStubProvider) Name() string { return s.name }
 23
 24func (s *stackStubProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
 25	mode = normalizeTranslationType(mode)
 26	s.searchCalls = append(s.searchCalls, s.name+":"+mode+":"+query)
 27	return s.searchResults[mode], nil
 28}
 29
 30func (s *stackStubProvider) EpisodesList(showID, mode string) ([]string, error) {
 31	return nil, nil
 32}
 33
 34func (s *stackStubProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
 35	return s.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
 36}
 37
 38func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
 39	mode = normalizeTranslationType(mode)
 40	s.calls = append(s.calls, s.name+":"+mode)
 41	if byID, ok := s.episodeErrors[id]; ok {
 42		if err := byID[mode]; err != nil {
 43			return nil, err
 44		}
 45	}
 46	if byID, ok := s.episodeResults[id]; ok {
 47		return byID[mode], nil
 48	}
 49	return nil, nil
 50}
 51
 52func withProviderFactories(t *testing.T, stubs ...*stackStubProvider) {
 53	t.Helper()
 54	withAllProvidersEnabledForTest(t)
 55	restores := make([]func(), 0, len(stubs))
 56	for _, stub := range stubs {
 57		stub := stub
 58		restores = append(restores, providers.SetFactoryForTest(stub.name, func() providers.Provider {
 59			return &stackStubProviderBridge{stub}
 60		}))
 61	}
 62	t.Cleanup(func() {
 63		for i := len(restores) - 1; i >= 0; i-- {
 64			restores[i]()
 65		}
 66	})
 67}
 68
 69type stackStubProviderBridge struct {
 70	*stackStubProvider
 71}
 72
 73func (s *stackStubProviderBridge) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
 74	options, err := s.stackStubProvider.SearchAnime(query, mode)
 75	return toProviderSelectionOptions(options), err
 76}
 77
 78func (s *stackStubProviderBridge) EpisodesList(showID, mode string) ([]string, error) {
 79	return s.stackStubProvider.EpisodesList(showID, mode)
 80}
 81
 82func (s *stackStubProviderBridge) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
 83	return s.stackStubProvider.GetEpisodeURL(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo)
 84}
 85
 86func (s *stackStubProviderBridge) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
 87	return s.stackStubProvider.GetEpisodeURLForMode(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo, mode)
 88}
 89
 90func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
 91	withAllProvidersEnabledForTest(t)
 92
 93	cases := []struct {
 94		name string
 95		cfg  *CurdConfig
 96		want []string
 97	}{
 98		{name: "empty", cfg: &CurdConfig{}, want: []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}},
 99		{name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}},
100		{name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}},
101		{name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}},
102		{name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}},
103	}
104
105	for _, tc := range cases {
106		got := ConfiguredProviderNames(tc.cfg)
107		if len(got) != len(tc.want) {
108			t.Fatalf("%s: got %v, want %v", tc.name, got, tc.want)
109		}
110		for i := range got {
111			if got[i] != tc.want[i] {
112				t.Fatalf("%s: got %v, want %v", tc.name, got, tc.want)
113			}
114		}
115	}
116}
117
118func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(t *testing.T) {
119	cases := []struct {
120		name string
121		raw  string
122		want string
123	}{
124		{name: "legacy allanime", raw: "allanime", want: `["allanime"]`},
125		{name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
126		{name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
127		{name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`},
128		{name: "empty default", raw: "", want: "stacked"},
129	}
130
131	for _, tc := range cases {
132		if got := canonicalProviderConfigValue(tc.raw); got != tc.want {
133			t.Fatalf("%s: got %s, want %s", tc.name, got, tc.want)
134		}
135	}
136}
137
138func TestLoadConfigMigratesLegacyProviderToListWithoutAddingAnimepahe(t *testing.T) {
139	configPath := filepath.Join(t.TempDir(), "curd.conf")
140	if err := os.WriteFile(configPath, []byte("Provider=allanime\nAddMissingOptions=true\n"), 0644); err != nil {
141		t.Fatalf("write config: %v", err)
142	}
143
144	config, err := LoadConfig(configPath)
145	if err != nil {
146		t.Fatalf("LoadConfig returned error: %v", err)
147	}
148	if config.Provider != `["allanime"]` {
149		t.Fatalf("got provider %s, want [\"allanime\"]", config.Provider)
150	}
151
152	contents, err := os.ReadFile(configPath)
153	if err != nil {
154		t.Fatalf("read config: %v", err)
155	}
156	if !strings.Contains(string(contents), `Provider=["allanime"]`) {
157		t.Fatalf("config file was not migrated to allanime-only list:\n%s", string(contents))
158	}
159	if strings.Contains(string(contents), "animepahe") {
160		t.Fatalf("migration added animepahe without consent:\n%s", string(contents))
161	}
162}
163
164func TestSearchAnimeDecliningAnimepaheWritesOptOutAndDoesNotAskAgain(t *testing.T) {
165	allanime := &stackStubProvider{
166		name:          "allanime",
167		searchResults: map[string][]SelectionOption{"sub": {}},
168	}
169	animepahe := &stackStubProvider{
170		name: "animepahe",
171		searchResults: map[string][]SelectionOption{
172			"sub": {{Title: "Hidden", Key: "pahe-id", Label: "Hidden"}},
173		},
174	}
175	withProviderFactories(t, allanime, animepahe)
176
177	configPath := filepath.Join(t.TempDir(), "curd.conf")
178	if err := os.WriteFile(configPath, []byte("Provider=[\"allanime\"]\n"), 0644); err != nil {
179		t.Fatalf("write config: %v", err)
180	}
181	previousConfigPath := GlobalConfigPath
182	GlobalConfigPath = configPath
183	config := &CurdConfig{Provider: `["allanime"]`}
184	previousConfig := GetGlobalConfig()
185	SetGlobalConfig(config)
186	t.Cleanup(func() {
187		GlobalConfigPath = previousConfigPath
188		SetGlobalConfig(previousConfig)
189	})
190
191	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
192		if len(options) < 2 || options[0].Key != "use" || options[1].Key != "never" {
193			t.Fatalf("unexpected Animepahe fallback options: %#v", options)
194		}
195		return SelectionOption{Key: "never"}, nil
196	})
197
198	results, err := SearchAnime("missing", "sub")
199	if err != nil {
200		t.Fatalf("SearchAnime returned error: %v", err)
201	}
202	if len(results) != 0 {
203		t.Fatalf("expected no results after declining Animepahe, got %#v", results)
204	}
205	if config.Provider != `["allanime","no-animepahe"]` {
206		t.Fatalf("provider config was not updated with opt out: %s", config.Provider)
207	}
208	contents, err := os.ReadFile(configPath)
209	if err != nil {
210		t.Fatalf("read config: %v", err)
211	}
212	if !strings.Contains(string(contents), `Provider=["allanime","no-animepahe"]`) {
213		t.Fatalf("config file missing opt out:\n%s", string(contents))
214	}
215
216	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
217		t.Fatalf("Animepahe prompt should not be shown after no-animepahe opt out")
218		return SelectionOption{}, nil
219	})
220	if _, err := SearchAnime("missing again", "sub"); err != nil {
221		t.Fatalf("SearchAnime after opt out returned error: %v", err)
222	}
223}
224
225func TestSearchAnimeAcceptingAnimepaheAddsItBeforeSearching(t *testing.T) {
226	allanime := &stackStubProvider{
227		name:          "allanime",
228		searchResults: map[string][]SelectionOption{"sub": {}},
229	}
230	animepahe := &stackStubProvider{
231		name: "animepahe",
232		searchResults: map[string][]SelectionOption{
233			"sub": {{Title: "Fallback", Key: "pahe-id", Label: "Fallback"}},
234		},
235	}
236	withProviderFactories(t, allanime, animepahe)
237
238	configPath := filepath.Join(t.TempDir(), "curd.conf")
239	if err := os.WriteFile(configPath, []byte("Provider=[\"allanime\"]\n"), 0644); err != nil {
240		t.Fatalf("write config: %v", err)
241	}
242	previousConfigPath := GlobalConfigPath
243	GlobalConfigPath = configPath
244	config := &CurdConfig{Provider: `["allanime"]`}
245	previousConfig := GetGlobalConfig()
246	SetGlobalConfig(config)
247	t.Cleanup(func() {
248		GlobalConfigPath = previousConfigPath
249		SetGlobalConfig(previousConfig)
250	})
251
252	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
253		return SelectionOption{Key: "use"}, nil
254	})
255
256	results, err := SearchAnime("missing", "sub")
257	if err != nil {
258		t.Fatalf("SearchAnime returned error: %v", err)
259	}
260	if len(results) != 1 || results[0].Key != "animepahe::pahe-id" {
261		t.Fatalf("expected Animepahe fallback result, got %#v", results)
262	}
263	if config.Provider != `["allanime","animepahe"]` {
264		t.Fatalf("provider config was not updated with Animepahe: %s", config.Provider)
265	}
266	contents, err := os.ReadFile(configPath)
267	if err != nil {
268		t.Fatalf("read config: %v", err)
269	}
270	if !strings.Contains(string(contents), `Provider=["allanime","animepahe"]`) {
271		t.Fatalf("config file missing Animepahe fallback:\n%s", string(contents))
272	}
273}
274
275func TestSearchAnimeReturnsProviderQualifiedStackResultsInOrder(t *testing.T) {
276	allanime := &stackStubProvider{
277		name: "allanime",
278		searchResults: map[string][]SelectionOption{
279			"sub": {{Title: "First", Key: "allanime-id", Label: "First"}},
280		},
281	}
282	animepahe := &stackStubProvider{
283		name: "animepahe",
284		searchResults: map[string][]SelectionOption{
285			"sub": {{Title: "Second", Key: "pahe-id", Label: "Second"}},
286		},
287	}
288	withProviderFactories(t, allanime, animepahe)
289
290	previousConfig := GetGlobalConfig()
291	SetGlobalConfig(&CurdConfig{Provider: `["allanime","animepahe"]`})
292	t.Cleanup(func() { SetGlobalConfig(previousConfig) })
293
294	results, err := SearchAnime("query", "sub")
295	if err != nil {
296		t.Fatalf("SearchAnime returned error: %v", err)
297	}
298	if len(results) != 2 {
299		t.Fatalf("got %d results, want 2: %#v", len(results), results)
300	}
301	if results[0].Key != "allanime::allanime-id" || results[1].Key != "animepahe::pahe-id" {
302		t.Fatalf("results were not provider-qualified in config order: %#v", results)
303	}
304}
305
306func TestResolveEpisodeURLUsesProviderListOrder(t *testing.T) {
307	allanime := &stackStubProvider{
308		name: "allanime",
309		episodeResults: map[string]map[string][]string{
310			"allanime-id": {"sub": {"allanime-sub"}},
311		},
312	}
313	animepahe := &stackStubProvider{
314		name: "animepahe",
315		episodeResults: map[string]map[string][]string{
316			"pahe-id": {"sub": {"animepahe-sub"}},
317		},
318		searchResults: map[string][]SelectionOption{
319			"sub": {{Title: "Example", Key: "pahe-id"}},
320		},
321	}
322	withProviderFactories(t, allanime, animepahe)
323
324	cfg := CurdConfig{Provider: `["animepahe","allanime"]`, SubOrDub: "sub"}
325	anime := &Anime{
326		Title:        AnimeTitle{Romaji: "Example"},
327		ProviderName: "allanime",
328		ProviderId:   "allanime-id",
329	}
330
331	result, err := ResolveEpisodeURL(cfg, anime, 1)
332	if err != nil {
333		t.Fatalf("ResolveEpisodeURL returned error: %v", err)
334	}
335	if result.ProviderName != "animepahe" || result.ProviderID != "pahe-id" || result.Links[0] != "animepahe-sub" {
336		t.Fatalf("expected animepahe to win by config order, got %#v", result)
337	}
338}
339
340func TestFilterExcludedProviders(t *testing.T) {
341	filtered := filterExcludedProviders([]string{"senshi", "allanime", "anipub"}, []string{"senshi", "SENSHI"})
342	if len(filtered) != 2 || filtered[0] != "allanime" || filtered[1] != "anipub" {
343		t.Fatalf("unexpected filtered providers: %#v", filtered)
344	}
345}
346
347func TestResolveEpisodeURLExcludingProviders(t *testing.T) {
348	allanime := &stackStubProvider{
349		name: "allanime",
350		episodeResults: map[string]map[string][]string{
351			"allanime-id": {"sub": {"allanime-sub"}},
352		},
353		searchResults: map[string][]SelectionOption{
354			"sub": {{Title: "Example", Key: "allanime-id"}},
355		},
356	}
357	senshi := &stackStubProvider{
358		name: "senshi",
359		episodeResults: map[string]map[string][]string{
360			"senshi-id": {"sub": {"senshi-sub"}},
361		},
362		searchResults: map[string][]SelectionOption{
363			"sub": {{Title: "Example", Key: "senshi-id"}},
364		},
365	}
366	withProviderFactories(t, allanime, senshi)
367
368	cfg := CurdConfig{Provider: `["senshi","allanime"]`, SubOrDub: "sub"}
369	anime := &Anime{
370		Title:        AnimeTitle{Romaji: "Example"},
371		ProviderName: "senshi",
372		ProviderId:   "senshi-id",
373	}
374
375	result, err := ResolveEpisodeURLExcludingProviders(cfg, anime, 1, []string{"senshi"})
376	if err != nil {
377		t.Fatalf("ResolveEpisodeURLExcludingProviders returned error: %v", err)
378	}
379	if result.ProviderName != "allanime" || result.Links[0] != "allanime-sub" {
380		t.Fatalf("expected allanime fallback, got %#v", result)
381	}
382}
383
384func TestResolveEpisodeURLExcludingProvidersModeUsesExplicitMode(t *testing.T) {
385	allanime := &stackStubProvider{
386		name: "allanime",
387		episodeResults: map[string]map[string][]string{
388			"allanime-id": {"dub": {"allanime-dub"}, "sub": {"allanime-sub"}},
389		},
390		searchResults: map[string][]SelectionOption{
391			"dub": {{Title: "Example", Key: "allanime-id"}},
392			"sub": {{Title: "Example", Key: "allanime-id"}},
393		},
394	}
395	withProviderFactories(t, allanime)
396
397	cfg := CurdConfig{Provider: `["allanime"]`, SubOrDub: "sub"}
398	anime := &Anime{
399		Title:        AnimeTitle{Romaji: "Example"},
400		ProviderName: "allanime",
401		ProviderId:   "allanime-id",
402	}
403
404	result, err := ResolveEpisodeURLExcludingProvidersMode(cfg, anime, 1, nil, "dub")
405	if err != nil {
406		t.Fatalf("ResolveEpisodeURLExcludingProvidersMode returned error: %v", err)
407	}
408	if result.Mode != "dub" || result.Links[0] != "allanime-dub" {
409		t.Fatalf("expected explicit dub mode, got %#v", result)
410	}
411}
412
413func TestResolveEpisodeURLAlternateModeWithPromptRequiresApproval(t *testing.T) {
414	allanime := &stackStubProvider{
415		name: "allanime",
416		episodeResults: map[string]map[string][]string{
417			"allanime-id": {"dub": {"allanime-dub"}},
418		},
419		searchResults: map[string][]SelectionOption{
420			"dub": {{Title: "Example", Key: "allanime-id"}},
421		},
422	}
423	withProviderFactories(t, allanime)
424
425	cfg := CurdConfig{Provider: `["allanime"]`, SubOrDub: "sub"}
426	anime := &Anime{
427		Title:        AnimeTitle{Romaji: "Example"},
428		ProviderName: "allanime",
429		ProviderId:   "allanime-id",
430	}
431
432	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
433		return SelectionOption{Key: "cancel"}, nil
434	})
435	if _, err := ResolveEpisodeURLAlternateModeWithPrompt(cfg, anime, 1, nil); err == nil {
436		t.Fatal("expected declined alternate mode to error")
437	}
438	if anime.ProviderId != "allanime-id" {
439		t.Fatalf("declined prompt should not change provider mapping, got %q", anime.ProviderId)
440	}
441
442	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
443		return SelectionOption{Key: "play"}, nil
444	})
445	result, err := ResolveEpisodeURLAlternateModeWithPrompt(cfg, anime, 1, nil)
446	if err != nil {
447		t.Fatalf("accepted alternate mode returned error: %v", err)
448	}
449	if result.Mode != "dub" || result.Links[0] != "allanime-dub" {
450		t.Fatalf("expected dub fallback, got %#v", result)
451	}
452}
453
454func TestResolveEpisodeURLForPlaybackTriesAllPreferredProvidersBeforeAudioFallback(t *testing.T) {
455	allanime := &stackStubProvider{
456		name: "allanime",
457		searchResults: map[string][]SelectionOption{
458			"dub": {{Title: "Example", Key: "shared-id"}},
459			"sub": {{Title: "Example", Key: "shared-id"}},
460		},
461		episodeResults: map[string]map[string][]string{
462			"shared-id": {"sub": {"allanime-sub"}},
463		},
464		episodeErrors: map[string]map[string]error{
465			"shared-id": {"dub": errors.New("no allanime dub")},
466		},
467	}
468	animepahe := &stackStubProvider{
469		name: "animepahe",
470		episodeResults: map[string]map[string][]string{
471			"pahe-id": {"dub": {"animepahe-dub"}},
472		},
473		searchResults: map[string][]SelectionOption{
474			"dub": {{Title: "Example", Key: "pahe-id"}},
475		},
476	}
477	withProviderFactories(t, allanime, animepahe)
478	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
479		t.Fatalf("audio fallback prompt should not be shown while another provider has preferred audio")
480		return SelectionOption{}, nil
481	})
482
483	cfg := CurdConfig{Provider: `["allanime","animepahe"]`, SubOrDub: "dub"}
484	anime := &Anime{
485		Title:        AnimeTitle{Romaji: "Example"},
486		ProviderName: "allanime",
487		ProviderId:   "shared-id",
488	}
489
490	result, err := ResolveEpisodeURLForPlayback(cfg, anime, 1)
491	if err != nil {
492		t.Fatalf("ResolveEpisodeURLForPlayback returned error: %v", err)
493	}
494	if result.ProviderName != "animepahe" || result.Mode != "dub" || result.Links[0] != "animepahe-dub" {
495		t.Fatalf("expected animepahe dub before sub fallback, got %#v", result)
496	}
497	for _, call := range allanime.calls {
498		if call == "allanime:sub" {
499			t.Fatalf("allanime sub fallback was tried before animepahe dub: %#v", allanime.calls)
500		}
501	}
502}
503
504func TestResolveEpisodeURLForPlaybackAcceptingAnimepaheUsesPreferredBeforeSubFallback(t *testing.T) {
505	allanime := &stackStubProvider{
506		name: "allanime",
507		episodeResults: map[string]map[string][]string{
508			"shared-id": {"sub": {"allanime-sub"}},
509		},
510		episodeErrors: map[string]map[string]error{
511			"shared-id": {"dub": errors.New("no allanime dub")},
512		},
513	}
514	animepahe := &stackStubProvider{
515		name: "animepahe",
516		episodeResults: map[string]map[string][]string{
517			"pahe-id": {"dub": {"animepahe-dub"}},
518		},
519		searchResults: map[string][]SelectionOption{
520			"dub": {{Title: "Example", Key: "pahe-id"}},
521		},
522	}
523	withProviderFactories(t, allanime, animepahe)
524
525	configPath := filepath.Join(t.TempDir(), "curd.conf")
526	if err := os.WriteFile(configPath, []byte("Provider=[\"allanime\"]\n"), 0644); err != nil {
527		t.Fatalf("write config: %v", err)
528	}
529	previousConfigPath := GlobalConfigPath
530	GlobalConfigPath = configPath
531	config := &CurdConfig{Provider: `["allanime"]`, SubOrDub: "dub"}
532	previousConfig := GetGlobalConfig()
533	SetGlobalConfig(config)
534	t.Cleanup(func() {
535		GlobalConfigPath = previousConfigPath
536		SetGlobalConfig(previousConfig)
537	})
538
539	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
540		switch options[0].Key {
541		case "use":
542			return SelectionOption{Key: "use"}, nil
543		case "play":
544			t.Fatalf("sub fallback prompt should not be shown while Animepahe has dub")
545		default:
546			t.Fatalf("unexpected prompt options: %#v", options)
547		}
548		return SelectionOption{}, nil
549	})
550
551	anime := &Anime{
552		Title:        AnimeTitle{Romaji: "Example"},
553		ProviderName: "allanime",
554		ProviderId:   "shared-id",
555	}
556	result, err := ResolveEpisodeURLForPlayback(*config, anime, 155)
557	if err != nil {
558		t.Fatalf("ResolveEpisodeURLForPlayback returned error: %v", err)
559	}
560	if result.ProviderName != "animepahe" || result.Mode != "dub" || result.Links[0] != "animepahe-dub" {
561		t.Fatalf("expected Animepahe dub before sub fallback, got %#v", result)
562	}
563	if config.Provider != `["allanime","animepahe"]` {
564		t.Fatalf("provider config was not updated with Animepahe: %s", config.Provider)
565	}
566	contents, err := os.ReadFile(configPath)
567	if err != nil {
568		t.Fatalf("read config: %v", err)
569	}
570	if !strings.Contains(string(contents), `Provider=["allanime","animepahe"]`) {
571		t.Fatalf("config file missing Animepahe fallback:\n%s", string(contents))
572	}
573	if got := strings.Join(allanime.calls, ","); got != "allanime:dub" {
574		t.Fatalf("expected one AllAnime dub attempt before Animepahe, got %s", got)
575	}
576	if got := strings.Join(animepahe.calls, ","); got != "animepahe:dub" {
577		t.Fatalf("expected Animepahe dub before sub fallback, got %s", got)
578	}
579}
580
581func TestResolveEpisodeURLForPlaybackDecliningAnimepaheFallsBackToAllanimeSub(t *testing.T) {
582	allanime := &stackStubProvider{
583		name: "allanime",
584		episodeResults: map[string]map[string][]string{
585			"shared-id": {"sub": {"allanime-sub"}},
586		},
587		episodeErrors: map[string]map[string]error{
588			"shared-id": {"dub": errors.New("no allanime dub")},
589		},
590	}
591	animepahe := &stackStubProvider{
592		name: "animepahe",
593		episodeResults: map[string]map[string][]string{
594			"pahe-id": {"dub": {"animepahe-dub"}, "sub": {"animepahe-sub"}},
595		},
596		searchResults: map[string][]SelectionOption{
597			"dub": {{Title: "Example", Key: "pahe-id"}},
598			"sub": {{Title: "Example", Key: "pahe-id"}},
599		},
600	}
601	withProviderFactories(t, allanime, animepahe)
602
603	configPath := filepath.Join(t.TempDir(), "curd.conf")
604	if err := os.WriteFile(configPath, []byte("Provider=[\"allanime\"]\n"), 0644); err != nil {
605		t.Fatalf("write config: %v", err)
606	}
607	previousConfigPath := GlobalConfigPath
608	GlobalConfigPath = configPath
609	config := &CurdConfig{Provider: `["allanime"]`, SubOrDub: "dub"}
610	previousConfig := GetGlobalConfig()
611	SetGlobalConfig(config)
612	t.Cleanup(func() {
613		GlobalConfigPath = previousConfigPath
614		SetGlobalConfig(previousConfig)
615	})
616
617	sawSubPrompt := false
618	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
619		switch options[0].Key {
620		case "use":
621			return SelectionOption{Key: "never"}, nil
622		case "play":
623			sawSubPrompt = true
624			return SelectionOption{Key: "play"}, nil
625		default:
626			t.Fatalf("unexpected prompt options: %#v", options)
627		}
628		return SelectionOption{}, nil
629	})
630
631	anime := &Anime{
632		Title:        AnimeTitle{Romaji: "Example"},
633		ProviderName: "allanime",
634		ProviderId:   "shared-id",
635	}
636	result, err := ResolveEpisodeURLForPlayback(*config, anime, 155)
637	if err != nil {
638		t.Fatalf("ResolveEpisodeURLForPlayback returned error: %v", err)
639	}
640	if result.ProviderName != "allanime" || result.Mode != "sub" || result.Links[0] != "allanime-sub" {
641		t.Fatalf("expected AllAnime sub fallback after declining Animepahe, got %#v", result)
642	}
643	if !sawSubPrompt {
644		t.Fatalf("expected prompt before playing sub fallback")
645	}
646	if config.Provider != `["allanime","no-animepahe"]` {
647		t.Fatalf("provider config was not updated with opt out: %s", config.Provider)
648	}
649	contents, err := os.ReadFile(configPath)
650	if err != nil {
651		t.Fatalf("read config: %v", err)
652	}
653	if !strings.Contains(string(contents), `Provider=["allanime","no-animepahe"]`) {
654		t.Fatalf("config file missing opt out:\n%s", string(contents))
655	}
656	if len(animepahe.searchCalls) != 0 || len(animepahe.calls) != 0 {
657		t.Fatalf("Animepahe should not be touched after opt out, search=%#v episode=%#v", animepahe.searchCalls, animepahe.calls)
658	}
659	if got := strings.Join(allanime.calls, ","); got != "allanime:dub,allanime:sub" {
660		t.Fatalf("expected AllAnime dub then AllAnime sub after declining Animepahe, got %s", got)
661	}
662}
663
664func TestResolveEpisodeURLForPlaybackNoAnimepaheSkipsConsentAndOffersAllanimeSub(t *testing.T) {
665	allanime := &stackStubProvider{
666		name: "allanime",
667		searchResults: map[string][]SelectionOption{
668			"dub": {{Title: "Example", Key: "shared-id"}},
669			"sub": {{Title: "Example", Key: "shared-id"}},
670		},
671		episodeResults: map[string]map[string][]string{
672			"shared-id": {"sub": {"allanime-sub"}},
673		},
674		episodeErrors: map[string]map[string]error{
675			"shared-id": {"dub": errors.New("no allanime dub")},
676		},
677	}
678	animepahe := &stackStubProvider{
679		name: "animepahe",
680		episodeResults: map[string]map[string][]string{
681			"pahe-id": {"dub": {"animepahe-dub"}, "sub": {"animepahe-sub"}},
682		},
683		searchResults: map[string][]SelectionOption{
684			"dub": {{Title: "Example", Key: "pahe-id"}},
685			"sub": {{Title: "Example", Key: "pahe-id"}},
686		},
687	}
688	withProviderFactories(t, allanime, animepahe)
689
690	config := &CurdConfig{Provider: `["allanime","no-animepahe"]`, SubOrDub: "dub"}
691	previousConfig := GetGlobalConfig()
692	SetGlobalConfig(config)
693	t.Cleanup(func() { SetGlobalConfig(previousConfig) })
694
695	sawSubPrompt := false
696	withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
697		switch options[0].Key {
698		case "use":
699			t.Fatalf("Animepahe consent prompt should not be shown when no-animepahe is configured")
700		case "play":
701			sawSubPrompt = true
702			return SelectionOption{Key: "play"}, nil
703		default:
704			t.Fatalf("unexpected prompt options: %#v", options)
705		}
706		return SelectionOption{}, nil
707	})
708
709	anime := &Anime{
710		Title:        AnimeTitle{Romaji: "Example"},
711		ProviderName: "animepahe",
712		ProviderId:   "pahe-id",
713	}
714	result, err := ResolveEpisodeURLForPlayback(*config, anime, 155)
715	if err != nil {
716		t.Fatalf("ResolveEpisodeURLForPlayback returned error: %v", err)
717	}
718	if result.ProviderName != "allanime" || result.Mode != "sub" || result.Links[0] != "allanime-sub" {
719		t.Fatalf("expected AllAnime sub fallback with no-animepahe, got %#v", result)
720	}
721	if !sawSubPrompt {
722		t.Fatalf("expected prompt before playing sub fallback")
723	}
724	if len(animepahe.searchCalls) != 0 || len(animepahe.calls) != 0 {
725		t.Fatalf("Animepahe should not be touched with no-animepahe, search=%#v episode=%#v", animepahe.searchCalls, animepahe.calls)
726	}
727	if got := strings.Join(allanime.calls, ","); got != "allanime:dub,allanime:sub" {
728		t.Fatalf("expected AllAnime dub then AllAnime sub with no-animepahe, got %s", got)
729	}
730}