Commit 16834a0625

16834a0625ddc72eee9a14d848c6aa0aa5c06b02

parent: c3fa51fd5f

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-27 07:44 UTC

Rofi Support Added (Beta)

Layout: unified · split

VERSION.txt +1 −1
@@ -1 +1 @@
10.0.3
\ No newline at end of file
10.0.4
\ No newline at end of file
cmd/curd/main.go +48 −42
@@ -23,14 +23,14 @@ func main() {
2323 var anime internal.Anime
2424 var user internal.User
2525
26 var homeDir string
27 if runtime.GOOS == "windows" {
28 homeDir = os.Getenv("USERPROFILE")
29 } else {
30 homeDir = os.Getenv("HOME")
31 }
26 var homeDir string
27 if runtime.GOOS == "windows" {
28 homeDir = os.Getenv("USERPROFILE")
29 } else {
30 homeDir = os.Getenv("HOME")
31 }
3232
33 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
33 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
3434
3535 // load curd userCurdConfig
3636 userCurdConfig, err := internal.LoadConfig(configFilePath)
@@ -38,6 +38,7 @@ func main() {
3838 fmt.Println("Error loading config:", err)
3939 return
4040 }
41 internal.SetGlobalConfig(&userCurdConfig)
4142
4243 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
4344 internal.ClearLogFile(logFile)
@@ -59,11 +60,12 @@ func main() {
5960 flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)")
6061 continueLast := flag.Bool("c", false, "Continue last episode")
6162 addNewAnime := flag.Bool("new", false, "Add new anime")
63 rofiSelection := flag.Bool("rofi", false, "Open selection in rofi")
6264 updateScript := flag.Bool("u", false, "Update the script")
6365 editConfig := flag.Bool("e", false, "Edit config")
6466 subFlag := flag.Bool("sub", false, "Watch sub version")
6567 dubFlag := flag.Bool("dub", false, "Watch dub version")
66
68
6769 // Custom help/usage function
6870 flag.Usage = func() {
6971 fmt.Fprintf(os.Stderr, "Curd is a CLI tool to manage anime playback with advanced features like skipping intro, outro, filler, recap, tracking progress, and integrating with Discord.\n")
@@ -72,34 +74,38 @@ func main() {
7274 }
7375
7476 flag.Parse()
75
77
7678 anime.Ep.ContinueLast = *continueLast
7779
78 if *updateScript{
80 if *updateScript {
7981 repo := "wraient/curd"
8082 fileName := "curd"
81
83
8284 if err := internal.UpdateCurd(repo, fileName); err != nil {
83 fmt.Printf("Error updating executable: %v\n", err)
85 internal.CurdOut(fmt.Sprintf("Error updating executable: %v\n", err))
8486 internal.ExitCurd(err)
8587 } else {
86 fmt.Println("Program Updated!")
88 internal.CurdOut("Program Updated!")
8789 internal.ExitCurd(nil)
8890 }
8991 }
9092
93 if *rofiSelection {
94 userCurdConfig.RofiSelection = true
95 }
96
9197 if *editConfig {
9298 internal.EditConfig(configFilePath)
9399 return
94100 }
95
101
96102 // Set SubOrDub based on the flags
97103 if *subFlag {
98104 userCurdConfig.SubOrDub = "sub"
99 } else if *dubFlag {
100 userCurdConfig.SubOrDub = "dub"
101 }
102
105 } else if *dubFlag {
106 userCurdConfig.SubOrDub = "dub"
107 }
108
103109 // Get the token from the token file
104110 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
105111 if err != nil {
@@ -110,29 +116,29 @@ func main() {
110116 fmt.Scanln(&user.Token)
111117 internal.WriteTokenToFile(user.Token, filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
112118 }
113
119
114120 // Load animes in database
115121 databaseFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt")
116122 databaseAnimes := internal.LocalGetAllAnime(databaseFile)
117
123
118124 if *addNewAnime {
119125 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
120126 internal.ExitCurd(fmt.Errorf("Added new anime!"))
121127 }
122128
123129 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
124
130
125131 temp_anime, err := internal.FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId))
126132 if err != nil {
127133 internal.Log("Error finding anime by Anilist ID: "+err.Error(), logFile)
128134 }
129
135
130136 if anime.TotalEpisodes == temp_anime.Progress {
131137 internal.Log(temp_anime.Progress, logFile)
132138 internal.Log(anime.TotalEpisodes, logFile)
133139 internal.Log(user.AnimeList, logFile)
134140 internal.Log("Rewatching anime: "+internal.GetAnimeName(anime), logFile)
135 anime.Rewatching = true
141 anime.Rewatching = true
136142 }
137143
138144 anime.Ep.Player.Speed = 1.0
@@ -168,7 +174,7 @@ func main() {
168174 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime), logFile)
169175 internal.Log(anime.Ep.Player.SocketPath, logFile)
170176 } else {
171 fmt.Println("Filler episode, skipping: ", anime.Ep.Number)
177 internal.CurdOut(fmt.Sprint("Filler episode, skipping: ", anime.Ep.Number))
172178 }
173179
174180 wg.Add(1)
@@ -184,12 +190,12 @@ func main() {
184190 // if filler episode or recap episode and skip is enabled
185191 if (userCurdConfig.SkipFiller || userCurdConfig.SkipRecap) && (anime.Ep.IsFiller || anime.Ep.IsRecap) {
186192 if anime.Ep.IsFiller && userCurdConfig.SkipFiller {
187 fmt.Println("Filler Episode, starting next episode: ", anime.Ep.Number+1)
193 internal.CurdOut(fmt.Sprint("Filler Episode, starting next episode: ", anime.Ep.Number+1))
188194 internal.Log("Filler episode detected", logFile)
189195 } else if anime.Ep.IsRecap && userCurdConfig.SkipRecap {
190 fmt.Println("Recap Episode, starting next episode: ", anime.Ep.Number+1)
196 internal.CurdOut(fmt.Sprint("Recap Episode, starting next episode: ", anime.Ep.Number+1))
191197 internal.Log("Recap episode detected", logFile)
192 }
198 }
193199 anime.Ep.Number++
194200 anime.Ep.Started = false
195201 anime.Ep.IsCompleted = true
@@ -202,7 +208,7 @@ func main() {
202208 }
203209 // Exit the skip loop
204210 close(skipLoopDone)
205 }
211 }
206212 }
207213 }()
208214
@@ -244,15 +250,15 @@ func main() {
244250 durationPos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
245251 if err != nil {
246252 internal.Log("Error getting video duration: "+err.Error(), logFile)
247 } else if durationPos != nil {
248 if duration, ok := durationPos.(float64); ok {
249 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
250 internal.Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration), logFile)
251 } else {
253 } else if durationPos != nil {
254 if duration, ok := durationPos.(float64); ok {
255 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
256 internal.Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration), logFile)
257 } else {
252258 internal.Log("Error: duration is not a float64", logFile)
253259 }
254260 }
255 break
261 break
256262 }
257263 }
258264 time.Sleep(1 * time.Second)
@@ -375,7 +381,7 @@ func main() {
375381 wg = sync.WaitGroup{}
376382
377383 if anime.Ep.IsCompleted && !anime.Rewatching {
378 go func(){
384 go func() {
379385 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1)
380386 if err != nil {
381387 internal.Log("Error updating Anilist progress: "+err.Error(), logFile)
@@ -383,11 +389,11 @@ func main() {
383389 }()
384390
385391 anime.Ep.IsCompleted = false
386 // fmt.Println(anime.Ep.Number, anime.TotalEpisodes)
392 // internal.CurdOut(anime.Ep.Number, anime.TotalEpisodes, &userCurdConfig)
387393 if anime.Ep.Number-1 == anime.TotalEpisodes && userCurdConfig.ScoreOnCompletion {
388394 anime.Ep.Number = anime.Ep.Number - 1
389395 var userScore float64
390 fmt.Println("Completed anime.")
396 internal.CurdOut("Completed anime.")
391397 fmt.Println("Rate this anime: ")
392398 fmt.Scanln(&userScore)
393399 internal.RateAnime(user.Token, anime.AnilistId, userScore)
@@ -397,7 +403,7 @@ func main() {
397403 }
398404 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes {
399405 anime.Ep.Number = anime.Ep.Number - 1
400 fmt.Println("Completed anime. (Rewatching so no scoring)")
406 internal.CurdOut("Completed anime. (Rewatching so no scoring)")
401407 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
402408 internal.ExitCurd(nil)
403409 }
@@ -411,9 +417,9 @@ func main() {
411417 internal.ExitCurd(nil)
412418 }
413419 }
414
415 fmt.Println("Starting next episode: "+fmt.Sprint(anime.Ep.Number))
416 anime.Ep.Started = false
420
421 internal.CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
422 anime.Ep.Started = false
417423
418424 }
419}
\ No newline at end of file
425}
go.mod +5
@@ -5,6 +5,7 @@ go 1.23.2
55require (
66 github.com/Microsoft/go-winio v0.6.2
77 github.com/charmbracelet/bubbletea v1.1.1
8 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4
89 github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2
910)
1011
@@ -14,6 +15,8 @@ require (
1415 github.com/charmbracelet/x/ansi v0.2.3 // indirect
1516 github.com/charmbracelet/x/term v0.2.0 // indirect
1617 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
18 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
19 github.com/godbus/dbus/v5 v5.1.0 // indirect
1720 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
1821 github.com/mattn/go-isatty v0.0.20 // indirect
1922 github.com/mattn/go-localereader v0.0.1 // indirect
@@ -21,7 +24,9 @@ require (
2124 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
2225 github.com/muesli/cancelreader v0.2.2 // indirect
2326 github.com/muesli/termenv v0.15.2 // indirect
27 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
2428 github.com/rivo/uniseg v0.4.7 // indirect
29 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
2530 golang.org/x/sync v0.8.0 // indirect
2631 golang.org/x/sys v0.24.0 // indirect
2732 golang.org/x/text v0.14.0 // indirect
go.sum +10
@@ -12,6 +12,12 @@ github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4h
1212github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
1313github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
1414github.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=
16github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4/go.mod h1:0W7dI87PvXJ1Sjs0QPvWXKcQmNERY77e8l7GFhZB/s4=
17github.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=
19github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
20github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
1521github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2 h1:9qOViOQGFIP5ar+2NorfAIsfuADEKXtklySC0zNnYf4=
1622github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2/go.mod h1:nGaW7CGfNZnhtiFxMpc4OZdqIexGXjUlBnlmpZmjEKA=
1723github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
@@ -28,9 +34,13 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
2834github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
2935github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
3036github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
37github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ=
38github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
3139github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
3240github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
3341github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
42github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
43github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
3444golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
3545golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
3646golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
internal/anilist.go +4 −4
@@ -177,7 +177,7 @@ func AddAnimeToWatchingList(animeID int, token string) error {
177177 return fmt.Errorf("failed to add anime: %w", err)
178178 }
179179
180 fmt.Printf("Anime with ID %d has been added to your watching list.\n", animeID)
180 CurdOut(fmt.Sprintf("Anime with ID %d has been added to your watching list.", animeID))
181181 return nil
182182}
183183
@@ -344,7 +344,7 @@ func UpdateAnimeProgress(token string, mediaID, progress int) error {
344344 return err
345345 }
346346
347 fmt.Println("Anime progress updated! Latest watched episode:", progress)
347 CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
348348 return nil
349349}
350350
@@ -375,7 +375,7 @@ func RateAnime(token string, mediaID int, score float64) error {
375375 return err
376376 }
377377
378 fmt.Printf("Successfully rated anime (mediaId: %d) with score: %.2f\n", mediaID, score)
378 CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
379379 return nil
380380}
381381
@@ -456,7 +456,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
456456 // Access the list entries in the input map
457457 if input["data"] == nil {
458458 Log("Anilist request failed", logFile)
459 fmt.Println("Anilist request failed")
459 CurdOut("Anilist request failed")
460460 ExitCurd(fmt.Errorf("Anilist request failed"))
461461 return animeList
462462 }
internal/config.go +33 −20
@@ -22,11 +22,43 @@ type CurdConfig struct {
2222 SkipEd bool `config:"SkipEd"`
2323 SkipFiller bool `config:"SkipFiller"`
2424 SkipRecap bool `config:"SkipRecap"`
25 RofiSelection bool `config:"RofiSelection"`
2526 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
2627 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
2728 DiscordPresence bool `config:"DiscordPresence"`
2829}
2930
31// Default configuration values as a map
32func defaultConfigMap() map[string]string {
33 return map[string]string{
34 "Player": "mpv",
35 "StoragePath": "$HOME/.local/share/curd",
36 "SubsLanguage": "english",
37 "SubOrDub": "sub",
38 "PercentageToMarkComplete": "85",
39 "NextEpisodePrompt": "false",
40 "SkipOp": "true",
41 "SkipEd": "true",
42 "SkipFiller": "true",
43 "SkipRecap": "true",
44 "RofiSelection": "false",
45 "ScoreOnCompletion": "true",
46 "SaveMpvSpeed": "true",
47 "DiscordPresence": "true",
48 }
49}
50
51var globalConfig *CurdConfig
52
53func SetGlobalConfig(config *CurdConfig) {
54 globalConfig = config
55}
56
57func GetGlobalConfig() *CurdConfig {
58 return globalConfig
59}
60
61
3062// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
3163func LoadConfig(configPath string) (CurdConfig, error) {
3264 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
@@ -34,7 +66,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
3466 // Check if config file exists
3567 if _, err := os.Stat(configPath); os.IsNotExist(err) {
3668 // Create the config file with default values if it doesn't exist
37 fmt.Println("Config file not found. Creating default config...")
69 CurdOut("Config file not found. Creating default config...")
3870 if err := createDefaultConfig(configPath); err != nil {
3971 return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
4072 }
@@ -69,25 +101,6 @@ func LoadConfig(configPath string) (CurdConfig, error) {
69101 return config, nil
70102}
71103
72// Default configuration values as a map
73func defaultConfigMap() map[string]string {
74 return map[string]string{
75 "Player": "mpv",
76 "StoragePath": "$HOME/.local/share/curd",
77 "SubsLanguage": "english",
78 "SubOrDub": "sub",
79 "PercentageToMarkComplete": "85",
80 "NextEpisodePrompt": "false",
81 "SkipOp": "true",
82 "SkipEd": "true",
83 "SkipFiller": "true",
84 "SkipRecap": "true",
85 "ScoreOnCompletion": "true",
86 "SaveMpvSpeed": "true",
87 "DiscordPresence": "true",
88 }
89}
90
91104// Create a config file with default values in key=value format
92105// Ensure the directory exists before creating the file
93106func createDefaultConfig(path string) error {
internal/curd.go +43 −16
@@ -7,6 +7,7 @@ import (
77 "net/http"
88 "os"
99 "os/exec"
10 "github.com/gen2brain/beeep"
1011 "path/filepath"
1112 "regexp"
1213 "runtime"
@@ -47,11 +48,11 @@ func EditConfig(configFilePath string) {
4748 // Run the editor command
4849 err := cmd.Run()
4950 if err != nil {
50 fmt.Printf("Error opening config file: %v\n", err)
51 CurdOut(fmt.Sprintf("Error opening config file: %v", err))
5152 return
5253 }
5354
54 fmt.Println("Config file edited successfully.")
55 CurdOut("Config file edited successfully.")
5556}
5657
5758// ClearLogFile removes all contents from the specified log file
@@ -112,21 +113,47 @@ func RestoreScreen() {
112113
113114func ExitCurd(err error) {
114115 RestoreScreen()
116 CurdOut("Have a great day!")
115117 if err != nil {
116 fmt.Println(err)
118 CurdOut(err)
117119 if runtime.GOOS == "windows" {
118120 fmt.Println("Press Enter to exit")
119121 var wait string
120122 fmt.Scanln(&wait)
121123 os.Exit(1)
122124 } else {
123 fmt.Println("Have a great day!")
124125 os.Exit(1)
125126 }
126127 }
127128 os.Exit(0)
128129}
129130
131func CurdOut(data interface{}) {
132 userCurdConfig := GetGlobalConfig()
133 if !userCurdConfig.RofiSelection {
134 fmt.Println(fmt.Sprintf("%v", data))
135 } else {
136 switch runtime.GOOS {
137 case "windows":
138 err := beeep.Notify(
139 "Curd",
140 fmt.Sprintf("%v", data),
141 "",
142 )
143
144 if err != nil {
145 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
146 }
147 case "linux":
148 cmd := exec.Command("notify-send", fmt.Sprintf("%v", data))
149 err := cmd.Run()
150 if err != nil {
151 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
152 }
153 }
154 }
155}
156
130157func UpdateCurd(repo, fileName string) error {
131158 // Get the path of the currently running executable
132159 executablePath, err := os.Executable()
@@ -177,7 +204,7 @@ func UpdateCurd(repo, fileName string) error {
177204 if err := os.Rename(tmpPath, executablePath); err != nil {
178205 return fmt.Errorf("failed to replace the current executable: %v", err)
179206 }
180 fmt.Println("Downloaded curd executable to", executablePath)
207 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
181208
182209 if runtime.GOOS != "windows" {
183210 // Ensure the new file has executable permissions
@@ -190,7 +217,7 @@ func UpdateCurd(repo, fileName string) error {
190217}
191218
192219func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
193 fmt.Println("Enter the anime name:")
220 CurdOut("Enter the anime name:")
194221 var query string
195222 fmt.Scanln(&query)
196223 animeMap, err := SearchAnimeAnilist(query, user.Token)
@@ -318,7 +345,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
318345
319346 // If unable to get Allanime id automatically get manually
320347 if anime.AllanimeId == "" {
321 fmt.Println("Failed to automatically select anime")
348 CurdOut("Failed to automatically select anime")
322349 selectedAllanimeAnime, err := DynamicSelect(animeList)
323350 if err != nil {
324351 // fmt.Println("No anime available")
@@ -357,17 +384,17 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
357384 }
358385
359386 if anime.TotalEpisodes == 0 { // If failed to get anime data
360 fmt.Println("Failed to get anime data. Attempting to retrieve from anime list.")
387 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
361388 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
362389 if err != nil {
363 fmt.Println("Failed to retrieve anime list:", err)
390 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
364391 } else {
365392 for allanimeId, label := range animeList {
366393 if allanimeId == anime.AllanimeId {
367394 // Extract total episodes from the label
368395 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
369396 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
370 fmt.Printf("Retrieved total episodes: %d\n", anime.TotalEpisodes)
397 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
371398 break
372399 }
373400 }
@@ -375,8 +402,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
375402 }
376403
377404 if anime.TotalEpisodes == 0 {
378 fmt.Println("Still unable to determine total episodes.")
379 fmt.Println("Your AniList progress:", selectedAnilistAnime.Progress)
405 CurdOut("Still unable to determine total episodes.")
406 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
380407 fmt.Print("Enter the episode you want to start from: ")
381408 var episodeNumber int
382409 fmt.Scanln(&episodeNumber)
@@ -425,15 +452,15 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
425452 // If unable to get episode link automatically get manually
426453 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
427454 if err != nil {
428 fmt.Println("No episode list found")
455 CurdOut("No episode list found")
429456 RestoreScreen()
430457 os.Exit(1)
431458 }
432 fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
459 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
433460 fmt.Scanln(&anime.Ep.Number)
434461 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
435462 if err != nil {
436 fmt.Println("Failed to get episode link")
463 CurdOut("Failed to get episode link")
437464 os.Exit(1)
438465 }
439466 // anime.Ep.Links = link
@@ -441,7 +468,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
441468 anime.Ep.Links = link
442469
443470 if len(anime.Ep.Links) == 0 {
444 fmt.Println("No episode links found")
471 CurdOut("No episode links found")
445472 os.Exit(1)
446473 }
447474
internal/localTracking.go +14 −14
@@ -12,7 +12,7 @@ import (
1212func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, watchingTime int, animeDuration int, animeName string) {
1313 file, err := os.OpenFile(databaseFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
1414 if err != nil {
15 fmt.Println("Error opening file:", err)
15 CurdOut(fmt.Sprintf("Error opening file: %v", err))
1616 return
1717 }
1818 defer file.Close()
@@ -29,9 +29,9 @@ func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchi
2929 animeName,
3030 })
3131 if err != nil {
32 fmt.Println("Error writing to file:", err)
32 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
3333 } else {
34 fmt.Println("Written to file")
34 CurdOut("Written to file")
3535 }
3636}
3737
@@ -40,7 +40,7 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
4040 animeList := [][]string{}
4141 file, err := os.Open(databaseFile)
4242 if err != nil {
43 fmt.Println("Error opening file:", err)
43 CurdOut(fmt.Sprintf("Error opening file: %v", err))
4444 return
4545 }
4646 defer file.Close()
@@ -48,7 +48,7 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
4848 reader := csv.NewReader(file)
4949 records, err := reader.ReadAll()
5050 if err != nil {
51 fmt.Println("Error reading file:", err)
51 CurdOut(fmt.Sprintf("Error reading file: %v", err))
5252 return
5353 }
5454
@@ -63,7 +63,7 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
6363 // Write the filtered list back to the file
6464 fileWrite, err := os.OpenFile(databaseFile, os.O_WRONLY|os.O_TRUNC, 0644)
6565 if err != nil {
66 fmt.Println("Error opening file for writing:", err)
66 CurdOut(fmt.Sprintf("Error opening file for writing: %v", err))
6767 return
6868 }
6969 defer fileWrite.Close()
@@ -73,7 +73,7 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
7373
7474 err = writer.WriteAll(animeList)
7575 if err != nil {
76 fmt.Println("Error writing to file:", err)
76 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
7777 }
7878}
7979
@@ -84,14 +84,14 @@ func LocalGetAllAnime(databaseFile string) []Anime {
8484 // Ensure the directory exists
8585 dir := filepath.Dir(databaseFile)
8686 if err := os.MkdirAll(dir, 0755); err != nil {
87 fmt.Println("Error creating directory:", err)
87 CurdOut(fmt.Sprintf("Error creating directory: %v", err))
8888 return animeList
8989 }
9090
9191 // Open the file, create if it doesn't exist
9292 file, err := os.OpenFile(databaseFile, os.O_RDONLY|os.O_CREATE, 0644)
9393 if err != nil {
94 fmt.Println("Error opening or creating file:", err)
94 CurdOut(fmt.Sprintf("Error opening or creating file: %v", err))
9595 return animeList
9696 }
9797 defer file.Close()
@@ -99,7 +99,7 @@ func LocalGetAllAnime(databaseFile string) []Anime {
9999 // If the file was just created, it will be empty, so return an empty list
100100 fileInfo, err := file.Stat()
101101 if err != nil {
102 fmt.Println("Error getting file info:", err)
102 CurdOut(fmt.Sprintf("Error getting file info: %v", err))
103103 return animeList
104104 }
105105 if fileInfo.Size() == 0 {
@@ -109,7 +109,7 @@ func LocalGetAllAnime(databaseFile string) []Anime {
109109 reader := csv.NewReader(file)
110110 records, err := reader.ReadAll()
111111 if err != nil {
112 fmt.Println("Error reading file:", err)
112 CurdOut(fmt.Sprintf("Error reading file: %v", err))
113113 return animeList
114114 }
115115
@@ -126,7 +126,7 @@ func LocalGetAllAnime(databaseFile string) []Anime {
126126// Function to parse a single row of anime data
127127func parseAnimeRow(row []string) *Anime {
128128 if len(row) < 5 {
129 fmt.Printf("Invalid row format: %v\n", row)
129 CurdOut(fmt.Sprintf("Invalid row format: %v", row))
130130 return nil
131131 }
132132
@@ -211,7 +211,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
211211 // Write updated list back to file
212212 file, err := os.Create(databaseFile)
213213 if err != nil {
214 fmt.Println("Error creating file:", err)
214 CurdOut(fmt.Sprintf("Error creating file: %v", err))
215215 return err
216216 }
217217 defer file.Close()
@@ -229,7 +229,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
229229 GetAnimeName(anime),
230230 }
231231 if err := writer.Write(record); err != nil {
232 fmt.Println("Error writing record:", err)
232 CurdOut(fmt.Sprintf("Error writing record: %v", err))
233233 }
234234 }
235235
internal/player.go +2 −2
@@ -56,7 +56,7 @@ func StartVideo(link string, args []string) (string, error) {
5656 // Get the path to mpv.exe for Windows
5757 mpvPath, err := getMPVPath()
5858 if err != nil {
59 fmt.Println("Error: Failed to get MPV path")
59 CurdOut("Error: Failed to get MPV path")
6060 Log("Failed to get mpv path.", logFile)
6161 return "", err
6262 }
@@ -71,7 +71,7 @@ func StartVideo(link string, args []string) (string, error) {
7171 // Start the mpv process
7272 err = command.Start()
7373 if err != nil {
74 fmt.Println("Error: Failed to start mpv process")
74 CurdOut("Error: Failed to start mpv process")
7575 return "", fmt.Errorf("failed to start mpv: %w", err)
7676 }
7777 return mpvSocketPath, nil
internal/selection_menu.go +62 −1
@@ -1,7 +1,9 @@
11package internal
22
33import (
4 "bytes"
45 "fmt"
6 "os/exec"
57 "sort"
68 "strings"
79
@@ -74,7 +76,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
7476 }
7577 case "enter":
7678 if m.filteredKeys[m.selected].Key == "add_new" {
77 fmt.Println("Adding a new anime...")
79 CurdOut("Adding a new anime...")
7880 m.filteredKeys[m.selected] = SelectionOption{"add_new", "0"}
7981 return m, tea.Quit
8082 }
@@ -168,8 +170,67 @@ func (m *Model) filterOptions() {
168170 })
169171}
170172
173func RofiSelect(options map[string]string) (SelectionOption, error) {
174 // Create a slice to store the options in the order we want
175 var optionsList []string
176 for _, value := range options {
177 optionsList = append(optionsList, value)
178 }
179
180 // Sort the options alphabetically
181 sort.Strings(optionsList)
182
183 // Add "Add new anime" and "Quit" options
184 optionsList = append(optionsList, "Add new anime", "Quit")
185
186 // Join all options into a single string, separated by newlines
187 optionsString := strings.Join(optionsList, "\n")
188
189 // Prepare the Rofi command
190 cmd := exec.Command("rofi", "-dmenu", "-i", "-p", "Select an anime")
191
192 // Set up pipes for input and output
193 cmd.Stdin = strings.NewReader(optionsString)
194 var out bytes.Buffer
195 cmd.Stdout = &out
196
197 // Run the command
198 err := cmd.Run()
199 if err != nil {
200 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
201 }
202
203 // Get the selected option
204 selected := strings.TrimSpace(out.String())
205
206 // Handle special cases
207 switch selected {
208 case "":
209 return SelectionOption{}, fmt.Errorf("no selection made")
210 case "Add new anime":
211 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
212 case "Quit":
213 return SelectionOption{Label: "Quit", Key: "-1"}, nil
214 }
215
216 // Find the key for the selected value
217 for key, value := range options {
218 if value == selected {
219 return SelectionOption{Label: value, Key: key}, nil
220 }
221 }
222
223 // If we get here, the selected option wasn't found in the original map
224 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
225}
226
171227// DynamicSelect displays a simple selection prompt without extra features
172228func DynamicSelect(options map[string]string) (SelectionOption, error) {
229
230 if GetGlobalConfig().RofiSelection {
231 return RofiSelect(options)
232 }
233
173234 model := &Model{
174235 options: options,
175236 filteredKeys: make([]SelectionOption, 0),