internal/providers/animepahe/provider_test.go

184 lines · 6161 bytes

  1package animepahe
  2
  3import (
  4	"io"
  5	"net/http"
  6	"net/http/cookiejar"
  7	"net/url"
  8	"os"
  9	"strings"
 10	"testing"
 11
 12	"github.com/wraient/curd/internal/curdhost"
 13)
 14
 15const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
 16
 17type roundTripFunc func(*http.Request) (*http.Response, error)
 18
 19func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
 20	return f(req)
 21}
 22
 23func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
 24	resp := &http.Response{
 25		StatusCode: statusCode,
 26		Header:     make(http.Header),
 27		Body:       io.NopCloser(strings.NewReader(body)),
 28		Request:    req,
 29	}
 30	for key, value := range headers {
 31		resp.Header.Set(key, value)
 32	}
 33	return resp
 34}
 35
 36func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
 37	t.Helper()
 38
 39	previousClient := curdhost.HTTPClient
 40	previousLog := curdhost.Log
 41	previousOut := curdhost.Out
 42	previousCookies := curdhost.SetCookiesForAnimepahe
 43	previousSolver := solveAnimepaheBrowserChallenge
 44	previousBypassed := animepaheCookiesBypassed
 45	previousStoragePath := curdhost.StoragePath
 46
 47	t.Cleanup(func() {
 48		curdhost.HTTPClient = previousClient
 49		curdhost.Log = previousLog
 50		curdhost.Out = previousOut
 51		curdhost.SetCookiesForAnimepahe = previousCookies
 52		solveAnimepaheBrowserChallenge = previousSolver
 53		animepaheCookiesBypassed = previousBypassed
 54		curdhost.StoragePath = previousStoragePath
 55	})
 56
 57	curdhost.HTTPClient = func() *http.Client { return client }
 58	curdhost.Log = func(string) {}
 59	curdhost.Out = func(string) {}
 60	curdhost.SetCookiesForAnimepahe = func(*url.URL, []*http.Cookie) {}
 61	solveAnimepaheBrowserChallenge = solver
 62	curdhost.StoragePath = func() string { return t.TempDir() }
 63}
 64
 65func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
 66	jar, err := cookiejar.New(nil)
 67	if err != nil {
 68		t.Fatalf("create cookie jar: %v", err)
 69	}
 70
 71	var releaseCalls int
 72	var searchChecks int
 73	var solverCalls int
 74	client := &http.Client{Jar: jar, Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
 75		switch req.URL.Query().Get("m") {
 76		case "release":
 77			releaseCalls++
 78			if releaseCalls == 1 {
 79				return animepaheTestResponse(req, http.StatusForbidden, animepaheChallengeHTML, map[string]string{
 80					"Content-Type": "text/html; charset=UTF-8",
 81					"Server":       "ddos-guard",
 82				}), nil
 83			}
 84			return animepaheTestResponse(req, http.StatusOK, `{"total":2,"per_page":30,"current_page":1,"last_page":1,"data":[{"episode":1},{"episode":2}]}`, map[string]string{
 85				"Content-Type": "application/json",
 86			}), nil
 87		case "search":
 88			searchChecks++
 89			return animepaheTestResponse(req, http.StatusOK, `{"total":0,"per_page":8,"current_page":1,"last_page":1,"data":[]}`, map[string]string{
 90				"Content-Type": "application/json",
 91			}), nil
 92		default:
 93			t.Fatalf("unexpected animepahe request: %s", req.URL.String())
 94			return nil, nil
 95		}
 96	})}
 97	withAnimepaheTestHooks(t, client, func() ([]*http.Cookie, error) {
 98		solverCalls++
 99		return []*http.Cookie{{Name: "__ddg2_", Value: "fresh"}}, nil
100	})
101	animepaheCookiesBypassed = true
102
103	episodes, err := (&Provider{}).EpisodesList("4:session-id", "sub")
104	if err != nil {
105		t.Fatalf("expected episode list retry to succeed: %v", err)
106	}
107	if got := strings.Join(episodes, ","); got != "1,2" {
108		t.Fatalf("unexpected animepahe episodes: %s", got)
109	}
110	if releaseCalls != 2 {
111		t.Fatalf("expected release endpoint to be retried once, got %d calls", releaseCalls)
112	}
113	if searchChecks != 1 {
114		t.Fatalf("expected refreshed session validation, got %d checks", searchChecks)
115	}
116	if solverCalls != 1 {
117		t.Fatalf("expected one browser challenge refresh, got %d", solverCalls)
118	}
119}
120
121func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.T) {
122	jar, err := cookiejar.New(nil)
123	if err != nil {
124		t.Fatalf("create cookie jar: %v", err)
125	}
126
127	var releaseCalls int
128	client := &http.Client{Jar: jar, Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
129		switch req.URL.Query().Get("m") {
130		case "release":
131			releaseCalls++
132			return animepaheTestResponse(req, http.StatusForbidden, animepaheChallengeHTML, map[string]string{
133				"Content-Type": "text/html; charset=UTF-8",
134				"Server":       "ddos-guard",
135			}), nil
136		case "search":
137			return animepaheTestResponse(req, http.StatusOK, `{"total":0,"per_page":8,"current_page":1,"last_page":1,"data":[]}`, map[string]string{
138				"Content-Type": "application/json",
139			}), nil
140		default:
141			t.Fatalf("unexpected animepahe request: %s", req.URL.String())
142			return nil, nil
143		}
144	})}
145	withAnimepaheTestHooks(t, client, func() ([]*http.Cookie, error) {
146		return []*http.Cookie{{Name: "__ddg2_", Value: "fresh"}}, nil
147	})
148	animepaheCookiesBypassed = true
149
150	_, err = (&Provider{}).EpisodesList("4:session-id", "sub")
151	if err == nil {
152		t.Fatalf("expected persistent DDoS-Guard challenge to fail")
153	}
154	if !strings.Contains(err.Error(), "still blocked by DDoS-Guard") {
155		t.Fatalf("unexpected error: %v", err)
156	}
157	if releaseCalls != 2 {
158		t.Fatalf("expected exactly one retry after challenge refresh, got %d release calls", releaseCalls)
159	}
160}
161
162func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
163	if os.Getenv("CURD_LIVE_ANIMEPAHE_TEST") != "1" {
164		t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
165	}
166
167	previousBypassed := animepaheCookiesBypassed
168	previousStoragePath := curdhost.StoragePath
169	t.Cleanup(func() {
170		animepaheCookiesBypassed = previousBypassed
171		curdhost.StoragePath = previousStoragePath
172	})
173	curdhost.StoragePath = func() string { return t.TempDir() }
174	animepaheCookiesBypassed = false
175
176	episodes, err := (&Provider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
177	if err != nil {
178		t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
179	}
180	t.Logf("live Animepahe One Piece episode count: %d", len(episodes))
181	if len(episodes) < 1000 {
182		t.Fatalf("expected One Piece to return a large live episode list, got %d episodes", len(episodes))
183	}
184}