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
1083 } 1083 }
1084 } 1084 }
1085 1085
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
1086 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe) 1095 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1087 if !found && ProviderStackContains(userCurdConfig, "animepahe") { 1096 if !found && ProviderEnabled("animepahe") && ProviderStackContains(userCurdConfig, "animepahe") {
1088 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...") 1097 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
1089 1098
1090 targetAnilistID := strconv.Itoa(anime.AnilistId) 1099 targetAnilistID := strconv.Itoa(anime.AnilistId)
@@ -1591,6 +1600,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1591 1600
1592 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) { 1601 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1593 anime.Ep.Links = anime.Ep.NextEpisode.Links 1602 anime.Ep.Links = anime.Ep.NextEpisode.Links
1603 anime.Ep.StreamReferrer = ""
1604 anime.Ep.SubtitleURL = ""
1594 if anime.Ep.NextEpisode.ProviderName != "" { 1605 if anime.Ep.NextEpisode.ProviderName != "" {
1595 anime.ProviderName = anime.Ep.NextEpisode.ProviderName 1606 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1596 anime.ProviderId = anime.Ep.NextEpisode.ProviderId 1607 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
@@ -1611,6 +1622,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1611 if err == nil { 1622 if err == nil {
1612 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link))) 1623 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1613 anime.Ep.Links = link 1624 anime.Ep.Links = link
1625 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1614 goto episodeLinksReady 1626 goto episodeLinksReady
1615 } 1627 }
1616 linkErr = err 1628 linkErr = err
@@ -1649,6 +1661,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1649 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link))) 1661 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1650 } 1662 }
1651 anime.Ep.Links = link 1663 anime.Ep.Links = link
1664 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1652 } 1665 }
1653 1666
1654episodeLinksReady: 1667episodeLinksReady:
@@ -1739,7 +1752,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1739 } 1752 }
1740 1753
1741 providerName, providerID := AnimeProviderID(anime) 1754 providerName, providerID := AnimeProviderID(anime)
1742 if providerName != "animepahe" { 1755 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1743 return nil 1756 return nil
1744 } 1757 }
1745 if !ProviderStackContains(userCurdConfig, "animepahe") { 1758 if !ProviderStackContains(userCurdConfig, "animepahe") {
@@ -1778,7 +1791,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1778 1791
1779func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool { 1792func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1780 providerName, _ := AnimeProviderID(anime) 1793 providerName, _ := AnimeProviderID(anime)
1781 if providerName != "animepahe" { 1794 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1782 return false 1795 return false
1783 } 1796 }
1784 1797
@@ -2108,6 +2121,8 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
2108 // Use prefetched links if available for the next episode 2121 // Use prefetched links if available for the next episode
2109 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) { 2122 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
2110 anime.Ep.Links = anime.Ep.NextEpisode.Links 2123 anime.Ep.Links = anime.Ep.NextEpisode.Links
2124 anime.Ep.StreamReferrer = ""
2125 anime.Ep.SubtitleURL = ""
2111 if anime.Ep.NextEpisode.ProviderName != "" { 2126 if anime.Ep.NextEpisode.ProviderName != "" {
2112 anime.ProviderName = anime.Ep.NextEpisode.ProviderName 2127 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
2113 anime.ProviderId = anime.Ep.NextEpisode.ProviderId 2128 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
@@ -2372,11 +2387,10 @@ func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToke
2372 2387
2373// ChangeProvider allows the user to switch the anime provider 2388// ChangeProvider allows the user to switch the anime provider
2374func ChangeProvider(userCurdConfig *CurdConfig) { 2389func ChangeProvider(userCurdConfig *CurdConfig) {
2375 options := []SelectionOption{ 2390 options := providerSelectionOptions()
2376 {Key: "[\"allanime\"]", Label: "allanime"}, 2391 if len(options) == 0 {
2377 {Key: "[\"animepahe\"]", Label: "animepahe"}, 2392 CurdOut("\nNo providers are currently enabled.\n")
2378 {Key: "[\"allanime\",\"animepahe\"]", Label: "allanime, then animepahe"}, 2393 return
2379 {Key: "[\"animepahe\",\"allanime\"]", Label: "animepahe, then allanime"},
2380 } 2394 }
2381 2395
2382 selected, err := DynamicSelect(options) 2396 selected, err := DynamicSelect(options)
internal/episode_url.go +122 −277
@@ -17,7 +17,6 @@ import (
17 "sort" 17 "sort"
18 "strconv" 18 "strconv"
19 "strings" 19 "strings"
20 "time"
21) 20)
22 21
23type allanimeSource struct { 22type allanimeSource struct {
@@ -42,12 +41,6 @@ type allanimeTobeparsedPayload struct {
42 } `json:"episode"` 41 } `json:"episode"`
43} 42}
44 43
45type result struct {
46 index int
47 links []string
48 err error
49}
50
51type filemoonResponse struct { 44type filemoonResponse struct {
52 IV string `json:"iv"` 45 IV string `json:"iv"`
53 Payload string `json:"payload"` 46 Payload string `json:"payload"`
@@ -55,6 +48,24 @@ type filemoonResponse struct {
55} 48}
56 49
57func decodeTobeparsed(blob string) ([]allanimeSource, error) { 50func 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) {
58 key := []byte("Xot36i3lK3:v1") 69 key := []byte("Xot36i3lK3:v1")
59 hash := sha256.Sum256(key) 70 hash := sha256.Sum256(key)
60 71
@@ -67,7 +78,6 @@ func decodeTobeparsed(blob string) ([]allanimeSource, error) {
67 return nil, fmt.Errorf("data too short to contain tobeparsed payload") 78 return nil, fmt.Errorf("data too short to contain tobeparsed payload")
68 } 79 }
69 80
70 // The payload format is: 1-byte header, 12-byte IV, ciphertext, 16-byte trailer.
71 iv := data[1:13] 81 iv := data[1:13]
72 ctLen := len(data) - 13 - 16 82 ctLen := len(data) - 13 - 16
73 if ctLen <= 0 { 83 if ctLen <= 0 {
@@ -87,17 +97,7 @@ func decodeTobeparsed(blob string) ([]allanimeSource, error) {
87 stream := cipher.NewCTR(block, ctrIV) 97 stream := cipher.NewCTR(block, ctrIV)
88 plain := make([]byte, len(ct)) 98 plain := make([]byte, len(ct))
89 stream.XORKeyStream(plain, ct) 99 stream.XORKeyStream(plain, ct)
90 100 return plain, nil
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
101} 101}
102 102
103func decodeProviderID(encoded string) string { 103func decodeProviderID(encoded string) string {
@@ -143,19 +143,33 @@ func decodeProviderID(encoded string) string {
143 return result 143 return result
144} 144}
145 145
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
146func isDirectPlayableAllanimeSource(source allanimeSource) bool { 159func isDirectPlayableAllanimeSource(source allanimeSource) bool {
147 sourceURL := strings.TrimSpace(source.SourceUrl) 160 sourceURL := strings.TrimSpace(source.SourceUrl)
148 if sourceURL == "" { 161 if sourceURL == "" {
149 return false 162 return false
150 } 163 }
151 164 if strings.HasPrefix(sourceURL, "--") {
152 if strings.EqualFold(source.SourceName, "Yt-mp4") || strings.EqualFold(source.SourceName, "S-mp4") { 165 return false
153 return true 166 }
167 if !strings.HasPrefix(sourceURL, "http://") && !strings.HasPrefix(sourceURL, "https://") {
168 return false
154 } 169 }
155 170
156 lowerURL := strings.ToLower(sourceURL) 171 if isUnreliableAllanimeDirectURL(sourceURL) {
157 if strings.Contains(lowerURL, "tools.fast4speed.rsvp/") { 172 return false
158 return true
159 } 173 }
160 174
161 parsedURL, err := url.Parse(sourceURL) 175 parsedURL, err := url.Parse(sourceURL)
@@ -164,7 +178,17 @@ func isDirectPlayableAllanimeSource(source allanimeSource) bool {
164 } 178 }
165 179
166 path := strings.ToLower(parsedURL.Path) 180 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/")
168} 192}
169 193
170func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource { 194func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource {
@@ -180,77 +204,6 @@ func sortAllanimeSourcesByPriority(sourceUrls []allanimeSource) []allanimeSource
180 return sorted 204 return sorted
181} 205}
182 206
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
254func normalizeAllanimeProviderPath(providerID string) string { 207func normalizeAllanimeProviderPath(providerID string) string {
255 const allanimePrefix = "/https://allanime.day" 208 const allanimePrefix = "/https://allanime.day"
256 209
@@ -432,7 +385,11 @@ func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
432 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo) 385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo)
433} 386}
434 387
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) {
436 const ( 393 const (
437 episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec" 394 episodeQueryHash = "d405d0edd690624b66baba3068e0edc3ac90f1597d898a1ec8db4e5c43c00fec"
438 ) 395 )
@@ -469,8 +426,8 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
469 return nil, fmt.Errorf("failed to create persisted query request: %w", err) 426 return nil, fmt.Errorf("failed to create persisted query request: %w", err)
470 } 427 }
471 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0") 428 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") 429 req.Header.Set("Referer", allanimePersistedQueryReferer)
473 req.Header.Set("Origin", "https://youtu-chan.com") 430 req.Header.Set("Origin", allanimePersistedQueryReferer)
474 431
475 resp, err := sharedHTTPClient.Do(req) 432 resp, err := sharedHTTPClient.Do(req)
476 if err != nil { 433 if err != nil {
@@ -491,6 +448,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
491 } 448 }
492 449
493 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0 450 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 }
494 if useFallback { 454 if useFallback {
495 query := episodeEmbedGQL 455 query := episodeEmbedGQL
496 456
@@ -509,9 +469,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
509 } 469 }
510 470
511 req.Header.Set("Content-Type", "application/json") 471 req.Header.Set("Content-Type", "application/json")
512 req.Header.Set("User-Agent", "Mozilla/5.0") 472 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0")
513 req.Header.Set("Referer", "https://allmanga.to") 473 req.Header.Set("Referer", allanimeGraphQLReferer)
514 req.Header.Set("Origin", "https://allanime.to") 474 req.Header.Set("Origin", allanimeGraphQLReferer)
515 475
516 resp, err := sharedHTTPClient.Do(req) 476 resp, err := sharedHTTPClient.Do(req)
517 if err != nil { 477 if err != nil {
@@ -541,199 +501,84 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
541 } 501 }
542 502
543 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources))) 503 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
544 return getLinksFromSourceUrls(decodedSources) 504 return decodedSources, nil
545 } 505 }
546 506
547 return getLinksFromSourceUrls(response.Data.Episode.SourceUrls) 507 return response.Data.Episode.SourceUrls, nil
548} 508}
549 509
550func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) { 510func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
551 sourceUrls = sortAllanimeSourcesByPriority(sourceUrls) 511 links, _, err := getAllanimeEpisodeStreamsForMode(id, mode, epNo)
552 512 return links, err
553 directURLs := make([]string, 0) 513}
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 }
573 514
574 decodedURL := decodeProviderID(sourceURL[2:]) 515func findNamedAllanimeSource(sourceUrls []allanimeSource, providerName string) (allanimeSource, bool) {
575 if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) { 516 for _, source := range sourceUrls {
576 priority := url.Priority 517 if strings.EqualFold(strings.TrimSpace(source.SourceName), providerName) {
577 if priority > highestPriority { 518 return source, true
578 highestPriority = priority
579 highestPriorityURL = sourceURL
580 }
581 } else {
582 validURLs = append(validURLs, sourceURL)
583 } 519 }
584 } 520 }
585 521 return allanimeSource{}, false
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)
600} 522}
601 523
602func getLinksFromURLs(validURLs []string) ([]string, error) { 524var wixstaticURLSetPattern = regexp.MustCompile(`^(https://video\.wixstatic\.com/video/[^/,]+/),([^/]*),/mp4/file\.mp4`)
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 }
648 525
649 // Check if any of the extracted links are high priority 526func expandWixmpLinks(link string) []string {
650 priorityDomains := LinkPriorities 527 normalized := strings.TrimSpace(link)
651 if len(priorityDomains) > 3 { 528 if normalized == "" {
652 priorityDomains = priorityDomains[:3] 529 return nil
653 } 530 }
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 }
667 531
668 results <- result{ 532 if strings.Contains(normalized, "repackager.wixmp.com") {
669 index: idx, 533 normalized = strings.TrimPrefix(normalized, "https://repackager.wixmp.com/")
670 links: links, 534 normalized = strings.TrimPrefix(normalized, "http://repackager.wixmp.com/")
671 } 535 if !strings.HasPrefix(normalized, "http") {
672 }(i, sourceUrl) 536 normalized = "https://" + normalized
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)
710 } 537 }
711 } 538 }
712 539
713 // If we have any errors but also some successes, log errors but continue 540 if idx := strings.Index(normalized, ".urlset"); idx != -1 {
714 if len(collectedErrors) > 0 { 541 normalized = normalized[:idx]
715 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
716 } 542 }
717 543
718 // Flatten and return results 544 if match := wixstaticURLSetPattern.FindStringSubmatch(normalized); len(match) == 3 {
719 allLinks := flattenResults(orderedResults) 545 base := match[1]
720 if len(allLinks) == 0 { 546 qualities := strings.Split(match[2], ",")
721 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors) 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 }
722 } 561 }
723 562
724 return allLinks, nil 563 return []string{link}
725} 564}
726 565
727// converts the ordered slice of link slices into a single slice 566func wixmpQualityScore(link string) int {
728func flattenResults(results [][]string) []string { 567 for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
729 var totalLen int 568 if strings.Contains(link, quality) {
730 for _, r := range results { 569 switch quality {
731 totalLen += len(r) 570 case "1080p":
732 } 571 return 1080
733 572 case "720p":
734 allLinks := make([]string, 0, totalLen) 573 return 720
735 for _, links := range results { 574 case "480p":
736 allLinks = append(allLinks, links...) 575 return 480
576 case "360p":
577 return 360
578 case "240p":
579 return 240
580 }
581 }
737 } 582 }
738 return allLinks 583 return 0
739} 584}
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 @@
1package internal 1package internal
2 2
3import "testing" 3import (
4 "strings"
5 "testing"
6)
4 7
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) {
6 t.Parallel() 22 t.Parallel()
7 23
8 sourceUrls := []allanimeSource{ 24 sourceUrls := []allanimeSource{
9 { 25 {
10 SourceUrl: "--175948514e4c4f57", 26 SourceUrl: "https://tools.fast4speed.rsvp/media9/videos/example/dub/1?Authorization=test",
11 SourceName: "Luf-Mp4",
12 Priority: 7.5,
13 },
14 {
15 SourceUrl: "https://tools.fast4speed.rsvp/media9/videos/example/sub/1?Authorization=test",
16 SourceName: "Yt-mp4", 27 SourceName: "Yt-mp4",
17 Priority: 7.9, 28 Priority: 7.9,
18 }, 29 },
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)
29 } 30 }
30 31
31 if len(links) != 1 { 32 _, _, err := getLinksFromEncodedSourceUrls(sourceUrls)
32 t.Fatalf("expected one direct playable source, got %d: %#v", len(links), links) 33 if err == nil {
33 } 34 t.Fatal("expected error when only direct fast4speed source is available")
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)
37 } 35 }
38} 36}
39 37
40func TestSortAllanimeSourcesByPriorityOrdersDescending(t *testing.T) { 38func TestGetLinksFromEncodedSourceUrlsRequiresEncodedProviders(t *testing.T) {
41 t.Parallel() 39 t.Parallel()
42 40
43 sourceUrls := []allanimeSource{ 41 sourceUrls := []allanimeSource{
44 {SourceUrl: "https://example.com/low.mp4", Priority: 1}, 42 {
45 {SourceUrl: "https://example.com/high.mp4", Priority: 9}, 43 SourceUrl: "https://tenant.sharepoint.com/video.mp4",
46 {SourceUrl: "https://example.com/mid.mp4", Priority: 5}, 44 SourceName: "S-mp4",
47 } 45 Priority: 7.4,
48 46 },
49 sorted := sortAllanimeSourcesByPriority(sourceUrls)
50 if len(sorted) != 3 {
51 t.Fatalf("expected 3 sorted sources, got %d", len(sorted))
52 } 47 }
53 48
54 if sorted[0].SourceUrl != "https://example.com/high.mp4" { 49 _, _, err := getLinksFromEncodedSourceUrls(sourceUrls)
55 t.Fatalf("expected highest priority source first, got %#v", sorted) 50 if err == nil {
56 } 51 t.Fatal("expected error when no encoded provider sources exist")
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)
62 } 52 }
63} 53}
64 54
65func TestIsDirectPlayableAllanimeSource(t *testing.T) { 55func TestParseAllanimeStreamInfScore(t *testing.T) {
66 t.Parallel() 56 t.Parallel()
67 57
68 cases := []struct { 58 line := `#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"`
69 name string 59 if got := parseAllanimeStreamInfScore(line); got != 1280 {
70 source allanimeSource 60 t.Fatalf("parseAllanimeStreamInfScore() = %d, want 1280", got)
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 },
105 } 61 }
62}
106 63
107 for _, tc := range cases { 64func TestResolveAllanimeRelativeURL(t *testing.T) {
108 tc := tc 65 t.Parallel()
109 t.Run(tc.name, func(t *testing.T) {
110 t.Parallel()
111 66
112 if got := isDirectPlayableAllanimeSource(tc.source); got != tc.want { 67 got := resolveAllanimeRelativeURL("https://example.com/path/", "720p/index.m3u8")
113 t.Fatalf("isDirectPlayableAllanimeSource(%+v) = %v, want %v", tc.source, got, tc.want) 68 want := "https://example.com/path/720p/index.m3u8"
114 } 69 if got != want {
115 }) 70 t.Fatalf("resolveAllanimeRelativeURL() = %q, want %q", got, want)
116 } 71 }
117} 72}
internal/links.go +19 −23
@@ -4,6 +4,7 @@ import "strings"
4 4
5// LinkPriorities defines the order of priority for link domains 5// LinkPriorities defines the order of priority for link domains
6var LinkPriorities = []string{ 6var LinkPriorities = []string{
7 "video.wixstatic.com",
7 "sharepoint.com", 8 "sharepoint.com",
8 "wixmp.com", 9 "wixmp.com",
9 "dropbox.com", 10 "dropbox.com",
@@ -18,31 +19,26 @@ func PrioritizeLink(links []string) string {
18 return "" 19 return ""
19 } 20 }
20 21
21 // Create a map for quick lookup of priorities 22 bestLink := links[0]
22 priorityMap := make(map[string]int) 23 bestScore := linkSelectionScore(bestLink)
23 for i, p := range LinkPriorities { 24 for _, link := range links[1:] {
24 priorityMap[p] = len(LinkPriorities) - i // Higher index means higher priority 25 score := linkSelectionScore(link)
25 } 26 if score > bestScore {
26 27 bestScore = score
27 highestPriority := -1 28 bestLink = link
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 }
39 } 29 }
40 } 30 }
31 return bestLink
32}
41 33
42 // If no priority link found, return the first link 34func linkSelectionScore(link string) int {
43 if bestLink == "" { 35 score := 0
44 return links[0] 36 for i, domain := range LinkPriorities {
37 if strings.Contains(link, domain) {
38 score += (len(LinkPriorities) - i) * 1000
39 break
40 }
45 } 41 }
46 42 score += wixmpQualityScore(link)
47 return bestLink 43 return score
48} 44}
internal/localTracking.go +1
@@ -442,6 +442,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
442 ExitCurd(fmt.Errorf("Failed to get episode link")) 442 ExitCurd(fmt.Errorf("Failed to get episode link"))
443 } 443 }
444 link := resolvedLink.Links 444 link := resolvedLink.Links
445 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints)
445 446
446 if len(link) == 0 { 447 if len(link) == 0 {
447 ExitCurd(fmt.Errorf("No episode links found")) 448 ExitCurd(fmt.Errorf("No episode links found"))
internal/logic_regression_test.go +18 −2
@@ -216,11 +216,27 @@ func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
216 SetGlobalConfig(previousConfig) 216 SetGlobalConfig(previousConfig)
217 }) 217 })
218 218
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
219 CurrentProvider = nil 235 CurrentProvider = nil
220 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "}) 236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
221 237
222 if got := GetProvider().Name(); got != "animepahe" { 238 if got := GetProvider().Name(); got != "allanime" {
223 t.Fatalf("expected animepahe provider, got %q", got) 239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got)
224 } 240 }
225} 241}
226 242
internal/player.go +39 −11
@@ -19,6 +19,16 @@ var logFile = "debug.log"
19// This is not generic but we have MpvArgs in CurdConfig to add custom ones 19// This is not generic but we have MpvArgs in CurdConfig to add custom ones
20const defaultStreamReferrer = "https://allanime.day/" 20const defaultStreamReferrer = "https://allanime.day/"
21 21
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
22// We should really handle this by Provider but keeping simple string here for now 32// We should really handle this by Provider but keeping simple string here for now
23 33
24func getBundledMPVPath() (string, error) { 34func getBundledMPVPath() (string, error) {
@@ -192,6 +202,19 @@ func hasMPVReferrerArg(args []string) bool {
192 return false 202 return false
193} 203}
194 204
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
195func normalizeReferrerValue(referrer string) string { 218func normalizeReferrerValue(referrer string) string {
196 referrer = strings.TrimSpace(referrer) 219 referrer = strings.TrimSpace(referrer)
197 if referrer == "" { 220 if referrer == "" {
@@ -262,13 +285,16 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
262 } 285 }
263 286
264 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args) 287 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args)
265 if shouldSetDefaultReferrer { 288 referrer := strings.TrimSpace(anime.Ep.StreamReferrer)
266 referrer := defaultStreamReferrer 289 if referrer == "" && shouldSetDefaultReferrer {
267 if CurrentAnimeProviderName(anime) == "animepahe" { 290 referrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
268 referrer = "https://kwik.cx/" 291 }
269 } 292 if referrer != "" && shouldSetDefaultReferrer {
270 args = append(args, fmt.Sprintf("--referrer=%s", referrer)) 293 args = append(args, fmt.Sprintf("--referrer=%s", referrer))
271 } 294 }
295 if subtitleURL := strings.TrimSpace(anime.Ep.SubtitleURL); subtitleURL != "" && !hasMPVSubtitleArg(args) {
296 args = append(args, fmt.Sprintf("--sub-file=%s", subtitleURL))
297 }
272 args = normalizeReferrerArgs(args) 298 args = normalizeReferrerArgs(args)
273 299
274 // Check if we have an existing socket and if MPV is still running 300 // 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,
277 mpvSocketPath = anime.Ep.Player.SocketPath 303 mpvSocketPath = anime.Ep.Player.SocketPath
278 304
279 if shouldSetDefaultReferrer { 305 if shouldSetDefaultReferrer {
280 referrer := defaultStreamReferrer 306 activeReferrer := strings.TrimSpace(anime.Ep.StreamReferrer)
281 if CurrentAnimeProviderName(anime) == "animepahe" { 307 if activeReferrer == "" {
282 referrer = "https://kwik.cx/" 308 activeReferrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
283 } 309 }
284 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", referrer}) 310 if activeReferrer != "" {
285 if referrerErr != nil { 311 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", activeReferrer})
286 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr)) 312 if referrerErr != nil {
313 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr))
314 }
287 } 315 }
288 } 316 }
289 317
internal/provider.go +90 −31
@@ -20,6 +20,7 @@ type ProviderModeResolver interface {
20 20
21type ProviderEpisodeResult struct { 21type ProviderEpisodeResult struct {
22 Links []string 22 Links []string
23 LinkHints map[string]StreamPlaybackHint
23 ProviderName string 24 ProviderName string
24 ProviderID string 25 ProviderID string
25 Mode string 26 Mode string
@@ -73,7 +74,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
73 74
74 normalizedRaw := strings.ToLower(rawProvider) 75 normalizedRaw := strings.ToLower(rawProvider)
75 if normalizedRaw == "stacked" || normalizedRaw == "stack" || normalizedRaw == "auto" || normalizedRaw == "all" { 76 if normalizedRaw == "stacked" || normalizedRaw == "stack" || normalizedRaw == "auto" || normalizedRaw == "all" {
76 return []string{"allanime", "animepahe"}, false 77 return defaultEnabledProviderStack(), false
77 } 78 }
78 79
79 buildConfig := func(parts []string) ([]string, bool) { 80 buildConfig := func(parts []string) ([]string, bool) {
@@ -124,7 +125,7 @@ func configuredProviderNames(config *CurdConfig) []string {
124 } 125 }
125 126
126 providers, _ := parseProviderConfig(rawProvider) 127 providers, _ := parseProviderConfig(rawProvider)
127 return providers 128 return ensureEnabledProviderNames(providers)
128} 129}
129 130
130func ConfiguredProviderNames(config *CurdConfig) []string { 131func ConfiguredProviderNames(config *CurdConfig) []string {
@@ -170,6 +171,9 @@ func ProviderStackContains(config *CurdConfig, providerName string) bool {
170 171
171func ProviderByName(providerName string) (Provider, error) { 172func ProviderByName(providerName string) (Provider, error) {
172 providerName = normalizeProviderName(providerName) 173 providerName = normalizeProviderName(providerName)
174 if reason := providerDisabledReason(providerName); reason != "" {
175 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176 }
173 factory, ok := providerFactories[providerName] 177 factory, ok := providerFactories[providerName]
174 if !ok { 178 if !ok {
175 return nil, fmt.Errorf("unknown provider %q", providerName) 179 return nil, fmt.Errorf("unknown provider %q", providerName)
@@ -267,6 +271,9 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
267 if providerName == "animepahe" && !ProviderStackContains(config, "animepahe") { 271 if providerName == "animepahe" && !ProviderStackContains(config, "animepahe") {
268 providerName = "" 272 providerName = ""
269 } 273 }
274 if providerName != "" && !ProviderEnabled(providerName) {
275 providerName = ""
276 }
270 if providerName != "" { 277 if providerName != "" {
271 if _, exists := seen[providerName]; !exists { 278 if _, exists := seen[providerName]; !exists {
272 result = append(result, providerName) 279 result = append(result, providerName)
@@ -360,7 +367,7 @@ func searchAnimeWithProviders(providerNames []string, query, mode string) ([]Sel
360} 367}
361 368
362func shouldOfferAnimepaheFallback(config *CurdConfig, providerNames []string) bool { 369func shouldOfferAnimepaheFallback(config *CurdConfig, providerNames []string) bool {
363 if config == nil || animepaheDeclinedInConfig(config) { 370 if config == nil || animepaheDeclinedInConfig(config) || !ProviderEnabled("animepahe") {
364 return false 371 return false
365 } 372 }
366 373
@@ -585,6 +592,23 @@ func GetEpisodeURLForPlayback(config CurdConfig, id string, epNo int) ([]string,
585 return fallbackLinks, fallbackMode, nil 592 return fallbackLinks, fallbackMode, nil
586} 593}
587 594
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
588func getProviderEpisodeURLForMode(provider Provider, config CurdConfig, id string, epNo int, mode string) ([]string, error) { 612func getProviderEpisodeURLForMode(provider Provider, config CurdConfig, id string, epNo int, mode string) ([]string, error) {
589 mode = normalizeTranslationType(mode) 613 mode = normalizeTranslationType(mode)
590 if resolver, ok := provider.(ProviderModeResolver); ok { 614 if resolver, ok := provider.(ProviderModeResolver); ok {
@@ -628,7 +652,7 @@ func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, m
628 continue 652 continue
629 } 653 }
630 654
631 links, err := getProviderEpisodeURLForMode(provider, config, providerID, epNo, mode) 655 links, linkHints, err := getProviderEpisodeURLForModeWithHints(provider, config, providerID, epNo, mode)
632 if err != nil || len(links) == 0 { 656 if err != nil || len(links) == 0 {
633 if err != nil { 657 if err != nil {
634 errors = append(errors, fmt.Sprintf("%s episode: %v", providerName, err)) 658 errors = append(errors, fmt.Sprintf("%s episode: %v", providerName, err))
@@ -642,6 +666,7 @@ func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, m
642 anime.ProviderId = providerID 666 anime.ProviderId = providerID
643 return ProviderEpisodeResult{ 667 return ProviderEpisodeResult{
644 Links: links, 668 Links: links,
669 LinkHints: linkHints,
645 ProviderName: providerName, 670 ProviderName: providerName,
646 ProviderID: providerID, 671 ProviderID: providerID,
647 Mode: mode, 672 Mode: mode,
@@ -777,9 +802,10 @@ func normalizeSearchTitle(title string) string {
777 return strings.Join(strings.Fields(title), " ") 802 return strings.Join(strings.Fields(title), " ")
778} 803}
779 804
780func selectBestProviderSearchResult(options []SelectionOption, anime *Anime, query string) (SelectionOption, bool) { 805func scoreProviderSearchOption(option SelectionOption, anime *Anime, query string, index, total int) int {
781 if len(options) == 0 { 806 optionTitle := normalizeSearchTitle(option.Title)
782 return SelectionOption{}, false 807 if optionTitle == "" {
808 optionTitle = normalizeSearchTitle(option.Label)
783 } 809 }
784 810
785 targetTitles := []string{ 811 targetTitles := []string{
@@ -789,42 +815,75 @@ func selectBestProviderSearchResult(options []SelectionOption, anime *Anime, que
789 normalizeSearchTitle(anime.Title.Japanese), 815 normalizeSearchTitle(anime.Title.Japanese),
790 } 816 }
791 817
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
792 bestIndex := 0 846 bestIndex := 0
793 bestScore := -1 847 bestScore := -1
794 for i, option := range options { 848 for i, option := range options {
795 optionTitle := normalizeSearchTitle(option.Title) 849 score := scoreProviderSearchOption(option, anime, query, i, len(options))
796 if optionTitle == "" { 850 if score > bestScore {
797 optionTitle = normalizeSearchTitle(option.Label) 851 bestScore = score
852 bestIndex = i
798 } 853 }
854 }
799 855
800 score := len(options) - i 856 return options[bestIndex], true
801 for _, targetTitle := range targetTitles { 857}
802 if targetTitle == "" { 858
803 continue 859// confidentProviderSearchMatch auto-selects when title/thumbnail scoring clearly
804 } 860// identifies one provider result, e.g. AniList romaji query against AllAnime englishName.
805 if optionTitle == targetTitle { 861func confidentProviderSearchMatch(options []SelectionOption, anime *Anime, query string) (SelectionOption, bool) {
806 score += 100 862 if len(options) == 0 {
807 } else if strings.Contains(optionTitle, targetTitle) || strings.Contains(targetTitle, optionTitle) { 863 return SelectionOption{}, false
808 score += 35 864 }
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 }
820 865
866 bestIndex := 0
867 bestScore := -1
868 secondBestScore := -1
869 for i, option := range options {
870 score := scoreProviderSearchOption(option, anime, query, i, len(options))
821 if score > bestScore { 871 if score > bestScore {
872 secondBestScore = bestScore
822 bestScore = score 873 bestScore = score
823 bestIndex = i 874 bestIndex = i
875 } else if score > secondBestScore {
876 secondBestScore = score
824 } 877 }
825 } 878 }
826 879
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
828} 887}
829 888
830func findProviderIDForAnime(provider Provider, anime *Anime, mode string) (string, error) { 889func 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)
19} 19}
20 20
21func (p *AllanimeProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) { 21func (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)
23} 28}
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
49 49
50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) { 50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
51 t.Helper() 51 t.Helper()
52 withAllProvidersEnabledForTest(t)
52 previousAllanime := providerFactories["allanime"] 53 previousAllanime := providerFactories["allanime"]
53 previousAnimepahe := providerFactories["animepahe"] 54 previousAnimepahe := providerFactories["animepahe"]
54 for _, provider := range providers { 55 for _, provider := range providers {
@@ -62,6 +63,8 @@ func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
62} 63}
63 64
64func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) { 65func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
66 withAllProvidersEnabledForTest(t)
67
65 cases := []struct { 68 cases := []struct {
66 name string 69 name string
67 cfg *CurdConfig 70 cfg *CurdConfig
internal/structs.go +2
@@ -51,6 +51,8 @@ type Episode struct {
51 Started bool `json:"started"` 51 Started bool `json:"started"`
52 Duration int `json:"duration"` 52 Duration int `json:"duration"`
53 Links []string `json:"links"` 53 Links []string `json:"links"`
54 StreamReferrer string `json:"-"`
55 SubtitleURL string `json:"-"`
54 NextEpisode NextEpisode `json:"next_episode"` 56 NextEpisode NextEpisode `json:"next_episode"`
55 IsFiller bool `json:"filler"` 57 IsFiller bool `json:"filler"`
56 IsRecap bool `json:"recap"` 58 IsRecap bool `json:"recap"`