internal/providers/anineko/provider_test.go

314 lines · 9284 bytes

  1package anineko
  2
  3import (
  4	"io"
  5	"net/http"
  6	"net/http/httptest"
  7	"strings"
  8	"testing"
  9
 10	"github.com/wraient/curd/internal/curdhost"
 11)
 12
 13type roundTripFunc func(*http.Request) (*http.Response, error)
 14
 15func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
 16	return f(req)
 17}
 18
 19func testResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
 20	resp := &http.Response{
 21		StatusCode: statusCode,
 22		Header:     make(http.Header),
 23		Body:       io.NopCloser(strings.NewReader(body)),
 24		Request:    req,
 25	}
 26	for key, value := range headers {
 27		resp.Header.Set(key, value)
 28	}
 29	return resp
 30}
 31
 32func withAninekoTestClient(t *testing.T, client *http.Client) {
 33	t.Helper()
 34	previous := curdhost.HTTPClient
 35	t.Cleanup(func() {
 36		curdhost.HTTPClient = previous
 37		resetVibeProxyForTest()
 38		resetSubStyleForTest()
 39	})
 40	curdhost.HTTPClient = func() *http.Client { return client }
 41}
 42
 43func TestSearchAnimeParsesResults(t *testing.T) {
 44	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 45		if r.URL.Path != "/ajax/search" {
 46			http.NotFound(w, r)
 47			return
 48		}
 49		_, _ = io.WriteString(w, `{"success":true,"results":[{"title":"One Piece","url":"/watch/one-piece","image":"/img/op.jpg","meta":"TV"}]}`)
 50	}))
 51	defer server.Close()
 52
 53	withAninekoTestClient(t, server.Client())
 54
 55	originalBase := baseURL
 56	t.Cleanup(func() { baseURL = originalBase })
 57	baseURL = server.URL
 58
 59	options, err := searchAnime("one piece", "sub")
 60	if err != nil {
 61		t.Fatalf("searchAnime: %v", err)
 62	}
 63	if len(options) != 1 {
 64		t.Fatalf("expected 1 option, got %d", len(options))
 65	}
 66	if options[0].Key != "one-piece" {
 67		t.Fatalf("unexpected key %q", options[0].Key)
 68	}
 69	if options[0].Thumbnail != server.URL+"/img/op.jpg" {
 70		t.Fatalf("unexpected thumbnail %q", options[0].Thumbnail)
 71	}
 72}
 73
 74func TestEpisodesListParsesEpisodeLinks(t *testing.T) {
 75	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 76		_, _ = io.WriteString(w, `<a href="/watch/frieren/ep-1">1</a><a href="/watch/frieren/ep-12">12</a>`)
 77	}))
 78	defer server.Close()
 79
 80	withAninekoTestClient(t, server.Client())
 81	originalBase := baseURL
 82	t.Cleanup(func() { baseURL = originalBase })
 83	baseURL = server.URL
 84
 85	episodes, err := episodesList("frieren", "sub")
 86	if err != nil {
 87		t.Fatalf("episodesList: %v", err)
 88	}
 89	if strings.Join(episodes, ",") != "1,12" {
 90		t.Fatalf("unexpected episodes %v", episodes)
 91	}
 92}
 93
 94func TestExtractLangEmbedURLs(t *testing.T) {
 95	html := `
 96<div class="server-items" data-id="sub">
 97  <div data-video="https://bibiemb.xyz/aaa"></div>
 98  <div data-video="https://vibeplayer.site/bbb?sub=https://cdn.example/sub.vtt"></div>
 99</div>
100<div class="server-items" data-id="dub">
101  <div data-video="https://bibiemb.xyz/ccc"></div>
102</div>`
103
104	groups := extractLangEmbedURLs(html)
105	if len(groups["sub"]) != 2 {
106		t.Fatalf("expected 2 sub urls, got %d", len(groups["sub"]))
107	}
108	if len(groups["dub"]) != 1 {
109		t.Fatalf("expected 1 dub url, got %d", len(groups["dub"]))
110	}
111	subURLs := embedURLsForSubStyle(groups, "soft")
112	if len(subURLs) != 2 {
113		t.Fatalf("expected 2 soft sub urls, got %d", len(subURLs))
114	}
115	if subtitleFromEmbedURL(subURLs[1]) != "https://cdn.example/sub.vtt" {
116		t.Fatalf("unexpected subtitle %q", subtitleFromEmbedURL(subURLs[1]))
117	}
118}
119
120func TestChooseSubStyleRespectsPreference(t *testing.T) {
121	groups := map[string][]string{
122		"hsub": {"https://vibeplayer.site/hard"},
123		"sub":  {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
124		"dub":  {"https://vibeplayer.site/dub"},
125	}
126
127	style, err := chooseSubStyle(groups, "soft")
128	if err != nil || style != "soft" {
129		t.Fatalf("chooseSubStyle soft: style=%q err=%v", style, err)
130	}
131
132	style, err = chooseSubStyle(groups, "hard")
133	if err != nil || style != "hard" {
134		t.Fatalf("chooseSubStyle hard: style=%q err=%v", style, err)
135	}
136}
137
138func TestChooseSubStylePromptSelectOnce(t *testing.T) {
139	groups := map[string][]string{
140		"hsub": {"https://vibeplayer.site/hard"},
141		"sub":  {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
142	}
143
144	prompts := 0
145	previousPrompt := curdhost.PromptSelect
146	previousOut := curdhost.Out
147	previousPersist := curdhost.PersistSubStylePreference
148	previousCurrent := curdhost.CurrentSubStyle
149	curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
150		prompts++
151		return curdhost.PromptOption{Key: "hard", Label: "Hard sub"}, nil
152	}
153	curdhost.Out = func(string) {}
154	saved := ""
155	curdhost.PersistSubStylePreference = func(style string) error {
156		saved = style
157		return nil
158	}
159	curdhost.CurrentSubStyle = func() string { return saved }
160	t.Cleanup(func() {
161		curdhost.PromptSelect = previousPrompt
162		curdhost.Out = previousOut
163		curdhost.PersistSubStylePreference = previousPersist
164		curdhost.CurrentSubStyle = previousCurrent
165		resetSubStyleForTest()
166	})
167
168	for i := 0; i < 2; i++ {
169		style, err := chooseSubStyle(groups, "ask")
170		if err != nil || style != "hard" {
171			t.Fatalf("iteration %d: style=%q err=%v", i, style, err)
172		}
173	}
174	if prompts != 1 {
175		t.Fatalf("expected 1 prompt, got %d", prompts)
176	}
177	if saved != "hard" {
178		t.Fatalf("expected saved preference hard, got %q", saved)
179	}
180}
181
182func TestResolveBibiembPicks1080pVariant(t *testing.T) {
183	const hash = "agdeadbeef"
184
185	var server *httptest.Server
186	server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
187		switch {
188		case r.URL.Path == "/"+hash:
189			_, _ = io.WriteString(w, `const src = "`+server.URL+`/`+hash+`/master.m3u8"`)
190		case r.URL.Path == "/"+hash+"/master.m3u8":
191			_, _ = io.WriteString(w, `#EXTM3U
192#EXT-X-STREAM-INF:BANDWIDTH=1,NAME="720p"
193`+server.URL+`/`+hash+`/720p/index.m3u8
194#EXT-X-STREAM-INF:BANDWIDTH=2,NAME="1080p"
195`+server.URL+`/`+hash+`/1080p/index.m3u8`)
196		default:
197			http.NotFound(w, r)
198		}
199	}))
200	defer server.Close()
201
202	withAninekoTestClient(t, server.Client())
203
204	stream, err := resolveBibiemb(server.URL + "/" + hash)
205	if err != nil {
206		t.Fatalf("resolveBibiemb: %v", err)
207	}
208	if !strings.HasSuffix(stream.URL, "/1080p/index.m3u8") {
209		t.Fatalf("expected 1080p variant, got %q", stream.URL)
210	}
211}
212
213func TestStripPNGWrapper(t *testing.T) {
214	png := []byte{
215		0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
216		0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
217		0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
218		0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
219		0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
220		0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
221		0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
222		0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
223		0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
224	}
225	payload := []byte{0x47, 0x01, 0x02, 0x03}
226	data := append(append([]byte{}, png...), payload...)
227	if got := stripPNGWrapper(data); string(got) != string(payload) {
228		t.Fatalf("unexpected stripped payload %v", got)
229	}
230}
231
232func TestVibeProxyRewritesAndStripsSegments(t *testing.T) {
233	const (
234		id      = "abc123"
235		variant = "1720.m3u8"
236	)
237
238	png := []byte{
239		0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
240		0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
241		0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
242		0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
243		0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
244		0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
245		0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
246		0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
247		0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0x47, 0x11,
248	}
249
250	remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251		switch r.URL.Path {
252		case "/public/stream/" + id + "/master.m3u8":
253			_, _ = io.WriteString(w, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,NAME=\"720p\"\n"+variant+"\n")
254		case "/public/stream/" + id + "/" + variant:
255			_, _ = io.WriteString(w, "#EXTM3U\n#EXTINF:10.0,\n/public/segment.bin\n")
256		case "/public/segment.bin":
257			_, _ = w.Write(png)
258		default:
259			http.NotFound(w, r)
260		}
261	}))
262	defer remote.Close()
263
264	withAninekoTestClient(t, remote.Client())
265	resetVibeProxyForTest()
266
267	masterURL := remote.URL + "/public/stream/" + id + "/master.m3u8"
268	proxyURL, err := registerVibeStream(masterURL, remote.URL+"/"+id)
269	if err != nil {
270		t.Fatalf("registerVibeStream: %v", err)
271	}
272
273	resp, err := http.Get(proxyURL)
274	if err != nil {
275		t.Fatalf("get master: %v", err)
276	}
277	body, _ := io.ReadAll(resp.Body)
278	resp.Body.Close()
279	if !strings.Contains(string(body), "/1720.m3u8") {
280		t.Fatalf("master not rewritten: %s", body)
281	}
282
283	variantURL := ""
284	for _, line := range strings.Split(strings.ReplaceAll(string(body), "\r\n", "\n"), "\n") {
285		line = strings.TrimSpace(line)
286		if line != "" && !strings.HasPrefix(line, "#") {
287			variantURL = line
288			break
289		}
290	}
291	resp, err = http.Get(variantURL)
292	if err != nil {
293		t.Fatalf("get variant: %v", err)
294	}
295	body, _ = io.ReadAll(resp.Body)
296	resp.Body.Close()
297	segURL := ""
298	for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
299		line = strings.TrimSpace(line)
300		if line != "" && !strings.HasPrefix(line, "#") {
301			segURL = line
302		}
303	}
304
305	resp, err = http.Get(segURL)
306	if err != nil {
307		t.Fatalf("get segment: %v", err)
308	}
309	segBody, _ := io.ReadAll(resp.Body)
310	resp.Body.Close()
311	if len(segBody) != 2 || segBody[0] != 0x47 {
312		t.Fatalf("expected stripped mpeg-ts payload, got %v", segBody)
313	}
314}