internal/provider_animepahe.go

728 lines · 18597 bytes

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