Commit d5d497d95a

d5d497d95aaa2025bdf3ba81ce4fa143b0268dd7

parent: 79b1ba9382

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2026-06-15 08:10 UTC
committer: <noreply@github.com>

Fix: Allanime (#101)

* Align AllAnime link resolution with ani-cli provider flow.

Use encoded clock.json providers, wixstatic and m3u8 expansion, playback referrers/subtitles, and skip dead fast4speed so fallback can run.

* disable: animepahe due to cloudflare protection

Layout: unified · split

internal/curd.go +22 −8
@@ -1083,8 +1083,17 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10831083 }
10841084 }
10851085
1086 // 1b. Title/thumbnail scoring (AllAnime englishName vs AniList romaji query, etc.)
1087 if !found {
1088 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok {
1089 anime.ProviderId = bestMatch.Key
1090 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label))
1091 found = true
1092 }
1093 }
1094
10861095 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1087 if !found && ProviderStackContains(userCurdConfig, "animepahe") {
1096 if !found && ProviderEnabled("animepahe") && ProviderStackContains(userCurdConfig, "animepahe") {
10881097 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
10891098
10901099 targetAnilistID := strconv.Itoa(anime.AnilistId)
@@ -1591,6 +1600,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
15911600
15921601 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
15931602 anime.Ep.Links = anime.Ep.NextEpisode.Links
1603 anime.Ep.StreamReferrer = ""
1604 anime.Ep.SubtitleURL = ""
15941605 if anime.Ep.NextEpisode.ProviderName != "" {
15951606 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
15961607 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
@@ -1611,6 +1622,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
16111622 if err == nil {
16121623 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
16131624 anime.Ep.Links = link
1625 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
16141626 goto episodeLinksReady
16151627 }
16161628 linkErr = err
@@ -1649,6 +1661,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
16491661 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
16501662 }
16511663 anime.Ep.Links = link
1664 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
16521665 }
16531666
16541667episodeLinksReady:
@@ -1739,7 +1752,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
17391752 }
17401753
17411754 providerName, providerID := AnimeProviderID(anime)
1742 if providerName != "animepahe" {
1755 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
17431756 return nil
17441757 }
17451758 if !ProviderStackContains(userCurdConfig, "animepahe") {
@@ -1778,7 +1791,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
17781791
17791792func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
17801793 providerName, _ := AnimeProviderID(anime)
1781 if providerName != "animepahe" {
1794 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
17821795 return false
17831796 }
17841797
@@ -2108,6 +2121,8 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
21082121 // Use prefetched links if available for the next episode
21092122 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
21102123 anime.Ep.Links = anime.Ep.NextEpisode.Links
2124 anime.Ep.StreamReferrer = ""
2125 anime.Ep.SubtitleURL = ""
21112126 if anime.Ep.NextEpisode.ProviderName != "" {
21122127 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
21132128 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
@@ -2372,11 +2387,10 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
23722387
23732388// ChangeProvider allows the user to switch the anime provider
23742389func ChangeProvider(userCurdConfig *CurdConfig) {
2375 options := []SelectionOption{
2376 {Key: "[\"allanime\"]", Label: "allanime"},
2377 {Key: "[\"animepahe\"]", Label: "animepahe"},
2378 {Key: "[\"allanime\",\"animepahe\"]", Label: "allanime, then animepahe"},
2379 {Key: "[\"animepahe\",\"allanime\"]", Label: "animepahe, then allanime"},
2390 options := providerSelectionOptions()
2391 if len(options) == 0 {
2392 CurdOut("\nNo providers are currently enabled.\n")
2393 return
23802394 }
23812395
23822396 selected, err := DynamicSelect(options)
internal/episode_url.go +122 −277
@@ -17,7 +17,6 @@ import (
1717 "sort"
1818 "strconv"
1919 "strings"
20 "time"
2120)
2221
2322type allanimeSource struct {
@@ -42,12 +41,6 @@ type allanimeTobeparsedPayload struct {
4241 } `json:"episode"`
4342}
4443
45type result struct {
46 index int
47 links []string
48 err error
49}
50
5144type filemoonResponse struct {
5245 IV string `json:"iv"`
5346 Payload string `json:"payload"`
@@ -55,6 +48,24 @@ type filemoonResponse struct {
5548}
5649
5750func decodeTobeparsed(blob string) ([]allanimeSource, error) {
51 plain, err := decryptTobeparsedPlain(blob)
52 if err != nil {
53 return nil, err
54 }
55
56 var payload allanimeTobeparsedPayload
57 if err := json.Unmarshal(plain, &payload); err != nil {
58 return nil, fmt.Errorf("failed to parse decrypted tobeparsed payload: %w", err)
59 }
60
61 if len(payload.Episode.SourceUrls) == 0 {
62 return nil, fmt.Errorf("no source URLs found in decrypted tobeparsed payload")
63 }
64
65 return payload.Episode.SourceUrls, nil
66}
67
68func decryptTobeparsedPlain(blob string) ([]byte, error) {
5869 key := []byte("Xot36i3lK3:v1")
5970 hash := sha256.Sum256(key)
6071
@@ -67,7 +78,6 @@ func decodeTobeparsed(blob string) ([]allanimeSource, error) {
6778 return nil, fmt.Errorf("data too short to contain tobeparsed payload")
6879 }
6980
70 // The payload format is: 1-byte header, 12-byte IV, ciphertext, 16-byte trailer.
7181 iv := data[1:13]
7282 ctLen := len(data) - 13 - 16
7383 if ctLen <= 0 {
@@ -87,17 +97,7 @@ func decodeTobeparsed(blob string) ([]allanimeSource, error) {
8797 stream := cipher.NewCTR(block, ctrIV)
8898 plain := make([]byte, len(ct))
8999 stream.XORKeyStream(plain, ct)
90
91 var payload allanimeTobeparsedPayload
92 if err := json.Unmarshal(plain, &payload); err != nil {
93 return nil, fmt.Errorf("failed to parse decrypted tobeparsed payload: %w", err)
94 }
95
96 if len(payload.Episode.SourceUrls) == 0 {
97 return nil, fmt.Errorf("no source URLs found in decrypted tobeparsed payload")
98 }
99
100 return payload.Episode.SourceUrls, nil
100 return plain, nil
101101}
102102
103103func decodeProviderID(encoded string) string {
@@ -143,19 +143,33 @@ func decodeProviderID(encoded string) string {
143143 return result
144144}
145145
146var allanimeNamedProviders = []string{
147 "Default",
148 "Yt-mp4",
149 "S-mp4",
150 "Fm-mp4",
151 "Luf-Mp4",
152}
153
154const (
155 allanimePersistedQueryReferer = "https://youtu-chan.com"
156 allanimeGraphQLReferer = "https://allanime.to"
157)
158
146159func isDirectPlayableAllanimeSource(source allanimeSource) bool {
147160 sourceURL := strings.TrimSpace(source.SourceUrl)
148161 if sourceURL == "" {
149162 return false
150163 }
151
152 if strings.EqualFold(source.SourceName, "Yt-mp4") || strings.EqualFold(source.SourceName, "S-mp4") {
153 return true
164 if strings.HasPrefix(sourceURL, "--") {
165 return false
166 }
167 if !strings.HasPrefix(sourceURL, "http://") && !strings.HasPrefix(sourceURL, "https://") {
168 return false
154169 }
155170
156 lowerURL := strings.ToLower(sourceURL)
157 if strings.Contains(lowerURL, "tools.fast4speed.rsvp/") {
158 return true
171 if isUnreliableAllanimeDirectURL(sourceURL) {
172 return false
159173 }
160174
161175 parsedURL, err := url.Parse(sourceURL)
@@ -164,7 +178,17 @@ func isDirectPlayableAllanimeSource(source allanimeSource) bool {
164178 }
165179
166180 path := strings.ToLower(parsedURL.Path)
167 return strings.HasSuffix(path, ".mp4") || strings.HasSuffix(path, ".m3u8")
181 if strings.HasSuffix(path, ".mp4") || strings.HasSuffix(path, ".m3u8") {
182 return true
183 }
184
185 host := strings.ToLower(parsedURL.Host)
186 return strings.Contains(host, "sharepoint.com") || strings.Contains(host, "wixmp.com")
187}
188
189func isUnreliableAllanimeDirectURL(sourceURL string) bool {
190 lowerURL := strings.ToLower(strings.TrimSpace(sourceURL))
191 return strings.Contains(lowerURL, "tools.fast4speed.rsvp/")
168192}
169193
170194func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource {
@@ -180,77 +204,6 @@ func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource
180204 return sorted
181205}
182206
183func extractLinks(provider_id string) map[string]interface{} {
184 provider_id = normalizeAllanimeProviderPath(provider_id)
185
186 // Check if provider_id is already a full URL (external link)
187 if strings.HasPrefix(provider_id, "http://") || strings.HasPrefix(provider_id, "https://") {
188 // It's an external direct video link, preserve it exactly as provided.
189 Log(fmt.Sprintf("Direct external link detected: %s", provider_id))
190 return map[string]interface{}{
191 "links": []interface{}{
192 map[string]interface{}{
193 "link": provider_id,
194 },
195 },
196 }
197 }
198
199 // It's a relative path for allanime API
200 allanime_base := "https://allanime.day"
201 url := allanime_base + provider_id
202 req, err := http.NewRequest("GET", url, nil)
203 var videoData map[string]interface{}
204 if err != nil {
205 Log(fmt.Sprint("Error creating request:", err))
206 return videoData
207 }
208
209 // Add the headers
210 req.Header.Set("Referer", "https://allanime.to")
211 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
212
213 // Send the request
214 resp, err := sharedHTTPClient.Do(req)
215 if err != nil {
216 Log(fmt.Sprint("Error sending request:", err))
217 return videoData
218 }
219 defer resp.Body.Close()
220
221 // Read the response body
222 body, err := io.ReadAll(resp.Body)
223 if err != nil {
224 Log(fmt.Sprint("Error reading response:", err))
225 return videoData
226 }
227 if !httpStatusOK(resp.StatusCode) {
228 Log(httpStatusError("allanime source extractor", resp.StatusCode, body))
229 return videoData
230 }
231
232 // Parse the JSON response
233 err = json.Unmarshal(body, &videoData)
234 if err != nil {
235 Log(fmt.Sprint("Error parsing JSON:", err))
236 return videoData
237 }
238
239 // Filemoon extractor payload does not return a top-level "links" field.
240 if _, hasLinks := videoData["links"]; !hasLinks {
241 if filemoonLinks := extractFilemoonLinks(videoData); len(filemoonLinks) > 0 {
242 links := make([]interface{}, 0, len(filemoonLinks))
243 for _, link := range filemoonLinks {
244 links = append(links, map[string]interface{}{"link": link})
245 }
246 videoData["links"] = links
247 }
248 }
249
250 // Process the data as needed
251 return videoData
252}
253
254207func normalizeAllanimeProviderPath(providerID string) string {
255208 const allanimePrefix = "/https://allanime.day"
256209
@@ -432,7 +385,11 @@ func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
432385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo)
433386}
434387
435func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
388func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
389 return fetchEpisodeSourcesForMode(id, normalizeTranslationType(mode), epNo)
390}
391
392func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
436393 const (
437394 episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
438395 )
@@ -469,8 +426,8 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
469426 return nil, fmt.Errorf("failed to create persisted query request: %w", err)
470427 }
471428 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
472 req.Header.Set("Referer", "https://allmanga.to")
473 req.Header.Set("Origin", "https://youtu-chan.com")
429 req.Header.Set("Referer", allanimePersistedQueryReferer)
430 req.Header.Set("Origin", allanimePersistedQueryReferer)
474431
475432 resp, err := sharedHTTPClient.Do(req)
476433 if err != nil {
@@ -491,6 +448,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
491448 }
492449
493450 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
451 if !useFallback && response.Data.Tobeparsed == "" && !strings.Contains(string(body), "tobeparsed") {
452 useFallback = true
453 }
494454 if useFallback {
495455 query := episodeEmbedGQL
496456
@@ -509,9 +469,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
509469 }
510470
511471 req.Header.Set("Content-Type", "application/json")
512 req.Header.Set("User-Agent", "Mozilla/5.0")
513 req.Header.Set("Referer", "https://allmanga.to")
514 req.Header.Set("Origin", "https://allanime.to")
472 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
473 req.Header.Set("Referer", allanimeGraphQLReferer)
474 req.Header.Set("Origin", allanimeGraphQLReferer)
515475
516476 resp, err := sharedHTTPClient.Do(req)
517477 if err != nil {
@@ -541,199 +501,84 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
541501 }
542502
543503 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
544 return getLinksFromSourceUrls(decodedSources)
504 return decodedSources, nil
545505 }
546506
547 return getLinksFromSourceUrls(response.Data.Episode.SourceUrls)
507 return response.Data.Episode.SourceUrls, nil
548508}
549509
550func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) {
551 sourceUrls = sortAllanimeSourcesByPriority(sourceUrls)
552
553 directURLs := make([]string, 0)
554 validURLs := make([]string, 0)
555 highestPriority := -1.0
556 var highestPriorityURL string
557
558 for _, url := range sourceUrls {
559 sourceURL := strings.TrimSpace(url.SourceUrl)
560 if sourceURL == "" {
561 continue
562 }
563
564 if isDirectPlayableAllanimeSource(url) {
565 directURLs = append(directURLs, sourceURL)
566 continue
567 }
568
569 if !strings.HasPrefix(sourceURL, "--") || len(sourceURL) <= 2 {
570 Log(fmt.Sprintf("Skipping unsupported Allanime source %q (%s)", url.SourceName, sourceURL))
571 continue
572 }
510func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
511 links, _, err := getAllanimeEpisodeStreamsForMode(id, mode, epNo)
512 return links, err
513}
573514
574 decodedURL := decodeProviderID(sourceURL[2:])
575 if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) {
576 priority := url.Priority
577 if priority > highestPriority {
578 highestPriority = priority
579 highestPriorityURL = sourceURL
580 }
581 } else {
582 validURLs = append(validURLs, sourceURL)
515func findNamedAllanimeSource(sourceUrls []allanimeSource, providerName string) (allanimeSource, bool) {
516 for _, source := range sourceUrls {
517 if strings.EqualFold(strings.TrimSpace(source.SourceName), providerName) {
518 return source, true
583519 }
584520 }
585
586 if len(directURLs) > 0 {
587 Log(fmt.Sprintf("Using %d direct Allanime source URL(s)", len(directURLs)))
588 return directURLs, nil
589 }
590
591 if highestPriorityURL != "" {
592 validURLs = []string{highestPriorityURL}
593 }
594
595 if len(validURLs) == 0 {
596 return nil, fmt.Errorf("no supported source URLs found in response")
597 }
598
599 return getLinksFromURLs(validURLs)
521 return allanimeSource{}, false
600522}
601523
602func getLinksFromURLs(validURLs []string) ([]string, error) {
603 results := make(chan result, len(validURLs))
604 orderedResults := make([][]string, len(validURLs))
605
606 highPriorityLink := make(chan []string, 1)
607
608 for i, sourceUrl := range validURLs {
609 go func(idx int, url string) {
610 decodedProviderID := decodeProviderID(url[2:])
611 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
612
613 extractedLinks := extractLinks(decodedProviderID)
614
615 if extractedLinks == nil {
616 results <- result{
617 index: idx,
618 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
619 }
620 return
621 }
622
623 linksInterface, ok := extractedLinks["links"].([]interface{})
624 if !ok {
625 results <- result{
626 index: idx,
627 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
628 }
629 return
630 }
631
632 var links []string
633 for _, linkInterface := range linksInterface {
634 linkMap, ok := linkInterface.(map[string]interface{})
635 if !ok {
636 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
637 continue
638 }
639
640 link, ok := linkMap["link"].(string)
641 if !ok {
642 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
643 continue
644 }
645
646 links = append(links, link)
647 }
524var wixstaticURLSetPattern = regexp.MustCompile(`^(https://video\.wixstatic\.com/video/[^/,]+/),([^/]*),/mp4/file\.mp4`)
648525
649 // Check if any of the extracted links are high priority
650 priorityDomains := LinkPriorities
651 if len(priorityDomains) > 3 {
652 priorityDomains = priorityDomains[:3]
653 }
654 for _, link := range links {
655 for _, domain := range priorityDomains {
656 if strings.Contains(link, domain) {
657 // Found high priority link, send it immediately
658 select {
659 case highPriorityLink <- []string{link}:
660 default:
661 // Channel already has a high priority link
662 }
663 break
664 }
665 }
666 }
526func expandWixmpLinks(link string) []string {
527 normalized := strings.TrimSpace(link)
528 if normalized == "" {
529 return nil
530 }
667531
668 results <- result{
669 index: idx,
670 links: links,
671 }
672 }(i, sourceUrl)
673 }
674
675 // Collect results with timeout
676 timeout := time.After(10 * time.Second)
677 var collectedErrors []error
678 successCount := 0
679
680 // First, try to get a high priority link
681 select {
682 case links := <-highPriorityLink:
683 return links, nil
684 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
685 // No high priority link found quickly, proceed with normal collection
686 }
687
688 // Continue with existing result collection logic
689 // Collect results maintaining order
690 completedCount := 0
691 for completedCount < len(validURLs) {
692 select {
693 case res := <-results:
694 completedCount++
695 if res.err != nil {
696 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
697 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
698 } else {
699 orderedResults[res.index] = res.links
700 successCount++
701 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
702 }
703 case <-timeout:
704 if successCount > 0 {
705 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
706 // Flatten available results
707 return flattenResults(orderedResults), nil
708 }
709 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
532 if strings.Contains(normalized, "repackager.wixmp.com") {
533 normalized = strings.TrimPrefix(normalized, "https://repackager.wixmp.com/")
534 normalized = strings.TrimPrefix(normalized, "http://repackager.wixmp.com/")
535 if !strings.HasPrefix(normalized, "http") {
536 normalized = "https://" + normalized
710537 }
711538 }
712539
713 // If we have any errors but also some successes, log errors but continue
714 if len(collectedErrors) > 0 {
715 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
540 if idx := strings.Index(normalized, ".urlset"); idx != -1 {
541 normalized = normalized[:idx]
716542 }
717543
718 // Flatten and return results
719 allLinks := flattenResults(orderedResults)
720 if len(allLinks) == 0 {
721 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
544 if match := wixstaticURLSetPattern.FindStringSubmatch(normalized); len(match) == 3 {
545 base := match[1]
546 qualities := strings.Split(match[2], ",")
547 expanded := make([]string, 0, len(qualities))
548 for _, quality := range qualities {
549 quality = strings.TrimSpace(quality)
550 if quality == "" {
551 continue
552 }
553 expanded = append(expanded, base+quality+"/mp4/file.mp4")
554 }
555 if len(expanded) > 0 {
556 sort.Slice(expanded, func(i, j int) bool {
557 return wixmpQualityScore(expanded[i]) > wixmpQualityScore(expanded[j])
558 })
559 return expanded
560 }
722561 }
723562
724 return allLinks, nil
563 return []string{link}
725564}
726565
727// converts the ordered slice of link slices into a single slice
728func flattenResults(results [][]string) []string {
729 var totalLen int
730 for _, r := range results {
731 totalLen += len(r)
732 }
733
734 allLinks := make([]string, 0, totalLen)
735 for _, links := range results {
736 allLinks = append(allLinks, links...)
566func wixmpQualityScore(link string) int {
567 for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
568 if strings.Contains(link, quality) {
569 switch quality {
570 case "1080p":
571 return 1080
572 case "720p":
573 return 720
574 case "480p":
575 return 480
576 case "360p":
577 return 360
578 case "240p":
579 return 240
580 }
581 }
737582 }
738 return allLinks
583 return 0
739584}
internal/episode_url_anicli.go added +465
@@ -0,0 +1,465 @@
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "regexp"
10 "sort"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15)
16
17const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
18
19// StreamPlaybackHint carries MPV playback metadata extracted from AllAnime clock.json.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25type allanimeResolvedStream struct {
26 URL string
27 Referrer string
28 SubtitleURL string
29 QualityScore int
30}
31
32var (
33 allanimeClockRefererPattern = regexp.MustCompile(`"Referer":"([^"]+)"`)
34 allanimeClockSubtitlePattern = regexp.MustCompile(`"subtitles":\[\{"lang":"en","label":"English","default":"default","src":"([^"]+)"`)
35 allanimeStreamResolutionPattern = regexp.MustCompile(`RESOLUTION=(\d+)x(\d+)`)
36 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`)
37)
38
39func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]StreamPlaybackHint, error) {
40 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo)
41 if err != nil {
42 return nil, nil, err
43 }
44 return getLinksFromEncodedSourceUrls(sourceUrls)
45}
46
47func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]StreamPlaybackHint, error) {
48 type providerJob struct {
49 index int
50 name string
51 url string
52 }
53
54 jobs := make([]providerJob, 0)
55 for _, providerName := range allanimeNamedProviders {
56 source, ok := findNamedAllanimeSource(sourceUrls, providerName)
57 if !ok {
58 continue
59 }
60 sourceURL := strings.TrimSpace(source.SourceUrl)
61 if !strings.HasPrefix(sourceURL, "--") || len(sourceURL) <= 2 {
62 continue
63 }
64 jobs = append(jobs, providerJob{
65 index: len(jobs),
66 name: providerName,
67 url: sourceURL,
68 })
69 }
70 if len(jobs) == 0 {
71 return nil, nil, fmt.Errorf("no encoded Allanime provider sources found")
72 }
73
74 type streamResult struct {
75 index int
76 streams []allanimeResolvedStream
77 err error
78 }
79
80 results := make(chan streamResult, len(jobs))
81 var wg sync.WaitGroup
82 for _, job := range jobs {
83 wg.Add(1)
84 go func(idx int, providerName, encodedURL string) {
85 defer wg.Done()
86 decodedProviderID := decodeProviderID(encodedURL[2:])
87 Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
88 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID)
89 results <- streamResult{index: idx, streams: streams, err: err}
90 }(job.index, job.name, job.url)
91 }
92 go func() {
93 wg.Wait()
94 close(results)
95 }()
96
97 orderedStreams := make([][]allanimeResolvedStream, len(jobs))
98 var collectedErrors []error
99 successCount := 0
100 timeout := time.After(15 * time.Second)
101 completedCount := 0
102 for completedCount < len(jobs) {
103 select {
104 case res, ok := <-results:
105 if !ok {
106 completedCount = len(jobs)
107 break
108 }
109 completedCount++
110 if res.err != nil {
111 Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
112 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err))
113 continue
114 }
115 if len(res.streams) > 0 {
116 orderedStreams[res.index] = res.streams
117 successCount++
118 Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
119 }
120 case <-timeout:
121 if successCount > 0 {
122 return buildAllanimeLinkResult(orderedStreams)
123 }
124 return nil, nil, fmt.Errorf("timeout waiting for Allanime provider links")
125 }
126 }
127
128 if successCount == 0 {
129 return nil, nil, fmt.Errorf("no valid links found from Allanime providers: %v", collectedErrors)
130 }
131 return buildAllanimeLinkResult(orderedStreams)
132}
133
134func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]StreamPlaybackHint, error) {
135 allStreams := make([]allanimeResolvedStream, 0)
136 for _, streams := range orderedStreams {
137 allStreams = append(allStreams, streams...)
138 }
139 sort.SliceStable(allStreams, func(i, j int) bool {
140 return allStreams[i].QualityScore > allStreams[j].QualityScore
141 })
142
143 links := make([]string, 0, len(allStreams))
144 hints := make(map[string]StreamPlaybackHint)
145 seen := make(map[string]struct{})
146 for _, stream := range allStreams {
147 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) {
148 continue
149 }
150 if _, exists := seen[stream.URL]; exists {
151 continue
152 }
153 seen[stream.URL] = struct{}{}
154 links = append(links, stream.URL)
155 referrer := stream.Referrer
156 if referrer == "" {
157 referrer = allanimeGraphQLReferer
158 }
159 hints[stream.URL] = StreamPlaybackHint{
160 Referrer: referrer,
161 Subtitle: stream.SubtitleURL,
162 }
163 }
164 if len(links) == 0 {
165 return nil, nil, fmt.Errorf("no reliable Allanime streams found")
166 }
167 return links, hints, nil
168}
169
170func resolveAllanimeClockProvider(providerName, providerPath string) ([]allanimeResolvedStream, error) {
171 providerPath = normalizeAllanimeProviderPath(providerPath)
172 if strings.HasPrefix(providerPath, "http://") || strings.HasPrefix(providerPath, "https://") {
173 if isUnreliableAllanimeDirectURL(providerPath) {
174 return nil, fmt.Errorf("skipping unreliable fast4speed source")
175 }
176 return []allanimeResolvedStream{{
177 URL: providerPath,
178 Referrer: allanimeGraphQLReferer,
179 QualityScore: 0,
180 }}, nil
181 }
182
183 rawBody, videoData, err := fetchAllanimeClockResponse(providerPath)
184 if err != nil {
185 return nil, err
186 }
187
188 if providerName == "Fm-mp4" {
189 if filemoonLinks := extractFilemoonLinks(videoData); len(filemoonLinks) > 0 {
190 return streamsFromPlainURLs(filemoonLinks, allanimeGraphQLReferer, ""), nil
191 }
192 }
193
194 referrer := extractAllanimeClockReferer(rawBody)
195 subtitleURL := extractAllanimeClockSubtitle(rawBody)
196 streams := make([]allanimeResolvedStream, 0)
197
198 linksInterface, ok := videoData["links"].([]interface{})
199 if !ok || len(linksInterface) == 0 {
200 return nil, fmt.Errorf("no links field in Allanime extractor response")
201 }
202
203 for _, linkInterface := range linksInterface {
204 linkMap, ok := linkInterface.(map[string]interface{})
205 if !ok {
206 continue
207 }
208 if _, hasLink := linkMap["link"]; !hasLink {
209 if _, cacheOnly := linkMap["mp4"].(bool); cacheOnly {
210 continue
211 }
212 }
213
214 resolutionScore := allanimeResolutionScore(linkMap["resolutionStr"])
215 if linkURL, ok := linkMap["link"].(string); ok && strings.TrimSpace(linkURL) != "" {
216 streams = append(streams, resolveAllanimeLinkURL(linkURL, referrer, subtitleURL, resolutionScore)...)
217 continue
218 }
219
220 if hlsMap, ok := linkMap["hls"].(map[string]interface{}); ok {
221 if hlsURL, ok := hlsMap["url"].(string); ok && strings.TrimSpace(hlsURL) != "" {
222 streams = append(streams, resolveAllanimeLinkURL(hlsURL, referrer, subtitleURL, resolutionScore)...)
223 }
224 }
225 }
226
227 if len(streams) == 0 {
228 return nil, fmt.Errorf("no playable links in Allanime extractor response")
229 }
230 sort.SliceStable(streams, func(i, j int) bool {
231 return streams[i].QualityScore > streams[j].QualityScore
232 })
233 return streams, nil
234}
235
236func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interface{}, error) {
237 requestURL := "https://allanime.day" + providerPath
238 req, err := http.NewRequest("GET", requestURL, nil)
239 if err != nil {
240 return nil, nil, err
241 }
242 req.Header.Set("Referer", allanimeGraphQLReferer)
243 req.Header.Set("User-Agent", allanimeUserAgent)
244
245 resp, err := sharedHTTPClient.Do(req)
246 if err != nil {
247 return nil, nil, err
248 }
249 defer resp.Body.Close()
250
251 body, err := io.ReadAll(resp.Body)
252 if err != nil {
253 return nil, nil, err
254 }
255 if !httpStatusOK(resp.StatusCode) {
256 return nil, nil, httpStatusError("allanime source extractor", resp.StatusCode, body)
257 }
258
259 var videoData map[string]interface{}
260 if err := json.Unmarshal(body, &videoData); err != nil {
261 return nil, nil, fmt.Errorf("failed to parse Allanime extractor JSON: %w", err)
262 }
263 return body, videoData, nil
264}
265
266func resolveAllanimeLinkURL(linkURL, referrer, subtitleURL string, resolutionScore int) []allanimeResolvedStream {
267 linkURL = strings.TrimSpace(linkURL)
268 if linkURL == "" {
269 return nil
270 }
271
272 if strings.Contains(linkURL, "repackager.wixmp.com") {
273 expanded := expandWixmpLinks(linkURL)
274 return streamsFromPlainURLs(expanded, referrer, subtitleURL, resolutionScore)
275 }
276
277 if strings.Contains(linkURL, "master.m3u8") {
278 if streams, err := fetchAllanimeM3U8VariantStreams(linkURL, referrer, subtitleURL); err == nil && len(streams) > 0 {
279 return streams
280 }
281 }
282
283 qualityScore := resolutionScore
284 if qualityScore == 0 {
285 qualityScore = wixmpQualityScore(linkURL)
286 }
287 return []allanimeResolvedStream{{
288 URL: linkURL,
289 Referrer: referrer,
290 SubtitleURL: subtitleURL,
291 QualityScore: qualityScore,
292 }}
293}
294
295func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([]allanimeResolvedStream, error) {
296 req, err := http.NewRequest("GET", masterURL, nil)
297 if err != nil {
298 return nil, err
299 }
300 if referrer == "" {
301 referrer = allanimeGraphQLReferer
302 }
303 req.Header.Set("Referer", referrer)
304 req.Header.Set("User-Agent", allanimeUserAgent)
305
306 resp, err := sharedHTTPClient.Do(req)
307 if err != nil {
308 return nil, err
309 }
310 body, err := io.ReadAll(resp.Body)
311 resp.Body.Close()
312 if err != nil {
313 return nil, err
314 }
315 if !httpStatusOK(resp.StatusCode) {
316 return nil, httpStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
317 }
318
319 playlist := string(body)
320 if !strings.Contains(playlist, "EXTM3U") {
321 return nil, fmt.Errorf("response is not an m3u8 playlist")
322 }
323
324 baseURL := masterURL
325 if idx := strings.LastIndex(baseURL, "/"); idx >= 0 {
326 baseURL = baseURL[:idx+1]
327 }
328
329 lines := strings.Split(playlist, "\n")
330 streams := make([]allanimeResolvedStream, 0)
331 for i := 0; i < len(lines); i++ {
332 line := strings.TrimSpace(lines[i])
333 if !strings.HasPrefix(line, "#EXT-X-STREAM-INF:") {
334 continue
335 }
336 qualityScore := parseAllanimeStreamInfScore(line)
337 i++
338 for i < len(lines) {
339 nextLine := strings.TrimSpace(lines[i])
340 if nextLine == "" {
341 i++
342 continue
343 }
344 if strings.HasPrefix(nextLine, "#EXT-X-I-FRAME-STREAM-INF") {
345 break
346 }
347 if strings.HasPrefix(nextLine, "#") {
348 i++
349 continue
350 }
351 streamURL := resolveAllanimeRelativeURL(baseURL, nextLine)
352 streams = append(streams, allanimeResolvedStream{
353 URL: streamURL,
354 Referrer: referrer,
355 SubtitleURL: subtitleURL,
356 QualityScore: qualityScore,
357 })
358 break
359 }
360 }
361
362 if len(streams) == 0 {
363 return nil, fmt.Errorf("no variant streams found in m3u8 playlist")
364 }
365 sort.SliceStable(streams, func(i, j int) bool {
366 return streams[i].QualityScore > streams[j].QualityScore
367 })
368 return streams, nil
369}
370
371func parseAllanimeStreamInfScore(line string) int {
372 if match := allanimeStreamResolutionPattern.FindStringSubmatch(line); len(match) == 3 {
373 if width, err := strconv.Atoi(match[1]); err == nil && width > 0 {
374 return width
375 }
376 }
377 if match := allanimeStreamBandwidthPattern.FindStringSubmatch(line); len(match) == 2 {
378 if bandwidth, err := strconv.Atoi(match[1]); err == nil && bandwidth > 0 {
379 return bandwidth / 1000
380 }
381 }
382 return 0
383}
384
385func resolveAllanimeRelativeURL(baseURL, uri string) string {
386 uri = strings.TrimSpace(uri)
387 if strings.HasPrefix(uri, "http://") || strings.HasPrefix(uri, "https://") {
388 return uri
389 }
390 if strings.HasPrefix(uri, "/") {
391 if parsed, err := url.Parse(baseURL); err == nil {
392 return parsed.Scheme + "://" + parsed.Host + uri
393 }
394 }
395 return baseURL + uri
396}
397
398func extractAllanimeClockReferer(rawBody []byte) string {
399 if match := allanimeClockRefererPattern.FindSubmatch(rawBody); len(match) == 2 {
400 return string(match[1])
401 }
402 return allanimeGraphQLReferer
403}
404
405func extractAllanimeClockSubtitle(rawBody []byte) string {
406 if match := allanimeClockSubtitlePattern.FindSubmatch(rawBody); len(match) == 2 {
407 return string(match[1])
408 }
409 return ""
410}
411
412func allanimeResolutionScore(value interface{}) int {
413 text := strings.TrimSpace(fmt.Sprint(value))
414 if text == "" {
415 return 0
416 }
417 if score := wixmpQualityScore(text); score > 0 {
418 return score
419 }
420 if digits := regexp.MustCompile(`(\d{3,4})`).FindStringSubmatch(text); len(digits) == 2 {
421 if score, err := strconv.Atoi(digits[1]); err == nil {
422 return score
423 }
424 }
425 return 0
426}
427
428func streamsFromPlainURLs(urls []string, referrer, subtitleURL string, qualityScores ...int) []allanimeResolvedStream {
429 defaultScore := 0
430 if len(qualityScores) > 0 {
431 defaultScore = qualityScores[0]
432 }
433 streams := make([]allanimeResolvedStream, 0, len(urls))
434 for _, linkURL := range urls {
435 linkURL = strings.TrimSpace(linkURL)
436 if linkURL == "" {
437 continue
438 }
439 score := defaultScore
440 if score == 0 {
441 score = wixmpQualityScore(linkURL)
442 }
443 streams = append(streams, allanimeResolvedStream{
444 URL: linkURL,
445 Referrer: referrer,
446 SubtitleURL: subtitleURL,
447 QualityScore: score,
448 })
449 }
450 return streams
451}
452
453func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
454 if anime == nil || len(links) == 0 {
455 return
456 }
457 selected := PrioritizeLink(links)
458 if hint, ok := hints[selected]; ok {
459 anime.Ep.StreamReferrer = hint.Referrer
460 anime.Ep.SubtitleURL = hint.Subtitle
461 return
462 }
463 anime.Ep.StreamReferrer = ""
464 anime.Ep.SubtitleURL = ""
465}
internal/episode_url_live_test.go added +48
@@ -0,0 +1,48 @@
1package internal
2
3import (
4 "os"
5 "strings"
6 "testing"
7)
8
9func TestAllanimeMarchLionDubEp1Live(t *testing.T) {
10 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
11 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
12 }
13
14 showID := "NPpCgzb2MbnpiyxZ3"
15 links, err := getAllanimeEpisodeURLForMode(showID, "dub", 1)
16 if err == nil {
17 for _, link := range links {
18 if strings.Contains(link, "fast4speed.rsvp") {
19 t.Fatalf("dub should not return unreliable fast4speed links, got %s", link)
20 }
21 }
22 t.Fatalf("expected dub lookup to fail without playable AllAnime sources, got links: %#v", links)
23 }
24}
25
26func TestAllanimeMarchLionSubEp1Live(t *testing.T) {
27 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
28 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
29 }
30
31 showID := "NPpCgzb2MbnpiyxZ3"
32 links, err := getAllanimeEpisodeURLForMode(showID, "sub", 1)
33 if err != nil {
34 t.Fatalf("sub episode link lookup failed: %v", err)
35 }
36 if len(links) == 0 {
37 t.Fatal("expected sub links")
38 }
39 picked := PrioritizeLink(links)
40 if strings.Contains(picked, "fast4speed.rsvp") {
41 t.Fatalf("sub should not play fast4speed when wixstatic providers exist, got %s", picked)
42 }
43 if !strings.Contains(picked, "video.wixstatic.com") &&
44 !strings.Contains(picked, "repackager.wixmp.com") &&
45 !strings.Contains(picked, "sharepoint.com") {
46 t.Fatalf("unexpected sub link source: %s", picked)
47 }
48}
internal/episode_url_test.go +42 −87
@@ -1,117 +1,72 @@
11package internal
22
3import "testing"
3import (
4 "strings"
5 "testing"
6)
47
5func TestGetLinksFromSourceUrlsPrefersDirectPlayableSources(t *testing.T) {
8func TestExpandWixmpLinksMatchesAniCLI(t *testing.T) {
9 t.Parallel()
10
11 input := "https://repackager.wixmp.com/video.wixstatic.com/video/4fa677_7daec0ccb9364ac7b032d43692c73617/,720p,480p,1080p,/mp4/file.mp4.urlset/master.m3u8"
12 links := expandWixmpLinks(input)
13 if len(links) != 3 {
14 t.Fatalf("expected 3 expanded links, got %d: %#v", len(links), links)
15 }
16 if !strings.HasPrefix(links[0], "https://video.wixstatic.com/video/4fa677_7daec0ccb9364ac7b032d43692c73617/1080p/mp4/file.mp4") {
17 t.Fatalf("expected 1080p wixstatic link first, got %q", links[0])
18 }
19}
20
21func TestGetLinksFromEncodedSourceUrlsSkipsUnreliableFast4speed(t *testing.T) {
622 t.Parallel()
723
824 sourceUrls := []allanimeSource{
925 {
10 SourceUrl: "--175948514e4c4f57",
11 SourceName: "Luf-Mp4",
12 Priority: 7.5,
13 },
14 {
15 SourceUrl: "https://tools.fast4speed.rsvp/media9/videos/example/sub/1?Authorization=test",
26 SourceUrl: "https://tools.fast4speed.rsvp/media9/videos/example/dub/1?Authorization=test",
1627 SourceName: "Yt-mp4",
1728 Priority: 7.9,
1829 },
19 {
20 SourceUrl: "https://mp4upload.com/embed-example.html",
21 SourceName: "Mp4",
22 Priority: 4,
23 },
24 }
25
26 links, err := getLinksFromSourceUrls(sourceUrls)
27 if err != nil {
28 t.Fatalf("expected direct Allanime sources to be returned without error, got %v", err)
2930 }
3031
31 if len(links) != 1 {
32 t.Fatalf("expected one direct playable source, got %d: %#v", len(links), links)
33 }
34
35 if got, want := links[0], "https://tools.fast4speed.rsvp/media9/videos/example/sub/1?Authorization=test"; got != want {
36 t.Fatalf("getLinksFromSourceUrls() returned %q, want %q", got, want)
32 _, _, err := getLinksFromEncodedSourceUrls(sourceUrls)
33 if err == nil {
34 t.Fatal("expected error when only direct fast4speed source is available")
3735 }
3836}
3937
40func TestSortAllanimeSourcesByPriorityOrdersDescending(t *testing.T) {
38func TestGetLinksFromEncodedSourceUrlsRequiresEncodedProviders(t *testing.T) {
4139 t.Parallel()
4240
4341 sourceUrls := []allanimeSource{
44 {SourceUrl: "https://example.com/low.mp4", Priority: 1},
45 {SourceUrl: "https://example.com/high.mp4", Priority: 9},
46 {SourceUrl: "https://example.com/mid.mp4", Priority: 5},
47 }
48
49 sorted := sortAllanimeSourcesByPriority(sourceUrls)
50 if len(sorted) != 3 {
51 t.Fatalf("expected 3 sorted sources, got %d", len(sorted))
42 {
43 SourceUrl: "https://tenant.sharepoint.com/video.mp4",
44 SourceName: "S-mp4",
45 Priority: 7.4,
46 },
5247 }
5348
54 if sorted[0].SourceUrl != "https://example.com/high.mp4" {
55 t.Fatalf("expected highest priority source first, got %#v", sorted)
56 }
57 if sorted[1].SourceUrl != "https://example.com/mid.mp4" {
58 t.Fatalf("expected middle priority source second, got %#v", sorted)
59 }
60 if sorted[2].SourceUrl != "https://example.com/low.mp4" {
61 t.Fatalf("expected lowest priority source last, got %#v", sorted)
49 _, _, err := getLinksFromEncodedSourceUrls(sourceUrls)
50 if err == nil {
51 t.Fatal("expected error when no encoded provider sources exist")
6252 }
6353}
6454
65func TestIsDirectPlayableAllanimeSource(t *testing.T) {
55func TestParseAllanimeStreamInfScore(t *testing.T) {
6656 t.Parallel()
6757
68 cases := []struct {
69 name string
70 source allanimeSource
71 want bool
72 }{
73 {
74 name: "fast4speed player url",
75 source: allanimeSource{
76 SourceName: "Yt-mp4",
77 SourceUrl: "https://tools.fast4speed.rsvp/media9/videos/example/sub/1?Authorization=test",
78 },
79 want: true,
80 },
81 {
82 name: "sharepoint mp4 source",
83 source: allanimeSource{
84 SourceName: "S-mp4",
85 SourceUrl: "https://tenant.sharepoint.com/video.mp4",
86 },
87 want: true,
88 },
89 {
90 name: "mp4upload embed url",
91 source: allanimeSource{
92 SourceName: "Mp4",
93 SourceUrl: "https://mp4upload.com/embed-example.html",
94 },
95 want: false,
96 },
97 {
98 name: "filemoon embed url",
99 source: allanimeSource{
100 SourceName: "Fm-Hls",
101 SourceUrl: "https://bysekoze.com/e/example",
102 },
103 want: false,
104 },
58 line := `#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"`
59 if got := parseAllanimeStreamInfScore(line); got != 1280 {
60 t.Fatalf("parseAllanimeStreamInfScore() = %d, want 1280", got)
10561 }
62}
10663
107 for _, tc := range cases {
108 tc := tc
109 t.Run(tc.name, func(t *testing.T) {
110 t.Parallel()
64func TestResolveAllanimeRelativeURL(t *testing.T) {
65 t.Parallel()
11166
112 if got := isDirectPlayableAllanimeSource(tc.source); got != tc.want {
113 t.Fatalf("isDirectPlayableAllanimeSource(%+v) = %v, want %v", tc.source, got, tc.want)
114 }
115 })
67 got := resolveAllanimeRelativeURL("https://example.com/path/", "720p/index.m3u8")
68 want := "https://example.com/path/720p/index.m3u8"
69 if got != want {
70 t.Fatalf("resolveAllanimeRelativeURL() = %q, want %q", got, want)
11671 }
11772}
internal/links.go +19 −23
@@ -4,6 +4,7 @@ import "strings"
44
55// LinkPriorities defines the order of priority for link domains
66var LinkPriorities = []string{
7 "video.wixstatic.com",
78 "sharepoint.com",
89 "wixmp.com",
910 "dropbox.com",
@@ -18,31 +19,26 @@ func PrioritizeLink(links []string) string {
1819 return ""
1920 }
2021
21 // Create a map for quick lookup of priorities
22 priorityMap := make(map[string]int)
23 for i, p := range LinkPriorities {
24 priorityMap[p] = len(LinkPriorities) - i // Higher index means higher priority
25 }
26
27 highestPriority := -1
28 var bestLink string
29
30 for _, link := range links {
31 for domain, priority := range priorityMap {
32 if strings.Contains(link, domain) {
33 if priority > highestPriority {
34 highestPriority = priority
35 bestLink = link
36 }
37 break
38 }
22 bestLink := links[0]
23 bestScore := linkSelectionScore(bestLink)
24 for _, link := range links[1:] {
25 score := linkSelectionScore(link)
26 if score > bestScore {
27 bestScore = score
28 bestLink = link
3929 }
4030 }
31 return bestLink
32}
4133
42 // If no priority link found, return the first link
43 if bestLink == "" {
44 return links[0]
34func linkSelectionScore(link string) int {
35 score := 0
36 for i, domain := range LinkPriorities {
37 if strings.Contains(link, domain) {
38 score += (len(LinkPriorities) - i) * 1000
39 break
40 }
4541 }
46
47 return bestLink
42 score += wixmpQualityScore(link)
43 return score
4844}
internal/localTracking.go +1
@@ -442,6 +442,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
442442 ExitCurd(fmt.Errorf("Failed to get episode link"))
443443 }
444444 link := resolvedLink.Links
445 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints)
445446
446447 if len(link) == 0 {
447448 ExitCurd(fmt.Errorf("No episode links found"))
internal/logic_regression_test.go +18 −2
@@ -216,11 +216,27 @@ func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
216216 SetGlobalConfig(previousConfig)
217217 })
218218
219 CurrentProvider = nil
220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
221
222 if got := GetProvider().Name(); got != "allanime" {
223 t.Fatalf("expected allanime provider, got %q", got)
224 }
225}
226
227func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
228 previousProvider := CurrentProvider
229 previousConfig := GetGlobalConfig()
230 t.Cleanup(func() {
231 CurrentProvider = previousProvider
232 SetGlobalConfig(previousConfig)
233 })
234
219235 CurrentProvider = nil
220236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
221237
222 if got := GetProvider().Name(); got != "animepahe" {
223 t.Fatalf("expected animepahe provider, got %q", got)
238 if got := GetProvider().Name(); got != "allanime" {
239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got)
224240 }
225241}
226242
internal/player.go +39 −11
@@ -19,6 +19,16 @@ var logFile = "debug.log"
1919// This is not generic but we have MpvArgs in CurdConfig to add custom ones
2020const defaultStreamReferrer = "https://allanime.day/"
2121
22func streamReferrerForLink(link, provider string) string {
23 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") {
24 return "https://allanime.to"
25 }
26 if provider == "animepahe" {
27 return "https://kwik.cx/"
28 }
29 return defaultStreamReferrer
30}
31
2232// We should really handle this by Provider but keeping simple string here for now
2333
2434func getBundledMPVPath() (string, error) {
@@ -192,6 +202,19 @@ func hasMPVReferrerArg(args []string) bool {
192202 return false
193203}
194204
205func hasMPVSubtitleArg(args []string) bool {
206 for i, arg := range args {
207 lowerArg := strings.ToLower(strings.TrimSpace(arg))
208 if strings.HasPrefix(lowerArg, "--sub-file=") || lowerArg == "--sub-file" {
209 return true
210 }
211 if lowerArg == "--sub-files" && i+1 < len(args) {
212 return true
213 }
214 }
215 return false
216}
217
195218func normalizeReferrerValue(referrer string) string {
196219 referrer = strings.TrimSpace(referrer)
197220 if referrer == "" {
@@ -262,13 +285,16 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
262285 }
263286
264287 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args)
265 if shouldSetDefaultReferrer {
266 referrer := defaultStreamReferrer
267 if CurrentAnimeProviderName(anime) == "animepahe" {
268 referrer = "https://kwik.cx/"
269 }
288 referrer := strings.TrimSpace(anime.Ep.StreamReferrer)
289 if referrer == "" && shouldSetDefaultReferrer {
290 referrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
291 }
292 if referrer != "" && shouldSetDefaultReferrer {
270293 args = append(args, fmt.Sprintf("--referrer=%s", referrer))
271294 }
295 if subtitleURL := strings.TrimSpace(anime.Ep.SubtitleURL); subtitleURL != "" && !hasMPVSubtitleArg(args) {
296 args = append(args, fmt.Sprintf("--sub-file=%s", subtitleURL))
297 }
272298 args = normalizeReferrerArgs(args)
273299
274300 // Check if we have an existing socket and if MPV is still running
@@ -277,13 +303,15 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
277303 mpvSocketPath = anime.Ep.Player.SocketPath
278304
279305 if shouldSetDefaultReferrer {
280 referrer := defaultStreamReferrer
281 if CurrentAnimeProviderName(anime) == "animepahe" {
282 referrer = "https://kwik.cx/"
306 activeReferrer := strings.TrimSpace(anime.Ep.StreamReferrer)
307 if activeReferrer == "" {
308 activeReferrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
283309 }
284 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", referrer})
285 if referrerErr != nil {
286 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr))
310 if activeReferrer != "" {
311 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", activeReferrer})
312 if referrerErr != nil {
313 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr))
314 }
287315 }
288316 }
289317
internal/provider.go +90 −31
@@ -20,6 +20,7 @@ type ProviderModeResolver interface {
2020
2121type ProviderEpisodeResult struct {
2222 Links []string
23 LinkHints map[string]StreamPlaybackHint
2324 ProviderName string
2425 ProviderID string
2526 Mode string
@@ -73,7 +74,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
7374
7475 normalizedRaw := strings.ToLower(rawProvider)
7576 if normalizedRaw == "stacked" || normalizedRaw == "stack" || normalizedRaw == "auto" || normalizedRaw == "all" {
76 return []string{"allanime", "animepahe"}, false
77 return defaultEnabledProviderStack(), false
7778 }
7879
7980 buildConfig := func(parts []string) ([]string, bool) {
@@ -124,7 +125,7 @@ func configuredProviderNames(config *CurdConfig) []string {
124125 }
125126
126127 providers, _ := parseProviderConfig(rawProvider)
127 return providers
128 return ensureEnabledProviderNames(providers)
128129}
129130
130131func ConfiguredProviderNames(config *CurdConfig) []string {
@@ -170,6 +171,9 @@ func ProviderStackContains(config *CurdConfig, providerName string) bool {
170171
171172func ProviderByName(providerName string) (Provider, error) {
172173 providerName = normalizeProviderName(providerName)
174 if reason := providerDisabledReason(providerName); reason != "" {
175 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176 }
173177 factory, ok := providerFactories[providerName]
174178 if !ok {
175179 return nil, fmt.Errorf("unknown provider %q", providerName)
@@ -267,6 +271,9 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
267271 if providerName == "animepahe" && !ProviderStackContains(config, "animepahe") {
268272 providerName = ""
269273 }
274 if providerName != "" && !ProviderEnabled(providerName) {
275 providerName = ""
276 }
270277 if providerName != "" {
271278 if _, exists := seen[providerName]; !exists {
272279 result = append(result, providerName)
@@ -360,7 +367,7 @@ func searchAnimeWithProviders(providerNames []string, query, mode string) ([]Sel
360367}
361368
362369func shouldOfferAnimepaheFallback(config *CurdConfig, providerNames []string) bool {
363 if config == nil || animepaheDeclinedInConfig(config) {
370 if config == nil || animepaheDeclinedInConfig(config) || !ProviderEnabled("animepahe") {
364371 return false
365372 }
366373
@@ -585,6 +592,23 @@ func GetEpisodeURLForPlayback(config CurdConfig, id string, epNo int) ([]string,
585592 return fallbackLinks, fallbackMode, nil
586593}
587594
595func getProviderEpisodeURLForModeWithHints(provider Provider, config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
596 mode = normalizeTranslationType(mode)
597 if withHints, ok := provider.(interface {
598 GetEpisodeURLForModeWithHints(CurdConfig, string, int, string) ([]string, map[string]StreamPlaybackHint, error)
599 }); ok {
600 return withHints.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
601 }
602 if resolver, ok := provider.(ProviderModeResolver); ok {
603 links, err := resolver.GetEpisodeURLForMode(config, id, epNo, mode)
604 return links, nil, err
605 }
606 modeConfig := config
607 modeConfig.SubOrDub = mode
608 links, err := provider.GetEpisodeURL(modeConfig, id, epNo)
609 return links, nil, err
610}
611
588612func getProviderEpisodeURLForMode(provider Provider, config CurdConfig, id string, epNo int, mode string) ([]string, error) {
589613 mode = normalizeTranslationType(mode)
590614 if resolver, ok := provider.(ProviderModeResolver); ok {
@@ -628,7 +652,7 @@ func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, m
628652 continue
629653 }
630654
631 links, err := getProviderEpisodeURLForMode(provider, config, providerID, epNo, mode)
655 links, linkHints, err := getProviderEpisodeURLForModeWithHints(provider, config, providerID, epNo, mode)
632656 if err != nil || len(links) == 0 {
633657 if err != nil {
634658 errors = append(errors, fmt.Sprintf("%s episode: %v", providerName, err))
@@ -642,6 +666,7 @@ func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, m
642666 anime.ProviderId = providerID
643667 return ProviderEpisodeResult{
644668 Links: links,
669 LinkHints: linkHints,
645670 ProviderName: providerName,
646671 ProviderID: providerID,
647672 Mode: mode,
@@ -777,9 +802,10 @@ func normalizeSearchTitle(title string) string {
777802 return strings.Join(strings.Fields(title), " ")
778803}
779804
780func selectBestProviderSearchResult(options []SelectionOption, anime *Anime, query string) (SelectionOption, bool) {
781 if len(options) == 0 {
782 return SelectionOption{}, false
805func scoreProviderSearchOption(option SelectionOption, anime *Anime, query string, index, total int) int {
806 optionTitle := normalizeSearchTitle(option.Title)
807 if optionTitle == "" {
808 optionTitle = normalizeSearchTitle(option.Label)
783809 }
784810
785811 targetTitles := []string{
@@ -789,42 +815,75 @@ func selectBestProviderSearchResult(options []SelectionOption, anime *Anime, que
789815 normalizeSearchTitle(anime.Title.Japanese),
790816 }
791817
818 score := total - index
819 for _, targetTitle := range targetTitles {
820 if targetTitle == "" {
821 continue
822 }
823 if optionTitle == targetTitle {
824 score += 100
825 } else if strings.Contains(optionTitle, targetTitle) || strings.Contains(targetTitle, optionTitle) {
826 score += 35
827 }
828 }
829 if anime.AnilistId != 0 && strings.Contains(option.Thumbnail, fmt.Sprintf("%d", anime.AnilistId)) {
830 score += 120
831 }
832 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
833 score += 20
834 }
835 if item, ok := option.ExtraData.(AnimepaheSearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
836 score += 20
837 }
838 return score
839}
840
841func selectBestProviderSearchResult(options []SelectionOption, anime *Anime, query string) (SelectionOption, bool) {
842 if len(options) == 0 {
843 return SelectionOption{}, false
844 }
845
792846 bestIndex := 0
793847 bestScore := -1
794848 for i, option := range options {
795 optionTitle := normalizeSearchTitle(option.Title)
796 if optionTitle == "" {
797 optionTitle = normalizeSearchTitle(option.Label)
849 score := scoreProviderSearchOption(option, anime, query, i, len(options))
850 if score > bestScore {
851 bestScore = score
852 bestIndex = i
798853 }
854 }
799855
800 score := len(options) - i
801 for _, targetTitle := range targetTitles {
802 if targetTitle == "" {
803 continue
804 }
805 if optionTitle == targetTitle {
806 score += 100
807 } else if strings.Contains(optionTitle, targetTitle) || strings.Contains(targetTitle, optionTitle) {
808 score += 35
809 }
810 }
811 if anime.AnilistId != 0 && strings.Contains(option.Thumbnail, fmt.Sprintf("%d", anime.AnilistId)) {
812 score += 120
813 }
814 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
815 score += 20
816 }
817 if item, ok := option.ExtraData.(AnimepaheSearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
818 score += 20
819 }
856 return options[bestIndex], true
857}
858
859// confidentProviderSearchMatch auto-selects when title/thumbnail scoring clearly
860// identifies one provider result, e.g. AniList romaji query against AllAnime englishName.
861func confidentProviderSearchMatch(options []SelectionOption, anime *Anime, query string) (SelectionOption, bool) {
862 if len(options) == 0 {
863 return SelectionOption{}, false
864 }
820865
866 bestIndex := 0
867 bestScore := -1
868 secondBestScore := -1
869 for i, option := range options {
870 score := scoreProviderSearchOption(option, anime, query, i, len(options))
821871 if score > bestScore {
872 secondBestScore = bestScore
822873 bestScore = score
823874 bestIndex = i
875 } else if score > secondBestScore {
876 secondBestScore = score
824877 }
825878 }
826879
827 return options[bestIndex], true
880 if bestScore >= 120 {
881 return options[bestIndex], true
882 }
883 if bestScore >= 100 && (len(options) == 1 || bestScore-secondBestScore >= 30) {
884 return options[bestIndex], true
885 }
886 return SelectionOption{}, false
828887}
829888
830889func findProviderIDForAnime(provider Provider, anime *Anime, mode string) (string, error) {
internal/provider_allanime.go +6 −1
@@ -19,5 +19,10 @@ func (p *AllanimeProvider) GetEpisodeURL(config CurdConfig, id string, epNo int)
1919}
2020
2121func (p *AllanimeProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
22 return getAllanimeEpisodeURLForMode(id, mode, epNo)
22 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
23 return links, err
24}
25
26func (p *AllanimeProvider) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
27 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
2328}
internal/provider_disabled.go added +105
@@ -0,0 +1,105 @@
1package internal
2
3import (
4 "sort"
5 "testing"
6)
7
8// disabledProviders lists providers kept in source but excluded from runtime use.
9// Remove a provider from this map to re-enable it without restoring deleted code.
10var disabledProviders = map[string]string{
11 "animepahe": "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12}
13
14var disabledProviderReasonForTest func(string) string
15
16func providerDisabledReason(name string) string {
17 name = normalizeProviderName(name)
18 if name == "" {
19 return ""
20 }
21 if disabledProviderReasonForTest != nil {
22 return disabledProviderReasonForTest(name)
23 }
24 return disabledProviders[name]
25}
26
27// ProviderEnabled reports whether a provider may be used at runtime.
28func ProviderEnabled(name string) bool {
29 return providerDisabledReason(name) == ""
30}
31
32// ProviderDisabledReason returns why a provider is disabled, or "" when enabled.
33func ProviderDisabledReason(name string) string {
34 return providerDisabledReason(name)
35}
36
37func filterEnabledProviders(names []string) []string {
38 if len(names) == 0 {
39 return nil
40 }
41 enabled := make([]string, 0, len(names))
42 seen := make(map[string]struct{}, len(names))
43 for _, name := range names {
44 name = normalizeProviderName(name)
45 if name == "" || !ProviderEnabled(name) {
46 continue
47 }
48 if _, exists := seen[name]; exists {
49 continue
50 }
51 seen[name] = struct{}{}
52 enabled = append(enabled, name)
53 }
54 return enabled
55}
56
57func defaultEnabledProviderStack() []string {
58 names := make([]string, 0, len(providerFactories))
59 for name := range providerFactories {
60 names = append(names, name)
61 }
62 sort.Strings(names)
63 return filterEnabledProviders(names)
64}
65
66func providerSelectionOptions() []SelectionOption {
67 enabled := defaultEnabledProviderStack()
68 options := make([]SelectionOption, 0, len(enabled)*len(enabled))
69 for _, name := range enabled {
70 options = append(options, SelectionOption{
71 Key: formatProviderConfigValue([]string{name}, false),
72 Label: name,
73 })
74 }
75 for _, primary := range enabled {
76 for _, secondary := range enabled {
77 if primary == secondary {
78 continue
79 }
80 names := []string{primary, secondary}
81 options = append(options, SelectionOption{
82 Key: formatProviderConfigValue(names, false),
83 Label: primary + ", then " + secondary,
84 })
85 }
86 }
87 return options
88}
89
90func ensureEnabledProviderNames(names []string) []string {
91 enabled := filterEnabledProviders(names)
92 if len(enabled) > 0 {
93 return enabled
94 }
95 return []string{"allanime"}
96}
97
98func withAllProvidersEnabledForTest(t *testing.T) {
99 t.Helper()
100 previous := disabledProviderReasonForTest
101 disabledProviderReasonForTest = func(string) string { return "" }
102 t.Cleanup(func() {
103 disabledProviderReasonForTest = previous
104 })
105}
internal/provider_disabled_test.go added +68
@@ -0,0 +1,68 @@
1package internal
2
3import "testing"
4
5func TestProviderEnabledDisablesAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != true {
7 t.Fatal("expected allanime to stay enabled")
8 }
9 if ProviderEnabled("animepahe") != false {
10 t.Fatal("expected animepahe to be disabled")
11 }
12 if reason := ProviderDisabledReason("animepahe"); reason == "" {
13 t.Fatal("expected animepahe disable reason")
14 }
15}
16
17func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
18 cases := []struct {
19 name string
20 cfg *CurdConfig
21 want []string
22 }{
23 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}},
24 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime"}},
25 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"allanime"}},
26 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime"}},
27 }
28
29 for _, tc := range cases {
30 got := ConfiguredProviderNames(tc.cfg)
31 if len(got) != len(tc.want) {
32 t.Fatalf("%s: got %v, want %v", tc.name, got, tc.want)
33 }
34 for i := range got {
35 if got[i] != tc.want[i] {
36 t.Fatalf("%s: got %v, want %v", tc.name, got, tc.want)
37 }
38 }
39 }
40}
41
42func TestConfiguredProviderNamesHonorsEnabledProvidersWhenOverridden(t *testing.T) {
43 withAllProvidersEnabledForTest(t)
44
45 cfg := &CurdConfig{Provider: `["allanime","animepahe"]`}
46 got := ConfiguredProviderNames(cfg)
47 if len(got) != 2 || got[0] != "allanime" || got[1] != "animepahe" {
48 t.Fatalf("got %v, want [allanime animepahe]", got)
49 }
50}
51
52func TestProviderByNameRejectsDisabledProvider(t *testing.T) {
53 if _, err := ProviderByName("animepahe"); err == nil {
54 t.Fatal("expected disabled provider error")
55 }
56}
57
58func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) {
59 withAllProvidersEnabledForTest(t)
60
61 provider, err := ProviderByName("animepahe")
62 if err != nil {
63 t.Fatalf("expected animepahe provider: %v", err)
64 }
65 if provider.Name() != "animepahe" {
66 t.Fatalf("got provider %q", provider.Name())
67 }
68}
internal/provider_match_test.go added +68
@@ -0,0 +1,68 @@
1package internal
2
3import (
4 "regexp"
5 "strings"
6 "testing"
7)
8
9func TestSelectBestProviderSearchResultMarchComesInLikeALion(t *testing.T) {
10 anime := &Anime{
11 AnilistId: 21366,
12 MalId: 31646,
13 TotalEpisodes: 22,
14 Title: AnimeTitle{Romaji: "3-gatsu no Lion", English: "March comes in like a lion"},
15 }
16 options := []SelectionOption{
17 {Title: "March comes in like a lion Season 2", Key: "s2", Label: "March comes in like a lion Season 2 (22 episodes)", Thumbnail: "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx98478-dF3mpSKiZkQu.jpg"},
18 {Title: "March comes in like a lion", Key: "s1", Label: "March comes in like a lion (23 episodes)", Thumbnail: "https://cdn.myanimelist.net/images/anime/1637/108857.jpg"},
19 }
20 best, ok := selectBestProviderSearchResult(options, anime, "3-gatsu no Lion")
21 if !ok {
22 t.Fatal("expected match")
23 }
24 if best.Key != "s1" {
25 t.Fatalf("expected season 1, got %q (%q)", best.Key, best.Title)
26 }
27}
28
29func TestConfidentProviderSearchMatchMarchComesInLikeALion(t *testing.T) {
30 anime := &Anime{
31 AnilistId: 21366,
32 MalId: 31646,
33 TotalEpisodes: 22,
34 Title: AnimeTitle{Romaji: "3-gatsu no Lion", English: "March comes in like a lion"},
35 }
36 options := []SelectionOption{
37 {Title: "March comes in like a lion Season 2", Key: "s2", Label: "March comes in like a lion Season 2 (22 episodes)", Thumbnail: "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx98478-dF3mpSKiZkQu.jpg"},
38 {Title: "March comes in like a lion", Key: "s1", Label: "March comes in like a lion (23 episodes)", Thumbnail: "https://cdn.myanimelist.net/images/anime/1637/108857.jpg"},
39 }
40 best, ok := confidentProviderSearchMatch(options, anime, "3-gatsu no Lion")
41 if !ok {
42 t.Fatal("expected confident auto-match")
43 }
44 if best.Key != "s1" {
45 t.Fatalf("expected season 1, got %q", best.Key)
46 }
47}
48
49func TestMalThumbnailMatchMarchComesInLikeALion(t *testing.T) {
50 jikanUrls := []string{"https://cdn.myanimelist.net/images/anime/1637/108857.jpg"}
51 thumb := "https://cdn.myanimelist.net/images/anime/1637/108857.jpg"
52 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
53 matches := malRegex.FindStringSubmatch(thumb)
54 if len(matches) < 2 {
55 t.Fatal("regex failed")
56 }
57 fileName := matches[1]
58 found := false
59 for _, url := range jikanUrls {
60 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
61 found = true
62 break
63 }
64 }
65 if !found {
66 t.Fatal("expected MAL thumbnail match")
67 }
68}
internal/provider_stack_test.go +3
@@ -49,6 +49,7 @@ func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
4949
5050func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
5151 t.Helper()
52 withAllProvidersEnabledForTest(t)
5253 previousAllanime := providerFactories["allanime"]
5354 previousAnimepahe := providerFactories["animepahe"]
5455 for _, provider := range providers {
@@ -62,6 +63,8 @@ func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
6263}
6364
6465func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
66 withAllProvidersEnabledForTest(t)
67
6568 cases := []struct {
6669 name string
6770 cfg *CurdConfig
internal/structs.go +2
@@ -51,6 +51,8 @@ type Episode struct {
5151 Started bool `json:"started"`
5252 Duration int `json:"duration"`
5353 Links []string `json:"links"`
54 StreamReferrer string `json:"-"`
55 SubtitleURL string `json:"-"`
5456 NextEpisode NextEpisode `json:"next_episode"`
5557 IsFiller bool `json:"filler"`
5658 IsRecap bool `json:"recap"`