internal/provider_animepahe.go

724 lines · 18381 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	if err := p.ensureBypass(); err != nil {
458		return nil, err
459	}
460	animeRef := parseAnimepaheProviderID(id)
461	if animeRef.Session == "" {
462		return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
463	}
464	apiID := animeRef.apiID()
465
466	// 1. Get episode session ID
467	// Map the 1-based Anilist episode number to Animepahe's actual episode number
468	eps, err := p.EpisodesList(id, "")
469	if err != nil {
470		return nil, err
471	}
472	if epNo < 1 || epNo > len(eps) {
473		return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps))
474	}
475
476	mappedEpNo, err := strconv.Atoi(eps[epNo-1])
477	if err != nil {
478		return nil, fmt.Errorf("invalid episode number format in provider: %v", err)
479	}
480
481	// Let's do a simple scan for the episode session:
482	var episodeSession string
483	page := 1
484	for {
485		reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
486		req, err := newAnimepaheAPIRequest(reqUrl)
487		if err != nil {
488			return nil, err
489		}
490
491		resp, err := sharedHTTPClient.Do(req)
492		if err != nil {
493			return nil, err
494		}
495
496		body, err := io.ReadAll(resp.Body)
497		resp.Body.Close()
498		if err != nil {
499			return nil, err
500		}
501		if !httpStatusOK(resp.StatusCode) {
502			return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body)
503		}
504
505		var epsResp animepaheEpisodesResponse
506		err = json.Unmarshal(body, &epsResp)
507		if err != nil {
508			return nil, err
509		}
510
511		for _, item := range epsResp.Data {
512			if item.Episode == mappedEpNo {
513				episodeSession = item.Session
514				break
515			}
516		}
517
518		if episodeSession != "" || epsResp.CurrentPage >= epsResp.LastPage {
519			break
520		}
521		page++
522	}
523
524	if episodeSession == "" {
525		return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo)
526	}
527
528	// player page: https://animepahe.pw/play/<anime_session>/<episode_session>
529	// stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
530	playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession)
531	req, err := newAnimepahePageRequest(playerUrl)
532	if err != nil {
533		return nil, err
534	}
535
536	resp, err := sharedHTTPClient.Do(req)
537	if err != nil {
538		return nil, err
539	}
540	defer resp.Body.Close()
541
542	body, err := io.ReadAll(resp.Body)
543	if err != nil {
544		return nil, err
545	}
546	if !httpStatusOK(resp.StatusCode) {
547		return nil, httpStatusError("animepahe player page", resp.StatusCode, body)
548	}
549
550	bodyStr := string(body)
551	type streamLink struct {
552		url string
553		res int
554	}
555	var subLinks []streamLink
556	var dubLinks []streamLink
557
558	parts := strings.Split(bodyStr, "<button")
559	for i := 1; i < len(parts); i++ {
560		part := parts[i]
561		srcIdx := strings.Index(part, "data-src=\"")
562		if srcIdx == -1 {
563			continue
564		}
565
566		startIdx := srcIdx + 10
567		endIdx := strings.Index(part[startIdx:], "\"")
568		if endIdx == -1 {
569			continue
570		}
571
572		link := part[startIdx : startIdx+endIdx]
573		if !strings.Contains(link, "kwik.cx") {
574			continue
575		}
576
577		resIdx := strings.Index(part, "data-resolution=\"")
578		res := 0
579		if resIdx != -1 {
580			startRes := resIdx + 17
581			endRes := strings.Index(part[startRes:], "\"")
582			if endRes != -1 {
583				res, _ = strconv.Atoi(part[startRes : startRes+endRes])
584			}
585		}
586
587		sLink := streamLink{url: link, res: res}
588		if strings.Contains(part, "data-audio=\"eng\"") {
589			dubLinks = append(dubLinks, sLink)
590		} else {
591			subLinks = append(subLinks, sLink)
592		}
593	}
594
595	// Sort by resolution descending
596	sortFunc := func(links []streamLink) {
597		sort.Slice(links, func(i, j int) bool {
598			return links[i].res > links[j].res
599		})
600	}
601	sortFunc(subLinks)
602	sortFunc(dubLinks)
603
604	var links []string
605	mode := normalizeTranslationType(config.SubOrDub)
606	if mode == "dub" {
607		for _, l := range dubLinks {
608			links = append(links, l.url)
609		}
610	} else {
611		for _, l := range subLinks {
612			links = append(links, l.url)
613		}
614	}
615	if len(links) == 0 {
616		return nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
617	}
618
619	var finalLinks []string
620	for _, kwikLink := range links {
621		m3u8, err := p.extractKwikM3u8(kwikLink)
622		if err == nil && m3u8 != "" {
623			finalLinks = append(finalLinks, m3u8)
624		}
625	}
626
627	if len(finalLinks) == 0 {
628		return nil, fmt.Errorf("failed to extract any %s stream links from kwik", mode)
629	}
630
631	return finalLinks, nil
632}
633
634func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
635	req, err := newAnimepahePageRequest(kwikUrl)
636	if err != nil {
637		return "", err
638	}
639
640	resp, err := sharedHTTPClient.Do(req)
641	if err != nil {
642		return "", err
643	}
644	defer resp.Body.Close()
645
646	body, err := io.ReadAll(resp.Body)
647	if err != nil {
648		return "", err
649	}
650	if !httpStatusOK(resp.StatusCode) {
651		return "", httpStatusError("kwik stream page", resp.StatusCode, body)
652	}
653	bodyStr := string(body)
654
655	re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
656	matches := re.FindAllStringSubmatch(bodyStr, -1)
657
658	for _, match := range matches {
659		pStr := match[1]
660		a, _ := strconv.Atoi(match[2])
661		c, _ := strconv.Atoi(match[3])
662		k := strings.Split(match[4], "|")
663
664		pStr = strings.ReplaceAll(pStr, "\\'", "'")
665		unpacked := unpackKwik(pStr, a, c, k)
666
667		if strings.Contains(unpacked, "m3u8") {
668			urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`)
669			urlMatch := urlRe.FindStringSubmatch(unpacked)
670			if len(urlMatch) > 1 {
671				return urlMatch[1], nil
672			}
673		}
674	}
675	return "", fmt.Errorf("m3u8 link not found in kwik page")
676}
677
678func unpackKwik(p string, a int, c int, k []string) string {
679	e := func(c int) string {
680		var helper func(c int) string
681		helper = func(c int) string {
682			res := ""
683			if c >= a {
684				res += helper(c / a)
685			}
686			mod := c % a
687			if mod > 35 {
688				res += string(rune(mod + 29))
689			} else {
690				res += strconv.FormatInt(int64(mod), 36)
691			}
692			return res
693		}
694		return helper(c)
695	}
696
697	d := make(map[string]string)
698	for i := c - 1; i >= 0; i-- {
699		val := k[i]
700		if val == "" {
701			val = e(i)
702		}
703		d[e(i)] = val
704	}
705
706	re := regexp.MustCompile(`[a-zA-Z0-9_]+`)
707	unpacked := re.ReplaceAllStringFunc(p, func(match string) string {
708		if val, ok := d[match]; ok && val != "" {
709			return val
710		}
711		return match
712	})
713
714	return unpacked
715}
716
717func contains(slice []string, val string) bool {
718	for _, item := range slice {
719		if item == val {
720			return true
721		}
722	}
723	return false
724}