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() {
20 var anime internal.Anime 20 var anime internal.Anime
21 var user internal.User 21 var user internal.User
22 22
23 internal.SetGlobalAnime(&anime)
24
23 var homeDir string 25 var homeDir string
24 if runtime.GOOS == "windows" { 26 if runtime.GOOS == "windows" {
25 homeDir = os.Getenv("USERPROFILE") 27 homeDir = os.Getenv("USERPROFILE")
@@ -42,6 +44,7 @@ func main() {
42 defer internal.RestoreScreen() 44 defer internal.RestoreScreen()
43 45
44 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log") 46 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
47 internal.SetGlobalLogFile(logFile)
45 internal.ClearLogFile(logFile) 48 internal.ClearLogFile(logFile)
46 49
47 // Flags configured here cause userconfig needs to be changed. 50 // Flags configured here cause userconfig needs to be changed.
@@ -137,7 +140,7 @@ func main() {
137 // Get the token from the token file 140 // Get the token from the token file
138 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token")) 141 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
139 if err != nil { 142 if err != nil {
140 internal.Log("Error reading token", logFile) 143 internal.Log("Error reading token")
141 } 144 }
142 if user.Token == "" { 145 if user.Token == "" {
143 internal.ChangeToken(&userCurdConfig, &user) 146 internal.ChangeToken(&userCurdConfig, &user)
@@ -154,7 +157,7 @@ func main() {
154 // Call the function to check and download files 157 // Call the function to check and download files
155 err := internal.CheckAndDownloadFiles(os.ExpandEnv(userCurdConfig.StoragePath), filesToCheck) 158 err := internal.CheckAndDownloadFiles(os.ExpandEnv(userCurdConfig.StoragePath), filesToCheck)
156 if err != nil { 159 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))
158 internal.CurdOut(fmt.Sprintf("Error checking and downloading files: %v\n", err)) 161 internal.CurdOut(fmt.Sprintf("Error checking and downloading files: %v\n", err))
159 internal.ExitCurd(err) 162 internal.ExitCurd(err)
160 } 163 }
@@ -165,22 +168,22 @@ func main() {
165 databaseAnimes := internal.LocalGetAllAnime(databaseFile) 168 databaseAnimes := internal.LocalGetAllAnime(databaseFile)
166 169
167 if *addNewAnime { 170 if *addNewAnime {
168 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes, logFile) 171 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes)
169 // internal.ExitCurd(fmt.Errorf("Added new anime!")) 172 // internal.ExitCurd(fmt.Errorf("Added new anime!"))
170 } 173 }
171 174
172 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes, logFile) 175 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes)
173 176
174 temp_anime, err := internal.FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)) 177 temp_anime, err := internal.FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId))
175 if err != nil { 178 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())
177 } 180 }
178 181
179 if anime.TotalEpisodes == temp_anime.Progress { 182 if anime.TotalEpisodes == temp_anime.Progress {
180 internal.Log(temp_anime.Progress, logFile) 183 internal.Log(temp_anime.Progress)
181 internal.Log(anime.TotalEpisodes, logFile) 184 internal.Log(anime.TotalEpisodes)
182 internal.Log(user.AnimeList, logFile) 185 internal.Log(user.AnimeList)
183 internal.Log("Rewatching anime: "+internal.GetAnimeName(anime), logFile) 186 internal.Log("Rewatching anime: "+internal.GetAnimeName(anime))
184 anime.Rewatching = true 187 anime.Rewatching = true
185 } 188 }
186 189
@@ -192,7 +195,7 @@ func main() {
192 if anime.MalId == 0 { 195 if anime.MalId == 0 {
193 malID, err := internal.GetAnimeMalID(anime.AnilistId) 196 malID, err := internal.GetAnimeMalID(anime.AnilistId)
194 if err != nil { 197 if err != nil {
195 internal.Log("Error getting MAL ID: "+err.Error(), logFile) 198 internal.Log("Error getting MAL ID: "+err.Error())
196 return 199 return
197 } 200 }
198 anime.MalId = malID 201 anime.MalId = malID
@@ -200,10 +203,10 @@ func main() {
200 203
201 fillerList, err := internal.FetchFillerEpisodes(anime.MalId) 204 fillerList, err := internal.FetchFillerEpisodes(anime.MalId)
202 if err != nil { 205 if err != nil {
203 internal.Log("Error getting filler list: "+err.Error(), logFile) 206 internal.Log("Error getting filler list: "+err.Error())
204 } else { 207 } else {
205 anime.FillerEpisodes = fillerList 208 anime.FillerEpisodes = fillerList
206 internal.Log("Filler list fetched successfully", logFile) 209 internal.Log("Filler list fetched successfully")
207 // fmt.Println("Filler episodes: ", anime.FillerEpisodes) 210 // fmt.Println("Filler episodes: ", anime.FillerEpisodes)
208 } 211 }
209 }() 212 }()
@@ -211,7 +214,7 @@ func main() {
211 // Main loop (loop to keep starting new episodes) 214 // Main loop (loop to keep starting new episodes)
212 for { 215 for {
213 216
214 internal.Log(anime, logFile) 217 internal.Log(anime)
215 218
216 // Create a channel to signal when to exit the skip loop 219 // Create a channel to signal when to exit the skip loop
217 var wg sync.WaitGroup 220 var wg sync.WaitGroup
@@ -221,16 +224,16 @@ func main() {
221 if userCurdConfig.DiscordPresence { 224 if userCurdConfig.DiscordPresence {
222 anime.MalId, anime.CoverImage, err = internal.GetAnimeIDAndImage(anime.AnilistId) 225 anime.MalId, anime.CoverImage, err = internal.GetAnimeIDAndImage(anime.AnilistId)
223 if err != nil { 226 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())
225 } 228 }
226 err = internal.DiscordPresence(discordClientId, anime, false) 229 err = internal.DiscordPresence(discordClientId, anime, false)
227 if err != nil { 230 if err != nil {
228 internal.Log("Error setting Discord presence: "+err.Error(), logFile) 231 internal.Log("Error setting Discord presence: "+err.Error())
229 } 232 }
230 } else if anime.MalId == 0 { 233 } else if anime.MalId == 0 {
231 anime.MalId, err = internal.GetAnimeMalID(anime.AnilistId) 234 anime.MalId, err = internal.GetAnimeMalID(anime.AnilistId)
232 if err != nil { 235 if err != nil {
233 internal.Log("Error getting anime MAL ID: "+err.Error(), logFile) 236 internal.Log("Error getting anime MAL ID: "+err.Error())
234 } 237 }
235 } 238 }
236 239
@@ -239,7 +242,7 @@ func main() {
239 // Check if current episode is filler/recap 242 // Check if current episode is filler/recap
240 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) 243 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime)
241 if err != nil { 244 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())
243 break // Break the loop and continue with playback 246 break // Break the loop and continue with playback
244 } 247 }
245 248
@@ -276,9 +279,9 @@ func main() {
276 } 279 }
277 280
278 // Now start playback for the non-filler episode 281 // Now start playback for the non-filler episode
279 anime.Ep.Player.SocketPath = internal.StartCurd(&userCurdConfig, &anime, logFile) 282 anime.Ep.Player.SocketPath = internal.StartCurd(&userCurdConfig, &anime)
280 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime), logFile) 283 internal.Log(fmt.Sprint("Playback starting time: ", anime.Ep.Player.PlaybackTime))
281 internal.Log(anime.Ep.Player.SocketPath, logFile) 284 internal.Log(anime.Ep.Player.SocketPath)
282 285
283 wg.Add(1) 286 wg.Add(1)
284 // Get episode data 287 // Get episode data
@@ -286,28 +289,28 @@ func main() {
286 defer wg.Done() 289 defer wg.Done()
287 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) 290 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime)
288 if err != nil { 291 if err != nil {
289 internal.Log("Error getting episode data: "+err.Error(), logFile) 292 internal.Log("Error getting episode data: "+err.Error())
290 } else { 293 } else {
291 internal.Log(anime, logFile) 294 internal.Log(anime)
292 295
293 // if filler episode or recap episode and skip is enabled 296 // if filler episode or recap episode and skip is enabled
294 if (anime.Ep.IsFiller && userCurdConfig.SkipFiller) || (anime.Ep.IsRecap && userCurdConfig.SkipRecap) { 297 if (anime.Ep.IsFiller && userCurdConfig.SkipFiller) || (anime.Ep.IsRecap && userCurdConfig.SkipRecap) {
295 if anime.Ep.IsFiller && userCurdConfig.SkipFiller { 298 if anime.Ep.IsFiller && userCurdConfig.SkipFiller {
296 internal.CurdOut(fmt.Sprint("Filler Episode, starting next episode: ", anime.Ep.Number+1)) 299 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")
298 } else if anime.Ep.IsRecap && userCurdConfig.SkipRecap { 301 } else if anime.Ep.IsRecap && userCurdConfig.SkipRecap {
299 internal.CurdOut(fmt.Sprint("Recap Episode, starting next episode: ", anime.Ep.Number+1)) 302 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")
301 } 304 }
302 anime.Ep.Number++ 305 anime.Ep.Number++
303 anime.Ep.Started = false 306 anime.Ep.Started = false
304 anime.Ep.IsCompleted = true 307 anime.Ep.IsCompleted = true
305 internal.Log("Skipping filler episode, starting next.", logFile) 308 internal.Log("Skipping filler episode, starting next.")
306 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime)) 309 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
307 // Send command to close MPV 310 // Send command to close MPV
308 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 311 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
309 if err != nil { 312 if err != nil {
310 internal.Log("Error closing MPV: "+err.Error(), logFile) 313 internal.Log("Error closing MPV: "+err.Error())
311 } 314 }
312 // Exit the skip loop 315 // Exit the skip loop
313 close(skipLoopDone) 316 close(skipLoopDone)
@@ -327,7 +330,7 @@ func main() {
327 default: 330 default:
328 isPaused, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "pause"}) 331 isPaused, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "pause"})
329 if err != nil { 332 if err != nil {
330 internal.Log("Error getting pause status: "+err.Error(), logFile) 333 internal.Log("Error getting pause status: "+err.Error())
331 } 334 }
332 if isPaused == nil { 335 if isPaused == nil {
333 isPaused = true 336 isPaused = true
@@ -336,7 +339,7 @@ func main() {
336 } 339 }
337 err = internal.DiscordPresence(discordClientId, anime, isPaused.(bool)) 340 err = internal.DiscordPresence(discordClientId, anime, isPaused.(bool))
338 if err != nil { 341 if err != nil {
339 // internal.Log("Error setting Discord presence: "+err.Error(), logFile) 342 // internal.Log("Error setting Discord presence: "+err.Error())
340 } 343 }
341 time.Sleep(1 * time.Second) 344 time.Sleep(1 * time.Second)
342 } 345 }
@@ -348,9 +351,9 @@ func main() {
348 go func() { 351 go func() {
349 err = internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime) 352 err = internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime)
350 if err != nil { 353 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())
352 } 355 }
353 internal.Log(anime.Ep.SkipTimes, logFile) 356 internal.Log(anime.Ep.SkipTimes)
354 }() 357 }()
355 358
356 // Get video duration 359 // Get video duration
@@ -361,13 +364,13 @@ func main() {
361 // Get video duration 364 // Get video duration
362 durationPos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"}) 365 durationPos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
363 if err != nil { 366 if err != nil {
364 internal.Log("Error getting video duration: "+err.Error(), logFile) 367 internal.Log("Error getting video duration: "+err.Error())
365 } else if durationPos != nil { 368 } else if durationPos != nil {
366 if duration, ok := durationPos.(float64); ok { 369 if duration, ok := durationPos.(float64); ok {
367 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer 370 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))
369 } else { 372 } else {
370 internal.Log("Error: duration is not a float64", logFile) 373 internal.Log("Error: duration is not a float64")
371 } 374 }
372 } 375 }
373 break 376 break
@@ -389,32 +392,32 @@ func main() {
389 time.Sleep(1 * time.Second) 392 time.Sleep(1 * time.Second)
390 393
391 // Get current playback time 394 // 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)
393 timePos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}) 396 timePos, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
394 if err != nil { 397 if err != nil {
395 internal.Log("Error getting playback time: "+err.Error(), logFile) 398 internal.Log("Error getting playback time: "+err.Error())
396 399
397 // Check if the error is due to invalid JSON 400 // Check if the error is due to invalid JSON
398 // User closed the video 401 // User closed the video
399 if anime.Ep.Started { 402 if anime.Ep.Started {
400 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 403 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
401 // Episode is completed 404 // Episode is completed
402 internal.Log(fmt.Sprint(percentageWatched), logFile) 405 internal.Log(fmt.Sprint(percentageWatched))
403 internal.Log(fmt.Sprint(anime.Ep.Player.Speed), logFile) 406 internal.Log(fmt.Sprint(anime.Ep.Player.Speed))
404 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime), logFile) 407 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
405 internal.Log(fmt.Sprint(anime.Ep.Duration), logFile) 408 internal.Log(fmt.Sprint(anime.Ep.Duration))
406 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete), logFile) 409 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
407 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 410 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
408 anime.Ep.Number++ 411 anime.Ep.Number++
409 anime.Ep.Started = false 412 anime.Ep.Started = false
410 internal.Log("Completed episode, starting next.", logFile) 413 internal.Log("Completed episode, starting next.")
411 anime.Ep.IsCompleted = true 414 anime.Ep.IsCompleted = true
412 // Exit the skip loop 415 // Exit the skip loop
413 close(skipLoopDone) 416 close(skipLoopDone)
414 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed 417 } 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...")
416 } else { 419 } else {
417 internal.Log("Episode is not completed, exiting", logFile) 420 internal.Log("Episode is not completed, exiting")
418 internal.ExitCurd(nil) 421 internal.ExitCurd(nil)
419 } 422 }
420 } 423 }
@@ -429,7 +432,7 @@ func main() {
429 speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed} 432 speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed}
430 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd) 433 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd)
431 if err != nil { 434 if err != nil {
432 internal.Log("Error setting playback speed: "+err.Error(), logFile) 435 internal.Log("Error setting playback speed: "+err.Error())
433 } 436 }
434 } 437 }
435 } 438 }
@@ -442,7 +445,7 @@ func main() {
442 445
443 animePosition, ok := timePos.(float64) 446 animePosition, ok := timePos.(float64)
444 if !ok { 447 if !ok {
445 internal.Log("Error: timePos is not a float64", logFile) 448 internal.Log("Error: timePos is not a float64")
446 continue 449 continue
447 } 450 }
448 451
@@ -450,20 +453,20 @@ func main() {
450 // Update Local Database 453 // Update Local Database
451 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime)) 454 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
452 if err != nil { 455 if err != nil {
453 internal.Log("Error updating local database: "+err.Error(), logFile) 456 internal.Log("Error updating local database: "+err.Error())
454 } else { 457 } else {
455 // internal.Log(fmt.Sprintf("Updated database: AnilistId=%d, AllanimeId=%s, EpNumber=%d, PlaybackTime=%d", 458 // 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))
457 } 460 }
458 } 461 }
459 462
460 // Check if anything is playing, if nothing is playing and episode was started, start next episode 463 // Check if anything is playing, if nothing is playing and episode was started, start next episode
461 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath) 464 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath)
462 if err != nil { 465 if err != nil {
463 internal.Log("Error checking playback status: "+err.Error(), logFile) 466 internal.Log("Error checking playback status: "+err.Error())
464 } else if !hasPlayback && anime.Ep.Started { 467 } else if !hasPlayback && anime.Ep.Started {
465 // Nothing is playing, start next episode 468 // 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")
467 anime.Ep.Number++ 470 anime.Ep.Number++
468 anime.Ep.Started = false 471 anime.Ep.Started = false
469 anime.Ep.IsCompleted = true 472 anime.Ep.IsCompleted = true
@@ -497,7 +500,7 @@ func main() {
497 if err == nil && anime.Ep.Started { 500 if err == nil && anime.Ep.Started {
498 anime.Ep.Player.Speed, err = internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath) 501 anime.Ep.Player.Speed, err = internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath)
499 if err != nil { 502 if err != nil {
500 internal.Log("Failed to get mpv speed "+err.Error(), logFile) 503 internal.Log("Failed to get mpv speed "+err.Error())
501 } 504 }
502 } 505 }
503 } 506 }
@@ -516,7 +519,7 @@ func main() {
516 go func() { 519 go func() {
517 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1) 520 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1)
518 if err != nil { 521 if err != nil {
519 internal.Log("Error updating Anilist progress: "+err.Error(), logFile) 522 internal.Log("Error updating Anilist progress: "+err.Error())
520 } 523 }
521 }() 524 }()
522 525
@@ -527,13 +530,13 @@ func main() {
527 // Get updated anime data to check if it's still airing 530 // Get updated anime data to check if it's still airing
528 updatedAnime, err := internal.GetAnimeDataByID(anime.AnilistId, user.Token) 531 updatedAnime, err := internal.GetAnimeDataByID(anime.AnilistId, user.Token)
529 if err != nil { 532 if err != nil {
530 internal.Log("Error getting updated anime data: "+err.Error(), logFile) 533 internal.Log("Error getting updated anime data: "+err.Error())
531 } else if !updatedAnime.IsAiring { 534 } else if !updatedAnime.IsAiring {
532 anime.Ep.Number = anime.Ep.Number - 1 535 anime.Ep.Number = anime.Ep.Number - 1
533 internal.CurdOut("Completed anime.") 536 internal.CurdOut("Completed anime.")
534 err = internal.RateAnime(user.Token, anime.AnilistId) 537 err = internal.RateAnime(user.Token, anime.AnilistId)
535 if err != nil { 538 if err != nil {
536 internal.Log("Error rating anime: "+err.Error(), logFile) 539 internal.Log("Error rating anime: "+err.Error())
537 internal.CurdOut("Error rating anime: " + err.Error()) 540 internal.CurdOut("Error rating anime: " + err.Error())
538 } 541 }
539 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId) 542 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
@@ -560,7 +563,7 @@ func main() {
560 // Send command to close MPV 563 // Send command to close MPV
561 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 564 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
562 if err != nil { 565 if err != nil {
563 internal.Log("Error closing MPV: "+err.Error(), logFile) 566 internal.Log("Error closing MPV: "+err.Error())
564 } 567 }
565 internal.ExitCurd(nil) 568 internal.ExitCurd(nil)
566 } 569 }
go.mod +10 −10
@@ -1,34 +1,34 @@
1module github.com/wraient/curd 1module github.com/wraient/curd
2 2
3go 1.23.2 3go 1.24.0
4 4
5require ( 5require (
6 github.com/Microsoft/go-winio v0.6.2 6 github.com/Microsoft/go-winio v0.6.2
7 github.com/charmbracelet/bubbletea v1.1.1 7 github.com/charmbracelet/bubbletea v1.3.3
8 github.com/charmbracelet/lipgloss v0.13.0 8 github.com/charmbracelet/lipgloss v1.0.0
9 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 9 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
11) 11)
12 12
13require ( 13require (
14 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect 14 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
15 github.com/charmbracelet/x/ansi v0.2.3 // indirect 15 github.com/charmbracelet/x/ansi v0.8.0 // indirect
16 github.com/charmbracelet/x/term v0.2.0 // indirect 16 github.com/charmbracelet/x/term v0.2.1 // indirect
17 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect 17 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
18 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect 18 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
19 github.com/godbus/dbus/v5 v5.1.0 // indirect 19 github.com/godbus/dbus/v5 v5.1.0 // indirect
20 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 20 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
21 github.com/mattn/go-isatty v0.0.20 // indirect 21 github.com/mattn/go-isatty v0.0.20 // indirect
22 github.com/mattn/go-localereader v0.0.1 // indirect 22 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
24 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect 24 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
25 github.com/muesli/cancelreader v0.2.2 // indirect 25 github.com/muesli/cancelreader v0.2.2 // indirect
26 github.com/muesli/termenv v0.15.2 // indirect 26 github.com/muesli/termenv v0.15.2 // indirect
27 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect 27 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
28 github.com/rivo/uniseg v0.4.7 // indirect 28 github.com/rivo/uniseg v0.4.7 // indirect
29 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect 29 github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
30 golang.org/x/sync v0.8.0 // indirect 30 golang.org/x/sync v0.11.0 // indirect
31 golang.org/x/sys v0.24.0 // indirect 31 golang.org/x/sys v0.30.0 // indirect
32 golang.org/x/text v0.14.0 // indirect 32 golang.org/x/text v0.3.8 // indirect
33 gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect 33 gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
34) 34)
go.sum +18 −18
@@ -2,14 +2,14 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
2github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= 2github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
3github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= 3github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
4github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 4github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
5github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY= 5github.com/charmbracelet/bubbletea v1.3.3 h1:WpU6fCY0J2vDWM3zfS3vIDi/ULq3SYphZhkAGGvmEUY=
6github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4= 6github.com/charmbracelet/bubbletea v1.3.3/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo=
7github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw= 7github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg=
8github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY= 8github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo=
9github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY= 9github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
10github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= 10github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
11github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= 11github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
12github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= 12github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
13github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= 13github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= 14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI= 15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI=
@@ -18,16 +18,14 @@ github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/Oq
18github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10= 18github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=
19github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= 19github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
20github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 20github.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=
23github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 21github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
24github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 22github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
25github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 23github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
26github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 24github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
27github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= 25github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
28github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= 26github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
29github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= 27github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
30github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 28github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
31github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= 29github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
32github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= 30github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
33github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= 31github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
@@ -41,13 +39,15 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
41github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 39github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
42github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk= 40github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
43github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o= 41github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
44golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= 42github.com/wraient/rich-go v0.0.0-20250215175626-21ded92fb65a h1:J6QBl/BbJglPMI3BBhbGHjEEc6Ju+mvh/+ylv39tELw=
45golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 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=
46golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 46golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
47golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 47golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
48golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= 48golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
49golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 49golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
50golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 50golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
51golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 51golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
52gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= 52gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU=
53gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= 53gopkg.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 {
59 populateMap := func(entries []Entry) { 59 populateMap := func(entries []Entry) {
60 for _, entry := range entries { 60 for _, entry := range entries {
61 // Only include entries with a non-empty English title 61 // 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))
63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ 64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
65 Title: entry.Media.Title.English, 65 Title: entry.Media.Title.English,
@@ -670,7 +670,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
670 670
671 // Access the list entries in the input map 671 // Access the list entries in the input map
672 if input["data"] == nil { 672 if input["data"] == nil {
673 Log("Anilist request failed", logFile) 673 Log("Anilist request failed")
674 CurdOut("Anilist request failed") 674 CurdOut("Anilist request failed")
675 ExitCurd(fmt.Errorf("Anilist request failed")) 675 ExitCurd(fmt.Errorf("Anilist request failed"))
676 return animeList 676 return animeList
internal/anime_list.go +8 −9
@@ -43,7 +43,6 @@ type response struct {
43 43
44func SearchAnime(query, mode string) (map[string]string, error) { 44func SearchAnime(query, mode string) (map[string]string, error) {
45 userCurdConfig := GetGlobalConfig() 45 userCurdConfig := GetGlobalConfig()
46 var logFile string
47 if userCurdConfig == nil { 46 if userCurdConfig == nil {
48 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log") 47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
49 } else { 48 } else {
@@ -87,7 +86,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
87 // Marshal the variables to JSON 86 // Marshal the variables to JSON
88 variablesJSON, err := json.Marshal(variables) 87 variablesJSON, err := json.Marshal(variables)
89 if err != nil { 88 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))
91 return animeList, err 90 return animeList, err
92 } 91 }
93 92
@@ -97,7 +96,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
97 // Make the HTTP request 96 // Make the HTTP request
98 req, err := http.NewRequest("GET", url, nil) 97 req, err := http.NewRequest("GET", url, nil)
99 if err != nil { 98 if err != nil {
100 Log(fmt.Sprintf("Error creating HTTP request: %v", err), logFile) 99 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
101 return animeList, err 100 return animeList, err
102 } 101 }
103 req.Header.Set("User-Agent", agent) 102 req.Header.Set("User-Agent", agent)
@@ -106,7 +105,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
106 client := &http.Client{} 105 client := &http.Client{}
107 resp, err := client.Do(req) 106 resp, err := client.Do(req)
108 if err != nil { 107 if err != nil {
109 Log(fmt.Sprintf("Error making HTTP request: %v", err), logFile) 108 Log(fmt.Sprintf("Error making HTTP request: %v", err))
110 return animeList, err 109 return animeList, err
111 } 110 }
112 defer resp.Body.Close() 111 defer resp.Body.Close()
@@ -114,19 +113,19 @@ func SearchAnime(query, mode string) (map[string]string, error) {
114 // Read the response body 113 // Read the response body
115 body, err := io.ReadAll(resp.Body) 114 body, err := io.ReadAll(resp.Body)
116 if err != nil { 115 if err != nil {
117 Log(fmt.Sprintf("Error reading response body: %v", err), logFile) 116 Log(fmt.Sprintf("Error reading response body: %v", err))
118 return animeList, err 117 return animeList, err
119 } 118 }
120 119
121 // Debug: Log the response status and first part of the body 120 // Debug: Log the response status and first part of the body
122 Log(fmt.Sprintf("Response Status: %s", resp.Status), logFile) 121 Log(fmt.Sprintf("Response Status: %s", resp.Status))
123 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])), logFile) 122 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
124 123
125 // Parse the JSON response 124 // Parse the JSON response
126 var response response 125 var response response
127 err = json.Unmarshal(body, &response) 126 err = json.Unmarshal(body, &response)
128 if err != nil { 127 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)))
130 return animeList, err 129 return animeList, err
131 } 130 }
132 131
@@ -136,7 +135,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
136 if subEpisodes, ok := episodes["sub"].(float64); ok { 135 if subEpisodes, ok := episodes["sub"].(float64); ok {
137 episodesStr = fmt.Sprintf("%d", int(subEpisodes)) 136 episodesStr = fmt.Sprintf("%d", int(subEpisodes))
138 } else { 137 } else {
139 Log(subEpisodes, logFile) 138 Log(subEpisodes)
140 episodesStr = "Unknown" 139 episodesStr = "Unknown"
141 } 140 }
142 } 141 }
internal/aniskip.go +3 −3
@@ -32,19 +32,19 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
32 32
33 resp, err := http.Get(url) 33 resp, err := http.Get(url)
34 if err != nil { 34 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))
36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err) 36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err)
37 } 37 }
38 defer resp.Body.Close() 38 defer resp.Body.Close()
39 39
40 if resp.StatusCode != http.StatusOK { 40 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))
42 return "", fmt.Errorf("failed with status %d", resp.StatusCode) 42 return "", fmt.Errorf("failed with status %d", resp.StatusCode)
43 } 43 }
44 44
45 body, err := io.ReadAll(resp.Body) 45 body, err := io.ReadAll(resp.Body)
46 if err != nil { 46 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))
48 return "", fmt.Errorf("failed to read response body %w", err) 48 return "", fmt.Errorf("failed to read response body %w", err)
49 } 49 }
50 50
internal/config.go +1 −1
@@ -240,7 +240,7 @@ func ChangeToken(config *CurdConfig, user *User) {
240 } 240 }
241 241
242 if err != nil { 242 if err != nil {
243 Log("Error getting user input: "+err.Error(), logFile) 243 Log("Error getting user input: "+err.Error())
244 ExitCurd(err) 244 ExitCurd(err)
245 } 245 }
246 246
internal/curd.go +422 −415
@@ -79,13 +79,14 @@ func ClearLogFile(logFile string) error {
79} 79}
80 80
81// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData 81// 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()
83 // Open or create the log file 84 // Open or create the log file
84 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) 85 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
85 if err != nil { 86 if err != nil {
86 return err 87 return err
87 } 88 }
88 defer file.Close() // Ensure the file is closed when done 89 defer file.Close()
89 90
90 // Attempt to marshal the data into JSON 91 // Attempt to marshal the data into JSON
91 jsonData, err := json.Marshal(data) 92 jsonData, err := json.Marshal(data)
@@ -118,9 +119,9 @@ func ClearScreen() {
118 return 119 return
119 } 120 }
120 121
121 fmt.Print("\033[?1049h") // Switch to alternate screen buffer 122 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
122 fmt.Print("\033[2J") // Clear the entire screen 123 fmt.Print("\033[2J") // Clear the entire screen
123 fmt.Print("\033[H") // Move cursor to the top left 124 fmt.Print("\033[H") // Move cursor to the top left
124} 125}
125 126
126// RestoreScreen restores the original terminal state 127// RestoreScreen restores the original terminal state
@@ -131,11 +132,20 @@ func RestoreScreen() {
131 return 132 return
132 } 133 }
133 134
134 fmt.Print("\033[?1049l") // Switch back to the main screen buffer 135 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
135} 136}
136 137
137func ExitCurd(err error) { 138func ExitCurd(err error) {
138 RestoreScreen() 139 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
139 CurdOut("Have a great day!") 149 CurdOut("Have a great day!")
140 if err != nil { 150 if err != nil {
141 CurdOut(err) 151 CurdOut(err)
@@ -166,9 +176,9 @@ func CurdOut(data interface{}) {
166 fmt.Sprintf("%v", data), 176 fmt.Sprintf("%v", data),
167 "", 177 "",
168 ) 178 )
169 179
170 if err != nil { 180 if err != nil {
171 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile) 181 Log(fmt.Sprintf("Failed to send notification: %v", err))
172 } 182 }
173 case "linux": 183 case "linux":
174 // Check if the input starts with "-i" for image notification 184 // Check if the input starts with "-i" for image notification
@@ -179,35 +189,35 @@ func CurdOut(data interface{}) {
179 if len(parts) == 3 { 189 if len(parts) == 3 {
180 // Remove quotes from the message 190 // Remove quotes from the message
181 message := strings.Trim(parts[2], "\"") 191 message := strings.Trim(parts[2], "\"")
182 cmd := exec.Command("notify-send", 192 cmd := exec.Command("notify-send",
183 "-a", "Curd", 193 "-a", "Curd",
184 "-h", "string:x-canonical-private-synchronous:curd-notification", 194 "-h", "string:x-canonical-private-synchronous:curd-notification",
185 "Curd", 195 "Curd",
186 "-i", parts[1], 196 "-i", parts[1],
187 message) 197 message)
188 err := cmd.Run() 198 err := cmd.Run()
189 if err != nil { 199 if err != nil {
190 Log(fmt.Sprintf("%v", cmd), logFile) 200 Log(fmt.Sprintf("%v", cmd))
191 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile) 201 Log(fmt.Sprintf("Failed to send notification: %v", err))
192 } 202 }
193 } 203 }
194 } else { 204 } else {
195 cmd := exec.Command("notify-send", 205 cmd := exec.Command("notify-send",
196 "-a", "Curd", 206 "-a", "Curd",
197 "-h", "string:x-canonical-private-synchronous:curd-notification", 207 "-h", "string:x-canonical-private-synchronous:curd-notification",
198 "Curd", 208 "Curd",
199 dataStr) 209 dataStr)
200 err := cmd.Run() 210 err := cmd.Run()
201 if err != nil { 211 if err != nil {
202 Log(fmt.Sprintf("%v", cmd), logFile) 212 Log(fmt.Sprintf("%v", cmd))
203 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile) 213 Log(fmt.Sprintf("Failed to send notification: %v", err))
204 } 214 }
205 } 215 }
206 } 216 }
207 } 217 }
208} 218}
209 219
210func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) { 220func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
211 // Create update options map 221 // Create update options map
212 updateOptions := map[string]string{ 222 updateOptions := map[string]string{
213 "CATEGORY": "Change Anime Category", 223 "CATEGORY": "Change Anime Category",
@@ -218,7 +228,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
218 // Select update option 228 // Select update option
219 updateSelection, err := DynamicSelect(updateOptions, false) 229 updateSelection, err := DynamicSelect(updateOptions, false)
220 if err != nil { 230 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))
222 ExitCurd(fmt.Errorf("Failed to select update option")) 232 ExitCurd(fmt.Errorf("Failed to select update option"))
223 } 233 }
224 234
@@ -331,7 +341,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
331 selectedAnime, err = DynamicSelect(animeListMap, false) 341 selectedAnime, err = DynamicSelect(animeListMap, false)
332 } 342 }
333 if err != nil { 343 if err != nil {
334 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile) 344 Log(fmt.Sprintf("Failed to select anime: %v", err))
335 ExitCurd(fmt.Errorf("Failed to select anime")) 345 ExitCurd(fmt.Errorf("Failed to select anime"))
336 } 346 }
337 347
@@ -341,17 +351,17 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
341 351
342 animeID, err := strconv.Atoi(selectedAnime.Key) 352 animeID, err := strconv.Atoi(selectedAnime.Key)
343 if err != nil { 353 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))
345 ExitCurd(fmt.Errorf("Failed to convert anime ID")) 355 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
346 } 356 }
347 357
348 // After getting animeID, get the current anime entry 358 // After getting animeID, get the current anime entry
349 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key) 359 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
350 if err != nil { 360 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))
352 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) 362 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
353 } 363 }
354 ClearScreen() 364 ClearScreen()
355 switch updateSelection.Key { 365 switch updateSelection.Key {
356 case "CATEGORY": 366 case "CATEGORY":
357 categories := map[string]string{ 367 categories := map[string]string{
@@ -370,7 +380,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
370 380
371 categorySelection, err := DynamicSelect(categories, false) 381 categorySelection, err := DynamicSelect(categories, false)
372 if err != nil { 382 if err != nil {
373 Log(fmt.Sprintf("Failed to select category: %v", err), logFile) 383 Log(fmt.Sprintf("Failed to select category: %v", err))
374 ExitCurd(fmt.Errorf("Failed to select category")) 384 ExitCurd(fmt.Errorf("Failed to select category"))
375 } 385 }
376 386
@@ -380,7 +390,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
380 390
381 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key) 391 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
382 if err != nil { 392 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))
384 ExitCurd(fmt.Errorf("Failed to update anime status")) 394 ExitCurd(fmt.Errorf("Failed to update anime status"))
385 } 395 }
386 396
@@ -394,7 +404,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
394 if userCurdConfig.RofiSelection { 404 if userCurdConfig.RofiSelection {
395 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress)) 405 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
396 if err != nil { 406 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))
398 ExitCurd(fmt.Errorf("Failed to get progress input")) 408 ExitCurd(fmt.Errorf("Failed to get progress input"))
399 } 409 }
400 } else { 410 } else {
@@ -405,13 +415,13 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
405 415
406 progressNum, err := strconv.Atoi(progress) 416 progressNum, err := strconv.Atoi(progress)
407 if err != nil { 417 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))
409 ExitCurd(fmt.Errorf("Failed to convert progress to number")) 419 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
410 } 420 }
411 421
412 err = UpdateAnimeProgress(user.Token, animeID, progressNum) 422 err = UpdateAnimeProgress(user.Token, animeID, progressNum)
413 if err != nil { 423 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))
415 ExitCurd(fmt.Errorf("Failed to update anime progress")) 425 ExitCurd(fmt.Errorf("Failed to update anime progress"))
416 } 426 }
417 427
@@ -424,7 +434,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
424 434
425 err = RateAnime(user.Token, animeID) 435 err = RateAnime(user.Token, animeID)
426 if err != nil { 436 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))
428 ExitCurd(fmt.Errorf("Failed to update anime score")) 438 ExitCurd(fmt.Errorf("Failed to update anime score"))
429 } 439 }
430 } 440 }
@@ -433,11 +443,11 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
433} 443}
434 444
435func UpdateCurd(repo, fileName string) error { 445func UpdateCurd(repo, fileName string) error {
436 // Get the path of the currently running executable 446 // Get the path of the currently running executable
437 executablePath, err := os.Executable() 447 executablePath, err := os.Executable()
438 if err != nil { 448 if err != nil {
439 return fmt.Errorf("unable to find current executable: %v", err) 449 return fmt.Errorf("unable to find current executable: %v", err)
440 } 450 }
441 451
442 // Determine the correct binary name based on OS and architecture 452 // Determine the correct binary name based on OS and architecture
443 var binaryName string 453 var binaryName string
@@ -463,47 +473,47 @@ func UpdateCurd(repo, fileName string) error {
463 } 473 }
464 default: 474 default:
465 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS) 475 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
466 } 476 }
467 477
468 // GitHub release URL for curd 478 // GitHub release URL for curd
469 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName) 479 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
470 480
471 // Temporary path for the downloaded curd executable 481 // Temporary path for the downloaded curd executable
472 tmpPath := executablePath + ".tmp" 482 tmpPath := executablePath + ".tmp"
473 483
474 // Download the curd executable 484 // Download the curd executable
475 resp, err := http.Get(url) 485 resp, err := http.Get(url)
476 if err != nil { 486 if err != nil {
477 return fmt.Errorf("failed to download file: %v", err) 487 return fmt.Errorf("failed to download file: %v", err)
478 } 488 }
479 defer resp.Body.Close() 489 defer resp.Body.Close()
480 490
481 // Check if the download was successful 491 // Check if the download was successful
482 if resp.StatusCode != http.StatusOK { 492 if resp.StatusCode != http.StatusOK {
483 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode) 493 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
484 } 494 }
485 495
486 // Create a new temporary file 496 // Create a new temporary file
487 out, err := os.Create(tmpPath) 497 out, err := os.Create(tmpPath)
488 if err != nil { 498 if err != nil {
489 return fmt.Errorf("failed to create temporary file: %v", err) 499 return fmt.Errorf("failed to create temporary file: %v", err)
490 } 500 }
491 defer out.Close() 501 defer out.Close()
492 502
493 // Write the downloaded content to the temporary file 503 // Write the downloaded content to the temporary file
494 _, err = io.Copy(out, resp.Body) 504 _, err = io.Copy(out, resp.Body)
495 if err != nil { 505 if err != nil {
496 return fmt.Errorf("failed to save downloaded file: %v", err) 506 return fmt.Errorf("failed to save downloaded file: %v", err)
497 } 507 }
498 508
499 // Close and rename the temporary file to replace the current executable 509 // Close and rename the temporary file to replace the current executable
500 out.Close() 510 out.Close()
501 511
502 // Replace the current executable with the downloaded curd 512 // Replace the current executable with the downloaded curd
503 if err := os.Rename(tmpPath, executablePath); err != nil { 513 if err := os.Rename(tmpPath, executablePath); err != nil {
504 return fmt.Errorf("failed to replace the current executable: %v", err) 514 return fmt.Errorf("failed to replace the current executable: %v", err)
505 } 515 }
506 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath)) 516 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
507 517
508 if runtime.GOOS != "windows" { 518 if runtime.GOOS != "windows" {
509 // Ensure the new file has executable permissions 519 // Ensure the new file has executable permissions
@@ -511,11 +521,11 @@ func UpdateCurd(repo, fileName string) error {
511 return fmt.Errorf("failed to set permissions on the new file: %v", err) 521 return fmt.Errorf("failed to set permissions on the new file: %v", err)
512 } 522 }
513 } 523 }
514 524
515 return nil 525 return nil
516} 526}
517 527
518func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption { 528func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
519 var query string 529 var query string
520 var animeMap map[string]string 530 var animeMap map[string]string
521 var animeMapPreview map[string]RofiSelectPreview 531 var animeMapPreview map[string]RofiSelectPreview
@@ -527,8 +537,8 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
527 if userCurdConfig.RofiSelection { 537 if userCurdConfig.RofiSelection {
528 userInput, err := GetUserInputFromRofi("Enter the anime name") 538 userInput, err := GetUserInputFromRofi("Enter the anime name")
529 if err != nil { 539 if err != nil {
530 Log("Error getting user input: "+err.Error(), logFile) 540 Log("Error getting user input: "+err.Error())
531 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error())) 541 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
532 } 542 }
533 query = userInput 543 query = userInput
534 } else { 544 } else {
@@ -541,7 +551,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
541 animeMap, err = SearchAnimeAnilist(query, user.Token) 551 animeMap, err = SearchAnimeAnilist(query, user.Token)
542 } 552 }
543 if err != nil { 553 if err != nil {
544 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile) 554 Log(fmt.Sprintf("Failed to search anime: %v", err))
545 ExitCurd(fmt.Errorf("Failed to search anime")) 555 ExitCurd(fmt.Errorf("Failed to search anime"))
546 } 556 }
547 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 557 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -555,23 +565,23 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
555 } 565 }
556 566
557 if err != nil { 567 if err != nil {
558 Log(fmt.Sprintf("No anime available: %v", err), logFile) 568 Log(fmt.Sprintf("No anime available: %v", err))
559 ExitCurd(fmt.Errorf("No anime available")) 569 ExitCurd(fmt.Errorf("No anime available"))
560 } 570 }
561 animeID, err := strconv.Atoi(anilistSelectedOption.Key) 571 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
562 if err != nil { 572 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))
564 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer")) 574 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
565 } 575 }
566 err = AddAnimeToWatchingList(animeID, user.Token) 576 err = AddAnimeToWatchingList(animeID, user.Token)
567 if err != nil { 577 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))
569 ExitCurd(fmt.Errorf("Failed to add anime to watching list")) 579 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
570 } 580 }
571 if user.Id == 0 { 581 if user.Id == 0 {
572 user.Id, user.Username, err = GetAnilistUserID(user.Token) 582 user.Id, user.Username, err = GetAnilistUserID(user.Token)
573 if err != nil { 583 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))
575 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 585 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
576 } 586 }
577 } 587 }
@@ -581,7 +591,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
581 anilistUserData, err = GetUserData(user.Token, user.Id) 591 anilistUserData, err = GetUserData(user.Token, user.Id)
582 } 592 }
583 if err != nil { 593 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))
585 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 595 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
586 } 596 }
587 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 597 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -593,71 +603,70 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
593 return anilistSelectedOption 603 return anilistSelectedOption
594} 604}
595 605
596func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) { 606func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
597 var err error 607 var err error
598 var anilistUserData map[string]interface{} 608 var anilistUserData map[string]interface{}
599 var anilistUserDataPreview map[string]interface{} 609 var anilistUserDataPreview map[string]interface{}
600 610
601 // Filter anime list based on selected category 611 // Filter anime list based on selected category
602 var animeListMap map[string]string 612 var animeListMap map[string]string
603 var animeListMapPreview map[string]RofiSelectPreview 613 var animeListMapPreview map[string]RofiSelectPreview
604 614
605 615 // Get user id, username and Anime list
606 // Get user id, username and Anime list 616 user.Id, user.Username, err = GetAnilistUserID(user.Token)
607 user.Id, user.Username, err = GetAnilistUserID(user.Token) 617 if err != nil {
608 if err != nil { 618 Log(fmt.Sprintf("Failed to get user ID: %v", err))
609 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile) 619 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
610 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 620 }
611 } 621
612 622 // Get the anime list data
613 // Get the anime list data 623 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
614 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 624 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
615 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id) 625 if err != nil {
616 if err != nil { 626 Log(fmt.Sprintf("Failed to get user data preview: %v", err))
617 Log(fmt.Sprintf("Failed to get user data preview: %v", err), logFile) 627 ExitCurd(fmt.Errorf("Failed to get user data preview"))
618 ExitCurd(fmt.Errorf("Failed to get user data preview")) 628 }
619 } 629 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
620 user.AnimeList = ParseAnimeList(anilistUserDataPreview) 630 } else {
621 } else { 631 anilistUserData, err = GetUserData(user.Token, user.Id)
622 anilistUserData, err = GetUserData(user.Token, user.Id) 632 if err != nil {
623 if err != nil { 633 Log(fmt.Sprintf("Failed to get user data: %v", err))
624 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile) 634 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
625 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 635 }
626 } 636 user.AnimeList = ParseAnimeList(anilistUserData)
627 user.AnimeList = ParseAnimeList(anilistUserData) 637 }
628 }
629 638
630 // If continueLast flag is set, directly get the last watched anime 639 // If continueLast flag is set, directly get the last watched anime
631 if anime.Ep.ContinueLast { 640 if anime.Ep.ContinueLast {
632 // Get the last anime ID from the curd_id file 641 // Get the last anime ID from the curd_id file
633 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id") 642 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
634 idBytes, err := os.ReadFile(idFilePath) 643 idBytes, err := os.ReadFile(idFilePath)
635 if err != nil { 644 if err != nil {
636 Log("Error reading curd_id file: "+err.Error(), logFile) 645 Log("Error reading curd_id file: "+err.Error())
637 ExitCurd(fmt.Errorf("No last watched anime found")) 646 ExitCurd(fmt.Errorf("No last watched anime found"))
638 } 647 }
639 648
640 anilistID, err := strconv.Atoi(string(idBytes)) 649 anilistID, err := strconv.Atoi(string(idBytes))
641 if err != nil { 650 if err != nil {
642 Log("Error converting anilist ID: "+err.Error(), logFile) 651 Log("Error converting anilist ID: "+err.Error())
643 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file")) 652 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
644 } 653 }
645 654
646 // Find the anime in database 655 // Find the anime in database
647 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "") 656 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
648 if animePointer == nil { 657 if animePointer == nil {
649 ExitCurd(fmt.Errorf("Last watched anime not found in database")) 658 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
650 } 659 }
651 660
652 // Set the anime details 661 // Set the anime details
653 anime.AnilistId = animePointer.AnilistId 662 anime.AnilistId = animePointer.AnilistId
654 // anime.AllanimeId = animePointer.AllanimeId 663 // anime.AllanimeId = animePointer.AllanimeId
655 // anime.Title = animePointer.Title 664 // anime.Title = animePointer.Title
656 // anime.Ep.Number = animePointer.Ep.Number 665 // anime.Ep.Number = animePointer.Ep.Number
657 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime 666 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
658 // anime.Ep.Resume = true 667 // anime.Ep.Resume = true
659 668
660 } else { 669 } else {
661 // Skip category selection if Current flag is set 670 // Skip category selection if Current flag is set
662 var categorySelection SelectionOption 671 var categorySelection SelectionOption
663 if userCurdConfig.CurrentCategory { 672 if userCurdConfig.CurrentCategory {
@@ -682,7 +691,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
682 var err error 691 var err error
683 categorySelection, err = DynamicSelect(categories, false) 692 categorySelection, err = DynamicSelect(categories, false)
684 if err != nil { 693 if err != nil {
685 Log(fmt.Sprintf("Failed to select category: %v", err), logFile) 694 Log(fmt.Sprintf("Failed to select category: %v", err))
686 ExitCurd(fmt.Errorf("Failed to select category")) 695 ExitCurd(fmt.Errorf("Failed to select category"))
687 } 696 }
688 697
@@ -693,17 +702,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
693 // Handle UPDATE option 702 // Handle UPDATE option
694 if categorySelection.Key == "UPDATE" { 703 if categorySelection.Key == "UPDATE" {
695 ClearScreen() 704 ClearScreen()
696 UpdateAnimeEntry(userCurdConfig, user, logFile) 705 UpdateAnimeEntry(userCurdConfig, user)
697 ExitCurd(nil) 706 ExitCurd(nil)
698 } else if categorySelection.Key == "UNTRACKED" { 707 } else if categorySelection.Key == "UNTRACKED" {
699 ClearScreen() 708 ClearScreen()
700 WatchUntracked(userCurdConfig, logFile) 709 WatchUntracked(userCurdConfig)
701 } 710 }
702 711
703 ClearScreen() 712 ClearScreen()
704 } 713 }
705 714
706
707 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 715 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
708 animeListMapPreview = make(map[string]RofiSelectPreview) 716 animeListMapPreview = make(map[string]RofiSelectPreview)
709 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) { 717 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
@@ -728,122 +736,122 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
728 } 736 }
729 } 737 }
730 738
731 var anilistSelectedOption SelectionOption 739 var anilistSelectedOption SelectionOption
732 var selectedAllanimeAnime SelectionOption 740 var selectedAllanimeAnime SelectionOption
733 var userQuery string 741 var userQuery string
734 742
735 if anime.Ep.ContinueLast { 743 if anime.Ep.ContinueLast {
736 // Get the last watched anime ID from the curd_id file 744 // Get the last watched anime ID from the curd_id file
737 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id") 745 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
738 curdIDBytes, err := os.ReadFile(curdIDPath) 746 curdIDBytes, err := os.ReadFile(curdIDPath)
739 if err != nil { 747 if err != nil {
740 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile) 748 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
741 ExitCurd(fmt.Errorf("Error reading curd_id file")) 749 ExitCurd(fmt.Errorf("Error reading curd_id file"))
742 } 750 }
743 751
744 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes))) 752 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
745 if err != nil { 753 if err != nil {
746 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile) 754 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
747 ExitCurd(fmt.Errorf("Error converting curd_id to integer")) 755 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
748 } 756 }
749 757
750 anime.AnilistId = lastWatchedID 758 anime.AnilistId = lastWatchedID
751 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID) 759 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
752 } else { 760 } else {
753 // Select anime to watch (Anilist) 761 // Select anime to watch (Anilist)
754 var err error 762 var err error
755 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 763 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
756 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true) 764 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
757 } else { 765 } else {
758 anilistSelectedOption, err = DynamicSelect(animeListMap, true) 766 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
759 } 767 }
760 if err != nil { 768 if err != nil {
761 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile) 769 Log(fmt.Sprintf("Error selecting anime: %v", err))
762 ExitCurd(fmt.Errorf("Error selecting anime")) 770 ExitCurd(fmt.Errorf("Error selecting anime"))
763 } 771 }
764 772
765 Log(anilistSelectedOption, logFile) 773 Log(anilistSelectedOption)
766 774
767 if anilistSelectedOption.Key == "-1" { 775 if anilistSelectedOption.Key == "-1" {
768 ExitCurd(nil) 776 ExitCurd(nil)
769 } 777 }
770 778
771 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" { 779 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
772 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile) 780 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
773 } 781 }
774 782
775 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key) 783 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
776 if err != nil { 784 if err != nil {
777 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile) 785 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
778 ExitCurd(fmt.Errorf("Error converting Anilist ID")) 786 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
779 } 787 }
780 } 788 }
781 // Find anime in Local history 789 // Find anime in Local history
782 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "") 790 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
783 791
784 // Get anime entry 792 // Get anime entry
785 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key) 793 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
786 if err != nil { 794 if err != nil {
787 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile) 795 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
788 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) 796 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
789 } 797 }
790 798
791 // Set anime entry 799 // Set anime entry
792 anime.Title = selectedAnilistAnime.Media.Title 800 anime.Title = selectedAnilistAnime.Media.Title
793 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 801 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
794 anime.Ep.Number = selectedAnilistAnime.Progress+1 802 anime.Ep.Number = selectedAnilistAnime.Progress + 1
795 var animeList map[string]string 803 var animeList map[string]string
796 userQuery = anime.Title.Romaji 804 userQuery = anime.Title.Romaji
797 805
798 // if anime not found in database, find it in animeList 806 // if anime not found in database, find it in animeList
799 if animePointer == nil { 807 if animePointer == nil {
800 Log("Anime not found in database, searching in animeList...", logFile) 808 Log("Anime not found in database, searching in animeList...")
801 // Get Anime list (All anime) 809 // Get Anime list (All anime)
802 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile) 810 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
803 811
804 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 812 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
805 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile) 813 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
806 if err != nil { 814 if err != nil {
807 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile) 815 Log(fmt.Sprintf("Failed to select anime: %v", err))
808 ExitCurd(fmt.Errorf("Failed to select anime")) 816 ExitCurd(fmt.Errorf("Failed to select anime"))
809 } 817 }
810 if len(animeList) == 0 { 818 if len(animeList) == 0 {
811 ExitCurd(fmt.Errorf("No results found.")) 819 ExitCurd(fmt.Errorf("No results found."))
812 } 820 }
813 821
814 // find anime in animeList 822 // find anime in animeList
815 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)) 823 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
816 if err != nil { 824 if err != nil {
817 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile) 825 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
818 } 826 }
819 827
820 // If unable to get Allanime id automatically get manually 828 // If unable to get Allanime id automatically get manually
821 if anime.AllanimeId == "" { 829 if anime.AllanimeId == "" {
822 CurdOut("Failed to automatically select anime") 830 CurdOut("Failed to automatically select anime")
823 selectedAllanimeAnime, err := DynamicSelect(animeList, false) 831 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
824 832
825 if selectedAllanimeAnime.Key == "-1" { 833 if selectedAllanimeAnime.Key == "-1" {
826 ExitCurd(nil) 834 ExitCurd(nil)
827 } 835 }
828 836
829 if err != nil { 837 if err != nil {
830 // fmt.Println("No anime available") 838 // fmt.Println("No anime available")
831 ExitCurd(fmt.Errorf("No anime available")) 839 ExitCurd(fmt.Errorf("No anime available"))
832 } 840 }
833 anime.AllanimeId = selectedAllanimeAnime.Key 841 anime.AllanimeId = selectedAllanimeAnime.Key
834 } 842 }
835 } else { 843 } else {
836 // if anime found in database, use it 844 // if anime found in database, use it
837 anime.AllanimeId = animePointer.AllanimeId 845 anime.AllanimeId = animePointer.AllanimeId
838 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime 846 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
839 if anime.Ep.Number == animePointer.Ep.Number { 847 if anime.Ep.Number == animePointer.Ep.Number {
840 anime.Ep.Resume = true 848 anime.Ep.Resume = true
841 } 849 }
842 } 850 }
843 851
844 if selectedAllanimeAnime.Key == "-1" { 852 if selectedAllanimeAnime.Key == "-1" {
845 ExitCurd(nil) 853 ExitCurd(nil)
846 } 854 }
847 855
848 // If anime is not in watching list, prompt user to add it into watching list 856 // If anime is not in watching list, prompt user to add it into watching list
849 isInWatchingList := false 857 isInWatchingList := false
@@ -867,28 +875,28 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
867 // Use rofi for selection 875 // Use rofi for selection
868 selectedOption, err = DynamicSelect(options, false) 876 selectedOption, err = DynamicSelect(options, false)
869 if err != nil { 877 if err != nil {
870 Log("Error in selection: "+err.Error(), logFile) 878 Log("Error in selection: "+err.Error())
871 ExitCurd(err) 879 ExitCurd(err)
872 } 880 }
873 881
874 if selectedOption.Key == "yes" { 882 if selectedOption.Key == "yes" {
875 err = AddAnimeToWatchingList(anime.AnilistId, user.Token) 883 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
876 if err != nil { 884 if err != nil {
877 Log("Error adding anime to watching list: "+err.Error(), logFile) 885 Log("Error adding anime to watching list: "+err.Error())
878 ExitCurd(err) 886 ExitCurd(err)
879 } 887 }
880 // Refresh user's anime list after adding 888 // Refresh user's anime list after adding
881 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 889 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
882 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id) 890 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
883 if err != nil { 891 if err != nil {
884 Log("Error refreshing anime list: "+err.Error(), logFile) 892 Log("Error refreshing anime list: "+err.Error())
885 ExitCurd(err) 893 ExitCurd(err)
886 } 894 }
887 user.AnimeList = ParseAnimeList(anilistUserDataPreview) 895 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
888 } else { 896 } else {
889 anilistUserData, err := GetUserData(user.Token, user.Id) 897 anilistUserData, err := GetUserData(user.Token, user.Id)
890 if err != nil { 898 if err != nil {
891 Log("Error refreshing anime list: "+err.Error(), logFile) 899 Log("Error refreshing anime list: "+err.Error())
892 ExitCurd(err) 900 ExitCurd(err)
893 } 901 }
894 user.AnimeList = ParseAnimeList(anilistUserData) 902 user.AnimeList = ParseAnimeList(anilistUserData)
@@ -898,142 +906,142 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
898 } 906 }
899 } 907 }
900 908
901 // If upstream is ahead, update the episode number 909 // If upstream is ahead, update the episode number
902 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil { 910 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
903 if temp_anime.Progress > anime.Ep.Number { 911 if temp_anime.Progress > anime.Ep.Number {
904 anime.Ep.Number = temp_anime.Progress 912 anime.Ep.Number = temp_anime.Progress
905 anime.Ep.Player.PlaybackTime = 0 913 anime.Ep.Player.PlaybackTime = 0
906 anime.Ep.Resume = false 914 anime.Ep.Resume = false
907 } 915 }
908 } 916 }
909 917
910 if anime.TotalEpisodes == 0 { 918 if anime.TotalEpisodes == 0 {
911 // Get updated anime data 919 // Get updated anime data
912 Log(selectedAllanimeAnime, logFile) 920 Log(selectedAllanimeAnime)
913 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token) 921 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
914 Log(updatedAnime, logFile) 922 Log(updatedAnime)
915 if err != nil { 923 if err != nil {
916 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile) 924 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
917 } else { 925 } else {
918 anime.TotalEpisodes = updatedAnime.TotalEpisodes 926 anime.TotalEpisodes = updatedAnime.TotalEpisodes
919 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile) 927 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
920 } 928 }
921 } 929 }
922 930
923 if anime.TotalEpisodes == 0 { // If failed to get anime data 931 if anime.TotalEpisodes == 0 { // If failed to get anime data
924 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.") 932 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
925 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 933 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
926 if err != nil { 934 if err != nil {
927 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 935 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
928 } else { 936 } else {
929 for allanimeId, label := range animeList { 937 for allanimeId, label := range animeList {
930 if allanimeId == anime.AllanimeId { 938 if allanimeId == anime.AllanimeId {
931 // Extract total episodes from the label 939 // Extract total episodes from the label
932 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 { 940 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
933 anime.TotalEpisodes, _ = strconv.Atoi(matches[1]) 941 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
934 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes)) 942 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
935 break 943 break
936 } 944 }
937 } 945 }
938 } 946 }
939 } 947 }
940 948
941 if anime.TotalEpisodes == 0 { 949 if anime.TotalEpisodes == 0 {
942 CurdOut("Still unable to determine total episodes.") 950 CurdOut("Still unable to determine total episodes.")
943 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress)) 951 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
944 var episodeNumber int 952 var episodeNumber int
945 if userCurdConfig.RofiSelection { 953 if userCurdConfig.RofiSelection {
946 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") 954 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
947 if err != nil { 955 if err != nil {
948 Log("Error getting user input: "+err.Error(), logFile) 956 Log("Error getting user input: "+err.Error())
949 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error())) 957 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
950 } 958 }
951 episodeNumber, err = strconv.Atoi(userInput) 959 episodeNumber, err = strconv.Atoi(userInput)
952 } else { 960 } else {
953 fmt.Print("Enter the episode you want to start from: ") 961 fmt.Print("Enter the episode you want to start from: ")
954 fmt.Scanln(&episodeNumber) 962 fmt.Scanln(&episodeNumber)
955 } 963 }
956 anime.Ep.Number = episodeNumber 964 anime.Ep.Number = episodeNumber
957 } else { 965 } else {
958 anime.Ep.Number = selectedAnilistAnime.Progress + 1 966 anime.Ep.Number = selectedAnilistAnime.Progress + 1
959 } 967 }
960 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases 968 } 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) 969 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
962 var answer string 970 var answer string
963 if userCurdConfig.RofiSelection { 971 if userCurdConfig.RofiSelection {
964 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)") 972 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
965 if err != nil { 973 if err != nil {
966 Log("Error getting user input: "+err.Error(), logFile) 974 Log("Error getting user input: "+err.Error())
967 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error())) 975 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
968 } 976 }
969 answer = userInput 977 answer = userInput
970 } else { 978 } else {
971 fmt.Printf("Would like to start the anime from beginning? (y/n)\n") 979 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
972 fmt.Scanln(&answer) 980 fmt.Scanln(&answer)
973 } 981 }
974 if answer == "y" { 982 if answer == "y" {
975 anime.Ep.Number = 1 983 anime.Ep.Number = 1
976 } else { 984 } else {
977 anime.Ep.Number = anime.TotalEpisodes 985 anime.Ep.Number = anime.TotalEpisodes
978 } 986 }
979 } 987 }
980 988
981} 989}
982 990
983// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it 991// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
984func WriteTokenToFile(token string, filePath string) error { 992func WriteTokenToFile(token string, filePath string) error {
985 // Extract the directory path 993 // Extract the directory path
986 dir := filepath.Dir(filePath) 994 dir := filepath.Dir(filePath)
987 995
988 // Create all necessary parent directories 996 // Create all necessary parent directories
989 if err := os.MkdirAll(dir, 0755); err != nil { 997 if err := os.MkdirAll(dir, 0755); err != nil {
990 return fmt.Errorf("failed to create directories: %v", err) 998 return fmt.Errorf("failed to create directories: %v", err)
991 } 999 }
992 1000
993 // Write the token to the file, creating it if it doesn't exist 1001 // Write the token to the file, creating it if it doesn't exist
994 err := os.WriteFile(filePath, []byte(token), 0644) 1002 err := os.WriteFile(filePath, []byte(token), 0644)
995 if err != nil { 1003 if err != nil {
996 return fmt.Errorf("failed to write token to file: %v", err) 1004 return fmt.Errorf("failed to write token to file: %v", err)
997 } 1005 }
998 1006
999 return nil 1007 return nil
1000} 1008}
1001 1009
1002func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string { 1010func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1003 1011
1004 if anime.Ep.NextEpisode.Number == anime.Ep.Number { 1012 if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1005 anime.Ep.Links = anime.Ep.NextEpisode.Links 1013 anime.Ep.Links = anime.Ep.NextEpisode.Links
1006 fmt.Println("using prefetched next episode link") 1014 fmt.Println("using prefetched next episode link")
1007 } else { 1015 } else {
1008 // Get episode link 1016 // Get episode link
1009 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1017 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)
1013 if err != nil { 1018 if err != nil {
1014 CurdOut("No episode list found") 1019 // If unable to get episode link automatically get manually
1015 RestoreScreen() 1020 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1016 os.Exit(1)
1017 }
1018 if userCurdConfig.RofiSelection {
1019 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1020 if err != nil { 1021 if err != nil {
1021 Log("Error getting user input: "+err.Error(), logFile) 1022 CurdOut("No episode list found")
1022 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error())) 1023 RestoreScreen()
1024 os.Exit(1)
1023 } 1025 }
1024 anime.Ep.Number, err = strconv.Atoi(userInput) 1026 if userCurdConfig.RofiSelection {
1025 } else { 1027 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1026 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) 1028 if err != nil {
1027 fmt.Scanln(&anime.Ep.Number) 1029 Log("Error getting user input: "+err.Error())
1028 } 1030 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1029 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1031 }
1030 if err != nil { 1032 anime.Ep.Number, err = strconv.Atoi(userInput)
1031 CurdOut("Failed to get episode link") 1033 } else {
1032 os.Exit(1) 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
1033 } 1043 }
1034 // anime.Ep.Links = link 1044 anime.Ep.Links = link
1035 }
1036 anime.Ep.Links = link
1037 } 1045 }
1038 1046
1039 if len(anime.Ep.Links) == 0 { 1047 if len(anime.Ep.Links) == 0 {
@@ -1041,7 +1049,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
1041 os.Exit(1) 1049 os.Exit(1)
1042 } 1050 }
1043 1051
1044 Log(anime, logFile) 1052 Log(anime)
1045 1053
1046 // Modify the goroutine in main.go where next episode links are fetched 1054 // Modify the goroutine in main.go where next episode links are fetched
1047 // Get next episode link in parallel 1055 // Get next episode link in parallel
@@ -1054,25 +1062,25 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
1054 } 1062 }
1055 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum) 1063 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1056 if err != nil { 1064 if err != nil {
1057 Log("Error getting next episode link: "+err.Error(), logFile) 1065 Log("Error getting next episode link: "+err.Error())
1058 } else { 1066 } else {
1059 anime.Ep.NextEpisode = NextEpisode{ 1067 anime.Ep.NextEpisode = NextEpisode{
1060 Number: nextEpNum, 1068 Number: nextEpNum,
1061 Links: nextLinks, 1069 Links: nextLinks,
1062 } 1070 }
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))
1064 } 1072 }
1065 } 1073 }
1066 }() 1074 }()
1067 1075
1068 // Write anime.AnilistId to curd_id in the storage path 1076 // Write anime.AnilistId to curd_id in the storage path
1069 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id") 1077 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1070 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile) 1078 Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1071 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil { 1079 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))
1073 } else { 1081 } else {
1074 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil { 1082 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))
1076 } 1084 }
1077 } 1085 }
1078 1086
@@ -1085,15 +1093,15 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
1085 1093
1086 // Display the image if it exists in cache 1094 // Display the image if it exists in cache
1087 _, err := os.Stat(cachePath) 1095 _, err := os.Stat(cachePath)
1088 if err == nil { 1096 if err == nil {
1089 // File exists 1097 // File exists
1090 Log(fmt.Sprintf("Image found at %s", cachePath), logFile) 1098 Log(fmt.Sprintf("Image found at %s", cachePath))
1091 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number)) 1099 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1092 } else { 1100 } else {
1093 // File does not exist 1101 // File does not exist
1094 Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile) 1102 Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1095 CurdOut(fmt.Sprintf("%s - Episode %d", 1103 CurdOut(fmt.Sprintf("%s - Episode %d",
1096 GetAnimeName(*anime), 1104 GetAnimeName(*anime),
1097 anime.Ep.Number)) 1105 anime.Ep.Number))
1098 1106
1099 } 1107 }
@@ -1103,7 +1111,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
1103 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime) 1111 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1104 1112
1105 if err != nil { 1113 if err != nil {
1106 Log("Failed to start mpv", logFile) 1114 Log("Failed to start mpv")
1107 os.Exit(1) 1115 os.Exit(1)
1108 } 1116 }
1109 1117
@@ -1153,28 +1161,27 @@ func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1153} 1161}
1154 1162
1155func getEntriesByCategory(list AnimeList, category string) []Entry { 1163func getEntriesByCategory(list AnimeList, category string) []Entry {
1156 switch category { 1164 switch category {
1157 case "ALL": 1165 case "ALL":
1158 // Combine all categories into one slice 1166 // Combine all categories into one slice
1159 allEntries := make([]Entry, 0) 1167 allEntries := make([]Entry, 0)
1160 allEntries = append(allEntries, list.Watching...) 1168 allEntries = append(allEntries, list.Watching...)
1161 allEntries = append(allEntries, list.Completed...) 1169 allEntries = append(allEntries, list.Completed...)
1162 allEntries = append(allEntries, list.Paused...) 1170 allEntries = append(allEntries, list.Paused...)
1163 allEntries = append(allEntries, list.Dropped...) 1171 allEntries = append(allEntries, list.Dropped...)
1164 allEntries = append(allEntries, list.Planning...) 1172 allEntries = append(allEntries, list.Planning...)
1165 return allEntries 1173 return allEntries
1166 case "CURRENT": 1174 case "CURRENT":
1167 return list.Watching 1175 return list.Watching
1168 case "COMPLETED": 1176 case "COMPLETED":
1169 return list.Completed 1177 return list.Completed
1170 case "PAUSED": 1178 case "PAUSED":
1171 return list.Paused 1179 return list.Paused
1172 case "DROPPED": 1180 case "DROPPED":
1173 return list.Dropped 1181 return list.Dropped
1174 case "PLANNING": 1182 case "PLANNING":
1175 return list.Planning 1183 return list.Planning
1176 default: 1184 default:
1177 return []Entry{} 1185 return []Entry{}
1178 } 1186 }
1179} 1187}
1180
internal/discord.go +13 −11
@@ -2,7 +2,8 @@ package internal
2 2
3import ( 3import (
4 "fmt" 4 "fmt"
5 "github.com/hugolgst/rich-go/client" 5
6 "github.com/wraient/rich-go/client"
6) 7)
7 8
8func DiscordPresence(clientId string, anime Anime, IsPaused bool) error { 9func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
@@ -13,14 +14,14 @@ func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
13 14
14 var state string 15 var state string
15 if IsPaused { 16 if IsPaused {
16 state = fmt.Sprintf("\nEpisode %d - %s (Paused)", 17 state = fmt.Sprintf("\nEpisode %d - %s (Paused)",
17 anime.Ep.Number, 18 anime.Ep.Number,
18 FormatTime(anime.Ep.Player.PlaybackTime), 19 FormatTime(anime.Ep.Player.PlaybackTime),
19 ) 20 )
20 } else { 21 } else {
21 state = fmt.Sprintf("\nEpisode %d - %s / %s", 22 state = fmt.Sprintf("\nEpisode %d - %s / %s",
22 anime.Ep.Number, 23 anime.Ep.Number,
23 FormatTime(anime.Ep.Player.PlaybackTime), 24 FormatTime(anime.Ep.Player.PlaybackTime),
24 FormatTime(anime.Ep.Duration), 25 FormatTime(anime.Ep.Duration),
25 ) 26 )
26 } 27 }
@@ -30,15 +31,16 @@ func DiscordPresence(clientId string, anime Anime, IsPaused bool) error {
30 LargeImage: anime.CoverImage, 31 LargeImage: anime.CoverImage,
31 LargeText: GetAnimeName(anime), // Would display while hovering over the large image 32 LargeText: GetAnimeName(anime), // Would display while hovering over the large image
32 State: state, 33 State: state,
34 Type: 3, // Watching type (0 = Playing, 1 = Streaming, 2 = Listening, 3 = Watching, 4 = Custom, 5 = Competing)
33 //SmallImage: anime.SmallCoverImage, // Image for the bottom left corner 35 //SmallImage: anime.SmallCoverImage, // Image for the bottom left corner
34 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image 36 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image
35 Buttons: []*client.Button{ 37 Buttons: []*client.Button{
36 &client.Button{ 38 {
37 Label: "View on AniList", // Button label 39 Label: "View on AniList", // Button label
38 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link 40 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link
39 }, 41 },
40 &client.Button{ 42 {
41 Label: "View on MAL", // Button label 43 Label: "View on MAL", // Button label
42 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link 44 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link
43 }, 45 },
44 }, 46 },
@@ -62,4 +64,4 @@ func FormatTime(seconds int) string {
62 64
63func ConvertSecondsToMinutes(seconds int) int { 65func ConvertSecondsToMinutes(seconds int) int {
64 return seconds / 60 66 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) {
48 // Make the HTTP request 48 // Make the HTTP request
49 req, err := http.NewRequest("GET", url, nil) 49 req, err := http.NewRequest("GET", url, nil)
50 if err != nil { 50 if err != nil {
51 Log(fmt.Sprint("Error creating HTTP request:", err), logFile) 51 Log(fmt.Sprint("Error creating HTTP request:", err))
52 return episodes, err 52 return episodes, err
53 } 53 }
54 req.Header.Set("User-Agent", agent) 54 req.Header.Set("User-Agent", agent)
@@ -57,14 +57,14 @@ func EpisodesList(showID, mode string) ([]string, error) {
57 client := &http.Client{} 57 client := &http.Client{}
58 resp, err := client.Do(req) 58 resp, err := client.Do(req)
59 if err != nil { 59 if err != nil {
60 Log(fmt.Sprint("Error making HTTP request:", err), logFile) 60 Log(fmt.Sprint("Error making HTTP request:", err))
61 return episodes, err 61 return episodes, err
62 } 62 }
63 defer resp.Body.Close() 63 defer resp.Body.Close()
64 64
65 body, err := io.ReadAll(resp.Body) 65 body, err := io.ReadAll(resp.Body)
66 if err != nil { 66 if err != nil {
67 Log(fmt.Sprint("Error reading response body:", err), logFile) 67 Log(fmt.Sprint("Error reading response body:", err))
68 return episodes, err 68 return episodes, err
69 } 69 }
70 70
@@ -72,7 +72,7 @@ func EpisodesList(showID, mode string) ([]string, error) {
72 var response episodesResponse 72 var response episodesResponse
73 err = json.Unmarshal(body, &response) 73 err = json.Unmarshal(body, &response)
74 if err != nil { 74 if err != nil {
75 Log(fmt.Sprint("Error parsing JSON:", err), logFile) 75 Log(fmt.Sprint("Error parsing JSON:", err))
76 return episodes, err 76 return episodes, err
77 } 77 }
78 78
internal/episode_url.go +12 −12
@@ -60,7 +60,7 @@ func extractLinks(provider_id string) map[string]interface{} {
60 req, err := http.NewRequest("GET", url, nil) 60 req, err := http.NewRequest("GET", url, nil)
61 var videoData map[string]interface{} 61 var videoData map[string]interface{}
62 if err != nil { 62 if err != nil {
63 Log(fmt.Sprint("Error creating request:", err), logFile) 63 Log(fmt.Sprint("Error creating request:", err))
64 return videoData 64 return videoData
65 } 65 }
66 66
@@ -71,7 +71,7 @@ func extractLinks(provider_id string) map[string]interface{} {
71 // Send the request 71 // Send the request
72 resp, err := client.Do(req) 72 resp, err := client.Do(req)
73 if err != nil { 73 if err != nil {
74 Log(fmt.Sprint("Error sending request:", err), logFile) 74 Log(fmt.Sprint("Error sending request:", err))
75 return videoData 75 return videoData
76 } 76 }
77 defer resp.Body.Close() 77 defer resp.Body.Close()
@@ -79,14 +79,14 @@ func extractLinks(provider_id string) map[string]interface{} {
79 // Read the response body 79 // Read the response body
80 body, err := io.ReadAll(resp.Body) 80 body, err := io.ReadAll(resp.Body)
81 if err != nil { 81 if err != nil {
82 Log(fmt.Sprint("Error reading response:", err), logFile) 82 Log(fmt.Sprint("Error reading response:", err))
83 return videoData 83 return videoData
84 } 84 }
85 85
86 // Parse the JSON response 86 // Parse the JSON response
87 err = json.Unmarshal(body, &videoData) 87 err = json.Unmarshal(body, &videoData)
88 if err != nil { 88 if err != nil {
89 Log(fmt.Sprint("Error parsing JSON:", err), logFile) 89 Log(fmt.Sprint("Error parsing JSON:", err))
90 return videoData 90 return videoData
91 } 91 }
92 92
@@ -148,7 +148,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
148 var response allanimeResponse 148 var response allanimeResponse
149 err = json.Unmarshal(body, &response) 149 err = json.Unmarshal(body, &response)
150 if err != nil { 150 if err != nil {
151 Log(fmt.Sprint("Error parsing JSON: ", err), logFile) 151 Log(fmt.Sprint("Error parsing JSON: ", err))
152 return nil, err 152 return nil, err
153 } 153 }
154 154
@@ -184,7 +184,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
184 <-rateLimiter.C // Rate limit the requests 184 <-rateLimiter.C // Rate limit the requests
185 185
186 decodedProviderID := decodeProviderID(url[2:]) 186 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))
188 188
189 extractedLinks := extractLinks(decodedProviderID) 189 extractedLinks := extractLinks(decodedProviderID)
190 190
@@ -209,13 +209,13 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
209 for _, linkInterface := range linksInterface { 209 for _, linkInterface := range linksInterface {
210 linkMap, ok := linkInterface.(map[string]interface{}) 210 linkMap, ok := linkInterface.(map[string]interface{})
211 if !ok { 211 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))
213 continue 213 continue
214 } 214 }
215 215
216 link, ok := linkMap["link"].(string) 216 link, ok := linkMap["link"].(string)
217 if !ok { 217 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))
219 continue 219 continue
220 } 220 }
221 221
@@ -239,16 +239,16 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
239 select { 239 select {
240 case res := <-results: 240 case res := <-results:
241 if res.err != nil { 241 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))
243 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err)) 243 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
244 } else { 244 } else {
245 orderedResults[res.index] = res.links 245 orderedResults[res.index] = res.links
246 successCount++ 246 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)))
248 } 248 }
249 case <-timeout: 249 case <-timeout:
250 if successCount > 0 { 250 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)))
252 // Flatten available results 252 // Flatten available results
253 return flattenResults(orderedResults), nil 253 return flattenResults(orderedResults), nil
254 } 254 }
@@ -258,7 +258,7 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
258 258
259 // If we have any errors but also some successes, log errors but continue 259 // If we have any errors but also some successes, log errors but continue
260 if len(collectedErrors) > 0 { 260 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))
262 } 262 }
263 263
264 // Flatten and return results 264 // 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 {
14 // Use the helper function for making the GET request 14 // Use the helper function for making the GET request
15 response, err := makeGetRequest(url, nil) 15 response, err := makeGetRequest(url, nil)
16 if err != nil { 16 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))
18 // Set default values when API fails 18 // Set default values when API fails
19 anime.Ep.IsFiller = false 19 anime.Ep.IsFiller = false
20 anime.Ep.IsRecap = false 20 anime.Ep.IsRecap = false
21 return nil // Return nil to allow the application to continue 21 return nil // Return nil to allow the application to continue
22 } 22 }
23 23
24 Log(response, logFile) 24 Log(response)
25 25
26 // Check if the 'data' field exists and is valid 26 // Check if the 'data' field exists and is valid
27 data, ok := response["data"].(map[string]interface{}) 27 data, ok := response["data"].(map[string]interface{})
28 if !ok { 28 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")
30 // Set default values when response is invalid 30 // Set default values when response is invalid
31 anime.Ep.IsFiller = false 31 anime.Ep.IsFiller = false
32 anime.Ep.IsRecap = false 32 anime.Ep.IsRecap = false
internal/localTracking.go +21 −21
@@ -248,7 +248,7 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
248 return nil 248 return nil
249} 249}
250 250
251func WatchUntracked(userCurdConfig *CurdConfig, logFile string) { 251func WatchUntracked(userCurdConfig *CurdConfig) {
252 var query string 252 var query string
253 var animeList map[string]string 253 var animeList map[string]string
254 var err error 254 var err error
@@ -258,7 +258,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
258 if userCurdConfig.RofiSelection { 258 if userCurdConfig.RofiSelection {
259 userInput, err := GetUserInputFromRofi("Enter the anime name") 259 userInput, err := GetUserInputFromRofi("Enter the anime name")
260 if err != nil { 260 if err != nil {
261 Log("Error getting user input: "+err.Error(), logFile) 261 Log("Error getting user input: "+err.Error())
262 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 262 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
263 } 263 }
264 query = userInput 264 query = userInput
@@ -270,7 +270,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
270 // Search for the anime 270 // Search for the anime
271 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub) 271 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
272 if err != nil { 272 if err != nil {
273 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile) 273 Log(fmt.Sprintf("Failed to search anime: %v", err))
274 ExitCurd(fmt.Errorf("Failed to search anime")) 274 ExitCurd(fmt.Errorf("Failed to search anime"))
275 } 275 }
276 276
@@ -281,7 +281,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
281 // Select anime from search results 281 // Select anime from search results
282 selectedAnime, err := DynamicSelect(animeList, false) 282 selectedAnime, err := DynamicSelect(animeList, false)
283 if err != nil { 283 if err != nil {
284 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile) 284 Log(fmt.Sprintf("Failed to select anime: %v", err))
285 ExitCurd(fmt.Errorf("Failed to select anime")) 285 ExitCurd(fmt.Errorf("Failed to select anime"))
286 } 286 }
287 287
@@ -297,12 +297,12 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
297 if userCurdConfig.RofiSelection { 297 if userCurdConfig.RofiSelection {
298 userInput, err := GetUserInputFromRofi("Enter the episode number") 298 userInput, err := GetUserInputFromRofi("Enter the episode number")
299 if err != nil { 299 if err != nil {
300 Log("Error getting episode number: "+err.Error(), logFile) 300 Log("Error getting episode number: "+err.Error())
301 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error())) 301 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
302 } 302 }
303 episodeNumber, err = strconv.Atoi(userInput) 303 episodeNumber, err = strconv.Atoi(userInput)
304 if err != nil { 304 if err != nil {
305 Log(fmt.Sprintf("Invalid episode number: %v", err), logFile) 305 Log(fmt.Sprintf("Invalid episode number: %v", err))
306 ExitCurd(fmt.Errorf("Invalid episode number")) 306 ExitCurd(fmt.Errorf("Invalid episode number"))
307 } 307 }
308 } else { 308 } else {
@@ -316,7 +316,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
316 // Get episode link 316 // Get episode link
317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
318 if err != nil { 318 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))
320 ExitCurd(fmt.Errorf("Failed to get episode link")) 320 ExitCurd(fmt.Errorf("Failed to get episode link"))
321 } 321 }
322 322
@@ -329,14 +329,14 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
329 // Start video playback 329 // Start video playback
330 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime) 330 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
331 if err != nil { 331 if err != nil {
332 Log("Failed to start mpv", logFile) 332 Log("Failed to start mpv")
333 os.Exit(1) 333 os.Exit(1)
334 } 334 }
335 335
336 anime.Ep.Player.SocketPath = mpvSocketPath 336 anime.Ep.Player.SocketPath = mpvSocketPath
337 anime.Ep.Started = false 337 anime.Ep.Started = false
338 338
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))
340 340
341 // Get video duration 341 // Get video duration
342 go func() { 342 go func() {
@@ -346,13 +346,13 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
346 // Get video duration 346 // Get video duration
347 durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"}) 347 durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
348 if err != nil { 348 if err != nil {
349 Log("Error getting video duration: "+err.Error(), logFile) 349 Log("Error getting video duration: "+err.Error())
350 } else if durationPos != nil { 350 } else if durationPos != nil {
351 if duration, ok := durationPos.(float64); ok { 351 if duration, ok := durationPos.(float64); ok {
352 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer 352 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))
354 } else { 354 } else {
355 Log("Error: duration is not a float64", logFile) 355 Log("Error: duration is not a float64")
356 } 356 }
357 } 357 }
358 break 358 break
@@ -366,28 +366,28 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
366 for { 366 for {
367 timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}) 367 timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
368 if err != nil { 368 if err != nil {
369 Log("Error getting playback time: "+err.Error(), logFile) 369 Log("Error getting playback time: "+err.Error())
370 370
371 // Check if the error is due to invalid JSON 371 // Check if the error is due to invalid JSON
372 // User closed the video 372 // User closed the video
373 if anime.Ep.Started { 373 if anime.Ep.Started {
374 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 374 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
375 // Episode is completed 375 // Episode is completed
376 Log(fmt.Sprint(percentageWatched), logFile) 376 Log(fmt.Sprint(percentageWatched))
377 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime), logFile) 377 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
378 Log(fmt.Sprint(anime.Ep.Duration), logFile) 378 Log(fmt.Sprint(anime.Ep.Duration))
379 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete), logFile) 379 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
380 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 380 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
381 anime.Ep.Number++ 381 anime.Ep.Number++
382 anime.Ep.Started = false 382 anime.Ep.Started = false
383 Log("Completed episode, starting next.", logFile) 383 Log("Completed episode, starting next.")
384 anime.Ep.IsCompleted = true 384 anime.Ep.IsCompleted = true
385 // Exit the skip loop 385 // Exit the skip loop
386 break 386 break
387 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed 387 } 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...")
389 } else { 389 } else {
390 Log("Episode is not completed, exiting", logFile) 390 Log("Episode is not completed, exiting")
391 ExitCurd(nil) 391 ExitCurd(nil)
392 } 392 }
393 } 393 }
@@ -401,7 +401,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
401 401
402 animePosition, ok := timePos.(float64) 402 animePosition, ok := timePos.(float64)
403 if !ok { 403 if !ok {
404 Log("Error: timePos is not a float64", logFile) 404 Log("Error: timePos is not a float64")
405 continue 405 continue
406 } 406 }
407 407
internal/player.go +5 −5
@@ -56,14 +56,14 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
56 titleCommand := []interface{}{"set_property", "force-media-title", title} 56 titleCommand := []interface{}{"set_property", "force-media-title", title}
57 _, err = MPVSendCommand(mpvSocketPath, titleCommand) 57 _, err = MPVSendCommand(mpvSocketPath, titleCommand)
58 if err != nil { 58 if err != nil {
59 Log(fmt.Sprintf("Failed to update title: %v", err), logFile) 59 Log(fmt.Sprintf("Failed to update title: %v", err))
60 } 60 }
61 61
62 // Also update the window title property 62 // Also update the window title property
63 windowTitleCommand := []interface{}{"set_property", "title", title} 63 windowTitleCommand := []interface{}{"set_property", "title", title}
64 _, err = MPVSendCommand(mpvSocketPath, windowTitleCommand) 64 _, err = MPVSendCommand(mpvSocketPath, windowTitleCommand)
65 if err != nil { 65 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))
67 } 67 }
68 68
69 return mpvSocketPath, nil 69 return mpvSocketPath, nil
@@ -74,7 +74,7 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
74 randomBytes := make([]byte, 4) 74 randomBytes := make([]byte, 4)
75 _, err = rand.Read(randomBytes) 75 _, err = rand.Read(randomBytes)
76 if err != nil { 76 if err != nil {
77 Log("Failed to generate random number", logFile) 77 Log("Failed to generate random number")
78 return "", fmt.Errorf("failed to generate random number: %w", err) 78 return "", fmt.Errorf("failed to generate random number: %w", err)
79 } 79 }
80 80
@@ -110,7 +110,7 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
110 mpvPath, err := getMPVPath() 110 mpvPath, err := getMPVPath()
111 if err != nil { 111 if err != nil {
112 CurdOut("Error: Failed to get MPV path") 112 CurdOut("Error: Failed to get MPV path")
113 Log("Failed to get mpv path.", logFile) 113 Log("Failed to get mpv path.")
114 return "", err 114 return "", err
115 } 115 }
116 116
@@ -202,7 +202,7 @@ func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
202func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) { 202func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
203 speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"}) 203 speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
204 if err != nil || speed == nil { 204 if err != nil || speed == nil {
205 Log("Failed to get playback speed.", logFile) 205 Log("Failed to get playback speed.")
206 return 0, err 206 return 0, err
207 } 207 }
208 208
internal/selection_menu.go +3 −3
@@ -228,7 +228,7 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
228 // Download and get cache path for the image 228 // Download and get cache path for the image
229 cachePath, err := downloadToCache(option.CoverImage) 229 cachePath, err := downloadToCache(option.CoverImage)
230 if err != nil { 230 if err != nil {
231 Log(fmt.Sprintf("Error caching image: %v", err), logFile) 231 Log(fmt.Sprintf("Error caching image: %v", err))
232 continue 232 continue
233 } 233 }
234 234
@@ -269,8 +269,8 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
269 err := rofiCmd.Run() 269 err := rofiCmd.Run()
270 if err != nil { 270 if err != nil {
271 // Log both stdout and stderr for debugging 271 // Log both stdout and stderr for debugging
272 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()), logFile) 272 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
273 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()), logFile) 273 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
274 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err) 274 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
275 } 275 }
276 276