internal/providers/anineko/provider_test.go
356 lines · 10709 bytes
16 symbols in this file
roundTripFuncroundTripFunc.RoundTriptestResponsewithAninekoTestClientTestSearchAnimeParsesResultsTestEpisodesListParsesEpisodeLinksTestExtractLangEmbedURLsTestSubtitleFromEmbedHTMLTestResolveSubtitlePrefersEmbedURLTestResolveEmbedHostDetectsVivibebeTestChooseSubStyleHardPromptsForSoftFallbackTestChooseSubStyleRespectsPreferenceTestChooseSubStylePromptSelectOnceTestResolveBibiembPicks1080pVariantTestStripPNGWrapperTestVibeProxyRewritesAndStripsSegments
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 TestSubtitleFromEmbedHTML(t *testing.T) {
121 html := `const subtitle = "https://cdn.example/page.vtt";`
122 if got := subtitleFromEmbedHTML(html); got != "https://cdn.example/page.vtt" {
123 t.Fatalf("unexpected subtitle %q", got)
124 }
125}
126
127func TestResolveSubtitlePrefersEmbedURL(t *testing.T) {
128 embedURL := "https://vibeplayer.site/soft?sub=https://cdn.example/url.vtt"
129 html := `const subtitle = "https://cdn.example/page.vtt";`
130 if got := resolveSubtitle(embedURL, html); got != "https://cdn.example/url.vtt" {
131 t.Fatalf("unexpected subtitle %q", got)
132 }
133}
134
135func TestResolveEmbedHostDetectsVivibebe(t *testing.T) {
136 if got := resolveEmbedHost("https://vivibebe.site/e6693c8de8202fbe"); got != "vibeplayer" {
137 t.Fatalf("expected vibeplayer host, got %q", got)
138 }
139}
140
141func TestChooseSubStyleHardPromptsForSoftFallback(t *testing.T) {
142 resetSubStyleForTest()
143 groups := map[string][]string{
144 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
145 }
146
147 previousPrompt := curdhost.PromptSelect
148 curdhost.PromptSelect = func([]curdhost.PromptOption) (curdhost.PromptOption, error) {
149 return curdhost.PromptOption{Key: "soft", Label: "Use soft subs"}, nil
150 }
151 t.Cleanup(func() {
152 curdhost.PromptSelect = previousPrompt
153 resetSubStyleForTest()
154 })
155
156 style, err := chooseSubStyle(groups, "hard")
157 if err != nil || style != "soft" {
158 t.Fatalf("expected soft after prompt, got style=%q err=%v", style, err)
159 }
160}
161
162func TestChooseSubStyleRespectsPreference(t *testing.T) {
163 groups := map[string][]string{
164 "hsub": {"https://vibeplayer.site/hard"},
165 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
166 "dub": {"https://vibeplayer.site/dub"},
167 }
168
169 style, err := chooseSubStyle(groups, "soft")
170 if err != nil || style != "soft" {
171 t.Fatalf("chooseSubStyle soft: style=%q err=%v", style, err)
172 }
173
174 style, err = chooseSubStyle(groups, "hard")
175 if err != nil || style != "hard" {
176 t.Fatalf("chooseSubStyle hard: style=%q err=%v", style, err)
177 }
178}
179
180func TestChooseSubStylePromptSelectOnce(t *testing.T) {
181 groups := map[string][]string{
182 "hsub": {"https://vibeplayer.site/hard"},
183 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
184 }
185
186 prompts := 0
187 previousPrompt := curdhost.PromptSelect
188 previousOut := curdhost.Out
189 previousPersist := curdhost.PersistSubStylePreference
190 previousCurrent := curdhost.CurrentSubStyle
191 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
192 prompts++
193 return curdhost.PromptOption{Key: "hard", Label: "Hard sub"}, nil
194 }
195 curdhost.Out = func(string) {}
196 saved := ""
197 curdhost.PersistSubStylePreference = func(style string) error {
198 saved = style
199 return nil
200 }
201 curdhost.CurrentSubStyle = func() string { return saved }
202 t.Cleanup(func() {
203 curdhost.PromptSelect = previousPrompt
204 curdhost.Out = previousOut
205 curdhost.PersistSubStylePreference = previousPersist
206 curdhost.CurrentSubStyle = previousCurrent
207 resetSubStyleForTest()
208 })
209
210 for i := 0; i < 2; i++ {
211 style, err := chooseSubStyle(groups, "ask")
212 if err != nil || style != "hard" {
213 t.Fatalf("iteration %d: style=%q err=%v", i, style, err)
214 }
215 }
216 if prompts != 1 {
217 t.Fatalf("expected 1 prompt, got %d", prompts)
218 }
219 if saved != "hard" {
220 t.Fatalf("expected saved preference hard, got %q", saved)
221 }
222}
223
224func TestResolveBibiembPicks1080pVariant(t *testing.T) {
225 const hash = "agdeadbeef"
226
227 var server *httptest.Server
228 server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
229 switch {
230 case r.URL.Path == "/"+hash:
231 _, _ = io.WriteString(w, `const src = "`+server.URL+`/`+hash+`/master.m3u8"`)
232 case r.URL.Path == "/"+hash+"/master.m3u8":
233 _, _ = io.WriteString(w, `#EXTM3U
234#EXT-X-STREAM-INF:BANDWIDTH=1,NAME="720p"
235`+server.URL+`/`+hash+`/720p/index.m3u8
236#EXT-X-STREAM-INF:BANDWIDTH=2,NAME="1080p"
237`+server.URL+`/`+hash+`/1080p/index.m3u8`)
238 default:
239 http.NotFound(w, r)
240 }
241 }))
242 defer server.Close()
243
244 withAninekoTestClient(t, server.Client())
245
246 stream, err := resolveBibiemb(server.URL + "/" + hash)
247 if err != nil {
248 t.Fatalf("resolveBibiemb: %v", err)
249 }
250 if !strings.HasSuffix(stream.URL, "/1080p/index.m3u8") {
251 t.Fatalf("expected 1080p variant, got %q", stream.URL)
252 }
253}
254
255func TestStripPNGWrapper(t *testing.T) {
256 png := []byte{
257 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
258 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
259 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
260 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
261 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
262 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
263 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
264 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
265 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
266 }
267 payload := []byte{0x47, 0x01, 0x02, 0x03}
268 data := append(append([]byte{}, png...), payload...)
269 if got := stripPNGWrapper(data); string(got) != string(payload) {
270 t.Fatalf("unexpected stripped payload %v", got)
271 }
272}
273
274func TestVibeProxyRewritesAndStripsSegments(t *testing.T) {
275 const (
276 id = "abc123"
277 variant = "1720.m3u8"
278 )
279
280 png := []byte{
281 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
282 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
283 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
284 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
285 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
286 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
287 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
288 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
289 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0x47, 0x11,
290 }
291
292 remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
293 switch r.URL.Path {
294 case "/public/stream/" + id + "/master.m3u8":
295 _, _ = io.WriteString(w, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,NAME=\"720p\"\n"+variant+"\n")
296 case "/public/stream/" + id + "/" + variant:
297 _, _ = io.WriteString(w, "#EXTM3U\n#EXTINF:10.0,\n/public/segment.bin\n")
298 case "/public/segment.bin":
299 _, _ = w.Write(png)
300 default:
301 http.NotFound(w, r)
302 }
303 }))
304 defer remote.Close()
305
306 withAninekoTestClient(t, remote.Client())
307 resetVibeProxyForTest()
308
309 masterURL := remote.URL + "/public/stream/" + id + "/master.m3u8"
310 proxyURL, err := registerVibeStream(masterURL, remote.URL+"/"+id)
311 if err != nil {
312 t.Fatalf("registerVibeStream: %v", err)
313 }
314
315 resp, err := http.Get(proxyURL)
316 if err != nil {
317 t.Fatalf("get master: %v", err)
318 }
319 body, _ := io.ReadAll(resp.Body)
320 resp.Body.Close()
321 if !strings.Contains(string(body), "/1720.m3u8") {
322 t.Fatalf("master not rewritten: %s", body)
323 }
324
325 variantURL := ""
326 for _, line := range strings.Split(strings.ReplaceAll(string(body), "\r\n", "\n"), "\n") {
327 line = strings.TrimSpace(line)
328 if line != "" && !strings.HasPrefix(line, "#") {
329 variantURL = line
330 break
331 }
332 }
333 resp, err = http.Get(variantURL)
334 if err != nil {
335 t.Fatalf("get variant: %v", err)
336 }
337 body, _ = io.ReadAll(resp.Body)
338 resp.Body.Close()
339 segURL := ""
340 for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
341 line = strings.TrimSpace(line)
342 if line != "" && !strings.HasPrefix(line, "#") {
343 segURL = line
344 }
345 }
346
347 resp, err = http.Get(segURL)
348 if err != nil {
349 t.Fatalf("get segment: %v", err)
350 }
351 segBody, _ := io.ReadAll(resp.Body)
352 resp.Body.Close()
353 if len(segBody) != 2 || segBody[0] != 0x47 {
354 t.Fatalf("expected stripped mpeg-ts payload, got %v", segBody)
355 }
356}