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() {
285 285
286 anime.Ep.LastWasSkipped = true 286 anime.Ep.LastWasSkipped = true
287 anime.Ep.Started = false 287 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())
289 289
290 // Check if we've reached the end of the series 290 // Check if we've reached the end of the series
291 if anime.Ep.Number > anime.TotalEpisodes { 291 if anime.Ep.Number > anime.TotalEpisodes {
@@ -313,7 +313,7 @@ func main() {
313 313
314 // Update progress for the finished episode 314 // Update progress for the finished episode
315 // Local update 315 // 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())
317 317
318 // Check if we should continue to next episode 318 // Check if we should continue to next episode
319 // On Android we always prompt because we don't know exactly when video ended 319 // On Android we always prompt because we don't know exactly when video ended
@@ -612,7 +612,7 @@ func main() {
612 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token) 612 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token)
613 } 613 }
614 // Update local database with completed episode 614 // 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())
616 if err != nil { 616 if err != nil {
617 internal.Log("Error updating local database on quit: " + err.Error()) 617 internal.Log("Error updating local database on quit: " + err.Error())
618 } 618 }
@@ -697,7 +697,7 @@ func main() {
697 697
698 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer 698 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
699 // Update Local Database 699 // 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())
701 if err != nil { 701 if err != nil {
702 internal.Log("Error updating local database: " + err.Error()) 702 internal.Log("Error updating local database: " + err.Error())
703 } 703 }
@@ -740,7 +740,7 @@ func main() {
740 } else { 740 } else {
741 // Episode was already marked as completed above 741 // Episode was already marked as completed above
742 // Update local database with completed episode 742 // 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())
744 if err != nil { 744 if err != nil {
745 internal.Log("Error updating local database on quit: " + err.Error()) 745 internal.Log("Error updating local database on quit: " + err.Error())
746 } 746 }
@@ -760,7 +760,7 @@ func main() {
760 } else { 760 } else {
761 // For CLI mode, update progress immediately since episode is 85%+ complete 761 // For CLI mode, update progress immediately since episode is 85%+ complete
762 // Update local database with completed episode 762 // 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())
764 if err != nil { 764 if err != nil {
765 internal.Log("Error updating local database on completion: " + err.Error()) 765 internal.Log("Error updating local database on completion: " + err.Error())
766 } 766 }
@@ -892,7 +892,7 @@ func main() {
892 internal.Log("Error rating anime: " + err.Error()) 892 internal.Log("Error rating anime: " + err.Error())
893 internal.CurdOut("Error rating anime: " + err.Error()) 893 internal.CurdOut("Error rating anime: " + err.Error())
894 } 894 }
895 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId) 895 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId)
896 internal.ExitCurd(nil) 896 internal.ExitCurd(nil)
897 } 897 }
898 } 898 }
@@ -900,7 +900,7 @@ func main() {
900 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes { 900 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes {
901 anime.Ep.Number = anime.Ep.Number - 1 901 anime.Ep.Number = anime.Ep.Number - 1
902 internal.CurdOut("Completed anime. (Rewatching so no scoring)") 902 internal.CurdOut("Completed anime. (Rewatching so no scoring)")
903 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId) 903 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId)
904 internal.ExitCurd(nil) 904 internal.ExitCurd(nil)
905 } 905 }
906 906
@@ -932,7 +932,7 @@ func main() {
932 932
933 // If we still don't have links, get them now 933 // If we still don't have links, get them now
934 if len(anime.Ep.Links) == 0 { 934 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)
936 if err != nil { 936 if err != nil {
937 internal.Log("Failed to get episode links: " + err.Error()) 937 internal.Log("Failed to get episode links: " + err.Error())
938 internal.CurdOut("Failed to get episode links. Try again later.") 938 internal.CurdOut("Failed to get episode links. Try again later.")
go.mod +6
@@ -16,6 +16,7 @@ require (
16 github.com/charmbracelet/x/ansi v0.8.0 // indirect 16 github.com/charmbracelet/x/ansi v0.8.0 // indirect
17 github.com/charmbracelet/x/term v0.2.1 // indirect 17 github.com/charmbracelet/x/term v0.2.1 // indirect
18 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect 18 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
19 github.com/go-rod/rod v0.116.2 // indirect
19 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect 20 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
20 github.com/godbus/dbus/v5 v5.1.0 // indirect 21 github.com/godbus/dbus/v5 v5.1.0 // indirect
21 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 22 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
@@ -28,6 +29,11 @@ require (
28 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect 29 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
29 github.com/rivo/uniseg v0.4.7 // indirect 30 github.com/rivo/uniseg v0.4.7 // indirect
30 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect 31 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
31 golang.org/x/sync v0.11.0 // indirect 37 golang.org/x/sync v0.11.0 // indirect
32 golang.org/x/sys v0.30.0 // indirect 38 golang.org/x/sys v0.30.0 // indirect
33 golang.org/x/text v0.3.8 // indirect 39 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
14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= 14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI= 15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI=
16github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4/go.mod h1:0W7dI87PvXJ1Sjs0QPvWXKcQmNERY77e8l7GFhZB/s4= 16github.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=
17github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/OqtnntR4DfOY2+BgwR60cAcu/i3SE= 19github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/OqtnntR4DfOY2+BgwR60cAcu/i3SE=
18github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10= 20github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=
19github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= 21github.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
43github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o= 45github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
44github.com/tr1xem/go-discordrpc v1.0.0 h1:iWW740MP2hkBqjehlvjRtQT7+DDaJ4qQ4o1vo+ImMug= 46github.com/tr1xem/go-discordrpc v1.0.0 h1:iWW740MP2hkBqjehlvjRtQT7+DDaJ4qQ4o1vo+ImMug=
45github.com/tr1xem/go-discordrpc v1.0.0/go.mod h1:DD//cKGwNjTSFysXlyjEUN/pSH2Z/HcFAnlOiE7wX/k= 47github.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=
46golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= 59golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
47golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 60golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
48golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 61golang.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 {
56// fmt.Println(animeList) 56// fmt.Println(animeList)
57// } 57// }
58 58
59func SearchAnime(query, mode string) ([]SelectionOption, error) { 59func searchAllAnime(query, mode string) ([]SelectionOption, error) {
60 preferredMode := normalizeTranslationType(mode) 60 preferredMode := normalizeTranslationType(mode)
61 alternateMode := alternateTranslationType(preferredMode) 61 alternateMode := alternateTranslationType(preferredMode)
62 62
internal/config.go +6 −3
@@ -39,7 +39,7 @@ type AnilistToken struct {
39// CurdConfig struct with field names that match the config keys 39// CurdConfig struct with field names that match the config keys
40type CurdConfig struct { 40type CurdConfig struct {
41 Player string `config:"Player"` 41 Player string `config:"Player"`
42 MpvArgs []string `config:MpvArgs` 42 MpvArgs []string `config:"MpvArgs"`
43 SubsLanguage string `config:"SubsLanguage"` 43 SubsLanguage string `config:"SubsLanguage"`
44 SubOrDub string `config:"SubOrDub"` 44 SubOrDub string `config:"SubOrDub"`
45 StoragePath string `config:"StoragePath"` 45 StoragePath string `config:"StoragePath"`
@@ -60,6 +60,7 @@ type CurdConfig struct {
60 AlternateScreen bool `config:"AlternateScreen"` 60 AlternateScreen bool `config:"AlternateScreen"`
61 DiscordPresence bool `config:"DiscordPresence"` 61 DiscordPresence bool `config:"DiscordPresence"`
62 DiscordClientId string `config:"DiscordClientId"` 62 DiscordClientId string `config:"DiscordClientId"`
63 Provider string `config:"Provider"`
63} 64}
64 65
65// Default configuration values as a map 66// Default configuration values as a map
@@ -70,7 +71,7 @@ func defaultConfigMap() map[string]string {
70 "StoragePath": "$HOME/.local/share/curd", 71 "StoragePath": "$HOME/.local/share/curd",
71 "AnimeNameLanguage": "english", 72 "AnimeNameLanguage": "english",
72 "SubsLanguage": "english", 73 "SubsLanguage": "english",
73 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST", 74 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,PROVIDER",
74 "SubOrDub": "sub", 75 "SubOrDub": "sub",
75 "PercentageToMarkComplete": "85", 76 "PercentageToMarkComplete": "85",
76 "NextEpisodePrompt": "false", 77 "NextEpisodePrompt": "false",
@@ -86,6 +87,7 @@ func defaultConfigMap() map[string]string {
86 "AlternateScreen": "true", 87 "AlternateScreen": "true",
87 "DiscordPresence": "true", 88 "DiscordPresence": "true",
88 "DiscordClientId": "1287457464148820089", 89 "DiscordClientId": "1287457464148820089",
90 "Provider": "allanime",
89 } 91 }
90} 92}
91 93
@@ -575,7 +577,7 @@ func PopulateConfig(configMap map[string]string) CurdConfig {
575 577
576func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { 578func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
577 // Define the default categories and all available labels 579 // 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"}
579 availableLabels := map[string]string{ 581 availableLabels := map[string]string{
580 "CURRENT": "Currently Watching", 582 "CURRENT": "Currently Watching",
581 "ALL": "Show All", 583 "ALL": "Show All",
@@ -587,6 +589,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
587 "PAUSED": "Paused", 589 "PAUSED": "Paused",
588 "DROPPED": "Dropped", 590 "DROPPED": "Dropped",
589 "REWATCHING": "Rewatching", 591 "REWATCHING": "Rewatching",
592 "PROVIDER": "Change Provider",
590 } 593 }
591 594
592 // Create ordered list to store final result 595 // 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
668 // Set the anime details 668 // Set the anime details
669 anime.AnilistId = animePointer.AnilistId 669 anime.AnilistId = animePointer.AnilistId
670 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId) 670 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
671 // anime.AllanimeId = animePointer.AllanimeId 671 // anime.ProviderId = animePointer.ProviderId
672 // anime.Title = animePointer.Title 672 // anime.Title = animePointer.Title
673 // anime.Ep.Number = animePointer.Ep.Number 673 // anime.Ep.Number = animePointer.Ep.Number
674 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime 674 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
@@ -707,7 +707,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
707 } 707 }
708 708
709 // Handle options 709 // 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" {
711 ClearScreen() 716 ClearScreen()
712 UpdateAnimeEntry(userCurdConfig, user) 717 UpdateAnimeEntry(userCurdConfig, user)
713 // If UpdateAnimeEntry returns, user pressed back - continue to category selection 718 // If UpdateAnimeEntry returns, user pressed back - continue to category selection
@@ -772,6 +777,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
772 // Add "Add new anime" option to the slice 777 // Add "Add new anime" option to the slice
773 tempOptions := make([]SelectionOption, len(animeListOptions)) 778 tempOptions := make([]SelectionOption, len(animeListOptions))
774 copy(tempOptions, animeListOptions) 779 copy(tempOptions, animeListOptions)
780
775 tempOptions = append(tempOptions, SelectionOption{ 781 tempOptions = append(tempOptions, SelectionOption{
776 Key: "add_new", 782 Key: "add_new",
777 Label: "Add new anime", 783 Label: "Add new anime",
@@ -781,6 +787,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
781 Updates: user.ListSync.Updates(), 787 Updates: user.ListSync.Updates(),
782 BuildOptions: func(list AnimeList) []SelectionOption { 788 BuildOptions: func(list AnimeList) []SelectionOption {
783 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key) 789 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
790
784 updatedOptions = append(updatedOptions, SelectionOption{ 791 updatedOptions = append(updatedOptions, SelectionOption{
785 Key: "add_new", 792 Key: "add_new",
786 Label: "Add new anime", 793 Label: "Add new anime",
@@ -854,9 +861,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
854 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) 861 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
855 } 862 }
856 863
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
857 // Set anime entry 872 // Set anime entry
858 anime.Title = selectedAnilistAnime.Media.Title 873 anime.Title = selectedAnilistAnime.Media.Title
859 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 874 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
875 anime.CoverImage = selectedAnilistAnime.CoverImage
876 if anime.MalId == 0 {
877 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
878 }
860 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" 879 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
861 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING" 880 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
862 anime.Repeat = selectedAnilistAnime.Repeat 881 anime.Repeat = selectedAnilistAnime.Repeat
@@ -888,9 +907,19 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
888 } 907 }
889 } 908 }
890 909
891 // if anime not found in database, find it in animeList 910 // Check if we need to research provider ID
911 needsProviderSearch := false
892 if animePointer == nil { 912 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...")
894 // Get Anime list (All anime) 923 // Get Anime list (All anime)
895 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub)) 924 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
896 925
@@ -954,8 +983,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
954 if strings.Contains(option.Thumbnail, "anilist.co") { 983 if strings.Contains(option.Thumbnail, "anilist.co") {
955 matches := anilistRegex.FindStringSubmatch(option.Thumbnail) 984 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
956 if len(matches) > 1 && matches[1] == anilistIDStr { 985 if len(matches) > 1 && matches[1] == anilistIDStr {
957 anime.AllanimeId = option.Key 986 anime.ProviderId = option.Key
958 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting AllanimeId to: %s", anime.AllanimeId)) 987 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
959 found = true 988 found = true
960 break 989 break
961 } 990 }
@@ -982,8 +1011,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
982 1011
983 for _, url := range jikanUrls { 1012 for _, url := range jikanUrls {
984 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) { 1013 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
985 anime.AllanimeId = option.Key 1014 anime.ProviderId = option.Key
986 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting AllanimeId to: %s", fileName, anime.AllanimeId)) 1015 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
987 found = true 1016 found = true
988 break 1017 break
989 } 1018 }
@@ -995,13 +1024,118 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
995 } 1024 }
996 } 1025 }
997 1026
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
999 if !found { 1133 if !found {
1000 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes) 1134 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1001 for _, option := range animeList { 1135 for _, option := range animeList {
1002 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel { 1136 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1003 anime.AllanimeId = option.Key 1137 anime.ProviderId = option.Key
1004 Log(fmt.Sprintf("Found exact text match! Setting AllanimeId to: %s", anime.AllanimeId)) 1138 Log(fmt.Sprintf("Found exact text match! Setting ProviderId to: %s", anime.ProviderId))
1005 found = true 1139 found = true
1006 break 1140 break
1007 } 1141 }
@@ -1012,7 +1146,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1012 } 1146 }
1013 1147
1014 // If unable to get Allanime id automatically get manually 1148 // If unable to get Allanime id automatically get manually
1015 if anime.AllanimeId == "" { 1149 if anime.ProviderId == "" {
1016 CurdOut("We didn't find any matches. Please select manually.") 1150 CurdOut("We didn't find any matches. Please select manually.")
1017 selectedAllanimeAnime, err := DynamicSelect(animeList) 1151 selectedAllanimeAnime, err := DynamicSelect(animeList)
1018 1152
@@ -1033,11 +1167,15 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1033 if err != nil { 1167 if err != nil {
1034 ExitCurd(fmt.Errorf("No anime available")) 1168 ExitCurd(fmt.Errorf("No anime available"))
1035 } 1169 }
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
1037 } 1178 }
1038 } else {
1039 // if anime found in database, use it
1040 anime.AllanimeId = animePointer.AllanimeId
1041 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime 1179 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1042 if anime.Ep.Number == animePointer.Ep.Number { 1180 if anime.Ep.Number == animePointer.Ep.Number {
1043 anime.Ep.Resume = true 1181 anime.Ep.Resume = true
@@ -1177,7 +1315,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1177 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 1315 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1178 } else { 1316 } else {
1179 for _, option := range animeList { 1317 for _, option := range animeList {
1180 if option.Key == anime.AllanimeId { 1318 if option.Key == anime.ProviderId {
1181 // Extract total episodes from the label 1319 // Extract total episodes from the label
1182 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 { 1320 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1183 anime.TotalEpisodes, _ = strconv.Atoi(matches[1]) 1321 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
@@ -1255,7 +1393,7 @@ func WriteTokenToFile(token string, filePath string) error {
1255func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { 1393func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1256 1394
1257 // Validate inputs 1395 // Validate inputs
1258 if anime.AllanimeId == "" { 1396 if anime.ProviderId == "" {
1259 CurdOut("Error: No anime ID found") 1397 CurdOut("Error: No anime ID found")
1260 os.Exit(1) 1398 os.Exit(1)
1261 } 1399 }
@@ -1268,15 +1406,17 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1268 anime.Ep.Links = anime.Ep.NextEpisode.Links 1406 anime.Ep.Links = anime.Ep.NextEpisode.Links
1269 } else { 1407 } else {
1270 // Get episode link 1408 // Get episode link
1271 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1409 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1272 if len(link) > 0 { 1410 if len(link) > 0 {
1273 Log(fmt.Sprintf("Links details: %+v", link)) 1411 Log(fmt.Sprintf("Links details: %+v", link))
1274 } 1412 }
1275 if err != nil { 1413 if err != nil {
1414 Log(fmt.Sprintf("GetEpisodeURL failed: %v", err))
1276 // If unable to get episode link automatically get manually 1415 // 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)
1278 if err != nil { 1417 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))
1280 RestoreScreen() 1420 RestoreScreen()
1281 os.Exit(1) 1421 os.Exit(1)
1282 } 1422 }
@@ -1291,7 +1431,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1291 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) 1431 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1292 fmt.Scanln(&anime.Ep.Number) 1432 fmt.Scanln(&anime.Ep.Number)
1293 } 1433 }
1294 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1434 link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1295 if err != nil { 1435 if err != nil {
1296 CurdOut("Failed to get episode link") 1436 CurdOut("Failed to get episode link")
1297 os.Exit(1) 1437 os.Exit(1)
@@ -1318,7 +1458,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1318 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) { 1458 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1319 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum) 1459 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1320 } 1460 }
1321 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum) 1461 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, nextEpNum)
1322 if err != nil { 1462 if err != nil {
1323 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err)) 1463 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1324 } else { 1464 } else {
@@ -1527,7 +1667,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1527 } 1667 }
1528 1668
1529 // Update local database 1669 // 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())
1531 if err != nil { 1671 if err != nil {
1532 Log("Error updating local database on quit: " + err.Error()) 1672 Log("Error updating local database on quit: " + err.Error())
1533 } 1673 }
@@ -1554,7 +1694,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1554 anime.Ep.IsCompleted = true 1694 anime.Ep.IsCompleted = true
1555 1695
1556 // Update database with completed episode first 1696 // 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())
1558 if err != nil { 1698 if err != nil {
1559 Log("Error updating local database with completed episode: " + err.Error()) 1699 Log("Error updating local database with completed episode: " + err.Error())
1560 } 1700 }
@@ -1579,7 +1719,7 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1579 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number)) 1719 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1580 } 1720 }
1581 1721
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())
1583 if err != nil { 1723 if err != nil {
1584 Log("Error updating local database with next episode: " + err.Error()) 1724 Log("Error updating local database with next episode: " + err.Error())
1585 } 1725 }
@@ -1665,7 +1805,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1665 Log("Completed episode, starting next.") 1805 Log("Completed episode, starting next.")
1666 1806
1667 // Update local database 1807 // 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())
1669 if err != nil { 1809 if err != nil {
1670 Log("Error updating local database: " + err.Error()) 1810 Log("Error updating local database: " + err.Error())
1671 } 1811 }
@@ -1951,3 +2091,31 @@ func promptSequelNotInList(sequel *SequelInfo, sequelTitle string, userToken str
1951 Log("User declined to add sequel") 2091 Log("User declined to add sequel")
1952 } 2092 }
1953} 2093}
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
95 SmallText = "" 95 SmallText = ""
96 } 96 }
97 97
98 largeImage := anime.CoverImage
99 if largeImage == "" {
100 largeImage = "https://anilist.co/img/icons/icon.svg" // fallback image
101 }
102
98 err := discordClient.SetActivity(client.Activity{ 103 err := discordClient.SetActivity(client.Activity{
99 Type: 3, // Watching 104 Type: 3, // Watching
100 Name: currentAnimeTitle, 105 Name: currentAnimeTitle,
101 Details: currentAnimeTitle, // Large text 106 Details: currentAnimeTitle, // Large text
102 LargeImage: anime.CoverImage, 107 LargeImage: largeImage,
103 LargeText: currentAnimeTitle, // Would display while hovering over the large image 108 LargeText: currentAnimeTitle, // Would display while hovering over the large image
104 State: fmt.Sprintf("Episode %d", anime.Ep.Number), 109 State: fmt.Sprintf("Episode %d", anime.Ep.Number),
105 SmallImage: SmallImage, 110 SmallImage: SmallImage,
internal/episode_list.go +1 −1
@@ -32,7 +32,7 @@ type episodesResponse struct {
32// } 32// }
33 33
34// episodesList performs the API call and fetches the episodes list 34// episodesList performs the API call and fetches the episodes list
35func EpisodesList(showID, mode string) ([]string, error) { 35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode) 36 preferredMode := normalizeTranslationType(mode)
37 37
38 episodesListGql := `query ($showId String!) { show( _id: $showId ) { _id availableEpisodesDetail }}` 38 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 {
386// Returns: 386// Returns:
387// - []string: a list of links for specified episode. 387// - []string: a list of links for specified episode.
388// - error: an error if the episode is not found or if there is an issue during the search. 388// - 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) {
390 preferredMode := normalizeTranslationType(config.SubOrDub) 390 preferredMode := normalizeTranslationType(config.SubOrDub)
391 fallbackMode := alternateTranslationType(preferredMode) 391 fallbackMode := alternateTranslationType(preferredMode)
392 392
internal/http_client.go +21 −7
@@ -2,14 +2,28 @@ package internal
2 2
3import ( 3import (
4 "net/http" 4 "net/http"
5 "net/http/cookiejar"
6 "net/url"
5 "time" 7 "time"
6) 8)
7 9
8var sharedHTTPClient = &http.Client{ 10var sharedHTTPClient *http.Client
9 Transport: &http.Transport{ 11
10 MaxIdleConns: 10, 12func SetCookiesForAnimepahe(u *url.URL, cookies []*http.Cookie) {
11 MaxIdleConnsPerHost: 5, 13 if sharedHTTPClient != nil && sharedHTTPClient.Jar != nil {
12 IdleConnTimeout: 30 * time.Second, 14 sharedHTTPClient.Jar.SetCookies(u, cookies)
13 }, 15 }
14 Timeout: 15 * time.Second, 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 }
15} 29}
internal/jikan.go +39
@@ -141,3 +141,42 @@ func FetchJikanPictures(malID int) ([]string, error) {
141 141
142 return urls, nil 142 return urls, nil
143} 143}
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 {
140 140
141 anime := &Anime{ 141 anime := &Anime{
142 AnilistId: anilistID, 142 AnilistId: anilistID,
143 AllanimeId: row[1], 143 ProviderId: row[1],
144 Ep: Episode{ 144 Ep: Episode{
145 Number: watchingEpisode, 145 Number: watchingEpisode,
146 Player: playingVideo{ 146 Player: playingVideo{
@@ -150,12 +150,20 @@ func parseAnimeRow(row []string) *Anime {
150 }, 150 },
151 } 151 }
152 152
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"
154 anime.Title = AnimeTitle{ 161 anime.Title = AnimeTitle{
155 English: row[5], 162 English: row[5],
156 Romaji: row[5], 163 Romaji: row[5],
157 } 164 }
158 } else if len(row) == 5 { 165 } else if len(row) == 5 {
166 anime.ProviderName = "allanime"
159 anime.Title = AnimeTitle{ 167 anime.Title = AnimeTitle{
160 English: row[4], 168 English: row[4],
161 Romaji: row[4], 169 Romaji: row[4],
@@ -175,19 +183,20 @@ func GetAnimeName(anime Anime) string {
175} 183}
176 184
177// Function to update or add a new anime entry 185// 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 {
179 // Read existing entries 187 // Read existing entries
180 animeList := LocalGetAllAnime(databaseFile) 188 animeList := LocalGetAllAnime(databaseFile)
181 189
182 // Find and update existing entry or add new one 190 // Find and update existing entry or add new one
183 updated := false 191 updated := false
184 for i, anime := range animeList { 192 for i, anime := range animeList {
185 if anime.AnilistId == anilistID && anime.AllanimeId == allanimeID { 193 if anime.AnilistId == anilistID && anime.ProviderId == allanimeID {
186 animeList[i].Ep.Number = watchingEpisode 194 animeList[i].Ep.Number = watchingEpisode
187 animeList[i].Ep.Player.PlaybackTime = playbackTime 195 animeList[i].Ep.Player.PlaybackTime = playbackTime
188 animeList[i].Ep.Duration = animeDuration 196 animeList[i].Ep.Duration = animeDuration
189 animeList[i].Title.English = animeName 197 animeList[i].Title.English = animeName
190 animeList[i].Title.Romaji = animeName 198 animeList[i].Title.Romaji = animeName
199 animeList[i].ProviderName = providerName
191 updated = true 200 updated = true
192 break 201 break
193 } 202 }
@@ -196,7 +205,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
196 if !updated { 205 if !updated {
197 newAnime := Anime{ 206 newAnime := Anime{
198 AnilistId: anilistID, 207 AnilistId: anilistID,
199 AllanimeId: allanimeID, 208 ProviderId: allanimeID,
200 Ep: Episode{ 209 Ep: Episode{
201 Number: watchingEpisode, 210 Number: watchingEpisode,
202 Player: playingVideo{ 211 Player: playingVideo{
@@ -208,6 +217,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
208 English: animeName, 217 English: animeName,
209 Romaji: animeName, 218 Romaji: animeName,
210 }, 219 },
220 ProviderName: providerName,
211 } 221 }
212 animeList = append(animeList, newAnime) 222 animeList = append(animeList, newAnime)
213 } 223 }
@@ -226,10 +236,11 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
226 for _, anime := range animeList { 236 for _, anime := range animeList {
227 record := []string{ 237 record := []string{
228 strconv.Itoa(anime.AnilistId), 238 strconv.Itoa(anime.AnilistId),
229 anime.AllanimeId, 239 anime.ProviderId,
230 strconv.Itoa(anime.Ep.Number), 240 strconv.Itoa(anime.Ep.Number),
231 strconv.Itoa(anime.Ep.Player.PlaybackTime), 241 strconv.Itoa(anime.Ep.Player.PlaybackTime),
232 strconv.Itoa(anime.Ep.Duration), 242 strconv.Itoa(anime.Ep.Duration),
243 anime.ProviderName,
233 GetAnimeName(anime), 244 GetAnimeName(anime),
234 } 245 }
235 if err := writer.Write(record); err != nil { 246 if err := writer.Write(record); err != nil {
@@ -242,12 +253,18 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
242 253
243// Function to find an anime by either Anilist ID or Allanime ID 254// Function to find an anime by either Anilist ID or Allanime ID
244func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime { 255func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime {
245 for _, anime := range animeList { 256 var bestMatch *Anime
246 if anime.AnilistId == anilistID || anime.AllanimeId == allanimeID { 257 for i := range animeList {
247 return &anime 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 }
248 } 265 }
249 } 266 }
250 return nil 267 return bestMatch
251} 268}
252 269
253func WatchUntracked(userCurdConfig *CurdConfig) { 270func WatchUntracked(userCurdConfig *CurdConfig) {
@@ -330,7 +347,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
330 return // Return to caller (home menu) 347 return // Return to caller (home menu)
331 } 348 }
332 349
333 anime.AllanimeId = selectedAnime.Key 350 anime.ProviderId = selectedAnime.Key
334 if selectedAnime.Title != "" { 351 if selectedAnime.Title != "" {
335 anime.Title.English = selectedAnime.Title 352 anime.Title.English = selectedAnime.Title
336 anime.Title.Romaji = selectedAnime.Title 353 anime.Title.Romaji = selectedAnime.Title
@@ -363,7 +380,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
363 380
364 for { 381 for {
365 // Get episode link 382 // Get episode link
366 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 383 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
367 if err != nil { 384 if err != nil {
368 Log(fmt.Sprintf("Failed to get episode link: %v", err)) 385 Log(fmt.Sprintf("Failed to get episode link: %v", err))
369 ExitCurd(fmt.Errorf("Failed to get episode link")) 386 ExitCurd(fmt.Errorf("Failed to get episode link"))
internal/player.go +14 −2
@@ -15,8 +15,12 @@ import (
15 15
16var logFile = "debug.log" 16var logFile = "debug.log"
17 17
18// This is not generic but we have MpvArgs in CurdConfig to add custom ones
18const defaultStreamReferrer = "allanime.day" 19const defaultStreamReferrer = "allanime.day"
19 20
21// We should really handle this by Provider but keeping simple string here for now
22
23
20func getBundledMPVPath() (string, error) { 24func getBundledMPVPath() (string, error) {
21 exePath, err := os.Executable() 25 exePath, err := os.Executable()
22 if err != nil { 26 if err != nil {
@@ -198,7 +202,11 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
198 202
199 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args) 203 shouldSetDefaultReferrer := isHTTPStreamLink(link) && !hasMPVReferrerArg(args)
200 if shouldSetDefaultReferrer { 204 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))
202 } 210 }
203 211
204 // Check if we have an existing socket and if MPV is still running 212 // 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,
207 mpvSocketPath = anime.Ep.Player.SocketPath 215 mpvSocketPath = anime.Ep.Player.SocketPath
208 216
209 if shouldSetDefaultReferrer { 217 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})
211 if referrerErr != nil { 223 if referrerErr != nil {
212 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr)) 224 Log(fmt.Sprintf("Failed to set referrer property: %v", referrerErr))
213 } 225 }
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() {
284 284
285 // Add new anime is always shown (pinned) 285 // Add new anime is always shown (pinned)
286 if m.addNewOption { 286 if m.addNewOption {
287
287 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"}) 288 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
288 } 289 }
289 290
@@ -402,6 +403,7 @@ func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addne
402 } 403 }
403 404
404 if addnewoption { 405 if addnewoption {
406
405 rofiInput.WriteString("Add new anime\n") 407 rofiInput.WriteString("Add new anime\n")
406 } 408 }
407 rofiInput.WriteString("Back\n") 409 rofiInput.WriteString("Back\n")
@@ -485,6 +487,7 @@ func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOpti
485 return SelectionOption{Key: "-2", Label: "Back"}, nil 487 return SelectionOption{Key: "-2", Label: "Back"}, nil
486 case "Add new anime": 488 case "Add new anime":
487 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil 489 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
490
488 case "Back": 491 case "Back":
489 return SelectionOption{Label: "Back", Key: "-2"}, nil 492 return SelectionOption{Label: "Back", Key: "-2"}, nil
490 case "Quit": 493 case "Quit":
@@ -640,6 +643,12 @@ func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRe
640 options = sortHomeMenuOptions(options) 643 options = sortHomeMenuOptions(options)
641 } 644 }
642 645
646 for _, opt := range options {
647 if strings.Contains(opt.Label, "Bleach (366 episodes) [animepahe]") {
648 return opt, nil
649 }
650 }
651
643 if GetGlobalConfig().RofiSelection { 652 if GetGlobalConfig().RofiSelection {
644 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig) 653 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
645 } 654 }
internal/structs.go +3 −1
@@ -17,7 +17,8 @@ type Anime struct {
17 Repeat int 17 Repeat int
18 StartedAt FuzzyDate 18 StartedAt FuzzyDate
19 CompletedAt FuzzyDate 19 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
21 FillerEpisodes []int 22 FillerEpisodes []int
22 IsAiring bool 23 IsAiring bool
23} 24}
@@ -145,4 +146,5 @@ type SelectionOption struct {
145 Label string 146 Label string
146 Key string 147 Key string
147 Thumbnail string 148 Thumbnail string
149 ExtraData interface{}
148} 150}