Commit 69322bef64

69322bef6432ca675ce8de8472709a575f6323c9

parent: efcb745f9c

Unsigned

Wraient <wraient.911@gmail.com> · 2025-02-17 15:22 UTC

chore: Globe variables

- Logfile is a global variable, no need to specify it in every call
- Anime is an global variable any function can use it without being passed

Layout: unified · split

cmd/curd/main.go +57 −54
@@ -20,6 +20,8 @@ func main() {
2020 var anime internal.Anime
2121 var user internal.User
2222
23 internal.SetGlobalAnime(&anime)
24
2325 var homeDir string
2426 if runtime.GOOS == "windows" {
2527 homeDir = os.Getenv("USERPROFILE")
@@ -42,6 +44,7 @@ func main() {
4244 defer internal.RestoreScreen()
4345
4446 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
47 internal.SetGlobalLogFile(logFile)
4548 internal.ClearLogFile(logFile)
4649
4750 // Flags configured here cause userconfig needs to be changed.
@@ -137,7 +140,7 @@ func main() {
137140 // Get the token from the token file
138141 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
139142 if err != nil {
140 internal.Log("Error reading token", logFile)
143 internal.Log("Error reading token")
141144 }
142145 if user.Token == "" {
143146 internal.ChangeToken(&userCurdConfig, &user)
@@ -154,7 +157,7 @@ func main() {
154157 // Call the function to check and download files
155158 err := internal.CheckAndDownloadFiles(os.ExpandEnv(userCurdConfig.StoragePath), filesToCheck)
156159 if err != nil {
157 internal.Log(fmt.Sprintf("Error checking and downloading files: %v\n", err), logFile)
160 internal.Log(fmt.Sprintf("Error checking and downloading files: %v\n", err))
158161 internal.CurdOut(fmt.Sprintf("Error checking and downloading files: %v\n", err))
159162 internal.ExitCurd(err)
160163 }
@@ -165,22 +168,22 @@ func main() {
165168 databaseAnimes := internal.LocalGetAllAnime(databaseFile)
166169
167170 if *addNewAnime {
168 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
171 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes)
169172 // internal.ExitCurd(fmt.Errorf("Added new anime!"))
170173 }
171174
172 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
175 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes)
173176
174177 temp_anime, err := internal.FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId))
175178 if err != nil {
176 internal.Log("Error finding anime by Anilist ID: "+err.Error(), logFile)
179 internal.Log("Error finding anime by Anilist ID: "+err.Error())
177180 }
178181
179182 if anime.TotalEpisodes == temp_anime.Progress {
180 internal.Log(temp_anime.Progress, logFile)
181 internal.Log(anime.TotalEpisodes, logFile)
182 internal.Log(user.AnimeList, logFile)
183 internal.Log("Rewatching anime: "+internal.GetAnimeName(anime), logFile)
183 internal.Log(temp_anime.Progress)
184 internal.Log(anime.TotalEpisodes)
185 internal.Log(user.AnimeList)
186 internal.Log("Rewatching anime: "+internal.GetAnimeName(anime))
184187 anime.Rewatching = true
185188 }
186189
@@ -192,7 +195,7 @@ func main() {
192195 if anime.MalId == 0 {
193196 malID, err := internal.GetAnimeMalID(anime.AnilistId)
194197 if err != nil {
195 internal.Log("Error getting MAL ID: "+err.Error(), logFile)
198 internal.Log("Error getting MAL ID: "+err.Error())
196199 return
197200 }
198201 anime.MalId = malID
@@ -200,10 +203,10 @@ func main() {
200203
201204 fillerList, err := internal.FetchFillerEpisodes(anime.MalId)
202205 if err != nil {
203 internal.Log("Error getting filler list: "+err.Error(), logFile)
206 internal.Log("Error getting filler list: "+err.Error())
204207 } else {
205208 anime.FillerEpisodes = fillerList
206 internal.Log("Filler list fetched successfully", logFile)
209 internal.Log("Filler list fetched successfully")
207210 // fmt.Println("Filler episodes: ", anime.FillerEpisodes)
208211 }
209212 }()
@@ -211,7 +214,7 @@ func main() {
211214 // Main loop (loop to keep starting new episodes)
212215 for {
213216
214 internal.Log(anime, logFile)
217 internal.Log(anime)
215218
216219 // Create a channel to signal when to exit the skip loop
217220 var wg sync.WaitGroup
@@ -221,16 +224,16 @@ func main() {
221224 if userCurdConfig.DiscordPresence {
222225 anime.MalId, anime.CoverImage, err = internal.GetAnimeIDAndImage(anime.AnilistId)
223226 if err != nil {
224 internal.Log("Error getting anime ID and image: "+err.Error(), logFile)
227 internal.Log("Error getting anime ID and image: "+err.Error())
225228 }
226229 err = internal.DiscordPresence(discordClientId, anime, false)
227230 if err != nil {
228 internal.Log("Error setting Discord presence: "+err.Error(), logFile)
231 internal.Log("Error setting Discord presence: "+err.Error())
229232 }
230233 } else if anime.MalId == 0 {
231234 anime.MalId, err = internal.GetAnimeMalID(anime.AnilistId)
232235 if err != nil {
233 internal.Log("Error getting anime MAL ID: "+err.Error(), logFile)
236 internal.Log("Error getting anime MAL ID: "+err.Error())
234237 }
235238 }
236239
@@ -239,7 +242,7 @@ func main() {
239242 // Check if current episode is filler/recap
240243 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime)
241244 if err != nil {
242 internal.Log("Error getting episode data, assuming non-filler: "+err.Error(), logFile)
245 internal.Log("Error getting episode data, assuming non-filler: "+err.Error())
243246 break // Break the loop and continue with playback
244247 }
245248
@@ -276,9 +279,9 @@ func main() {
276279 }
277280
278281 // Now start playback for the non-filler episode
279 anime.Ep.Player.SocketPath = internal.StartCurd(&userCurdConfig, &anime, logFile)
280 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime), logFile)
281 internal.Log(anime.Ep.Player.SocketPath, logFile)
282 anime.Ep.Player.SocketPath = internal.StartCurd(&userCurdConfig, &anime)
283 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime))
284 internal.Log(anime.Ep.Player.SocketPath)
282285
283286 wg.Add(1)
284287 // Get episode data
@@ -286,28 +289,28 @@ func main() {
286289 defer wg.Done()
287290 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime)
288291 if err != nil {
289 internal.Log("Error getting episode data: "+err.Error(), logFile)
292 internal.Log("Error getting episode data: "+err.Error())
290293 } else {
291 internal.Log(anime, logFile)
294 internal.Log(anime)
292295
293296 // if filler episode or recap episode and skip is enabled
294297 if (anime.Ep.IsFiller && userCurdConfig.SkipFiller) || (anime.Ep.IsRecap && userCurdConfig.SkipRecap) {
295298 if anime.Ep.IsFiller && userCurdConfig.SkipFiller {
296299 internal.CurdOut(fmt.Sprint("Filler Episode, starting next episode: ", anime.Ep.Number+1))
297 internal.Log("Filler episode detected", logFile)
300 internal.Log("Filler episode detected")
298301 } else if anime.Ep.IsRecap && userCurdConfig.SkipRecap {
299302 internal.CurdOut(fmt.Sprint("Recap Episode, starting next episode: ", anime.Ep.Number+1))
300 internal.Log("Recap episode detected", logFile)
303 internal.Log("Recap episode detected")
301304 }
302305 anime.Ep.Number++
303306 anime.Ep.Started = false
304307 anime.Ep.IsCompleted = true
305 internal.Log("Skipping filler episode, starting next.", logFile)
308 internal.Log("Skipping filler episode, starting next.")
306309 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
307310 // Send command to close MPV
308311 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
309312 if err != nil {
310 internal.Log("Error closing MPV: "+err.Error(), logFile)
313 internal.Log("Error closing MPV: "+err.Error())
311314 }
312315 // Exit the skip loop
313316 close(skipLoopDone)
@@ -327,7 +330,7 @@ func main() {
327330 default:
328331 isPaused, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "pause"})
329332 if err != nil {
330 internal.Log("Error getting pause status: "+err.Error(), logFile)
333 internal.Log("Error getting pause status: "+err.Error())
331334 }
332335 if isPaused == nil {
333336 isPaused = true
@@ -336,7 +339,7 @@ func main() {
336339 }
337340 err = internal.DiscordPresence(discordClientId, anime, isPaused.(bool))
338341 if err != nil {
339 // internal.Log("Error setting Discord presence: "+err.Error(), logFile)
342 // internal.Log("Error setting Discord presence: "+err.Error())
340343 }
341344 time.Sleep(1 * time.Second)
342345 }
@@ -348,9 +351,9 @@ func main() {
348351 go func() {
349352 err = internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime)
350353 if err != nil {
351 internal.Log("Error getting and parsing AniSkip data: "+err.Error(), logFile)
354 internal.Log("Error getting and parsing AniSkip data: "+err.Error())
352355 }
353 internal.Log(anime.Ep.SkipTimes, logFile)
356 internal.Log(anime.Ep.SkipTimes)
354357 }()
355358
356359 // Get video duration
@@ -361,13 +364,13 @@ func main() {
361364 // Get video duration
362365 durationPos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
363366 if err != nil {
364 internal.Log("Error getting video duration: "+err.Error(), logFile)
367 internal.Log("Error getting video duration: "+err.Error())
365368 } else if durationPos != nil {
366369 if duration, ok := durationPos.(float64); ok {
367370 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
368 internal.Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration), logFile)
371 internal.Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration))
369372 } else {
370 internal.Log("Error: duration is not a float64", logFile)
373 internal.Log("Error: duration is not a float64")
371374 }
372375 }
373376 break
@@ -389,32 +392,32 @@ func main() {
389392 time.Sleep(1 * time.Second)
390393
391394 // Get current playback time
392 // internal.Log("Getting playback time "+anime.Ep.Player.SocketPath, logFile)
395 // internal.Log("Getting playback time "+anime.Ep.Player.SocketPath)
393396 timePos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
394397 if err != nil {
395 internal.Log("Error getting playback time: "+err.Error(), logFile)
398 internal.Log("Error getting playback time: "+err.Error())
396399
397400 // Check if the error is due to invalid JSON
398401 // User closed the video
399402 if anime.Ep.Started {
400403 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
401404 // Episode is completed
402 internal.Log(fmt.Sprint(percentageWatched), logFile)
403 internal.Log(fmt.Sprint(anime.Ep.Player.Speed), logFile)
404 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime), logFile)
405 internal.Log(fmt.Sprint(anime.Ep.Duration), logFile)
406 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete), logFile)
405 internal.Log(fmt.Sprint(percentageWatched))
406 internal.Log(fmt.Sprint(anime.Ep.Player.Speed))
407 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
408 internal.Log(fmt.Sprint(anime.Ep.Duration))
409 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
407410 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
408411 anime.Ep.Number++
409412 anime.Ep.Started = false
410 internal.Log("Completed episode, starting next.", logFile)
413 internal.Log("Completed episode, starting next.")
411414 anime.Ep.IsCompleted = true
412415 // Exit the skip loop
413416 close(skipLoopDone)
414417 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
415 internal.Log("Received invalid JSON response, continuing...", logFile)
418 internal.Log("Received invalid JSON response, continuing...")
416419 } else {
417 internal.Log("Episode is not completed, exiting", logFile)
420 internal.Log("Episode is not completed, exiting")
418421 internal.ExitCurd(nil)
419422 }
420423 }
@@ -429,7 +432,7 @@ func main() {
429432 speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed}
430433 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd)
431434 if err != nil {
432 internal.Log("Error setting playback speed: "+err.Error(), logFile)
435 internal.Log("Error setting playback speed: "+err.Error())
433436 }
434437 }
435438 }
@@ -442,7 +445,7 @@ func main() {
442445
443446 animePosition, ok := timePos.(float64)
444447 if !ok {
445 internal.Log("Error: timePos is not a float64", logFile)
448 internal.Log("Error: timePos is not a float64")
446449 continue
447450 }
448451
@@ -450,20 +453,20 @@ func main() {
450453 // Update Local Database
451454 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
452455 if err != nil {
453 internal.Log("Error updating local database: "+err.Error(), logFile)
456 internal.Log("Error updating local database: "+err.Error())
454457 } else {
455458 // internal.Log(fmt.Sprintf("Updated database: AnilistId=%d, AllanimeId=%s, EpNumber=%d, PlaybackTime=%d",
456 // anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime), logFile)
459 // anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime))
457460 }
458461 }
459462
460463 // Check if anything is playing, if nothing is playing and episode was started, start next episode
461464 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath)
462465 if err != nil {
463 internal.Log("Error checking playback status: "+err.Error(), logFile)
466 internal.Log("Error checking playback status: "+err.Error())
464467 } else if !hasPlayback && anime.Ep.Started {
465468 // Nothing is playing, start next episode
466 internal.Log("Nothing playing in MPV, starting next episode", logFile)
469 internal.Log("Nothing playing in MPV, starting next episode")
467470 anime.Ep.Number++
468471 anime.Ep.Started = false
469472 anime.Ep.IsCompleted = true
@@ -497,7 +500,7 @@ func main() {
497500 if err == nil && anime.Ep.Started {
498501 anime.Ep.Player.Speed, err = internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath)
499502 if err != nil {
500 internal.Log("Failed to get mpv speed "+err.Error(), logFile)
503 internal.Log("Failed to get mpv speed "+err.Error())
501504 }
502505 }
503506 }
@@ -516,7 +519,7 @@ func main() {
516519 go func() {
517520 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1)
518521 if err != nil {
519 internal.Log("Error updating Anilist progress: "+err.Error(), logFile)
522 internal.Log("Error updating Anilist progress: "+err.Error())
520523 }
521524 }()
522525
@@ -527,13 +530,13 @@ func main() {
527530 // Get updated anime data to check if it's still airing
528531 updatedAnime, err := internal.GetAnimeDataByID(anime.AnilistId, user.Token)
529532 if err != nil {
530 internal.Log("Error getting updated anime data: "+err.Error(), logFile)
533 internal.Log("Error getting updated anime data: "+err.Error())
531534 } else if !updatedAnime.IsAiring {
532535 anime.Ep.Number = anime.Ep.Number - 1
533536 internal.CurdOut("Completed anime.")
534537 err = internal.RateAnime(user.Token, anime.AnilistId)
535538 if err != nil {
536 internal.Log("Error rating anime: "+err.Error(), logFile)
539 internal.Log("Error rating anime: "+err.Error())
537540 internal.CurdOut("Error rating anime: " + err.Error())
538541 }
539542 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
@@ -560,7 +563,7 @@ func main() {
560563 // Send command to close MPV
561564 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
562565 if err != nil {
563 internal.Log("Error closing MPV: "+err.Error(), logFile)
566 internal.Log("Error closing MPV: "+err.Error())
564567 }
565568 internal.ExitCurd(nil)
566569 }
go.mod +10 −10
@@ -1,34 +1,34 @@
11module github.com/wraient/curd
22
3go 1.23.2
3go 1.24.0
44
55require (
66 github.com/Microsoft/go-winio v0.6.2
7 github.com/charmbracelet/bubbletea v1.1.1
8 github.com/charmbracelet/lipgloss v0.13.0
7 github.com/charmbracelet/bubbletea v1.3.3
8 github.com/charmbracelet/lipgloss v1.0.0
99 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4
10 github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2
10 github.com/wraient/rich-go v0.0.0-20250215175626-21ded92fb65a
1111)
1212
1313require (
1414 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
15 github.com/charmbracelet/x/ansi v0.2.3 // indirect
16 github.com/charmbracelet/x/term v0.2.0 // indirect
15 github.com/charmbracelet/x/ansi v0.8.0 // indirect
16 github.com/charmbracelet/x/term v0.2.1 // indirect
1717 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
1818 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
1919 github.com/godbus/dbus/v5 v5.1.0 // indirect
2020 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
2121 github.com/mattn/go-isatty v0.0.20 // indirect
2222 github.com/mattn/go-localereader v0.0.1 // indirect
23 github.com/mattn/go-runewidth v0.0.15 // indirect
23 github.com/mattn/go-runewidth v0.0.16 // indirect
2424 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
2525 github.com/muesli/cancelreader v0.2.2 // indirect
2626 github.com/muesli/termenv v0.15.2 // indirect
2727 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
2828 github.com/rivo/uniseg v0.4.7 // indirect
2929 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
30 golang.org/x/sync v0.8.0 // indirect
31 golang.org/x/sys v0.24.0 // indirect
32 golang.org/x/text v0.14.0 // indirect
30 golang.org/x/sync v0.11.0 // indirect
31 golang.org/x/sys v0.30.0 // indirect
32 golang.org/x/text v0.3.8 // indirect
3333 gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
3434)
go.sum +18 −18
@@ -2,14 +2,14 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
22github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
33github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
44github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
5github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY=
6github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4=
7github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw=
8github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY=
9github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY=
10github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
11github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=
12github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
5github.com/charmbracelet/bubbletea v1.3.3 h1:WpU6fCY0J2vDWM3zfS3vIDi/ULq3SYphZhkAGGvmEUY=
6github.com/charmbracelet/bubbletea v1.3.3/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo=
7github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg=
8github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo=
9github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
10github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
11github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
12github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
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=
1515github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI=
@@ -18,16 +18,14 @@ github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/Oq
1818github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=
1919github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
2020github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
21github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2 h1:9qOViOQGFIP5ar+2NorfAIsfuADEKXtklySC0zNnYf4=
22github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2/go.mod h1:nGaW7CGfNZnhtiFxMpc4OZdqIexGXjUlBnlmpZmjEKA=
2321github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
2422github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
2523github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
2624github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
2725github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
2826github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
29github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
30github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
27github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
28github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
3129github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
3230github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
3331github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
@@ -41,13 +39,15 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
4139github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
4240github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
4341github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
44golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
45golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
42github.com/wraient/rich-go v0.0.0-20250215175626-21ded92fb65a h1:J6QBl/BbJglPMI3BBhbGHjEEc6Ju+mvh/+ylv39tELw=
43github.com/wraient/rich-go v0.0.0-20250215175626-21ded92fb65a/go.mod h1:VUn80i3gP5BKP8LjJh37rJy9o4P1CLj2z+w4CloUNhU=
44golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
45golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
4646golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
4747golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
48golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
49golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
50golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
51golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
48golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
49golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
50golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
51golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
5252gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU=
5353gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
internal/anilist.go +2 −2
@@ -59,7 +59,7 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
5959 populateMap := func(entries []Entry) {
6060 for _, entry := range entries {
6161 // Only include entries with a non-empty English title
62 Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage), logFile)
62 Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage))
6363 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
6464 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
6565 Title: entry.Media.Title.English,
@@ -670,7 +670,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
670670
671671 // Access the list entries in the input map
672672 if input["data"] == nil {
673 Log("Anilist request failed", logFile)
673 Log("Anilist request failed")
674674 CurdOut("Anilist request failed")
675675 ExitCurd(fmt.Errorf("Anilist request failed"))
676676 return animeList
internal/anime_list.go +8 −9
@@ -43,7 +43,6 @@ type response struct {
4343
4444func SearchAnime(query, mode string) (map[string]string, error) {
4545 userCurdConfig := GetGlobalConfig()
46 var logFile string
4746 if userCurdConfig == nil {
4847 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
4948 } else {
@@ -87,7 +86,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
8786 // Marshal the variables to JSON
8887 variablesJSON, err := json.Marshal(variables)
8988 if err != nil {
90 Log(fmt.Sprintf("Error encoding variables to JSON: %v", err), logFile)
89 Log(fmt.Sprintf("Error encoding variables to JSON: %v", err))
9190 return animeList, err
9291 }
9392
@@ -97,7 +96,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
9796 // Make the HTTP request
9897 req, err := http.NewRequest("GET", url, nil)
9998 if err != nil {
100 Log(fmt.Sprintf("Error creating HTTP request: %v", err), logFile)
99 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
101100 return animeList, err
102101 }
103102 req.Header.Set("User-Agent", agent)
@@ -106,7 +105,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
106105 client := &http.Client{}
107106 resp, err := client.Do(req)
108107 if err != nil {
109 Log(fmt.Sprintf("Error making HTTP request: %v", err), logFile)
108 Log(fmt.Sprintf("Error making HTTP request: %v", err))
110109 return animeList, err
111110 }
112111 defer resp.Body.Close()
@@ -114,19 +113,19 @@ func SearchAnime(query, mode string) (map[string]string, error) {
114113 // Read the response body
115114 body, err := io.ReadAll(resp.Body)
116115 if err != nil {
117 Log(fmt.Sprintf("Error reading response body: %v", err), logFile)
116 Log(fmt.Sprintf("Error reading response body: %v", err))
118117 return animeList, err
119118 }
120119
121120 // Debug: Log the response status and first part of the body
122 Log(fmt.Sprintf("Response Status: %s", resp.Status), logFile)
123 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])), logFile)
121 Log(fmt.Sprintf("Response Status: %s", resp.Status))
122 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
124123
125124 // Parse the JSON response
126125 var response response
127126 err = json.Unmarshal(body, &response)
128127 if err != nil {
129 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)), logFile)
128 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
130129 return animeList, err
131130 }
132131
@@ -136,7 +135,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
136135 if subEpisodes, ok := episodes["sub"].(float64); ok {
137136 episodesStr = fmt.Sprintf("%d", int(subEpisodes))
138137 } else {
139 Log(subEpisodes, logFile)
138 Log(subEpisodes)
140139 episodesStr = "Unknown"
141140 }
142141 }
internal/aniskip.go +3 −3
@@ -32,19 +32,19 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
3232
3333 resp, err := http.Get(url)
3434 if err != nil {
35 Log(fmt.Errorf("error fetching data from AniSkip API: %w", err), logFile)
35 Log(fmt.Errorf("error fetching data from AniSkip API: %w", err))
3636 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err)
3737 }
3838 defer resp.Body.Close()
3939
4040 if resp.StatusCode != http.StatusOK {
41 Log(fmt.Sprintf("failed with status %d", resp.StatusCode), logFile)
41 Log(fmt.Sprintf("failed with status %d", resp.StatusCode))
4242 return "", fmt.Errorf("failed with status %d", resp.StatusCode)
4343 }
4444
4545 body, err := io.ReadAll(resp.Body)
4646 if err != nil {
47 Log(fmt.Errorf("failed to read response body %w", err), logFile)
47 Log(fmt.Errorf("failed to read response body %w", err))
4848 return "", fmt.Errorf("failed to read response body %w", err)
4949 }
5050
internal/config.go +1 −1
@@ -240,7 +240,7 @@ func ChangeToken(config *CurdConfig, user *User) {
240240 }
241241
242242 if err != nil {
243 Log("Error getting user input: "+err.Error(), logFile)
243 Log("Error getting user input: "+err.Error())
244244 ExitCurd(err)
245245 }
246246
internal/curd.go +422 −415
@@ -79,13 +79,14 @@ func ClearLogFile(logFile string) error {
7979}
8080
8181// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
82func Log(data interface{}, logFile string) error {
82func Log(data interface{}) error {
83 logFile := GetGlobalLogFile()
8384 // Open or create the log file
8485 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
8586 if err != nil {
8687 return err
8788 }
88 defer file.Close() // Ensure the file is closed when done
89 defer file.Close()
8990
9091 // Attempt to marshal the data into JSON
9192 jsonData, err := json.Marshal(data)
@@ -118,9 +119,9 @@ func ClearScreen() {
118119 return
119120 }
120121
121 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
122 fmt.Print("\033[2J") // Clear the entire screen
123 fmt.Print("\033[H") // Move cursor to the top left
122 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
123 fmt.Print("\033[2J") // Clear the entire screen
124 fmt.Print("\033[H") // Move cursor to the top left
124125}
125126
126127// RestoreScreen restores the original terminal state
@@ -131,11 +132,20 @@ func RestoreScreen() {
131132 return
132133 }
133134
134 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
135 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
135136}
136137
137138func ExitCurd(err error) {
138139 RestoreScreen()
140
141 anime := GetGlobalAnime()
142 if anime != nil && anime.Ep.Player.SocketPath != "" {
143 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
144 if err != nil {
145 Log("Error closing MPV: "+err.Error())
146 }
147 }
148
139149 CurdOut("Have a great day!")
140150 if err != nil {
141151 CurdOut(err)
@@ -166,9 +176,9 @@ func CurdOut(data interface{}) {
166176 fmt.Sprintf("%v", data),
167177 "",
168178 )
169
179
170180 if err != nil {
171 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
181 Log(fmt.Sprintf("Failed to send notification: %v", err))
172182 }
173183 case "linux":
174184 // Check if the input starts with "-i" for image notification
@@ -179,35 +189,35 @@ func CurdOut(data interface{}) {
179189 if len(parts) == 3 {
180190 // Remove quotes from the message
181191 message := strings.Trim(parts[2], "\"")
182 cmd := exec.Command("notify-send",
183 "-a", "Curd",
184 "-h", "string:x-canonical-private-synchronous:curd-notification",
185 "Curd",
186 "-i", parts[1],
187 message)
192 cmd := exec.Command("notify-send",
193 "-a", "Curd",
194 "-h", "string:x-canonical-private-synchronous:curd-notification",
195 "Curd",
196 "-i", parts[1],
197 message)
188198 err := cmd.Run()
189199 if err != nil {
190 Log(fmt.Sprintf("%v", cmd), logFile)
191 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
200 Log(fmt.Sprintf("%v", cmd))
201 Log(fmt.Sprintf("Failed to send notification: %v", err))
192202 }
193203 }
194204 } else {
195 cmd := exec.Command("notify-send",
196 "-a", "Curd",
197 "-h", "string:x-canonical-private-synchronous:curd-notification",
198 "Curd",
199 dataStr)
205 cmd := exec.Command("notify-send",
206 "-a", "Curd",
207 "-h", "string:x-canonical-private-synchronous:curd-notification",
208 "Curd",
209 dataStr)
200210 err := cmd.Run()
201211 if err != nil {
202 Log(fmt.Sprintf("%v", cmd), logFile)
203 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
212 Log(fmt.Sprintf("%v", cmd))
213 Log(fmt.Sprintf("Failed to send notification: %v", err))
204214 }
205215 }
206216 }
207217 }
208218}
209219
210func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
220func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
211221 // Create update options map
212222 updateOptions := map[string]string{
213223 "CATEGORY": "Change Anime Category",
@@ -218,7 +228,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
218228 // Select update option
219229 updateSelection, err := DynamicSelect(updateOptions, false)
220230 if err != nil {
221 Log(fmt.Sprintf("Failed to select update option: %v", err), logFile)
231 Log(fmt.Sprintf("Failed to select update option: %v", err))
222232 ExitCurd(fmt.Errorf("Failed to select update option"))
223233 }
224234
@@ -331,7 +341,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
331341 selectedAnime, err = DynamicSelect(animeListMap, false)
332342 }
333343 if err != nil {
334 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
344 Log(fmt.Sprintf("Failed to select anime: %v", err))
335345 ExitCurd(fmt.Errorf("Failed to select anime"))
336346 }
337347
@@ -341,17 +351,17 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
341351
342352 animeID, err := strconv.Atoi(selectedAnime.Key)
343353 if err != nil {
344 Log(fmt.Sprintf("Failed to convert anime ID: %v", err), logFile)
354 Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
345355 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
346356 }
347357
348358 // After getting animeID, get the current anime entry
349359 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
350360 if err != nil {
351 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
361 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
352362 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
353363 }
354 ClearScreen()
364 ClearScreen()
355365 switch updateSelection.Key {
356366 case "CATEGORY":
357367 categories := map[string]string{
@@ -370,7 +380,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
370380
371381 categorySelection, err := DynamicSelect(categories, false)
372382 if err != nil {
373 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
383 Log(fmt.Sprintf("Failed to select category: %v", err))
374384 ExitCurd(fmt.Errorf("Failed to select category"))
375385 }
376386
@@ -380,7 +390,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
380390
381391 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
382392 if err != nil {
383 Log(fmt.Sprintf("Failed to update anime status: %v", err), logFile)
393 Log(fmt.Sprintf("Failed to update anime status: %v", err))
384394 ExitCurd(fmt.Errorf("Failed to update anime status"))
385395 }
386396
@@ -394,7 +404,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
394404 if userCurdConfig.RofiSelection {
395405 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
396406 if err != nil {
397 Log(fmt.Sprintf("Failed to get progress input: %v", err), logFile)
407 Log(fmt.Sprintf("Failed to get progress input: %v", err))
398408 ExitCurd(fmt.Errorf("Failed to get progress input"))
399409 }
400410 } else {
@@ -405,13 +415,13 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
405415
406416 progressNum, err := strconv.Atoi(progress)
407417 if err != nil {
408 Log(fmt.Sprintf("Failed to convert progress to number: %v", err), logFile)
418 Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
409419 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
410420 }
411421
412422 err = UpdateAnimeProgress(user.Token, animeID, progressNum)
413423 if err != nil {
414 Log(fmt.Sprintf("Failed to update anime progress: %v", err), logFile)
424 Log(fmt.Sprintf("Failed to update anime progress: %v", err))
415425 ExitCurd(fmt.Errorf("Failed to update anime progress"))
416426 }
417427
@@ -424,7 +434,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
424434
425435 err = RateAnime(user.Token, animeID)
426436 if err != nil {
427 Log(fmt.Sprintf("Failed to update anime score: %v", err), logFile)
437 Log(fmt.Sprintf("Failed to update anime score: %v", err))
428438 ExitCurd(fmt.Errorf("Failed to update anime score"))
429439 }
430440 }
@@ -433,11 +443,11 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
433443}
434444
435445func UpdateCurd(repo, fileName string) error {
436 // Get the path of the currently running executable
437 executablePath, err := os.Executable()
438 if err != nil {
439 return fmt.Errorf("unable to find current executable: %v", err)
440 }
446 // Get the path of the currently running executable
447 executablePath, err := os.Executable()
448 if err != nil {
449 return fmt.Errorf("unable to find current executable: %v", err)
450 }
441451
442452 // Determine the correct binary name based on OS and architecture
443453 var binaryName string
@@ -463,47 +473,47 @@ func UpdateCurd(repo, fileName string) error {
463473 }
464474 default:
465475 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
466 }
476 }
467477
468 // GitHub release URL for curd
478 // GitHub release URL for curd
469479 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
470480
471 // Temporary path for the downloaded curd executable
472 tmpPath := executablePath + ".tmp"
473
474 // Download the curd executable
475 resp, err := http.Get(url)
476 if err != nil {
477 return fmt.Errorf("failed to download file: %v", err)
478 }
479 defer resp.Body.Close()
480
481 // Check if the download was successful
482 if resp.StatusCode != http.StatusOK {
483 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
484 }
485
486 // Create a new temporary file
487 out, err := os.Create(tmpPath)
488 if err != nil {
489 return fmt.Errorf("failed to create temporary file: %v", err)
490 }
491 defer out.Close()
492
493 // Write the downloaded content to the temporary file
494 _, err = io.Copy(out, resp.Body)
495 if err != nil {
496 return fmt.Errorf("failed to save downloaded file: %v", err)
497 }
498
499 // Close and rename the temporary file to replace the current executable
500 out.Close()
501
502 // Replace the current executable with the downloaded curd
503 if err := os.Rename(tmpPath, executablePath); err != nil {
504 return fmt.Errorf("failed to replace the current executable: %v", err)
505 }
506 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
481 // Temporary path for the downloaded curd executable
482 tmpPath := executablePath + ".tmp"
483
484 // Download the curd executable
485 resp, err := http.Get(url)
486 if err != nil {
487 return fmt.Errorf("failed to download file: %v", err)
488 }
489 defer resp.Body.Close()
490
491 // Check if the download was successful
492 if resp.StatusCode != http.StatusOK {
493 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
494 }
495
496 // Create a new temporary file
497 out, err := os.Create(tmpPath)
498 if err != nil {
499 return fmt.Errorf("failed to create temporary file: %v", err)
500 }
501 defer out.Close()
502
503 // Write the downloaded content to the temporary file
504 _, err = io.Copy(out, resp.Body)
505 if err != nil {
506 return fmt.Errorf("failed to save downloaded file: %v", err)
507 }
508
509 // Close and rename the temporary file to replace the current executable
510 out.Close()
511
512 // Replace the current executable with the downloaded curd
513 if err := os.Rename(tmpPath, executablePath); err != nil {
514 return fmt.Errorf("failed to replace the current executable: %v", err)
515 }
516 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
507517
508518 if runtime.GOOS != "windows" {
509519 // Ensure the new file has executable permissions
@@ -511,11 +521,11 @@ func UpdateCurd(repo, fileName string) error {
511521 return fmt.Errorf("failed to set permissions on the new file: %v", err)
512522 }
513523 }
514
515 return nil
524
525 return nil
516526}
517527
518func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption {
528func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
519529 var query string
520530 var animeMap map[string]string
521531 var animeMapPreview map[string]RofiSelectPreview
@@ -527,8 +537,8 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
527537 if userCurdConfig.RofiSelection {
528538 userInput, err := GetUserInputFromRofi("Enter the anime name")
529539 if err != nil {
530 Log("Error getting user input: "+err.Error(), logFile)
531 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
540 Log("Error getting user input: "+err.Error())
541 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
532542 }
533543 query = userInput
534544 } else {
@@ -541,7 +551,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
541551 animeMap, err = SearchAnimeAnilist(query, user.Token)
542552 }
543553 if err != nil {
544 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
554 Log(fmt.Sprintf("Failed to search anime: %v", err))
545555 ExitCurd(fmt.Errorf("Failed to search anime"))
546556 }
547557 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -555,23 +565,23 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
555565 }
556566
557567 if err != nil {
558 Log(fmt.Sprintf("No anime available: %v", err), logFile)
568 Log(fmt.Sprintf("No anime available: %v", err))
559569 ExitCurd(fmt.Errorf("No anime available"))
560570 }
561571 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
562572 if err != nil {
563 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
573 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
564574 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
565575 }
566576 err = AddAnimeToWatchingList(animeID, user.Token)
567577 if err != nil {
568 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
578 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err))
569579 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
570580 }
571581 if user.Id == 0 {
572582 user.Id, user.Username, err = GetAnilistUserID(user.Token)
573583 if err != nil {
574 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
584 Log(fmt.Sprintf("Failed to get user ID: %v", err))
575585 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
576586 }
577587 }
@@ -581,7 +591,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
581591 anilistUserData, err = GetUserData(user.Token, user.Id)
582592 }
583593 if err != nil {
584 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
594 Log(fmt.Sprintf("Failed to get user data: %v", err))
585595 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
586596 }
587597 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -593,71 +603,70 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
593603 return anilistSelectedOption
594604}
595605
596func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
597 var err error
598 var anilistUserData map[string]interface{}
599 var anilistUserDataPreview map[string]interface{}
600
606func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
607 var err error
608 var anilistUserData map[string]interface{}
609 var anilistUserDataPreview map[string]interface{}
610
601611 // Filter anime list based on selected category
602612 var animeListMap map[string]string
603613 var animeListMapPreview map[string]RofiSelectPreview
604
605
606 // Get user id, username and Anime list
607 user.Id, user.Username, err = GetAnilistUserID(user.Token)
608 if err != nil {
609 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
610 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
611 }
612
613 // Get the anime list data
614 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
615 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
616 if err != nil {
617 Log(fmt.Sprintf("Failed to get user data preview: %v", err), logFile)
618 ExitCurd(fmt.Errorf("Failed to get user data preview"))
619 }
620 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
621 } else {
622 anilistUserData, err = GetUserData(user.Token, user.Id)
623 if err != nil {
624 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
625 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
626 }
627 user.AnimeList = ParseAnimeList(anilistUserData)
628 }
614
615 // Get user id, username and Anime list
616 user.Id, user.Username, err = GetAnilistUserID(user.Token)
617 if err != nil {
618 Log(fmt.Sprintf("Failed to get user ID: %v", err))
619 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
620 }
621
622 // Get the anime list data
623 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
624 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
625 if err != nil {
626 Log(fmt.Sprintf("Failed to get user data preview: %v", err))
627 ExitCurd(fmt.Errorf("Failed to get user data preview"))
628 }
629 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
630 } else {
631 anilistUserData, err = GetUserData(user.Token, user.Id)
632 if err != nil {
633 Log(fmt.Sprintf("Failed to get user data: %v", err))
634 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
635 }
636 user.AnimeList = ParseAnimeList(anilistUserData)
637 }
629638
630639 // If continueLast flag is set, directly get the last watched anime
631 if anime.Ep.ContinueLast {
632 // Get the last anime ID from the curd_id file
633 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
634 idBytes, err := os.ReadFile(idFilePath)
635 if err != nil {
636 Log("Error reading curd_id file: "+err.Error(), logFile)
637 ExitCurd(fmt.Errorf("No last watched anime found"))
638 }
639
640 anilistID, err := strconv.Atoi(string(idBytes))
641 if err != nil {
642 Log("Error converting anilist ID: "+err.Error(), logFile)
643 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
644 }
645
646 // Find the anime in database
647 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
648 if animePointer == nil {
649 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
650 }
651
652 // Set the anime details
653 anime.AnilistId = animePointer.AnilistId
654 // anime.AllanimeId = animePointer.AllanimeId
655 // anime.Title = animePointer.Title
656 // anime.Ep.Number = animePointer.Ep.Number
657 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
658 // anime.Ep.Resume = true
659
660 } else {
640 if anime.Ep.ContinueLast {
641 // Get the last anime ID from the curd_id file
642 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
643 idBytes, err := os.ReadFile(idFilePath)
644 if err != nil {
645 Log("Error reading curd_id file: "+err.Error())
646 ExitCurd(fmt.Errorf("No last watched anime found"))
647 }
648
649 anilistID, err := strconv.Atoi(string(idBytes))
650 if err != nil {
651 Log("Error converting anilist ID: "+err.Error())
652 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
653 }
654
655 // Find the anime in database
656 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
657 if animePointer == nil {
658 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
659 }
660
661 // Set the anime details
662 anime.AnilistId = animePointer.AnilistId
663 // anime.AllanimeId = animePointer.AllanimeId
664 // anime.Title = animePointer.Title
665 // anime.Ep.Number = animePointer.Ep.Number
666 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
667 // anime.Ep.Resume = true
668
669 } else {
661670 // Skip category selection if Current flag is set
662671 var categorySelection SelectionOption
663672 if userCurdConfig.CurrentCategory {
@@ -682,7 +691,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
682691 var err error
683692 categorySelection, err = DynamicSelect(categories, false)
684693 if err != nil {
685 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
694 Log(fmt.Sprintf("Failed to select category: %v", err))
686695 ExitCurd(fmt.Errorf("Failed to select category"))
687696 }
688697
@@ -693,17 +702,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
693702 // Handle UPDATE option
694703 if categorySelection.Key == "UPDATE" {
695704 ClearScreen()
696 UpdateAnimeEntry(userCurdConfig, user, logFile)
705 UpdateAnimeEntry(userCurdConfig, user)
697706 ExitCurd(nil)
698707 } else if categorySelection.Key == "UNTRACKED" {
699708 ClearScreen()
700 WatchUntracked(userCurdConfig, logFile)
709 WatchUntracked(userCurdConfig)
701710 }
702711
703712 ClearScreen()
704713 }
705714
706
707715 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
708716 animeListMapPreview = make(map[string]RofiSelectPreview)
709717 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
@@ -728,122 +736,122 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
728736 }
729737 }
730738
731 var anilistSelectedOption SelectionOption
732 var selectedAllanimeAnime SelectionOption
733 var userQuery string
734
735 if anime.Ep.ContinueLast {
736 // Get the last watched anime ID from the curd_id file
737 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
738 curdIDBytes, err := os.ReadFile(curdIDPath)
739 if err != nil {
740 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
741 ExitCurd(fmt.Errorf("Error reading curd_id file"))
742 }
743
744 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
745 if err != nil {
746 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
747 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
748 }
749
750 anime.AnilistId = lastWatchedID
751 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
752 } else {
753 // Select anime to watch (Anilist)
754 var err error
755 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
756 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
757 } else {
758 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
759 }
760 if err != nil {
761 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
762 ExitCurd(fmt.Errorf("Error selecting anime"))
763 }
764
765 Log(anilistSelectedOption, logFile)
766
767 if anilistSelectedOption.Key == "-1" {
768 ExitCurd(nil)
769 }
770
771 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
772 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
773 }
774
775 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
776 if err != nil {
777 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
778 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
779 }
780 }
781 // Find anime in Local history
782 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
783
784 // Get anime entry
785 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
786 if err != nil {
787 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
788 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
789 }
790
791 // Set anime entry
792 anime.Title = selectedAnilistAnime.Media.Title
793 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
794 anime.Ep.Number = selectedAnilistAnime.Progress+1
795 var animeList map[string]string
796 userQuery = anime.Title.Romaji
797
798 // if anime not found in database, find it in animeList
799 if animePointer == nil {
800 Log("Anime not found in database, searching in animeList...", logFile)
801 // Get Anime list (All anime)
802 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile)
803
804 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
805 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile)
806 if err != nil {
807 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
808 ExitCurd(fmt.Errorf("Failed to select anime"))
809 }
810 if len(animeList) == 0 {
811 ExitCurd(fmt.Errorf("No results found."))
812 }
813
814 // find anime in animeList
815 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
816 if err != nil {
817 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
818 }
819
820 // If unable to get Allanime id automatically get manually
821 if anime.AllanimeId == "" {
822 CurdOut("Failed to automatically select anime")
823 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
739 var anilistSelectedOption SelectionOption
740 var selectedAllanimeAnime SelectionOption
741 var userQuery string
742
743 if anime.Ep.ContinueLast {
744 // Get the last watched anime ID from the curd_id file
745 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
746 curdIDBytes, err := os.ReadFile(curdIDPath)
747 if err != nil {
748 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
749 ExitCurd(fmt.Errorf("Error reading curd_id file"))
750 }
751
752 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
753 if err != nil {
754 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
755 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
756 }
757
758 anime.AnilistId = lastWatchedID
759 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
760 } else {
761 // Select anime to watch (Anilist)
762 var err error
763 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
764 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
765 } else {
766 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
767 }
768 if err != nil {
769 Log(fmt.Sprintf("Error selecting anime: %v", err))
770 ExitCurd(fmt.Errorf("Error selecting anime"))
771 }
772
773 Log(anilistSelectedOption)
774
775 if anilistSelectedOption.Key == "-1" {
776 ExitCurd(nil)
777 }
778
779 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
780 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
781 }
782
783 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
784 if err != nil {
785 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
786 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
787 }
788 }
789 // Find anime in Local history
790 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
791
792 // Get anime entry
793 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
794 if err != nil {
795 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
796 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
797 }
798
799 // Set anime entry
800 anime.Title = selectedAnilistAnime.Media.Title
801 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
802 anime.Ep.Number = selectedAnilistAnime.Progress + 1
803 var animeList map[string]string
804 userQuery = anime.Title.Romaji
805
806 // if anime not found in database, find it in animeList
807 if animePointer == nil {
808 Log("Anime not found in database, searching in animeList...")
809 // Get Anime list (All anime)
810 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
811
812 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
813 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
814 if err != nil {
815 Log(fmt.Sprintf("Failed to select anime: %v", err))
816 ExitCurd(fmt.Errorf("Failed to select anime"))
817 }
818 if len(animeList) == 0 {
819 ExitCurd(fmt.Errorf("No results found."))
820 }
821
822 // find anime in animeList
823 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
824 if err != nil {
825 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
826 }
827
828 // If unable to get Allanime id automatically get manually
829 if anime.AllanimeId == "" {
830 CurdOut("Failed to automatically select anime")
831 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
824832
825833 if selectedAllanimeAnime.Key == "-1" {
826834 ExitCurd(nil)
827835 }
828836
829 if err != nil {
830 // fmt.Println("No anime available")
831 ExitCurd(fmt.Errorf("No anime available"))
832 }
833 anime.AllanimeId = selectedAllanimeAnime.Key
834 }
835 } else {
836 // if anime found in database, use it
837 if err != nil {
838 // fmt.Println("No anime available")
839 ExitCurd(fmt.Errorf("No anime available"))
840 }
841 anime.AllanimeId = selectedAllanimeAnime.Key
842 }
843 } else {
844 // if anime found in database, use it
837845 anime.AllanimeId = animePointer.AllanimeId
838846 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
839847 if anime.Ep.Number == animePointer.Ep.Number {
840848 anime.Ep.Resume = true
841849 }
842 }
850 }
843851
844 if selectedAllanimeAnime.Key == "-1" {
845 ExitCurd(nil)
846 }
852 if selectedAllanimeAnime.Key == "-1" {
853 ExitCurd(nil)
854 }
847855
848856 // If anime is not in watching list, prompt user to add it into watching list
849857 isInWatchingList := false
@@ -867,28 +875,28 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
867875 // Use rofi for selection
868876 selectedOption, err = DynamicSelect(options, false)
869877 if err != nil {
870 Log("Error in selection: "+err.Error(), logFile)
878 Log("Error in selection: "+err.Error())
871879 ExitCurd(err)
872880 }
873881
874882 if selectedOption.Key == "yes" {
875883 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
876884 if err != nil {
877 Log("Error adding anime to watching list: "+err.Error(), logFile)
885 Log("Error adding anime to watching list: "+err.Error())
878886 ExitCurd(err)
879887 }
880888 // Refresh user's anime list after adding
881889 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
882890 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
883891 if err != nil {
884 Log("Error refreshing anime list: "+err.Error(), logFile)
892 Log("Error refreshing anime list: "+err.Error())
885893 ExitCurd(err)
886894 }
887895 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
888896 } else {
889897 anilistUserData, err := GetUserData(user.Token, user.Id)
890898 if err != nil {
891 Log("Error refreshing anime list: "+err.Error(), logFile)
899 Log("Error refreshing anime list: "+err.Error())
892900 ExitCurd(err)
893901 }
894902 user.AnimeList = ParseAnimeList(anilistUserData)
@@ -898,142 +906,142 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
898906 }
899907 }
900908
901 // If upstream is ahead, update the episode number
902 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
903 if temp_anime.Progress > anime.Ep.Number {
904 anime.Ep.Number = temp_anime.Progress
905 anime.Ep.Player.PlaybackTime = 0
906 anime.Ep.Resume = false
907 }
908 }
909
910 if anime.TotalEpisodes == 0 {
911 // Get updated anime data
912 Log(selectedAllanimeAnime, logFile)
913 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
914 Log(updatedAnime, logFile)
915 if err != nil {
916 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
917 } else {
918 anime.TotalEpisodes = updatedAnime.TotalEpisodes
919 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
920 }
921 }
922
923 if anime.TotalEpisodes == 0 { // If failed to get anime data
924 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
925 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
926 if err != nil {
927 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
928 } else {
929 for allanimeId, label := range animeList {
930 if allanimeId == anime.AllanimeId {
931 // Extract total episodes from the label
932 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
933 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
934 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
935 break
936 }
937 }
938 }
939 }
940
941 if anime.TotalEpisodes == 0 {
942 CurdOut("Still unable to determine total episodes.")
943 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
944 var episodeNumber int
945 if userCurdConfig.RofiSelection {
946 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
947 if err != nil {
948 Log("Error getting user input: "+err.Error(), logFile)
949 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
950 }
951 episodeNumber, err = strconv.Atoi(userInput)
952 } else {
953 fmt.Print("Enter the episode you want to start from: ")
954 fmt.Scanln(&episodeNumber)
955 }
956 anime.Ep.Number = episodeNumber
957 } else {
958 anime.Ep.Number = selectedAnilistAnime.Progress + 1
959 }
960 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
961 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
962 var answer string
963 if userCurdConfig.RofiSelection {
964 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
965 if err != nil {
966 Log("Error getting user input: "+err.Error(), logFile)
967 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
968 }
969 answer = userInput
970 } else {
971 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
972 fmt.Scanln(&answer)
973 }
974 if answer == "y" {
975 anime.Ep.Number = 1
976 } else {
977 anime.Ep.Number = anime.TotalEpisodes
978 }
979 }
909 // If upstream is ahead, update the episode number
910 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
911 if temp_anime.Progress > anime.Ep.Number {
912 anime.Ep.Number = temp_anime.Progress
913 anime.Ep.Player.PlaybackTime = 0
914 anime.Ep.Resume = false
915 }
916 }
917
918 if anime.TotalEpisodes == 0 {
919 // Get updated anime data
920 Log(selectedAllanimeAnime)
921 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
922 Log(updatedAnime)
923 if err != nil {
924 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
925 } else {
926 anime.TotalEpisodes = updatedAnime.TotalEpisodes
927 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
928 }
929 }
930
931 if anime.TotalEpisodes == 0 { // If failed to get anime data
932 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
933 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
934 if err != nil {
935 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
936 } else {
937 for allanimeId, label := range animeList {
938 if allanimeId == anime.AllanimeId {
939 // Extract total episodes from the label
940 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
941 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
942 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
943 break
944 }
945 }
946 }
947 }
948
949 if anime.TotalEpisodes == 0 {
950 CurdOut("Still unable to determine total episodes.")
951 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
952 var episodeNumber int
953 if userCurdConfig.RofiSelection {
954 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
955 if err != nil {
956 Log("Error getting user input: "+err.Error())
957 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
958 }
959 episodeNumber, err = strconv.Atoi(userInput)
960 } else {
961 fmt.Print("Enter the episode you want to start from: ")
962 fmt.Scanln(&episodeNumber)
963 }
964 anime.Ep.Number = episodeNumber
965 } else {
966 anime.Ep.Number = selectedAnilistAnime.Progress + 1
967 }
968 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
969 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
970 var answer string
971 if userCurdConfig.RofiSelection {
972 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
973 if err != nil {
974 Log("Error getting user input: "+err.Error())
975 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
976 }
977 answer = userInput
978 } else {
979 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
980 fmt.Scanln(&answer)
981 }
982 if answer == "y" {
983 anime.Ep.Number = 1
984 } else {
985 anime.Ep.Number = anime.TotalEpisodes
986 }
987 }
980988
981989}
982990
983991// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
984992func WriteTokenToFile(token string, filePath string) error {
985 // Extract the directory path
986 dir := filepath.Dir(filePath)
993 // Extract the directory path
994 dir := filepath.Dir(filePath)
987995
988 // Create all necessary parent directories
989 if err := os.MkdirAll(dir, 0755); err != nil {
990 return fmt.Errorf("failed to create directories: %v", err)
991 }
996 // Create all necessary parent directories
997 if err := os.MkdirAll(dir, 0755); err != nil {
998 return fmt.Errorf("failed to create directories: %v", err)
999 }
9921000
993 // Write the token to the file, creating it if it doesn't exist
994 err := os.WriteFile(filePath, []byte(token), 0644)
995 if err != nil {
996 return fmt.Errorf("failed to write token to file: %v", err)
997 }
1001 // Write the token to the file, creating it if it doesn't exist
1002 err := os.WriteFile(filePath, []byte(token), 0644)
1003 if err != nil {
1004 return fmt.Errorf("failed to write token to file: %v", err)
1005 }
9981006
999 return nil
1007 return nil
10001008}
10011009
1002func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
1010func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
10031011
10041012 if anime.Ep.NextEpisode.Number == anime.Ep.Number {
10051013 anime.Ep.Links = anime.Ep.NextEpisode.Links
10061014 fmt.Println("using prefetched next episode link")
10071015 } else {
1008 // Get episode link
1009 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1010 if err != nil {
1011 // If unable to get episode link automatically get manually
1012 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1016 // Get episode link
1017 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
10131018 if err != nil {
1014 CurdOut("No episode list found")
1015 RestoreScreen()
1016 os.Exit(1)
1017 }
1018 if userCurdConfig.RofiSelection {
1019 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1019 // If unable to get episode link automatically get manually
1020 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
10201021 if err != nil {
1021 Log("Error getting user input: "+err.Error(), logFile)
1022 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
1022 CurdOut("No episode list found")
1023 RestoreScreen()
1024 os.Exit(1)
10231025 }
1024 anime.Ep.Number, err = strconv.Atoi(userInput)
1025 } else {
1026 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1027 fmt.Scanln(&anime.Ep.Number)
1028 }
1029 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1030 if err != nil {
1031 CurdOut("Failed to get episode link")
1032 os.Exit(1)
1026 if userCurdConfig.RofiSelection {
1027 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1028 if err != nil {
1029 Log("Error getting user input: "+err.Error())
1030 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1031 }
1032 anime.Ep.Number, err = strconv.Atoi(userInput)
1033 } else {
1034 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1035 fmt.Scanln(&anime.Ep.Number)
1036 }
1037 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1038 if err != nil {
1039 CurdOut("Failed to get episode link")
1040 os.Exit(1)
1041 }
1042 // anime.Ep.Links = link
10331043 }
1034 // anime.Ep.Links = link
1035 }
1036 anime.Ep.Links = link
1044 anime.Ep.Links = link
10371045 }
10381046
10391047 if len(anime.Ep.Links) == 0 {
@@ -1041,7 +1049,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
10411049 os.Exit(1)
10421050 }
10431051
1044 Log(anime, logFile)
1052 Log(anime)
10451053
10461054 // Modify the goroutine in main.go where next episode links are fetched
10471055 // Get next episode link in parallel
@@ -1054,25 +1062,25 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
10541062 }
10551063 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
10561064 if err != nil {
1057 Log("Error getting next episode link: "+err.Error(), logFile)
1065 Log("Error getting next episode link: "+err.Error())
10581066 } else {
10591067 anime.Ep.NextEpisode = NextEpisode{
10601068 Number: nextEpNum,
10611069 Links: nextLinks,
10621070 }
1063 Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum), logFile)
1071 Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
10641072 }
10651073 }
10661074 }()
10671075
10681076 // Write anime.AnilistId to curd_id in the storage path
10691077 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1070 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
1078 Log(fmt.Sprintf("idFilePath: %v", idFilePath))
10711079 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1072 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
1080 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
10731081 } else {
10741082 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1075 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
1083 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
10761084 }
10771085 }
10781086
@@ -1085,15 +1093,15 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
10851093
10861094 // Display the image if it exists in cache
10871095 _, err := os.Stat(cachePath)
1088 if err == nil {
1096 if err == nil {
10891097 // File exists
1090 Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
1098 Log(fmt.Sprintf("Image found at %s", cachePath))
10911099 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
10921100 } else {
10931101 // File does not exist
1094 Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
1095 CurdOut(fmt.Sprintf("%s - Episode %d",
1096 GetAnimeName(*anime),
1102 Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1103 CurdOut(fmt.Sprintf("%s - Episode %d",
1104 GetAnimeName(*anime),
10971105 anime.Ep.Number))
10981106
10991107 }
@@ -1103,7 +1111,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
11031111 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
11041112
11051113 if err != nil {
1106 Log("Failed to start mpv", logFile)
1114 Log("Failed to start mpv")
11071115 os.Exit(1)
11081116 }
11091117
@@ -1153,28 +1161,27 @@ func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
11531161}
11541162
11551163func getEntriesByCategory(list AnimeList, category string) []Entry {
1156 switch category {
1157 case "ALL":
1158 // Combine all categories into one slice
1159 allEntries := make([]Entry, 0)
1160 allEntries = append(allEntries, list.Watching...)
1161 allEntries = append(allEntries, list.Completed...)
1162 allEntries = append(allEntries, list.Paused...)
1163 allEntries = append(allEntries, list.Dropped...)
1164 allEntries = append(allEntries, list.Planning...)
1165 return allEntries
1166 case "CURRENT":
1167 return list.Watching
1168 case "COMPLETED":
1169 return list.Completed
1170 case "PAUSED":
1171 return list.Paused
1172 case "DROPPED":
1173 return list.Dropped
1174 case "PLANNING":
1175 return list.Planning
1176 default:
1177 return []Entry{}
1178 }
1164 switch category {
1165 case "ALL":
1166 // Combine all categories into one slice
1167 allEntries := make([]Entry, 0)
1168 allEntries = append(allEntries, list.Watching...)
1169 allEntries = append(allEntries, list.Completed...)
1170 allEntries = append(allEntries, list.Paused...)
1171 allEntries = append(allEntries, list.Dropped...)
1172 allEntries = append(allEntries, list.Planning...)
1173 return allEntries
1174 case "CURRENT":
1175 return list.Watching
1176 case "COMPLETED":
1177 return list.Completed
1178 case "PAUSED":
1179 return list.Paused
1180 case "DROPPED":
1181 return list.Dropped
1182 case "PLANNING":
1183 return list.Planning
1184 default:
1185 return []Entry{}
1186 }
11791187}
1180
internal/discord.go +13 −11
@@ -2,7 +2,8 @@ package internal
22
33import (
44 "fmt"
5 "github.com/hugolgst/rich-go/client"
5
6 "github.com/wraient/rich-go/client"
67)
78
89func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
@@ -13,14 +14,14 @@ func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
1314
1415 var state string
1516 if IsPaused {
16 state = fmt.Sprintf("\nEpisode %d - %s (Paused)",
17 anime.Ep.Number,
17 state = fmt.Sprintf("\nEpisode %d - %s (Paused)",
18 anime.Ep.Number,
1819 FormatTime(anime.Ep.Player.PlaybackTime),
1920 )
2021 } else {
21 state = fmt.Sprintf("\nEpisode %d - %s / %s",
22 anime.Ep.Number,
23 FormatTime(anime.Ep.Player.PlaybackTime),
22 state = fmt.Sprintf("\nEpisode %d - %s / %s",
23 anime.Ep.Number,
24 FormatTime(anime.Ep.Player.PlaybackTime),
2425 FormatTime(anime.Ep.Duration),
2526 )
2627 }
@@ -30,15 +31,16 @@ func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
3031 LargeImage: anime.CoverImage,
3132 LargeText: GetAnimeName(anime), // Would display while hovering over the large image
3233 State: state,
34 Type: 3, // Watching type (0 = Playing, 1 = Streaming, 2 = Listening, 3 = Watching, 4 = Custom, 5 = Competing)
3335 //SmallImage: anime.SmallCoverImage, // Image for the bottom left corner
3436 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image
3537 Buttons: []*client.Button{
36 &client.Button{
37 Label: "View on AniList", // Button label
38 {
39 Label: "View on AniList", // Button label
3840 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link
3941 },
40 &client.Button{
41 Label: "View on MAL", // Button label
42 {
43 Label: "View on MAL", // Button label
4244 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link
4345 },
4446 },
@@ -62,4 +64,4 @@ func FormatTime(seconds int) string {
6264
6365func ConvertSecondsToMinutes(seconds int) int {
6466 return seconds / 60
65}
\ No newline at end of file
67}
internal/episode_list.go +4 −4
@@ -48,7 +48,7 @@ func EpisodesList(showID, mode string) ([]string, error) {
4848 // Make the HTTP request
4949 req, err := http.NewRequest("GET", url, nil)
5050 if err != nil {
51 Log(fmt.Sprint("Error creating HTTP request:", err), logFile)
51 Log(fmt.Sprint("Error creating HTTP request:", err))
5252 return episodes, err
5353 }
5454 req.Header.Set("User-Agent", agent)
@@ -57,14 +57,14 @@ func EpisodesList(showID, mode string) ([]string, error) {
5757 client := &http.Client{}
5858 resp, err := client.Do(req)
5959 if err != nil {
60 Log(fmt.Sprint("Error making HTTP request:", err), logFile)
60 Log(fmt.Sprint("Error making HTTP request:", err))
6161 return episodes, err
6262 }
6363 defer resp.Body.Close()
6464
6565 body, err := io.ReadAll(resp.Body)
6666 if err != nil {
67 Log(fmt.Sprint("Error reading response body:", err), logFile)
67 Log(fmt.Sprint("Error reading response body:", err))
6868 return episodes, err
6969 }
7070
@@ -72,7 +72,7 @@ func EpisodesList(showID, mode string) ([]string, error) {
7272 var response episodesResponse
7373 err = json.Unmarshal(body, &response)
7474 if err != nil {
75 Log(fmt.Sprint("Error parsing JSON:", err), logFile)
75 Log(fmt.Sprint("Error parsing JSON:", err))
7676 return episodes, err
7777 }
7878
internal/episode_url.go +12 −12
@@ -60,7 +60,7 @@ func extractLinks(provider_id string) map[string]interface{} {
6060 req, err := http.NewRequest("GET", url, nil)
6161 var videoData map[string]interface{}
6262 if err != nil {
63 Log(fmt.Sprint("Error creating request:", err), logFile)
63 Log(fmt.Sprint("Error creating request:", err))
6464 return videoData
6565 }
6666
@@ -71,7 +71,7 @@ func extractLinks(provider_id string) map[string]interface{} {
7171 // Send the request
7272 resp, err := client.Do(req)
7373 if err != nil {
74 Log(fmt.Sprint("Error sending request:", err), logFile)
74 Log(fmt.Sprint("Error sending request:", err))
7575 return videoData
7676 }
7777 defer resp.Body.Close()
@@ -79,14 +79,14 @@ func extractLinks(provider_id string) map[string]interface{} {
7979 // Read the response body
8080 body, err := io.ReadAll(resp.Body)
8181 if err != nil {
82 Log(fmt.Sprint("Error reading response:", err), logFile)
82 Log(fmt.Sprint("Error reading response:", err))
8383 return videoData
8484 }
8585
8686 // Parse the JSON response
8787 err = json.Unmarshal(body, &videoData)
8888 if err != nil {
89 Log(fmt.Sprint("Error parsing JSON:", err), logFile)
89 Log(fmt.Sprint("Error parsing JSON:", err))
9090 return videoData
9191 }
9292
@@ -148,7 +148,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
148148 var response allanimeResponse
149149 err = json.Unmarshal(body, &response)
150150 if err != nil {
151 Log(fmt.Sprint("Error parsing JSON: ", err), logFile)
151 Log(fmt.Sprint("Error parsing JSON: ", err))
152152 return nil, err
153153 }
154154
@@ -184,7 +184,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
184184 <-rateLimiter.C // Rate limit the requests
185185
186186 decodedProviderID := decodeProviderID(url[2:])
187 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID), logFile)
187 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID))
188188
189189 extractedLinks := extractLinks(decodedProviderID)
190190
@@ -209,13 +209,13 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
209209 for _, linkInterface := range linksInterface {
210210 linkMap, ok := linkInterface.(map[string]interface{})
211211 if !ok {
212 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID), logFile)
212 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID))
213213 continue
214214 }
215215
216216 link, ok := linkMap["link"].(string)
217217 if !ok {
218 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID), logFile)
218 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID))
219219 continue
220220 }
221221
@@ -239,16 +239,16 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
239239 select {
240240 case res := <-results:
241241 if res.err != nil {
242 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err), logFile)
242 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
243243 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
244244 } else {
245245 orderedResults[res.index] = res.links
246246 successCount++
247 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)), logFile)
247 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)))
248248 }
249249 case <-timeout:
250250 if successCount > 0 {
251 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)), logFile)
251 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)))
252252 // Flatten available results
253253 return flattenResults(orderedResults), nil
254254 }
@@ -258,7 +258,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
258258
259259 // If we have any errors but also some successes, log errors but continue
260260 if len(collectedErrors) > 0 {
261 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors), logFile)
261 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors))
262262 }
263263
264264 // Flatten and return results
internal/globals.go added +26
@@ -0,0 +1,26 @@
1package internal
2
3var (
4 globalAnime *Anime
5 globalLogFile string
6)
7
8// SetGlobalAnime sets the global anime reference
9func SetGlobalAnime(anime *Anime) {
10 globalAnime = anime
11}
12
13// GetGlobalAnime gets the global anime reference
14func GetGlobalAnime() *Anime {
15 return globalAnime
16}
17
18// SetGlobalLogFile sets the global log file path
19func SetGlobalLogFile(logFile string) {
20 globalLogFile = logFile
21}
22
23// GetGlobalLogFile gets the global log file path
24func GetGlobalLogFile() string {
25 return globalLogFile
26}
internal/jikan.go +3 −3
@@ -14,19 +14,19 @@ func GetEpisodeData(animeID int, episodeNo int, anime *Anime) error {
1414 // Use the helper function for making the GET request
1515 response, err := makeGetRequest(url, nil)
1616 if err != nil {
17 Log(fmt.Sprintf("Warning: Jikan API error: %v - continuing without filler data", err), logFile)
17 Log(fmt.Sprintf("Warning: Jikan API error: %v - continuing without filler data", err))
1818 // Set default values when API fails
1919 anime.Ep.IsFiller = false
2020 anime.Ep.IsRecap = false
2121 return nil // Return nil to allow the application to continue
2222 }
2323
24 Log(response, logFile)
24 Log(response)
2525
2626 // Check if the 'data' field exists and is valid
2727 data, ok := response["data"].(map[string]interface{})
2828 if !ok {
29 Log("Warning: Invalid Jikan API response - continuing without filler data", logFile)
29 Log("Warning: Invalid Jikan API response - continuing without filler data")
3030 // Set default values when response is invalid
3131 anime.Ep.IsFiller = false
3232 anime.Ep.IsRecap = false
internal/localTracking.go +21 −21
@@ -248,7 +248,7 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
248248 return nil
249249}
250250
251func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
251func WatchUntracked(userCurdConfig *CurdConfig) {
252252 var query string
253253 var animeList map[string]string
254254 var err error
@@ -258,7 +258,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
258258 if userCurdConfig.RofiSelection {
259259 userInput, err := GetUserInputFromRofi("Enter the anime name")
260260 if err != nil {
261 Log("Error getting user input: "+err.Error(), logFile)
261 Log("Error getting user input: "+err.Error())
262262 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
263263 }
264264 query = userInput
@@ -270,7 +270,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
270270 // Search for the anime
271271 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
272272 if err != nil {
273 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
273 Log(fmt.Sprintf("Failed to search anime: %v", err))
274274 ExitCurd(fmt.Errorf("Failed to search anime"))
275275 }
276276
@@ -281,7 +281,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
281281 // Select anime from search results
282282 selectedAnime, err := DynamicSelect(animeList, false)
283283 if err != nil {
284 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
284 Log(fmt.Sprintf("Failed to select anime: %v", err))
285285 ExitCurd(fmt.Errorf("Failed to select anime"))
286286 }
287287
@@ -297,12 +297,12 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
297297 if userCurdConfig.RofiSelection {
298298 userInput, err := GetUserInputFromRofi("Enter the episode number")
299299 if err != nil {
300 Log("Error getting episode number: "+err.Error(), logFile)
300 Log("Error getting episode number: "+err.Error())
301301 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
302302 }
303303 episodeNumber, err = strconv.Atoi(userInput)
304304 if err != nil {
305 Log(fmt.Sprintf("Invalid episode number: %v", err), logFile)
305 Log(fmt.Sprintf("Invalid episode number: %v", err))
306306 ExitCurd(fmt.Errorf("Invalid episode number"))
307307 }
308308 } else {
@@ -316,7 +316,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
316316 // Get episode link
317317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
318318 if err != nil {
319 Log(fmt.Sprintf("Failed to get episode link: %v", err), logFile)
319 Log(fmt.Sprintf("Failed to get episode link: %v", err))
320320 ExitCurd(fmt.Errorf("Failed to get episode link"))
321321 }
322322
@@ -329,14 +329,14 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
329329 // Start video playback
330330 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
331331 if err != nil {
332 Log("Failed to start mpv", logFile)
332 Log("Failed to start mpv")
333333 os.Exit(1)
334334 }
335335
336336 anime.Ep.Player.SocketPath = mpvSocketPath
337337 anime.Ep.Started = false
338338
339 Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath), logFile)
339 Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath))
340340
341341 // Get video duration
342342 go func() {
@@ -346,13 +346,13 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
346346 // Get video duration
347347 durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
348348 if err != nil {
349 Log("Error getting video duration: "+err.Error(), logFile)
349 Log("Error getting video duration: "+err.Error())
350350 } else if durationPos != nil {
351351 if duration, ok := durationPos.(float64); ok {
352352 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
353 Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration), logFile)
353 Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration))
354354 } else {
355 Log("Error: duration is not a float64", logFile)
355 Log("Error: duration is not a float64")
356356 }
357357 }
358358 break
@@ -366,28 +366,28 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
366366 for {
367367 timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
368368 if err != nil {
369 Log("Error getting playback time: "+err.Error(), logFile)
369 Log("Error getting playback time: "+err.Error())
370370
371371 // Check if the error is due to invalid JSON
372372 // User closed the video
373373 if anime.Ep.Started {
374374 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
375375 // Episode is completed
376 Log(fmt.Sprint(percentageWatched), logFile)
377 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime), logFile)
378 Log(fmt.Sprint(anime.Ep.Duration), logFile)
379 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete), logFile)
376 Log(fmt.Sprint(percentageWatched))
377 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
378 Log(fmt.Sprint(anime.Ep.Duration))
379 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
380380 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
381381 anime.Ep.Number++
382382 anime.Ep.Started = false
383 Log("Completed episode, starting next.", logFile)
383 Log("Completed episode, starting next.")
384384 anime.Ep.IsCompleted = true
385385 // Exit the skip loop
386386 break
387387 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
388 Log("Received invalid JSON response, continuing...", logFile)
388 Log("Received invalid JSON response, continuing...")
389389 } else {
390 Log("Episode is not completed, exiting", logFile)
390 Log("Episode is not completed, exiting")
391391 ExitCurd(nil)
392392 }
393393 }
@@ -401,7 +401,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
401401
402402 animePosition, ok := timePos.(float64)
403403 if !ok {
404 Log("Error: timePos is not a float64", logFile)
404 Log("Error: timePos is not a float64")
405405 continue
406406 }
407407
internal/player.go +5 −5
@@ -56,14 +56,14 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
5656 titleCommand := []interface{}{"set_property", "force-media-title", title}
5757 _, err = MPVSendCommand(mpvSocketPath, titleCommand)
5858 if err != nil {
59 Log(fmt.Sprintf("Failed to update title: %v", err), logFile)
59 Log(fmt.Sprintf("Failed to update title: %v", err))
6060 }
6161
6262 // Also update the window title property
6363 windowTitleCommand := []interface{}{"set_property", "title", title}
6464 _, err = MPVSendCommand(mpvSocketPath, windowTitleCommand)
6565 if err != nil {
66 Log(fmt.Sprintf("Failed to update window title: %v", err), logFile)
66 Log(fmt.Sprintf("Failed to update window title: %v", err))
6767 }
6868
6969 return mpvSocketPath, nil
@@ -74,7 +74,7 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
7474 randomBytes := make([]byte, 4)
7575 _, err = rand.Read(randomBytes)
7676 if err != nil {
77 Log("Failed to generate random number", logFile)
77 Log("Failed to generate random number")
7878 return "", fmt.Errorf("failed to generate random number: %w", err)
7979 }
8080
@@ -110,7 +110,7 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
110110 mpvPath, err := getMPVPath()
111111 if err != nil {
112112 CurdOut("Error: Failed to get MPV path")
113 Log("Failed to get mpv path.", logFile)
113 Log("Failed to get mpv path.")
114114 return "", err
115115 }
116116
@@ -202,7 +202,7 @@ func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
202202func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
203203 speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
204204 if err != nil || speed == nil {
205 Log("Failed to get playback speed.", logFile)
205 Log("Failed to get playback speed.")
206206 return 0, err
207207 }
208208
internal/selection_menu.go +3 −3
@@ -228,7 +228,7 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
228228 // Download and get cache path for the image
229229 cachePath, err := downloadToCache(option.CoverImage)
230230 if err != nil {
231 Log(fmt.Sprintf("Error caching image: %v", err), logFile)
231 Log(fmt.Sprintf("Error caching image: %v", err))
232232 continue
233233 }
234234
@@ -269,8 +269,8 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
269269 err := rofiCmd.Run()
270270 if err != nil {
271271 // Log both stdout and stderr for debugging
272 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()), logFile)
273 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()), logFile)
272 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
273 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
274274 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
275275 }
276276