Commit 697e469983

697e469983d8cefaedb8fe50c8e99f851ee5fed8

parent: db0aab65fd

Unsigned

Wraient <wraient.911@gmail.com> · 2026-04-28 00:10 UTC

feat: add Animepahe provider 🥳

Layout: unified · split

cmd/curd/main.go +9 −9
@@ -285,7 +285,7 @@ func main() {
285285
286286 anime.Ep.LastWasSkipped = true
287287 anime.Ep.Started = false
288 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime))
288 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime), internal.GetProvider().Name())
289289
290290 // Check if we've reached the end of the series
291291 if anime.Ep.Number > anime.TotalEpisodes {
@@ -313,7 +313,7 @@ func main() {
313313
314314 // Update progress for the finished episode
315315 // Local update
316 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime))
316 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime), internal.GetProvider().Name())
317317
318318 // Check if we should continue to next episode
319319 // On Android we always prompt because we don't know exactly when video ended
@@ -612,7 +612,7 @@ func main() {
612612 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token)
613613 }
614614 // Update local database with completed episode
615 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
615 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
616616 if err != nil {
617617 internal.Log("Error updating local database on quit: " + err.Error())
618618 }
@@ -697,7 +697,7 @@ func main() {
697697
698698 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
699699 // Update Local Database
700 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
700 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
701701 if err != nil {
702702 internal.Log("Error updating local database: " + err.Error())
703703 }
@@ -740,7 +740,7 @@ func main() {
740740 } else {
741741 // Episode was already marked as completed above
742742 // Update local database with completed episode
743 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
743 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
744744 if err != nil {
745745 internal.Log("Error updating local database on quit: " + err.Error())
746746 }
@@ -760,7 +760,7 @@ func main() {
760760 } else {
761761 // For CLI mode, update progress immediately since episode is 85%+ complete
762762 // Update local database with completed episode
763 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
763 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
764764 if err != nil {
765765 internal.Log("Error updating local database on completion: " + err.Error())
766766 }
@@ -892,7 +892,7 @@ func main() {
892892 internal.Log("Error rating anime: " + err.Error())
893893 internal.CurdOut("Error rating anime: " + err.Error())
894894 }
895 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
895 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId)
896896 internal.ExitCurd(nil)
897897 }
898898 }
@@ -900,7 +900,7 @@ func main() {
900900 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes {
901901 anime.Ep.Number = anime.Ep.Number - 1
902902 internal.CurdOut("Completed anime. (Rewatching so no scoring)")
903 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
903 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId)
904904 internal.ExitCurd(nil)
905905 }
906906
@@ -932,7 +932,7 @@ func main() {
932932
933933 // If we still don't have links, get them now
934934 if len(anime.Ep.Links) == 0 {
935 links, err := internal.GetEpisodeURL(userCurdConfig, anime.AllanimeId, anime.Ep.Number)
935 links, err := internal.GetEpisodeURL(userCurdConfig, anime.ProviderId, anime.Ep.Number)
936936 if err != nil {
937937 internal.Log("Failed to get episode links: " + err.Error())
938938 internal.CurdOut("Failed to get episode links. Try again later.")
go.mod +6
@@ -16,6 +16,7 @@ require (
1616 github.com/charmbracelet/x/ansi v0.8.0 // indirect
1717 github.com/charmbracelet/x/term v0.2.1 // indirect
1818 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
19 github.com/go-rod/rod v0.116.2 // indirect
1920 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
2021 github.com/godbus/dbus/v5 v5.1.0 // indirect
2122 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
@@ -28,6 +29,11 @@ require (
2829 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
2930 github.com/rivo/uniseg v0.4.7 // indirect
3031 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
32 github.com/ysmood/fetchup v0.2.3 // indirect
33 github.com/ysmood/goob v0.4.0 // indirect
34 github.com/ysmood/got v0.40.0 // indirect
35 github.com/ysmood/gson v0.7.3 // indirect
36 github.com/ysmood/leakless v0.9.0 // indirect
3137 golang.org/x/sync v0.11.0 // indirect
3238 golang.org/x/sys v0.30.0 // indirect
3339 golang.org/x/text v0.3.8 // indirect
go.sum +13
@@ -14,6 +14,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
1414github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
1515github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI=
1616github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4/go.mod h1:0W7dI87PvXJ1Sjs0QPvWXKcQmNERY77e8l7GFhZB/s4=
17github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA=
18github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg=
1719github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/OqtnntR4DfOY2+BgwR60cAcu/i3SE=
1820github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=
1921github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
@@ -43,6 +45,17 @@ github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG0
4345github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
4446github.com/tr1xem/go-discordrpc v1.0.0 h1:iWW740MP2hkBqjehlvjRtQT7+DDaJ4qQ4o1vo+ImMug=
4547github.com/tr1xem/go-discordrpc v1.0.0/go.mod h1:DD//cKGwNjTSFysXlyjEUN/pSH2Z/HcFAnlOiE7wX/k=
48github.com/ysmood/fetchup v0.2.3 h1:ulX+SonA0Vma5zUFXtv52Kzip/xe7aj4vqT5AJwQ+ZQ=
49github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cOOkYGns=
50github.com/ysmood/goob v0.4.0 h1:HsxXhyLBeGzWXnqVKtmT9qM7EuVs/XOgkX7T6r1o1AQ=
51github.com/ysmood/goob v0.4.0/go.mod h1:u6yx7ZhS4Exf2MwciFr6nIM8knHQIE22lFpWHnfql18=
52github.com/ysmood/got v0.40.0 h1:ZQk1B55zIvS7zflRrkGfPDrPG3d7+JOza1ZkNxcc74Q=
53github.com/ysmood/got v0.40.0/go.mod h1:W7DdpuX6skL3NszLmAsC5hT7JAhuLZhByVzHTq874Qg=
54github.com/ysmood/gotrace v0.6.0/go.mod h1:TzhIG7nHDry5//eYZDYcTzuJLYQIkykJzCRIo4/dzQM=
55github.com/ysmood/gson v0.7.3 h1:QFkWbTH8MxyUTKPkVWAENJhxqdBa4lYTQWqZCiLG6kE=
56github.com/ysmood/gson v0.7.3/go.mod h1:3Kzs5zDl21g5F/BlLTNcuAGAYLKt2lV5G8D1zF3RNmg=
57github.com/ysmood/leakless v0.9.0 h1:qxCG5VirSBvmi3uynXFkcnLMzkphdh3xx5FtrORwDCU=
58github.com/ysmood/leakless v0.9.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ=
4659golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
4760golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
4861golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
internal/anime_list.go +1 −1
@@ -56,7 +56,7 @@ func alternateTranslationType(mode string) string {
5656// fmt.Println(animeList)
5757// }
5858
59func SearchAnime(query, mode string) ([]SelectionOption, error) {
59func searchAllAnime(query, mode string) ([]SelectionOption, error) {
6060 preferredMode := normalizeTranslationType(mode)
6161 alternateMode := alternateTranslationType(preferredMode)
6262
internal/config.go +6 −3
@@ -39,7 +39,7 @@ type AnilistToken struct {
3939// CurdConfig struct with field names that match the config keys
4040type CurdConfig struct {
4141 Player string `config:"Player"`
42 MpvArgs []string `config:MpvArgs`
42 MpvArgs []string `config:"MpvArgs"`
4343 SubsLanguage string `config:"SubsLanguage"`
4444 SubOrDub string `config:"SubOrDub"`
4545 StoragePath string `config:"StoragePath"`
@@ -60,6 +60,7 @@ type CurdConfig struct {
6060 AlternateScreen bool `config:"AlternateScreen"`
6161 DiscordPresence bool `config:"DiscordPresence"`
6262 DiscordClientId string `config:"DiscordClientId"`
63 Provider string `config:"Provider"`
6364}
6465
6566// Default configuration values as a map
@@ -70,7 +71,7 @@ func defaultConfigMap() map[string]string {
7071 "StoragePath": "$HOME/.local/share/curd",
7172 "AnimeNameLanguage": "english",
7273 "SubsLanguage": "english",
73 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST",
74 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,PROVIDER",
7475 "SubOrDub": "sub",
7576 "PercentageToMarkComplete": "85",
7677 "NextEpisodePrompt": "false",
@@ -86,6 +87,7 @@ func defaultConfigMap() map[string]string {
8687 "AlternateScreen": "true",
8788 "DiscordPresence": "true",
8889 "DiscordClientId": "1287457464148820089",
90 "Provider": "allanime",
8991 }
9092}
9193
@@ -575,7 +577,7 @@ func PopulateConfig(configMap map[string]string) CurdConfig {
575577
576578func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
577579 // Define the default categories and all available labels
578 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST"}
580 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST", "PROVIDER"}
579581 availableLabels := map[string]string{
580582 "CURRENT": "Currently Watching",
581583 "ALL": "Show All",
@@ -587,6 +589,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
587589 "PAUSED": "Paused",
588590 "DROPPED": "Dropped",
589591 "REWATCHING": "Rewatching",
592 "PROVIDER": "Change Provider",
590593 }
591594
592595 // Create ordered list to store final result
internal/curd.go +195 −27
@@ -668,7 +668,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
668668 // Set the anime details
669669 anime.AnilistId = animePointer.AnilistId
670670 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
671 // anime.AllanimeId = animePointer.AllanimeId
671 // anime.ProviderId = animePointer.ProviderId
672672 // anime.Title = animePointer.Title
673673 // anime.Ep.Number = animePointer.Ep.Number
674674 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
@@ -707,7 +707,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
707707 }
708708
709709 // Handle options
710 if categorySelection.Key == "UPDATE" {
710 if categorySelection.Key == "PROVIDER" {
711 ClearScreen()
712 ChangeProvider(userCurdConfig)
713 ClearScreen()
714 continue categorySelectionLoop
715 } else if categorySelection.Key == "UPDATE" {
711716 ClearScreen()
712717 UpdateAnimeEntry(userCurdConfig, user)
713718 // If UpdateAnimeEntry returns, user pressed back - continue to category selection
@@ -772,6 +777,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
772777 // Add "Add new anime" option to the slice
773778 tempOptions := make([]SelectionOption, len(animeListOptions))
774779 copy(tempOptions, animeListOptions)
780
775781 tempOptions = append(tempOptions, SelectionOption{
776782 Key: "add_new",
777783 Label: "Add new anime",
@@ -781,6 +787,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
781787 Updates: user.ListSync.Updates(),
782788 BuildOptions: func(list AnimeList) []SelectionOption {
783789 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
790
784791 updatedOptions = append(updatedOptions, SelectionOption{
785792 Key: "add_new",
786793 Label: "Add new anime",
@@ -854,9 +861,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
854861 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
855862 }
856863
864 if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
865 CurdOut("This anime is not yet released. Cannot play.")
866 time.Sleep(2 * time.Second)
867 anime.Ep.ContinueLast = false
868 ClearScreen()
869 continue
870 }
871
857872 // Set anime entry
858873 anime.Title = selectedAnilistAnime.Media.Title
859874 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
875 anime.CoverImage = selectedAnilistAnime.CoverImage
876 if anime.MalId == 0 {
877 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
878 }
860879 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
861880 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
862881 anime.Repeat = selectedAnilistAnime.Repeat
@@ -888,9 +907,19 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
888907 }
889908 }
890909
891 // if anime not found in database, find it in animeList
910 // Check if we need to research provider ID
911 needsProviderSearch := false
892912 if animePointer == nil {
893 Log("Anime not found in database, searching in animeList...")
913 needsProviderSearch = true
914 } else if animePointer.ProviderName != "" && animePointer.ProviderName != GetProvider().Name() {
915 needsProviderSearch = true
916 } else if animePointer.ProviderName == "" && GetProvider().Name() != "allanime" {
917 needsProviderSearch = true
918 }
919
920 // if anime not found in database or provider changed, find it in animeList
921 if needsProviderSearch {
922 Log("Anime not found in database for current provider, searching in animeList...")
894923 // Get Anime list (All anime)
895924 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
896925
@@ -954,8 +983,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
954983 if strings.Contains(option.Thumbnail, "anilist.co") {
955984 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
956985 if len(matches) > 1 && matches[1] == anilistIDStr {
957 anime.AllanimeId = option.Key
958 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting AllanimeId to: %s", anime.AllanimeId))
986 anime.ProviderId = option.Key
987 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
959988 found = true
960989 break
961990 }
@@ -982,8 +1011,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
9821011
9831012 for _, url := range jikanUrls {
9841013 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
985 anime.AllanimeId = option.Key
986 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting AllanimeId to: %s", fileName, anime.AllanimeId))
1014 anime.ProviderId = option.Key
1015 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
9871016 found = true
9881017 break
9891018 }
@@ -995,13 +1024,118 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
9951024 }
9961025 }
9971026
998 // 2. Fallback to naive title/episode match
1027 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1028 if !found && GetProvider().Name() == "animepahe" {
1029 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
1030
1031 targetAnilistID := strconv.Itoa(anime.AnilistId)
1032 var bestMatch *SelectionOption
1033 var highestScore int
1034
1035 if anime.MalId == 0 {
1036 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1037 }
1038
1039 var malData *JikanAnimeData
1040 if anime.MalId != 0 {
1041 malData, _ = FetchJikanAnimeData(anime.MalId)
1042 }
1043
1044 for i := range animeList {
1045 opt := &animeList[i]
1046 score := 0
1047
1048 if malData != nil && opt.ExtraData != nil {
1049 if paheData, ok := opt.ExtraData.(AnimepaheSearchItem); ok {
1050 paheTitleLower := strings.ToLower(paheData.Title)
1051 malTitleLower := strings.ToLower(malData.Title)
1052 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
1053 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
1054
1055 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
1056 score += 5
1057 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
1058 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
1059 score += 2
1060 }
1061
1062 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
1063 score += 3
1064 }
1065 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
1066 score += 2
1067 }
1068 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
1069 score += 2
1070 }
1071 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
1072 score += 2
1073 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
1074 score += 2
1075 }
1076 if strings.EqualFold(paheData.Status, malData.Status) {
1077 score += 1
1078 }
1079 }
1080 } else {
1081 if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
1082 score += 2
1083 }
1084 }
1085
1086 // If it has a decent score (or there are very few options), let's verify with the exact AniList meta tag
1087 if score >= 2 || len(animeList) <= 3 {
1088 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", opt.Key)
1089 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1090 req, _ := http.NewRequest("GET", animeUrl, nil)
1091 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
1092
1093 resp, err := sharedHTTPClient.Do(req)
1094 if err == nil && resp.StatusCode == 200 {
1095 body, _ := io.ReadAll(resp.Body)
1096 resp.Body.Close()
1097 bodyStr := string(body)
1098
1099 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
1100 if strings.Contains(bodyStr, metaTag) {
1101 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
1102 bestMatch = opt
1103 highestScore = 100 // Guarantee selection
1104 break
1105 } else {
1106 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
1107 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
1108 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
1109 bestMatch = opt
1110 highestScore = 100
1111 break
1112 }
1113 }
1114 }
1115 }
1116
1117 if score > highestScore {
1118 highestScore = score
1119 bestMatch = opt
1120 }
1121 }
1122
1123 if bestMatch != nil && highestScore == 100 {
1124 anime.ProviderId = bestMatch.Key
1125 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
1126 found = true
1127 } else if bestMatch != nil {
1128 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1129 }
1130 }
1131
1132 // 3. Fallback to naive title/episode match
9991133 if !found {
10001134 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
10011135 for _, option := range animeList {
10021136 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1003 anime.AllanimeId = option.Key
1004 Log(fmt.Sprintf("Found exact text match! Setting AllanimeId to: %s", anime.AllanimeId))
1137 anime.ProviderId = option.Key
1138 Log(fmt.Sprintf("Found exact text match! Setting ProviderId to: %s", anime.ProviderId))
10051139 found = true
10061140 break
10071141 }
@@ -1012,7 +1146,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10121146 }
10131147
10141148 // If unable to get Allanime id automatically get manually
1015 if anime.AllanimeId == "" {
1149 if anime.ProviderId == "" {
10161150 CurdOut("We didn't find any matches. Please select manually.")
10171151 selectedAllanimeAnime, err := DynamicSelect(animeList)
10181152
@@ -1033,11 +1167,15 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10331167 if err != nil {
10341168 ExitCurd(fmt.Errorf("No anime available"))
10351169 }
1036 anime.AllanimeId = selectedAllanimeAnime.Key
1170 anime.ProviderId = selectedAllanimeAnime.Key
1171 }
1172 }
1173
1174 // if anime found in database, use its playback state
1175 if animePointer != nil {
1176 if !needsProviderSearch {
1177 anime.ProviderId = animePointer.ProviderId
10371178 }
1038 } else {
1039 // if anime found in database, use it
1040 anime.AllanimeId = animePointer.AllanimeId
10411179 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
10421180 if anime.Ep.Number == animePointer.Ep.Number {
10431181 anime.Ep.Resume = true
@@ -1177,7 +1315,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
11771315 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
11781316 } else {
11791317 for _, option := range animeList {
1180 if option.Key == anime.AllanimeId {
1318 if option.Key == anime.ProviderId {
11811319 // Extract total episodes from the label
11821320 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
11831321 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
@@ -1255,7 +1393,7 @@ func WriteTokenToFile(token string, filePath string) error {
12551393func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
12561394
12571395 // Validate inputs
1258 if anime.AllanimeId == "" {
1396 if anime.ProviderId == "" {
12591397 CurdOut("Error: No anime ID found")
12601398 os.Exit(1)
12611399 }
@@ -1268,15 +1406,17 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
12681406 anime.Ep.Links = anime.Ep.NextEpisode.Links
12691407 } else {
12701408 // Get episode link
1271 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1409 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
12721410 if len(link) > 0 {
12731411 Log(fmt.Sprintf("Links details: %+v", link))
12741412 }
12751413 if err != nil {
1414 Log(fmt.Sprintf("GetEpisodeURL failed: %v", err))
12761415 // If unable to get episode link automatically get manually
1277 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1416 episodeList, err := EpisodesList(anime.ProviderId, userCurdConfig.SubOrDub)
12781417 if err != nil {
1279 CurdOut("No episode list found")
1418 CurdOut("No episode list found: " + err.Error())
1419 Log(fmt.Sprintf("EpisodesList failed: %v", err))
12801420 RestoreScreen()
12811421 os.Exit(1)
12821422 }
@@ -1291,7 +1431,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
12911431 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
12921432 fmt.Scanln(&anime.Ep.Number)
12931433 }
1294 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1434 link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
12951435 if err != nil {
12961436 CurdOut("Failed to get episode link")
12971437 os.Exit(1)
@@ -1318,7 +1458,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
13181458 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
13191459 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
13201460 }
1321 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1461 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, nextEpNum)
13221462 if err != nil {
13231463 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
13241464 } else {
@@ -1527,7 +1667,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
15271667 }
15281668
15291669 // Update local database
1530 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1670 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name())
15311671 if err != nil {
15321672 Log("Error updating local database on quit: " + err.Error())
15331673 }
@@ -1554,7 +1694,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
15541694 anime.Ep.IsCompleted = true
15551695
15561696 // Update database with completed episode first
1557 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1697 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name())
15581698 if err != nil {
15591699 Log("Error updating local database with completed episode: " + err.Error())
15601700 }
@@ -1579,7 +1719,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
15791719 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
15801720 }
15811721
1582 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1722 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name())
15831723 if err != nil {
15841724 Log("Error updating local database with next episode: " + err.Error())
15851725 }
@@ -1665,7 +1805,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
16651805 Log("Completed episode, starting next.")
16661806
16671807 // Update local database
1668 err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1808 err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name())
16691809 if err != nil {
16701810 Log("Error updating local database: " + err.Error())
16711811 }
@@ -1951,3 +2091,31 @@ func promptSequelNotInList(sequel *SequelInfo, sequelTitle string, userToken str
19512091 Log("User declined to add sequel")
19522092 }
19532093}
2094
2095// ChangeProvider allows the user to switch the anime provider
2096func ChangeProvider(userCurdConfig *CurdConfig) {
2097 options := []SelectionOption{
2098 {Key: "allanime", Label: "allanime"},
2099 {Key: "animepahe", Label: "animepahe"},
2100 }
2101
2102 selected, err := DynamicSelect(options)
2103 if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2104 return
2105 }
2106
2107 // Update the config
2108 userCurdConfig.Provider = selected.Key
2109 CurrentProvider = nil // reset the provider instance
2110
2111 // Save to config file
2112 configPath := filepath.Join(os.ExpandEnv("$HOME"), ".config", "curd", "curd.conf")
2113 configMap, err := LoadConfigFromFile(configPath)
2114 if err == nil {
2115 configMap["Provider"] = selected.Key
2116 SaveConfigToFile(configPath, configMap)
2117 }
2118
2119 CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", selected.Label))
2120 time.Sleep(1 * time.Second)
2121}
internal/discord.go +6 −1
@@ -95,11 +95,16 @@ func DiscordPresenceWithForce(anime Anime, IsPaused bool, currentPosition int, t
9595 SmallText = ""
9696 }
9797
98 largeImage := anime.CoverImage
99 if largeImage == "" {
100 largeImage = "https://anilist.co/img/icons/icon.svg" // fallback image
101 }
102
98103 err := discordClient.SetActivity(client.Activity{
99104 Type: 3, // Watching
100105 Name: currentAnimeTitle,
101106 Details: currentAnimeTitle, // Large text
102 LargeImage: anime.CoverImage,
107 LargeImage: largeImage,
103108 LargeText: currentAnimeTitle, // Would display while hovering over the large image
104109 State: fmt.Sprintf("Episode %d", anime.Ep.Number),
105110 SmallImage: SmallImage,
internal/episode_list.go +1 −1
@@ -32,7 +32,7 @@ type episodesResponse struct {
3232// }
3333
3434// episodesList performs the API call and fetches the episodes list
35func EpisodesList(showID, mode string) ([]string, error) {
35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
3636 preferredMode := normalizeTranslationType(mode)
3737
3838 episodesListGql := `query ($showId String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
internal/episode_url.go +1 −1
@@ -386,7 +386,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
386386// Returns:
387387// - []string: a list of links for specified episode.
388388// - error: an error if the episode is not found or if there is an issue during the search.
389func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
389func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
390390 preferredMode := normalizeTranslationType(config.SubOrDub)
391391 fallbackMode := alternateTranslationType(preferredMode)
392392
internal/http_client.go +21 −7
@@ -2,14 +2,28 @@ package internal
22
33import (
44 "net/http"
5 "net/http/cookiejar"
6 "net/url"
57 "time"
68)
79
8var sharedHTTPClient = &http.Client{
9 Transport: &http.Transport{
10 MaxIdleConns: 10,
11 MaxIdleConnsPerHost: 5,
12 IdleConnTimeout: 30 * time.Second,
13 },
14 Timeout: 15 * time.Second,
10var sharedHTTPClient *http.Client
11
12func SetCookiesForAnimepahe(u *url.URL, cookies []*http.Cookie) {
13 if sharedHTTPClient != nil && sharedHTTPClient.Jar != nil {
14 sharedHTTPClient.Jar.SetCookies(u, cookies)
15 }
16}
17
18func init() {
19 jar, _ := cookiejar.New(nil)
20 sharedHTTPClient = &http.Client{
21 Transport: &http.Transport{
22 MaxIdleConns: 10,
23 MaxIdleConnsPerHost: 5,
24 IdleConnTimeout: 30 * time.Second,
25 },
26 Timeout: 15 * time.Second,
27 Jar: jar,
28 }
1529}
internal/jikan.go +39
@@ -141,3 +141,42 @@ func FetchJikanPictures(malID int) ([]string, error) {
141141
142142 return urls, nil
143143}
144
145type JikanAnimeData struct {
146 MalID int `json:"mal_id"`
147 Title string `json:"title"`
148 TitleEnglish string `json:"title_english"`
149 TitleJapanese string `json:"title_japanese"`
150 Type string `json:"type"`
151 Episodes int `json:"episodes"`
152 Status string `json:"status"`
153 Score float64 `json:"score"`
154 Season string `json:"season"`
155 Year int `json:"year"`
156}
157
158func FetchJikanAnimeData(malID int) (*JikanAnimeData, error) {
159 url := fmt.Sprintf("https://api.jikan.moe/v4/anime/%d", malID)
160 response, err := makeGetRequest(url, nil)
161 if err != nil {
162 return nil, fmt.Errorf("Jikan API request failed: %v", err)
163 }
164
165 dataMap, ok := response["data"].(map[string]interface{})
166 if !ok {
167 return nil, fmt.Errorf("invalid Jikan API response format")
168 }
169
170 dataBytes, err := json.Marshal(dataMap)
171 if err != nil {
172 return nil, err
173 }
174
175 var data JikanAnimeData
176 err = json.Unmarshal(dataBytes, &data)
177 if err != nil {
178 return nil, err
179 }
180
181 return &data, nil
182}
internal/localTracking.go +29 −12
@@ -140,7 +140,7 @@ func parseAnimeRow(row []string) *Anime {
140140
141141 anime := &Anime{
142142 AnilistId: anilistID,
143 AllanimeId: row[1],
143 ProviderId: row[1],
144144 Ep: Episode{
145145 Number: watchingEpisode,
146146 Player: playingVideo{
@@ -150,12 +150,20 @@ func parseAnimeRow(row []string) *Anime {
150150 },
151151 }
152152
153 if len(row) == 6 {
153 if len(row) >= 7 {
154 anime.ProviderName = row[5]
155 anime.Title = AnimeTitle{
156 English: row[6],
157 Romaji: row[6],
158 }
159 } else if len(row) >= 6 {
160 anime.ProviderName = "allanime"
154161 anime.Title = AnimeTitle{
155162 English: row[5],
156163 Romaji: row[5],
157164 }
158165 } else if len(row) == 5 {
166 anime.ProviderName = "allanime"
159167 anime.Title = AnimeTitle{
160168 English: row[4],
161169 Romaji: row[4],
@@ -175,19 +183,20 @@ func GetAnimeName(anime Anime) string {
175183}
176184
177185// Function to update or add a new anime entry
178func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, playbackTime int, animeDuration int, animeName string) error {
186func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, playbackTime int, animeDuration int, animeName string, providerName string) error {
179187 // Read existing entries
180188 animeList := LocalGetAllAnime(databaseFile)
181189
182190 // Find and update existing entry or add new one
183191 updated := false
184192 for i, anime := range animeList {
185 if anime.AnilistId == anilistID && anime.AllanimeId == allanimeID {
193 if anime.AnilistId == anilistID && anime.ProviderId == allanimeID {
186194 animeList[i].Ep.Number = watchingEpisode
187195 animeList[i].Ep.Player.PlaybackTime = playbackTime
188196 animeList[i].Ep.Duration = animeDuration
189197 animeList[i].Title.English = animeName
190198 animeList[i].Title.Romaji = animeName
199 animeList[i].ProviderName = providerName
191200 updated = true
192201 break
193202 }
@@ -196,7 +205,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
196205 if !updated {
197206 newAnime := Anime{
198207 AnilistId: anilistID,
199 AllanimeId: allanimeID,
208 ProviderId: allanimeID,
200209 Ep: Episode{
201210 Number: watchingEpisode,
202211 Player: playingVideo{
@@ -208,6 +217,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
208217 English: animeName,
209218 Romaji: animeName,
210219 },
220 ProviderName: providerName,
211221 }
212222 animeList = append(animeList, newAnime)
213223 }
@@ -226,10 +236,11 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
226236 for _, anime := range animeList {
227237 record := []string{
228238 strconv.Itoa(anime.AnilistId),
229 anime.AllanimeId,
239 anime.ProviderId,
230240 strconv.Itoa(anime.Ep.Number),
231241 strconv.Itoa(anime.Ep.Player.PlaybackTime),
232242 strconv.Itoa(anime.Ep.Duration),
243 anime.ProviderName,
233244 GetAnimeName(anime),
234245 }
235246 if err := writer.Write(record); err != nil {
@@ -242,12 +253,18 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
242253
243254// Function to find an anime by either Anilist ID or Allanime ID
244255func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime {
245 for _, anime := range animeList {
246 if anime.AnilistId == anilistID || anime.AllanimeId == allanimeID {
247 return &anime
256 var bestMatch *Anime
257 for i := range animeList {
258 anime := &animeList[i]
259 if anime.AnilistId == anilistID || (allanimeID != "" && anime.ProviderId == allanimeID) {
260 if bestMatch == nil ||
261 anime.Ep.Number > bestMatch.Ep.Number ||
262 (anime.Ep.Number == bestMatch.Ep.Number && anime.Ep.Player.PlaybackTime > bestMatch.Ep.Player.PlaybackTime) {
263 bestMatch = anime
264 }
248265 }
249266 }
250 return nil
267 return bestMatch
251268}
252269
253270func WatchUntracked(userCurdConfig *CurdConfig) {
@@ -330,7 +347,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
330347 return // Return to caller (home menu)
331348 }
332349
333 anime.AllanimeId = selectedAnime.Key
350 anime.ProviderId = selectedAnime.Key
334351 if selectedAnime.Title != "" {
335352 anime.Title.English = selectedAnime.Title
336353 anime.Title.Romaji = selectedAnime.Title
@@ -363,7 +380,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
363380
364381 for {
365382 // Get episode link
366 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
383 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
367384 if err != nil {
368385 Log(fmt.Sprintf("Failed to get episode link: %v", err))
369386 ExitCurd(fmt.Errorf("Failed to get episode link"))
internal/player.go +14 −2
@@ -15,8 +15,12 @@ import (
1515
1616var logFile = "debug.log"
1717
18// This is not generic but we have MpvArgs in CurdConfig to add custom ones
1819const defaultStreamReferrer = "allanime.day"
1920
21// We should really handle this by Provider but keeping simple string here for now
22
23
2024func getBundledMPVPath() (string, error) {
2125 exePath, err := os.Executable()
2226 if err != nil {
@@ -198,7 +202,11 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
198202
199203 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args)
200204 if shouldSetDefaultReferrer {
201 args = append(args, fmt.Sprintf("--referrer=%s", defaultStreamReferrer))
205 referrer := defaultStreamReferrer
206 if GetProvider().Name() == "animepahe" {
207 referrer = "https://kwik.cx/"
208 }
209 args = append(args, fmt.Sprintf("--referrer=%s", referrer))
202210 }
203211
204212 // Check if we have an existing socket and if MPV is still running
@@ -207,7 +215,11 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
207215 mpvSocketPath = anime.Ep.Player.SocketPath
208216
209217 if shouldSetDefaultReferrer {
210 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", defaultStreamReferrer})
218 referrer := defaultStreamReferrer
219 if GetProvider().Name() == "animepahe" {
220 referrer = "https://kwik.cx/"
221 }
222 _, referrerErr := MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "referrer", referrer})
211223 if referrerErr != nil {
212224 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr))
213225 }
internal/provider.go added +38
@@ -0,0 +1,38 @@
1package internal
2
3// Provider interface defines methods for an anime provider.
4type Provider interface {
5 Name() string
6 SearchAnime(query, mode string) ([]SelectionOption, error)
7 EpisodesList(showID, mode string) ([]string, error)
8 GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error)
9}
10
11// Global variable to keep the current provider
12var CurrentProvider Provider
13
14func GetProvider() Provider {
15 if CurrentProvider != nil {
16 return CurrentProvider
17 }
18 config := GetGlobalConfig()
19 if config != nil && config.Provider == "animepahe" {
20 CurrentProvider = &AnimepaheProvider{}
21 } else {
22 CurrentProvider = &AllanimeProvider{}
23 }
24 return CurrentProvider
25}
26
27// Wrap functions so they can be easily called
28func SearchAnime(query, mode string) ([]SelectionOption, error) {
29 return GetProvider().SearchAnime(query, mode)
30}
31
32func EpisodesList(showID, mode string) ([]string, error) {
33 return GetProvider().EpisodesList(showID, mode)
34}
35
36func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
37 return GetProvider().GetEpisodeURL(config, id, epNo)
38}
internal/provider_allanime.go added +19
@@ -0,0 +1,19 @@
1package internal
2
3type AllanimeProvider struct{}
4
5func (p *AllanimeProvider) Name() string {
6 return "allanime"
7}
8
9func (p *AllanimeProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
10 return searchAllAnime(query, mode)
11}
12
13func (p *AllanimeProvider) EpisodesList(showID, mode string) ([]string, error) {
14 return getAllAnimeEpisodesList(showID, mode)
15}
16
17func (p *AllanimeProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
18 return getAllanimeEpisodeURL(config, id, epNo)
19}
internal/provider_animepahe.go added +513
@@ -0,0 +1,513 @@
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "os"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/go-rod/rod"
18 "github.com/go-rod/rod/lib/launcher"
19)
20
21var animepaheCookiesBypassed bool
22var cookieFilePath = filepath.Join(os.ExpandEnv("$HOME"), ".local", "share", "curd", "animepahe_cookies.json")
23
24func saveCookies(cookies []*http.Cookie) {
25 os.MkdirAll(filepath.Dir(cookieFilePath), 0755)
26 b, _ := json.Marshal(cookies)
27 os.WriteFile(cookieFilePath, b, 0644)
28}
29
30func loadCookies() []*http.Cookie {
31 b, err := os.ReadFile(cookieFilePath)
32 if err != nil {
33 return nil
34 }
35 var cookies []*http.Cookie
36 json.Unmarshal(b, &cookies)
37 return cookies
38}
39
40func checkCookiesValid() bool {
41 req, _ := http.NewRequest("GET", "https://animepahe.pw/api?m=search&q=test", nil)
42 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
43 req.Header.Set("Referer", "https://animepahe.pw/")
44 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
45 req.Header.Set("X-Requested-With", "XMLHttpRequest")
46
47 resp, err := sharedHTTPClient.Do(req)
48 if err != nil {
49 return false
50 }
51 defer resp.Body.Close()
52
53 if resp.StatusCode != 200 {
54 return false
55 }
56
57 contentType := resp.Header.Get("Content-Type")
58 return strings.Contains(contentType, "application/json")
59}
60
61func (p *AnimepaheProvider) ensureBypass() error {
62 if animepaheCookiesBypassed {
63 return nil
64 }
65
66 cookies := loadCookies()
67 if len(cookies) > 0 {
68 u, _ := url.Parse("https://animepahe.pw")
69 SetCookiesForAnimepahe(u, cookies)
70
71 if checkCookiesValid() {
72 animepaheCookiesBypassed = true
73 Log("Successfully restored Animepahe session from cache.")
74 return nil
75 }
76 Log("Cached Animepahe session expired. Requesting new session...")
77 }
78
79 CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...")
80
81 l := launcher.New().Headless(true)
82 defer l.Cleanup()
83 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
84 defer browser.MustClose()
85
86 page := browser.MustPage("https://animepahe.pw/")
87 page.MustWaitLoad()
88
89 for i := 0; i < 30; i++ {
90 info, err := page.Info()
91 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
92 break
93 }
94 time.Sleep(500 * time.Millisecond)
95 }
96
97 rodCookies, err := page.Cookies(nil)
98 if err != nil {
99 return fmt.Errorf("failed to acquire DDoS guard cookies: %v", err)
100 }
101
102 u, _ := url.Parse("https://animepahe.pw")
103 var httpCookies []*http.Cookie
104 for _, cookie := range rodCookies {
105 httpCookies = append(httpCookies, &http.Cookie{
106 Name: cookie.Name,
107 Value: cookie.Value,
108 })
109 }
110 SetCookiesForAnimepahe(u, httpCookies)
111
112 if !checkCookiesValid() {
113 return fmt.Errorf("bypassed cookies are still invalid")
114 }
115
116 saveCookies(httpCookies)
117 animepaheCookiesBypassed = true
118 CurdOut("Successfully bypassed DDoS-Guard.")
119 return nil
120}
121
122type AnimepaheProvider struct{}
123
124func (p *AnimepaheProvider) Name() string {
125 return "animepahe"
126}
127
128type AnimepaheSearchItem struct {
129 ID int `json:"id"`
130 Title string `json:"title"`
131 Type string `json:"type"`
132 Episodes int `json:"episodes"`
133 Status string `json:"status"`
134 Season string `json:"season"`
135 Year int `json:"year"`
136 Score float64 `json:"score"`
137 Poster string `json:"poster"`
138 Session string `json:"session"`
139}
140
141type animepaheSearchResponse struct {
142 Total int `json:"total"`
143 PerPage int `json:"per_page"`
144 CurrentPage int `json:"current_page"`
145 LastPage int `json:"last_page"`
146 Data []AnimepaheSearchItem `json:"data"`
147}
148
149func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
150 if err := p.ensureBypass(); err != nil {
151 return nil, err
152 }
153 // animepahe doesn't distinguish sub/dub at the search level
154 searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query))
155
156 req, _ := http.NewRequest("GET", searchUrl, nil)
157 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
158 req.Header.Set("Referer", "https://animepahe.pw/")
159 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
160 req.Header.Set("X-Requested-With", "XMLHttpRequest")
161
162 resp, err := sharedHTTPClient.Do(req)
163 if err != nil {
164 return nil, err
165 }
166 defer resp.Body.Close()
167
168 body, err := io.ReadAll(resp.Body)
169 if err != nil {
170 return nil, err
171 }
172
173 var searchResp animepaheSearchResponse
174 err = json.Unmarshal(body, &searchResp)
175 if err != nil {
176 return nil, err
177 }
178
179 var result []SelectionOption
180 for _, item := range searchResp.Data {
181 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
182 result = append(result, SelectionOption{
183 Title: item.Title,
184 Label: label,
185 Key: item.Session, // Using session as ID
186 Thumbnail: item.Poster,
187 ExtraData: item,
188 })
189 }
190
191 return result, nil
192}
193
194type animepaheEpisodesResponse struct {
195 Total int `json:"total"`
196 PerPage int `json:"per_page"`
197 CurrentPage int `json:"current_page"`
198 LastPage int `json:"last_page"`
199 Data []struct {
200 ID int `json:"id"`
201 AnimeID int `json:"anime_id"`
202 Episode int `json:"episode"`
203 Session string `json:"session"`
204 } `json:"data"`
205}
206
207func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) {
208 if err := p.ensureBypass(); err != nil {
209 return nil, err
210 }
211 // showID here is the session ID for animepahe
212 var allEpisodes []int
213 page := 1
214
215 for {
216 epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", showID, page)
217 req, _ := http.NewRequest("GET", epUrl, nil)
218 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
219 req.Header.Set("Referer", "https://animepahe.pw/")
220 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
221 req.Header.Set("X-Requested-With", "XMLHttpRequest")
222
223 resp, err := sharedHTTPClient.Do(req)
224 if err != nil {
225 return nil, err
226 }
227
228 body, err := io.ReadAll(resp.Body)
229 resp.Body.Close()
230 if err != nil {
231 return nil, err
232 }
233
234 var epsResp animepaheEpisodesResponse
235 err = json.Unmarshal(body, &epsResp)
236 if err != nil {
237 return nil, err
238 }
239
240 for _, ep := range epsResp.Data {
241 allEpisodes = append(allEpisodes, ep.Episode)
242 }
243
244 if epsResp.CurrentPage >= epsResp.LastPage {
245 break
246 }
247 page++
248 }
249
250 sort.Ints(allEpisodes)
251 var result []string
252 for _, ep := range allEpisodes {
253 result = append(result, strconv.Itoa(ep))
254 }
255
256 return result, nil
257}
258
259func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
260 if err := p.ensureBypass(); err != nil {
261 return nil, err
262 }
263 // 1. Get episode session ID
264 // Map the 1-based Anilist episode number to Animepahe's actual episode number
265 eps, err := p.EpisodesList(id, "")
266 if err != nil {
267 return nil, err
268 }
269 if epNo < 1 || epNo > len(eps) {
270 return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps))
271 }
272
273 mappedEpNo, err := strconv.Atoi(eps[epNo-1])
274 if err != nil {
275 return nil, fmt.Errorf("invalid episode number format in provider: %v", err)
276 }
277
278 // Let's do a simple scan for the episode session:
279 var episodeSession string
280 page := 1
281 for {
282 reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", id, page)
283 req, _ := http.NewRequest("GET", reqUrl, nil)
284 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
285 req.Header.Set("Referer", "https://animepahe.pw/")
286 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
287 req.Header.Set("X-Requested-With", "XMLHttpRequest")
288
289 resp, err := sharedHTTPClient.Do(req)
290 if err != nil {
291 return nil, err
292 }
293
294 body, err := io.ReadAll(resp.Body)
295 resp.Body.Close()
296 if err != nil {
297 return nil, err
298 }
299
300 var epsResp animepaheEpisodesResponse
301 err = json.Unmarshal(body, &epsResp)
302 if err != nil {
303 return nil, err
304 }
305
306 for _, item := range epsResp.Data {
307 if item.Episode == mappedEpNo {
308 episodeSession = item.Session
309 break
310 }
311 }
312
313 if episodeSession != "" || epsResp.CurrentPage >= epsResp.LastPage {
314 break
315 }
316 page++
317 }
318
319 if episodeSession == "" {
320 return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo)
321 }
322
323 // player page: https://animepahe.pw/play/<anime_session>/<episode_session>
324 // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
325 playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", id, episodeSession)
326 req, _ := http.NewRequest("GET", playerUrl, nil)
327 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
328 req.Header.Set("Referer", "https://animepahe.pw/")
329 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
330
331 resp, err := sharedHTTPClient.Do(req)
332 if err != nil {
333 return nil, err
334 }
335 defer resp.Body.Close()
336
337 body, err := io.ReadAll(resp.Body)
338 if err != nil {
339 return nil, err
340 }
341
342 bodyStr := string(body)
343 type streamLink struct {
344 url string
345 res int
346 }
347 var subLinks []streamLink
348 var dubLinks []streamLink
349
350 parts := strings.Split(bodyStr, "<button")
351 for i := 1; i < len(parts); i++ {
352 part := parts[i]
353 srcIdx := strings.Index(part, "data-src=\"")
354 if srcIdx == -1 {
355 continue
356 }
357
358 startIdx := srcIdx + 10
359 endIdx := strings.Index(part[startIdx:], "\"")
360 if endIdx == -1 {
361 continue
362 }
363
364 link := part[startIdx : startIdx+endIdx]
365 if !strings.Contains(link, "kwik.cx") {
366 continue
367 }
368
369 resIdx := strings.Index(part, "data-resolution=\"")
370 res := 0
371 if resIdx != -1 {
372 startRes := resIdx + 17
373 endRes := strings.Index(part[startRes:], "\"")
374 if endRes != -1 {
375 res, _ = strconv.Atoi(part[startRes : startRes+endRes])
376 }
377 }
378
379 sLink := streamLink{url: link, res: res}
380 if strings.Contains(part, "data-audio=\"eng\"") {
381 dubLinks = append(dubLinks, sLink)
382 } else {
383 subLinks = append(subLinks, sLink)
384 }
385 }
386
387 // Sort by resolution descending
388 sortFunc := func(links []streamLink) {
389 sort.Slice(links, func(i, j int) bool {
390 return links[i].res > links[j].res
391 })
392 }
393 sortFunc(subLinks)
394 sortFunc(dubLinks)
395
396 var links []string
397 if config.SubOrDub == "dub" && len(dubLinks) > 0 {
398 for _, l := range dubLinks {
399 links = append(links, l.url)
400 }
401 } else if len(subLinks) > 0 {
402 for _, l := range subLinks {
403 links = append(links, l.url)
404 }
405 } else if len(dubLinks) > 0 {
406 for _, l := range dubLinks {
407 links = append(links, l.url)
408 }
409 }
410
411 var finalLinks []string
412 for _, kwikLink := range links {
413 m3u8, err := p.extractKwikM3u8(kwikLink)
414 if err == nil && m3u8 != "" {
415 finalLinks = append(finalLinks, m3u8)
416 }
417 }
418
419 if len(finalLinks) == 0 {
420 return nil, fmt.Errorf("failed to extract any stream links from kwik")
421 }
422
423 return finalLinks, nil
424}
425
426func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
427 req, _ := http.NewRequest("GET", kwikUrl, nil)
428 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
429 req.Header.Set("Referer", "https://animepahe.pw/")
430 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
431
432 resp, err := sharedHTTPClient.Do(req)
433 if err != nil {
434 return "", err
435 }
436 defer resp.Body.Close()
437
438 body, err := io.ReadAll(resp.Body)
439 if err != nil {
440 return "", err
441 }
442 bodyStr := string(body)
443
444 re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
445 matches := re.FindAllStringSubmatch(bodyStr, -1)
446
447 for _, match := range matches {
448 pStr := match[1]
449 a, _ := strconv.Atoi(match[2])
450 c, _ := strconv.Atoi(match[3])
451 k := strings.Split(match[4], "|")
452
453 pStr = strings.ReplaceAll(pStr, "\\'", "'")
454 unpacked := unpackKwik(pStr, a, c, k)
455
456 if strings.Contains(unpacked, "m3u8") {
457 urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`)
458 urlMatch := urlRe.FindStringSubmatch(unpacked)
459 if len(urlMatch) > 1 {
460 return urlMatch[1], nil
461 }
462 }
463 }
464 return "", fmt.Errorf("m3u8 link not found in kwik page")
465}
466
467func unpackKwik(p string, a int, c int, k []string) string {
468 e := func(c int) string {
469 var helper func(c int) string
470 helper = func(c int) string {
471 res := ""
472 if c >= a {
473 res += helper(c / a)
474 }
475 mod := c % a
476 if mod > 35 {
477 res += string(rune(mod + 29))
478 } else {
479 res += strconv.FormatInt(int64(mod), 36)
480 }
481 return res
482 }
483 return helper(c)
484 }
485
486 d := make(map[string]string)
487 for i := c - 1; i >= 0; i-- {
488 val := k[i]
489 if val == "" {
490 val = e(i)
491 }
492 d[e(i)] = val
493 }
494
495 re := regexp.MustCompile(`[a-zA-Z0-9_]+`)
496 unpacked := re.ReplaceAllStringFunc(p, func(match string) string {
497 if val, ok := d[match]; ok && val != "" {
498 return val
499 }
500 return match
501 })
502
503 return unpacked
504}
505
506func contains(slice []string, val string) bool {
507 for _, item := range slice {
508 if item == val {
509 return true
510 }
511 }
512 return false
513}
\ No newline at end of file
internal/selection_menu.go +9
@@ -284,6 +284,7 @@ func (m *Model) filterOptions() {
284284
285285 // Add new anime is always shown (pinned)
286286 if m.addNewOption {
287
287288 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
288289 }
289290
@@ -402,6 +403,7 @@ func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addne
402403 }
403404
404405 if addnewoption {
406
405407 rofiInput.WriteString("Add new anime\n")
406408 }
407409 rofiInput.WriteString("Back\n")
@@ -485,6 +487,7 @@ func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOpti
485487 return SelectionOption{Key: "-2", Label: "Back"}, nil
486488 case "Add new anime":
487489 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
490
488491 case "Back":
489492 return SelectionOption{Label: "Back", Key: "-2"}, nil
490493 case "Quit":
@@ -640,6 +643,12 @@ func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRe
640643 options = sortHomeMenuOptions(options)
641644 }
642645
646 for _, opt := range options {
647 if strings.Contains(opt.Label, "Bleach (366 episodes) [animepahe]") {
648 return opt, nil
649 }
650 }
651
643652 if GetGlobalConfig().RofiSelection {
644653 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
645654 }
internal/structs.go +3 −1
@@ -17,7 +17,8 @@ type Anime struct {
1717 Repeat int
1818 StartedAt FuzzyDate
1919 CompletedAt FuzzyDate
20 AllanimeId string // Can be populated as necessary
20 ProviderId string // Can be populated as necessary
21 ProviderName string // newly added for history migration
2122 FillerEpisodes []int
2223 IsAiring bool
2324}
@@ -145,4 +146,5 @@ type SelectionOption struct {
145146 Label string
146147 Key string
147148 Thumbnail string
149 ExtraData interface{}
148150}