internal/providers/animepahe/provider.go
739 lines · 19095 bytes
1package animepahe
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "os"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/go-rod/rod"
18 "github.com/go-rod/rod/lib/launcher"
19
20 "github.com/wraient/curd/internal/curdhost"
21 "github.com/wraient/curd/internal/providers"
22)
23
24var animepaheCookiesBypassed bool
25var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
26
27func getCookieFilePath() string {
28 return filepath.Join(curdhost.StoragePath(), "animepahe_cookies.json")
29}
30
31func saveCookies(cookies []*http.Cookie) {
32 cookieFilePath := getCookieFilePath()
33 os.MkdirAll(filepath.Dir(cookieFilePath), 0755)
34 b, _ := json.Marshal(cookies)
35 os.WriteFile(cookieFilePath, b, 0644)
36}
37
38func loadCookies() []*http.Cookie {
39 cookieFilePath := getCookieFilePath()
40 b, err := os.ReadFile(cookieFilePath)
41 if err != nil {
42 return nil
43 }
44 var cookies []*http.Cookie
45 if err := json.Unmarshal(b, &cookies); err != nil {
46 return nil
47 }
48 return cookies
49}
50
51func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
52 req, err := http.NewRequest("GET", rawURL, nil)
53 if err != nil {
54 return nil, err
55 }
56 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
57 req.Header.Set("Referer", "https://animepahe.pw/")
58 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
59 req.Header.Set("X-Requested-With", "XMLHttpRequest")
60 return req, nil
61}
62
63// NewPageRequest builds an HTTP request for animepahe HTML pages.
64func NewPageRequest(rawURL string) (*http.Request, error) {
65 return newAnimepahePageRequest(rawURL)
66}
67
68func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
69 req, err := http.NewRequest("GET", rawURL, nil)
70 if err != nil {
71 return nil, err
72 }
73 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
74 req.Header.Set("Referer", "https://animepahe.pw/")
75 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
76 return req, nil
77}
78
79func checkCookiesValid() bool {
80 req, err := newAnimepaheAPIRequest("https://animepahe.pw/api?m=search&q=test")
81 if err != nil {
82 return false
83 }
84
85 resp, err := curdhost.HTTPClient().Do(req)
86 if err != nil {
87 return false
88 }
89 defer resp.Body.Close()
90
91 body, err := io.ReadAll(resp.Body)
92 if err != nil {
93 return false
94 }
95 if resp.StatusCode != 200 {
96 return false
97 }
98 if isAnimepaheChallengeBody(body) {
99 return false
100 }
101
102 contentType := resp.Header.Get("Content-Type")
103 return strings.Contains(contentType, "application/json")
104}
105
106func isAnimepaheChallengeResponse(resp *http.Response, body []byte) bool {
107 if resp == nil {
108 return false
109 }
110 if isAnimepaheChallengeBody(body) {
111 return true
112 }
113 return resp.StatusCode == http.StatusForbidden && strings.Contains(strings.ToLower(resp.Header.Get("Server")), "ddos-guard")
114}
115
116func isAnimepaheChallengeBody(body []byte) bool {
117 normalized := strings.ToLower(string(body))
118 return strings.Contains(normalized, "ddos-guard") ||
119 strings.Contains(normalized, "/.well-known/ddos-guard/") ||
120 strings.Contains(normalized, "checking your browser")
121}
122
123func (p *Provider) ensureBypass() (err error) {
124 defer func() {
125 if recovered := recover(); recovered != nil {
126 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
127 }
128 }()
129
130 if animepaheCookiesBypassed {
131 return nil
132 }
133
134 cookies := loadCookies()
135 if len(cookies) > 0 {
136 u, _ := url.Parse("https://animepahe.pw")
137 curdhost.SetCookiesForAnimepahe(u, cookies)
138
139 if checkCookiesValid() {
140 animepaheCookiesBypassed = true
141 curdhost.Log("Successfully restored Animepahe session from cache.")
142 return nil
143 }
144 curdhost.Log("Cached Animepahe session expired. Requesting new session...")
145 }
146
147 return p.refreshBypass()
148}
149
150func (p *Provider) refreshBypass() error {
151 u, _ := url.Parse("https://animepahe.pw")
152 animepaheCookiesBypassed = false
153 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) {
154 curdhost.Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
155 }
156
157 curdhost.Out("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
158 httpCookies, err := solveAnimepaheBrowserChallenge()
159 if err != nil {
160 curdhost.Out("Animepahe browser challenge failed. Try again later or switch provider.")
161 return fmt.Errorf("animepahe browser challenge failed: %w", err)
162 }
163 if len(httpCookies) == 0 {
164 return fmt.Errorf("animepahe browser challenge returned no cookies")
165 }
166 curdhost.SetCookiesForAnimepahe(u, httpCookies)
167
168 if !checkCookiesValid() {
169 return fmt.Errorf("bypassed cookies are still invalid")
170 }
171
172 saveCookies(httpCookies)
173 animepaheCookiesBypassed = true
174 curdhost.Out("Successfully bypassed DDoS-Guard.")
175 return nil
176}
177
178func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err error) {
179 if err := rod.Try(func() {
180 l := launcher.New().Headless(true)
181 defer l.Cleanup()
182 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
183 defer browser.MustClose()
184
185 page := browser.MustPage("https://animepahe.pw/")
186 page.MustWaitLoad()
187
188 for i := 0; i < 30; i++ {
189 info, err := page.Info()
190 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
191 break
192 }
193 time.Sleep(500 * time.Millisecond)
194 }
195
196 rodCookies, err := page.Cookies(nil)
197 if err != nil {
198 panic(err)
199 }
200 for _, cookie := range rodCookies {
201 httpCookies = append(httpCookies, &http.Cookie{
202 Name: cookie.Name,
203 Value: cookie.Value,
204 })
205 }
206 }); err != nil {
207 return nil, err
208 }
209 return httpCookies, nil
210}
211
212type Provider struct{}
213
214func (p *Provider) Name() string {
215 return "animepahe"
216}
217
218// SearchItem is an animepahe API search result payload.
219type SearchItem struct {
220 ID int `json:"id"`
221 Title string `json:"title"`
222 Type string `json:"type"`
223 Episodes int `json:"episodes"`
224 Status string `json:"status"`
225 Season string `json:"season"`
226 Year int `json:"year"`
227 Score float64 `json:"score"`
228 Poster string `json:"poster"`
229 Session string `json:"session"`
230}
231
232type AnimeRef struct {
233 ReleaseID string
234 Session string
235}
236
237func (r AnimeRef) apiID() string {
238 if r.Session != "" {
239 return r.Session
240 }
241 return r.ReleaseID
242}
243
244func formatAnimepaheProviderID(item SearchItem) string {
245 if item.ID > 0 && item.Session != "" {
246 return fmt.Sprintf("%d:%s", item.ID, item.Session)
247 }
248 if item.Session != "" {
249 return item.Session
250 }
251 if item.ID > 0 {
252 return strconv.Itoa(item.ID)
253 }
254 return ""
255}
256
257// ParseProviderID parses a stored animepahe show identifier.
258func ParseProviderID(providerID string) AnimeRef {
259 providerID = strings.TrimSpace(providerID)
260 if providerID == "" {
261 return AnimeRef{}
262 }
263
264 parts := strings.SplitN(providerID, ":", 2)
265 if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
266 if _, err := strconv.Atoi(parts[0]); err == nil {
267 return AnimeRef{ReleaseID: parts[0], Session: parts[1]}
268 }
269 }
270
271 if _, err := strconv.Atoi(providerID); err == nil {
272 return AnimeRef{ReleaseID: providerID}
273 }
274
275 return AnimeRef{Session: providerID}
276}
277
278// StableProviderID returns the release id portion used for history matching.
279func StableProviderID(providerID string) string {
280 animeRef := ParseProviderID(providerID)
281 if animeRef.ReleaseID != "" {
282 return animeRef.ReleaseID
283 }
284 return providerID
285}
286
287func (p *Provider) ResolveProviderID(providerID, query string) (string, error) {
288 animeRef := ParseProviderID(providerID)
289 query = strings.TrimSpace(query)
290 if query == "" {
291 if animeRef.Session != "" {
292 return providerID, nil
293 }
294 return "", fmt.Errorf("cannot resolve animepahe provider id %q without an anime title", providerID)
295 }
296
297 options, err := p.SearchAnime(query, "")
298 if err != nil {
299 if animeRef.Session != "" {
300 curdhost.Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
301 return providerID, nil
302 }
303 return "", err
304 }
305
306 for _, option := range options {
307 item, ok := option.ExtraData.(SearchItem)
308 if !ok {
309 continue
310 }
311
312 if animeRef.ReleaseID != "" && strconv.Itoa(item.ID) == animeRef.ReleaseID {
313 return formatAnimepaheProviderID(item), nil
314 }
315 if animeRef.Session != "" && item.Session == animeRef.Session {
316 return formatAnimepaheProviderID(item), nil
317 }
318 }
319
320 if animeRef.Session != "" {
321 curdhost.Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
322 return providerID, nil
323 }
324
325 return "", fmt.Errorf("animepahe id %q was not found in search results for %q", providerID, query)
326}
327
328type animepaheSearchResponse struct {
329 Total int `json:"total"`
330 PerPage int `json:"per_page"`
331 CurrentPage int `json:"current_page"`
332 LastPage int `json:"last_page"`
333 Data []SearchItem `json:"data"`
334}
335
336func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
337 if err := p.ensureBypass(); err != nil {
338 return nil, err
339 }
340 // animepahe doesn't distinguish sub/dub at the search level
341 searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query))
342
343 req, err := newAnimepaheAPIRequest(searchUrl)
344 if err != nil {
345 return nil, err
346 }
347
348 resp, err := curdhost.HTTPClient().Do(req)
349 if err != nil {
350 return nil, err
351 }
352 defer resp.Body.Close()
353
354 body, err := io.ReadAll(resp.Body)
355 if err != nil {
356 return nil, err
357 }
358 if !curdhost.HTTPStatusOK(resp.StatusCode) {
359 return nil, curdhost.HTTPStatusError("animepahe search", resp.StatusCode, body)
360 }
361
362 var searchResp animepaheSearchResponse
363 err = json.Unmarshal(body, &searchResp)
364 if err != nil {
365 return nil, err
366 }
367
368 var result []providers.SelectionOption
369 for _, item := range searchResp.Data {
370 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
371 result = append(result, providers.SelectionOption{
372 Title: item.Title,
373 Label: label,
374 Key: formatAnimepaheProviderID(item),
375 Thumbnail: item.Poster,
376 ExtraData: item,
377 })
378 }
379
380 return result, nil
381}
382
383type animepaheEpisodesResponse struct {
384 Total int `json:"total"`
385 PerPage int `json:"per_page"`
386 CurrentPage int `json:"current_page"`
387 LastPage int `json:"last_page"`
388 Data []struct {
389 ID int `json:"id"`
390 AnimeID int `json:"anime_id"`
391 Episode int `json:"episode"`
392 Session string `json:"session"`
393 } `json:"data"`
394}
395
396func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
397 if err := p.ensureBypass(); err != nil {
398 return nil, err
399 }
400 animeRef := ParseProviderID(showID)
401 apiID := animeRef.apiID()
402 if apiID == "" {
403 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID)
404 }
405
406 var allEpisodes []int
407 page := 1
408 challengeRetried := false
409
410 for {
411 epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
412 req, err := newAnimepaheAPIRequest(epUrl)
413 if err != nil {
414 return nil, err
415 }
416
417 resp, err := curdhost.HTTPClient().Do(req)
418 if err != nil {
419 return nil, err
420 }
421
422 body, err := io.ReadAll(resp.Body)
423 resp.Body.Close()
424 if err != nil {
425 return nil, err
426 }
427 if isAnimepaheChallengeResponse(resp, body) {
428 if challengeRetried {
429 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
430 }
431 curdhost.Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
432 if err := p.refreshBypass(); err != nil {
433 return nil, err
434 }
435 challengeRetried = true
436 continue
437 }
438 if !curdhost.HTTPStatusOK(resp.StatusCode) {
439 return nil, curdhost.HTTPStatusError("animepahe episode list", resp.StatusCode, body)
440 }
441
442 var epsResp animepaheEpisodesResponse
443 err = json.Unmarshal(body, &epsResp)
444 if err != nil {
445 return nil, err
446 }
447
448 for _, ep := range epsResp.Data {
449 allEpisodes = append(allEpisodes, ep.Episode)
450 }
451
452 if epsResp.CurrentPage >= epsResp.LastPage {
453 break
454 }
455 page++
456 }
457
458 sort.Ints(allEpisodes)
459 var result []string
460 for _, ep := range allEpisodes {
461 result = append(result, strconv.Itoa(ep))
462 }
463
464 return result, nil
465}
466
467func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
468 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
469}
470
471func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
472 if err := p.ensureBypass(); err != nil {
473 return nil, err
474 }
475 animeRef := ParseProviderID(id)
476 if animeRef.Session == "" {
477 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
478 }
479 apiID := animeRef.apiID()
480
481 // 1. Get episode session ID
482 // Map the 1-based Anilist episode number to Animepahe's actual episode number
483 eps, err := p.EpisodesList(id, "")
484 if err != nil {
485 return nil, err
486 }
487 if epNo < 1 || epNo > len(eps) {
488 return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps))
489 }
490
491 mappedEpNo, err := strconv.Atoi(eps[epNo-1])
492 if err != nil {
493 return nil, fmt.Errorf("invalid episode number format in provider: %v", err)
494 }
495
496 // Let's do a simple scan for the episode session:
497 var episodeSession string
498 page := 1
499 for {
500 reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
501 req, err := newAnimepaheAPIRequest(reqUrl)
502 if err != nil {
503 return nil, err
504 }
505
506 resp, err := curdhost.HTTPClient().Do(req)
507 if err != nil {
508 return nil, err
509 }
510
511 body, err := io.ReadAll(resp.Body)
512 resp.Body.Close()
513 if err != nil {
514 return nil, err
515 }
516 if !curdhost.HTTPStatusOK(resp.StatusCode) {
517 return nil, curdhost.HTTPStatusError("animepahe episode lookup", resp.StatusCode, body)
518 }
519
520 var epsResp animepaheEpisodesResponse
521 err = json.Unmarshal(body, &epsResp)
522 if err != nil {
523 return nil, err
524 }
525
526 for _, item := range epsResp.Data {
527 if item.Episode == mappedEpNo {
528 episodeSession = item.Session
529 break
530 }
531 }
532
533 if episodeSession != "" || epsResp.CurrentPage >= epsResp.LastPage {
534 break
535 }
536 page++
537 }
538
539 if episodeSession == "" {
540 return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo)
541 }
542
543 // player page: https://animepahe.pw/play/<anime_session>/<episode_session>
544 // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
545 playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession)
546 req, err := newAnimepahePageRequest(playerUrl)
547 if err != nil {
548 return nil, err
549 }
550
551 resp, err := curdhost.HTTPClient().Do(req)
552 if err != nil {
553 return nil, err
554 }
555 defer resp.Body.Close()
556
557 body, err := io.ReadAll(resp.Body)
558 if err != nil {
559 return nil, err
560 }
561 if !curdhost.HTTPStatusOK(resp.StatusCode) {
562 return nil, curdhost.HTTPStatusError("animepahe player page", resp.StatusCode, body)
563 }
564
565 bodyStr := string(body)
566 type streamLink struct {
567 url string
568 res int
569 }
570 var subLinks []streamLink
571 var dubLinks []streamLink
572
573 parts := strings.Split(bodyStr, "<button")
574 for i := 1; i < len(parts); i++ {
575 part := parts[i]
576 srcIdx := strings.Index(part, "data-src=\"")
577 if srcIdx == -1 {
578 continue
579 }
580
581 startIdx := srcIdx + 10
582 endIdx := strings.Index(part[startIdx:], "\"")
583 if endIdx == -1 {
584 continue
585 }
586
587 link := part[startIdx : startIdx+endIdx]
588 if !strings.Contains(link, "kwik.cx") {
589 continue
590 }
591
592 resIdx := strings.Index(part, "data-resolution=\"")
593 res := 0
594 if resIdx != -1 {
595 startRes := resIdx + 17
596 endRes := strings.Index(part[startRes:], "\"")
597 if endRes != -1 {
598 res, _ = strconv.Atoi(part[startRes : startRes+endRes])
599 }
600 }
601
602 sLink := streamLink{url: link, res: res}
603 if strings.Contains(part, "data-audio=\"eng\"") {
604 dubLinks = append(dubLinks, sLink)
605 } else {
606 subLinks = append(subLinks, sLink)
607 }
608 }
609
610 // Sort by resolution descending
611 sortFunc := func(links []streamLink) {
612 sort.Slice(links, func(i, j int) bool {
613 return links[i].res > links[j].res
614 })
615 }
616 sortFunc(subLinks)
617 sortFunc(dubLinks)
618
619 var links []string
620 requestedMode := providers.NormalizeTranslationType(mode)
621 if requestedMode == "dub" {
622 for _, l := range dubLinks {
623 links = append(links, l.url)
624 }
625 } else {
626 for _, l := range subLinks {
627 links = append(links, l.url)
628 }
629 }
630 if len(links) == 0 {
631 return nil, fmt.Errorf("no %s streams found for episode %d", requestedMode, epNo)
632 }
633
634 var finalLinks []string
635 for _, kwikLink := range links {
636 m3u8, err := p.extractKwikM3u8(kwikLink)
637 if err == nil && m3u8 != "" {
638 finalLinks = append(finalLinks, m3u8)
639 }
640 }
641
642 if len(finalLinks) == 0 {
643 return nil, fmt.Errorf("failed to extract any %s stream links from kwik", requestedMode)
644 }
645
646 return finalLinks, nil
647}
648
649func (p *Provider) extractKwikM3u8(kwikUrl string) (string, error) {
650 req, err := newAnimepahePageRequest(kwikUrl)
651 if err != nil {
652 return "", err
653 }
654
655 resp, err := curdhost.HTTPClient().Do(req)
656 if err != nil {
657 return "", err
658 }
659 defer resp.Body.Close()
660
661 body, err := io.ReadAll(resp.Body)
662 if err != nil {
663 return "", err
664 }
665 if !curdhost.HTTPStatusOK(resp.StatusCode) {
666 return "", curdhost.HTTPStatusError("kwik stream page", resp.StatusCode, body)
667 }
668 bodyStr := string(body)
669
670 re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
671 matches := re.FindAllStringSubmatch(bodyStr, -1)
672
673 for _, match := range matches {
674 pStr := match[1]
675 a, _ := strconv.Atoi(match[2])
676 c, _ := strconv.Atoi(match[3])
677 k := strings.Split(match[4], "|")
678
679 pStr = strings.ReplaceAll(pStr, "\\'", "'")
680 unpacked := unpackKwik(pStr, a, c, k)
681
682 if strings.Contains(unpacked, "m3u8") {
683 urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`)
684 urlMatch := urlRe.FindStringSubmatch(unpacked)
685 if len(urlMatch) > 1 {
686 return urlMatch[1], nil
687 }
688 }
689 }
690 return "", fmt.Errorf("m3u8 link not found in kwik page")
691}
692
693func unpackKwik(p string, a int, c int, k []string) string {
694 e := func(c int) string {
695 var helper func(c int) string
696 helper = func(c int) string {
697 res := ""
698 if c >= a {
699 res += helper(c / a)
700 }
701 mod := c % a
702 if mod > 35 {
703 res += string(rune(mod + 29))
704 } else {
705 res += strconv.FormatInt(int64(mod), 36)
706 }
707 return res
708 }
709 return helper(c)
710 }
711
712 d := make(map[string]string)
713 for i := c - 1; i >= 0; i-- {
714 val := k[i]
715 if val == "" {
716 val = e(i)
717 }
718 d[e(i)] = val
719 }
720
721 re := regexp.MustCompile(`[a-zA-Z0-9_]+`)
722 unpacked := re.ReplaceAllStringFunc(p, func(match string) string {
723 if val, ok := d[match]; ok && val != "" {
724 return val
725 }
726 return match
727 })
728
729 return unpacked
730}
731
732func contains(slice []string, val string) bool {
733 for _, item := range slice {
734 if item == val {
735 return true
736 }
737 }
738 return false
739}