Commit 7ac32f496f

7ac32f496fcb0ff006f8f47c58a1155dad0dfdba

parent: b4e3ac84d5

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-28 08:30 UTC

Feat: Image Preview in rofi added

Layout: unified · split

VERSION.txt +1 −1
@@ -1 +1 @@
10.0.5\ No newline at end of file 10.0.6\ No newline at end of file
cmd/curd/main.go +14 −2
@@ -99,10 +99,22 @@ func main() {
99 } 99 }
100 100
101 if *rofiSelection { 101 if *rofiSelection {
102 // Define a slice of file names to check and download
103 filesToCheck := []string{
104 "selectanimepreview.rasi",
105 "selectanime.rasi",
106 "userinput.rasi",
107 }
108
109 // Call the function to check and download files
110 if err := internal.CheckAndDownloadFiles(userCurdConfig.StoragePath, filesToCheck); err != nil {
111 internal.CurdOut(fmt.Sprintf("Error checking and downloading files: %v\n", err))
112 internal.ExitCurd(err)
113 }
102 userCurdConfig.RofiSelection = true 114 userCurdConfig.RofiSelection = true
103 } 115 }
104 116
105 if *noRofi { 117 if *noRofi || runtime.GOOS == "windows" {
106 userCurdConfig.RofiSelection = false 118 userCurdConfig.RofiSelection = false
107 } 119 }
108 120
@@ -133,7 +145,7 @@ func main() {
133 145
134 if *addNewAnime { 146 if *addNewAnime {
135 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes, logFile) 147 internal.AddNewAnime(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
136 internal.ExitCurd(fmt.Errorf("Added new anime!")) 148 // internal.ExitCurd(fmt.Errorf("Added new anime!"))
137 } 149 }
138 150
139 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes, logFile) 151 internal.SetupCurd(&userCurdConfig, &anime, &user, &databaseAnimes, logFile)
internal/anilist.go +157 −1
@@ -49,6 +49,118 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
49 return animeMap 49 return animeMap
50} 50}
51 51
52// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
53func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
54 animeMap := make(map[string]RofiSelectPreview)
55
56 // Helper function to populate the map from a slice of entries
57 populateMap := func(entries []Entry) {
58 for _, entry := range entries {
59 // Only include entries with a non-empty English title
60 if entry.Media.Title.English != "" {
61 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
62 Title: entry.Media.Title.English,
63 CoverImage: entry.CoverImage,
64 }
65 } else {
66 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
67 Title: entry.Media.Title.Romaji,
68 CoverImage: entry.CoverImage,
69 }
70 }
71 }
72 }
73
74 // Populate the map for each category
75 populateMap(animeList.Watching)
76 populateMap(animeList.Completed)
77 populateMap(animeList.Paused)
78 populateMap(animeList.Dropped)
79 populateMap(animeList.Planning)
80
81 return animeMap
82}
83
84// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
85func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
86 url := "https://graphql.anilist.co"
87
88 queryString := `
89 query ($search: String) {
90 Page(page: 1, perPage: 10) {
91 media(search: $search, type: ANIME) {
92 id
93 title {
94 romaji
95 english
96 native
97 }
98 coverImage {
99 large
100 }
101 }
102 }
103 }`
104
105 variables := map[string]string{"search": query}
106 requestBody, err := json.Marshal(map[string]interface{}{
107 "query": queryString,
108 "variables": variables,
109 })
110 if err != nil {
111 return nil, fmt.Errorf("failed to marshal request body: %w", err)
112 }
113
114 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
115 if err != nil {
116 return nil, fmt.Errorf("failed to create new request: %w", err)
117 }
118
119 req.Header.Set("Authorization", "Bearer "+token)
120 req.Header.Set("Content-Type", "application/json")
121
122 client := &http.Client{}
123 resp, err := client.Do(req)
124 if err != nil {
125 return nil, fmt.Errorf("failed to make request: %w", err)
126 }
127 defer resp.Body.Close()
128
129 if resp.StatusCode != http.StatusOK {
130 body, _ := io.ReadAll(resp.Body)
131 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
132 }
133
134 body, err := io.ReadAll(resp.Body)
135 if err != nil {
136 return nil, fmt.Errorf("failed to read response body: %w", err)
137 }
138
139 var responseData map[string]ResponseData
140 err = json.Unmarshal(body, &responseData)
141 if err != nil {
142 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
143 }
144
145 animeList := responseData["data"].Page.Media
146 animeDict := make(map[string]RofiSelectPreview)
147
148 // Map titles and cover images to their IDs
149 for _, anime := range animeList {
150 idStr := strconv.Itoa(anime.ID)
151 title := anime.Title.English
152 if title == "" {
153 title = anime.Title.Romaji
154 }
155 animeDict[idStr] = RofiSelectPreview{
156 Title: title,
157 CoverImage: anime.CoverImage.Large,
158 }
159 }
160
161 return animeDict, nil
162}
163
52// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID 164// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
53func SearchAnimeAnilist(query, token string) (map[string]string, error) { 165func SearchAnimeAnilist(query, token string) (map[string]string, error) {
54 url := "https://graphql.anilist.co" 166 url := "https://graphql.anilist.co"
@@ -271,6 +383,46 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) {
271 return response, nil 383 return response, nil
272} 384}
273 385
386func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
387 query := fmt.Sprintf(`
388 {
389 MediaListCollection(userId: %d, type: ANIME) {
390 lists {
391 entries {
392 media {
393 id
394 episodes
395 duration
396 coverImage {
397 large
398 }
399 title {
400 romaji
401 english
402 native
403 }
404 }
405 status
406 score
407 progress
408 }
409 }
410 }
411 }`, userID)
412
413 headers := map[string]string{
414 "Authorization": "Bearer " + token,
415 "Content-Type": "application/json",
416 }
417
418 response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
419 if err != nil {
420 return nil, err
421 }
422
423 return response, nil
424}
425
274// Function to load a JSON file 426// Function to load a JSON file
275func LoadJSONFile(filePath string) (map[string]interface{}, error) { 427func LoadJSONFile(filePath string) (map[string]interface{}, error) {
276 data, err := os.ReadFile(filepath.Clean(filePath)) 428 data, err := os.ReadFile(filepath.Clean(filePath))
@@ -449,6 +601,7 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
449 601
450func ParseAnimeList(input map[string]interface{}) AnimeList { 602func ParseAnimeList(input map[string]interface{}) AnimeList {
451 var animeList AnimeList 603 var animeList AnimeList
604 userCurdConfig := GetGlobalConfig()
452 605
453 toInt := func(value interface{}) int { 606 toInt := func(value interface{}) int {
454 switch v := value.(type) { 607 switch v := value.(type) {
@@ -491,7 +644,6 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
491 for _, entry := range entries { 644 for _, entry := range entries {
492 entryData := entry.(map[string]interface{}) 645 entryData := entry.(map[string]interface{})
493 media := entryData["media"].(map[string]interface{}) 646 media := entryData["media"].(map[string]interface{})
494
495 animeEntry := Entry{ 647 animeEntry := Entry{
496 Media: Media{ 648 Media: Media{
497 Duration: toInt(media["duration"]), 649 Duration: toInt(media["duration"]),
@@ -508,6 +660,10 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
508 Status: safeString(entryData["status"]), // Ensure status is fetched safely 660 Status: safeString(entryData["status"]), // Ensure status is fetched safely
509 } 661 }
510 662
663 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
664 animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"])
665 }
666
511 // Append entries based on their status 667 // Append entries based on their status
512 switch animeEntry.Status { 668 switch animeEntry.Status {
513 case "CURRENT": 669 case "CURRENT":
internal/config.go +2
@@ -21,6 +21,7 @@ type CurdConfig struct {
21 SkipOp bool `config:"SkipOp"` 21 SkipOp bool `config:"SkipOp"`
22 SkipEd bool `config:"SkipEd"` 22 SkipEd bool `config:"SkipEd"`
23 SkipFiller bool `config:"SkipFiller"` 23 SkipFiller bool `config:"SkipFiller"`
24 ImagePreview bool `config:"ImagePreview"`
24 SkipRecap bool `config:"SkipRecap"` 25 SkipRecap bool `config:"SkipRecap"`
25 RofiSelection bool `config:"RofiSelection"` 26 RofiSelection bool `config:"RofiSelection"`
26 ScoreOnCompletion bool `config:"ScoreOnCompletion"` 27 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
@@ -42,6 +43,7 @@ func defaultConfigMap() map[string]string {
42 "SkipFiller": "true", 43 "SkipFiller": "true",
43 "SkipRecap": "true", 44 "SkipRecap": "true",
44 "RofiSelection": "false", 45 "RofiSelection": "false",
46 "ImagePreview": "false",
45 "ScoreOnCompletion": "true", 47 "ScoreOnCompletion": "true",
46 "SaveMpvSpeed": "true", 48 "SaveMpvSpeed": "true",
47 "DiscordPresence": "true", 49 "DiscordPresence": "true",
internal/curd.go +107 −19
@@ -90,7 +90,7 @@ func Log(data interface{}, logFile string) error {
90 90
91 // Log the current time and the JSON representation along with caller info 91 // Log the current time and the JSON representation along with caller info
92 currentTime := time.Now().Format("2006/01/02 15:04:05") 92 currentTime := time.Now().Format("2006/01/02 15:04:05")
93 logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData) 93 logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
94 _, err = fmt.Fprint(file, logMessage) // Write to the file 94 _, err = fmt.Fprint(file, logMessage) // Write to the file
95 if err != nil { 95 if err != nil {
96 return err 96 return err
@@ -219,8 +219,15 @@ func UpdateCurd(repo, fileName string) error {
219 return nil 219 return nil
220} 220}
221 221
222func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) { 222func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption {
223 var query string 223 var query string
224 var animeMap map[string]string
225 var animeMapPreview map[string]RofiSelectPreview
226 var err error
227 var anilistSelectedOption SelectionOption
228 var anilistUserData map[string]interface{}
229 var anilistUserDataPreview map[string]interface{}
230
224 if userCurdConfig.RofiSelection { 231 if userCurdConfig.RofiSelection {
225 userInput, err := GetUserInputFromRofi("Enter the anime name:") 232 userInput, err := GetUserInputFromRofi("Enter the anime name:")
226 if err != nil { 233 if err != nil {
@@ -232,12 +239,20 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
232 CurdOut("Enter the anime name:") 239 CurdOut("Enter the anime name:")
233 fmt.Scanln(&query) 240 fmt.Scanln(&query)
234 } 241 }
235 animeMap, err := SearchAnimeAnilist(query, user.Token) 242 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
243 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
244 } else {
245 animeMap, err = SearchAnimeAnilist(query, user.Token)
246 }
236 if err != nil { 247 if err != nil {
237 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile) 248 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
238 ExitCurd(fmt.Errorf("Failed to search anime")) 249 ExitCurd(fmt.Errorf("Failed to search anime"))
239 } 250 }
240 anilistSelectedOption, err := DynamicSelect(animeMap) 251 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
252 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
253 } else {
254 anilistSelectedOption, err = DynamicSelect(animeMap, false)
255 }
241 if err != nil { 256 if err != nil {
242 Log(fmt.Sprintf("No anime available: %v", err), logFile) 257 Log(fmt.Sprintf("No anime available: %v", err), logFile)
243 ExitCurd(fmt.Errorf("No anime available")) 258 ExitCurd(fmt.Errorf("No anime available"))
@@ -259,16 +274,30 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
259 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 274 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
260 } 275 }
261 } 276 }
262 anilistUserData, err := GetUserData(user.Token, user.Id) 277 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
278 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
279 } else {
280 anilistUserData, err = GetUserData(user.Token, user.Id)
281 }
263 if err != nil { 282 if err != nil {
264 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile) 283 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
265 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 284 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
266 } 285 }
267 user.AnimeList = ParseAnimeList(anilistUserData) 286 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
287 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
288 } else {
289 user.AnimeList = ParseAnimeList(anilistUserData)
290 }
291
292 return anilistSelectedOption
268} 293}
269 294
270func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) { 295func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
271 var err error 296 var err error
297 var anilistUserData map[string]interface{}
298 var anilistUserDataPreview map[string]interface{}
299 var animeListMap map[string]string
300 var animeListMapPreview map[string]RofiSelectPreview
272 301
273 // Get user id, username and Anime list 302 // Get user id, username and Anime list
274 user.Id, user.Username, err = GetAnilistUserID(user.Token) 303 user.Id, user.Username, err = GetAnilistUserID(user.Token)
@@ -276,13 +305,22 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
276 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile) 305 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
277 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 306 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
278 } 307 }
279 anilistUserData, err := GetUserData(user.Token, user.Id) 308 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
280 if err != nil { 309 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
281 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile) 310 Log(anilistUserDataPreview, logFile)
282 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 311 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
312 Log(user.AnimeList, logFile)
313 animeListMapPreview = GetAnimeMapPreview(user.AnimeList)
314 Log(animeListMapPreview, logFile)
315 } else {
316 anilistUserData, err = GetUserData(user.Token, user.Id)
317 if err != nil {
318 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
319 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
320 }
321 user.AnimeList = ParseAnimeList(anilistUserData)
322 animeListMap = GetAnimeMap(user.AnimeList)
283 } 323 }
284 user.AnimeList = ParseAnimeList(anilistUserData)
285 animeListMap := GetAnimeMap(user.AnimeList)
286 var anilistSelectedOption SelectionOption 324 var anilistSelectedOption SelectionOption
287 var selectedAllanimeAnime SelectionOption 325 var selectedAllanimeAnime SelectionOption
288 var userQuery string 326 var userQuery string
@@ -307,18 +345,24 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
307 } else { 345 } else {
308 // Select anime to watch (Anilist) 346 // Select anime to watch (Anilist)
309 var err error 347 var err error
310 anilistSelectedOption, err = DynamicSelect(animeListMap) 348 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
349 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
350 } else {
351 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
352 }
311 if err != nil { 353 if err != nil {
312 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile) 354 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
313 ExitCurd(fmt.Errorf("Error selecting anime")) 355 ExitCurd(fmt.Errorf("Error selecting anime"))
314 } 356 }
315 357
358 Log(anilistSelectedOption, logFile)
359
316 if anilistSelectedOption.Key == "-1" { 360 if anilistSelectedOption.Key == "-1" {
317 ExitCurd(nil) 361 ExitCurd(nil)
318 } 362 }
319 363
320 if anilistSelectedOption.Label == "add_new" { 364 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
321 AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile) 365 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
322 } 366 }
323 367
324 userQuery = anilistSelectedOption.Label 368 userQuery = anilistSelectedOption.Label
@@ -342,11 +386,13 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
342 anime.Title = selectedAnilistAnime.Media.Title 386 anime.Title = selectedAnilistAnime.Media.Title
343 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 387 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
344 anime.Ep.Number = selectedAnilistAnime.Progress+1 388 anime.Ep.Number = selectedAnilistAnime.Progress+1
389 var animeList map[string]string
345 390
346 // if anime not found in database, find it in animeList 391 // if anime not found in database, find it in animeList
347 if animePointer == nil { 392 if animePointer == nil {
348 // Get Anime list (All anime) 393 // Get Anime list (All anime)
349 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 394
395 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
350 if err != nil { 396 if err != nil {
351 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile) 397 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
352 ExitCurd(fmt.Errorf("Failed to select anime")) 398 ExitCurd(fmt.Errorf("Failed to select anime"))
@@ -361,11 +407,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
361 if err != nil { 407 if err != nil {
362 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile) 408 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
363 } 409 }
364 410
365 // If unable to get Allanime id automatically get manually 411 // If unable to get Allanime id automatically get manually
366 if anime.AllanimeId == "" { 412 if anime.AllanimeId == "" {
367 CurdOut("Failed to automatically select anime") 413 CurdOut("Failed to automatically select anime")
368 selectedAllanimeAnime, err := DynamicSelect(animeList) 414 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
415
369 if err != nil { 416 if err != nil {
370 // fmt.Println("No anime available") 417 // fmt.Println("No anime available")
371 ExitCurd(fmt.Errorf("No anime available")) 418 ExitCurd(fmt.Errorf("No anime available"))
@@ -541,3 +588,44 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string
541 return mpvSocketPath 588 return mpvSocketPath
542} 589}
543 590
591func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
592 // Create storage directory if it doesn't exist
593 storagePath = os.ExpandEnv(storagePath)
594 if err := os.MkdirAll(storagePath, 0755); err != nil {
595 return fmt.Errorf("failed to create storage directory: %v", err)
596 }
597
598 // Base URL for downloading config files
599 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
600
601 // Check each file
602 for _, fileName := range filesToCheck {
603 filePath := filepath.Join(storagePath, fileName)
604
605 // Skip if file already exists
606 if _, err := os.Stat(filePath); err == nil {
607 continue
608 }
609
610 // Download file if it doesn't exist
611 resp, err := http.Get(baseURL + fileName)
612 if err != nil {
613 return fmt.Errorf("failed to download %s: %v", fileName, err)
614 }
615 defer resp.Body.Close()
616
617 // Create the file
618 out, err := os.Create(filePath)
619 if err != nil {
620 return fmt.Errorf("failed to create file %s: %v", fileName, err)
621 }
622 defer out.Close()
623
624 // Write the content
625 if _, err := io.Copy(out, resp.Body); err != nil {
626 return fmt.Errorf("failed to write file %s: %v", fileName, err)
627 }
628 }
629
630 return nil
631}
internal/rofi.go +7 −1
@@ -4,6 +4,8 @@ import (
4 "bytes" 4 "bytes"
5 "fmt" 5 "fmt"
6 "os/exec" 6 "os/exec"
7 "os"
8 "path/filepath"
7 "strings" 9 "strings"
8) 10)
9 11
@@ -35,8 +37,12 @@ func GetTokenFromRofi() (string, error) {
35 37
36// GetUserInputFromRofi prompts the user for input using Rofi with a custom message 38// GetUserInputFromRofi prompts the user for input using Rofi with a custom message
37func GetUserInputFromRofi(message string) (string, error) { 39func GetUserInputFromRofi(message string) (string, error) {
40 userCurdConfig := GetGlobalConfig()
41 if userCurdConfig.StoragePath == "" {
42 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
43 }
38 // Create the Rofi command 44 // Create the Rofi command
39 cmd := exec.Command("rofi", "-dmenu", "-p", "Input", "-mesg", message) 45 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(userCurdConfig.StoragePath, "userinput.rasi"), "-p", "Input", "-mesg", message)
40 46
41 // Set up pipes for output 47 // Set up pipes for output
42 var out bytes.Buffer 48 var out bytes.Buffer
internal/selection_menu.go +173 −7
@@ -3,11 +3,16 @@ package internal
3import ( 3import (
4 "bytes" 4 "bytes"
5 "fmt" 5 "fmt"
6 "io"
7 "net/http"
8 "os"
6 "os/exec" 9 "os/exec"
7 "sort" 10 "sort"
8 "strings" 11 "strings"
9 12 "time"
10 tea "github.com/charmbracelet/bubbletea" 13 "github.com/charmbracelet/bubbletea"
14 "crypto/md5"
15 "path/filepath"
11) 16)
12 17
13// SelectionOption holds the label and the internal key 18// SelectionOption holds the label and the internal key
@@ -170,7 +175,164 @@ func (m *Model) filterOptions() {
170 }) 175 })
171} 176}
172 177
173func RofiSelect(options map[string]string) (SelectionOption, error) { 178
179func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
180 // Pre-download first 14 images in background
181 go preDownloadImages(options, 14)
182
183 userCurdConfig := GetGlobalConfig()
184 if userCurdConfig.StoragePath == "" {
185 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
186 }
187
188 // Prepare Rofi input with anime titles and their cached image paths
189 var rofiInput strings.Builder
190 for _, option := range options {
191 // Download and get cache path for the image
192 cachePath, err := downloadToCache(option.CoverImage)
193 if err != nil {
194 Log(fmt.Sprintf("Error caching image: %v", err), logFile)
195 continue
196 }
197
198 // Format: "Title\x00icon\x1f/path/to/cached/image\n"
199 // This tells Rofi to use the image as an icon for this entry
200 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath))
201 }
202
203 // Add "Add new anime" and "Quit" options
204 if addnewoption {
205 rofiInput.WriteString("Add new anime\n")
206 }
207 rofiInput.WriteString("Quit\n")
208
209 // Get the absolute path to the rasi config
210 configPath := filepath.Join(userCurdConfig.StoragePath, "selectanimepreview.rasi")
211
212 // Create the command with explicit arguments
213 args := []string{
214 "-dmenu",
215 "-theme", configPath,
216 "-show-icons",
217 "-p", "Select Anime",
218 "-i", // Case-insensitive matching
219 "-no-custom", // Disable custom input
220 }
221
222 // Create the command
223 rofiCmd := exec.Command("rofi", args...)
224
225 // Set up pipes for input/output
226 rofiCmd.Stdin = strings.NewReader(rofiInput.String())
227 var stdout, stderr bytes.Buffer
228 rofiCmd.Stdout = &stdout
229 rofiCmd.Stderr = &stderr
230
231 // Run the command
232 err := rofiCmd.Run()
233 if err != nil {
234 // Log both stdout and stderr for debugging
235 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()), logFile)
236 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()), logFile)
237 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
238 }
239
240 selectedTitle := strings.TrimSpace(stdout.String())
241
242 // Handle special cases
243 switch selectedTitle {
244 case "":
245 return SelectionOption{}, fmt.Errorf("no selection made")
246 case "Add new anime":
247 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
248 case "Quit":
249 return SelectionOption{Label: "Quit", Key: "-1"}, nil
250 }
251
252 // Find the selected anime in options
253 for id, option := range options {
254 if option.Title == selectedTitle {
255 return SelectionOption{
256 Label: option.Title,
257 Key: id,
258 }, nil
259 }
260 }
261
262 return SelectionOption{}, fmt.Errorf("selection not found in options")
263}
264
265func preDownloadImages(options map[string]RofiSelectPreview, count int) {
266 i := 0
267 for _, option := range options {
268 if i >= count {
269 break
270 }
271 downloadToCache(option.CoverImage)
272 i++
273 }
274}
275
276func downloadToCache(imageURL string) (string, error) {
277 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
278 if err := os.MkdirAll(cacheDir, 0755); err != nil {
279 return "", fmt.Errorf("failed to create cache directory: %w", err)
280 }
281
282 // Create a hash of the URL to use as filename
283 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
284 cachePath := filepath.Join(cacheDir, filename)
285
286 // Check if file already exists in cache
287 if _, err := os.Stat(cachePath); err == nil {
288 return cachePath, nil
289 }
290
291 // Download the image
292 resp, err := http.Get(imageURL)
293 if err != nil {
294 return "", err
295 }
296 defer resp.Body.Close()
297
298 file, err := os.Create(cachePath)
299 if err != nil {
300 return "", err
301 }
302 defer file.Close()
303
304 _, err = io.Copy(file, resp.Body)
305 if err != nil {
306 os.Remove(cachePath) // Clean up on error
307 return "", err
308 }
309
310 return cachePath, nil
311}
312
313func showCachedImagePreview(imageURL string) error {
314 cachePath, err := downloadToCache(imageURL)
315 if err != nil {
316 return err
317 }
318
319 // Display the image with ueberzug
320 cmd := exec.Command("ueberzug", "layer", "--silent", "add", "preview", "--path", cachePath)
321 err = cmd.Start()
322 if err != nil {
323 return fmt.Errorf("failed to start image preview: %w", err)
324 }
325 time.Sleep(2 * time.Second) // Allow image to load for a moment
326 return nil
327}
328
329
330func RofiSelect(options map[string]string, addanimeopt bool) (SelectionOption, error) {
331 userCurdConfig := GetGlobalConfig()
332 if userCurdConfig.StoragePath == "" {
333 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
334 }
335
174 // Create a slice to store the options in the order we want 336 // Create a slice to store the options in the order we want
175 var optionsList []string 337 var optionsList []string
176 for _, value := range options { 338 for _, value := range options {
@@ -181,13 +343,17 @@ func RofiSelect(options map[string]string) (SelectionOption, error) {
181 sort.Strings(optionsList) 343 sort.Strings(optionsList)
182 344
183 // Add "Add new anime" and "Quit" options 345 // Add "Add new anime" and "Quit" options
184 optionsList = append(optionsList, "Add new anime", "Quit") 346 if addanimeopt {
347 optionsList = append(optionsList, "Add new anime", "Quit")
348 } else {
349 optionsList = append(optionsList, "Quit")
350 }
185 351
186 // Join all options into a single string, separated by newlines 352 // Join all options into a single string, separated by newlines
187 optionsString := strings.Join(optionsList, "\n") 353 optionsString := strings.Join(optionsList, "\n")
188 354
189 // Prepare the Rofi command 355 // Prepare the Rofi command
190 cmd := exec.Command("rofi", "-dmenu", "-i", "-p", "Select an anime") 356 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(userCurdConfig.StoragePath, "selectanime.rasi"), "-i", "-p", "Select an anime")
191 357
192 // Set up pipes for input and output 358 // Set up pipes for input and output
193 cmd.Stdin = strings.NewReader(optionsString) 359 cmd.Stdin = strings.NewReader(optionsString)
@@ -225,10 +391,10 @@ func RofiSelect(options map[string]string) (SelectionOption, error) {
225} 391}
226 392
227// DynamicSelect displays a simple selection prompt without extra features 393// DynamicSelect displays a simple selection prompt without extra features
228func DynamicSelect(options map[string]string) (SelectionOption, error) { 394func DynamicSelect(options map[string]string, addnewoption bool) (SelectionOption, error) {
229 395
230 if GetGlobalConfig().RofiSelection { 396 if GetGlobalConfig().RofiSelection {
231 return RofiSelect(options) 397 return RofiSelect(options, addnewoption)
232 } 398 }
233 399
234 model := &Model{ 400 model := &Model{
internal/structs.go +9
@@ -66,6 +66,9 @@ type AniListAnime struct {
66 English string `json:"english"` 66 English string `json:"english"`
67 Native string `json:"native"` 67 Native string `json:"native"`
68 } `json:"title"` 68 } `json:"title"`
69 CoverImage struct {
70 Large string `json:"large"`
71 } `json:"coverImage"`
69} 72}
70 73
71// Page represents the page in AniList response 74// Page represents the page in AniList response
@@ -90,6 +93,7 @@ type Entry struct {
90 Progress int `json:"progress"` 93 Progress int `json:"progress"`
91 Score float64 `json:"score"` 94 Score float64 `json:"score"`
92 Status string `json:"status"` 95 Status string `json:"status"`
96 CoverImage string `json:"coverImage"`
93} 97}
94 98
95type AnimeList struct { 99type AnimeList struct {
@@ -98,4 +102,9 @@ type AnimeList struct {
98 Paused []Entry `json:"paused"` 102 Paused []Entry `json:"paused"`
99 Dropped []Entry `json:"dropped"` 103 Dropped []Entry `json:"dropped"`
100 Planning []Entry `json:"planning"` 104 Planning []Entry `json:"planning"`
105}
106
107type RofiSelectPreview struct {
108 Title string `json:"title"`
109 CoverImage string `json:"coverImage"`
101}\ No newline at end of file 110}\ No newline at end of file
rofi/selectanime.rasi added +79
@@ -0,0 +1,79 @@
1configuration {
2 font: "Sans 12";
3 line-margin: 10;
4 display-drun: "";
5}
6
7* {
8 background: #000000; /* Black background for everything */
9 background-alt: #000000; /* Ensures no alternation */
10 foreground: #CCCCCC;
11 selected: #3584E4;
12 active: #2E7D32;
13 urgent: #C62828;
14}
15
16window {
17 fullscreen: false;
18 background-color: rgba(0, 0, 0, 1); /* Solid black background */
19}
20
21mainbox {
22 padding: 50px 100px;
23 background-color: rgba(0, 0, 0, 1); /* Ensures black background fills entire main area */
24 children: [inputbar, listview];
25 spacing: 20px;
26}
27
28inputbar {
29 background-color: #333333; /* Dark gray background for input bar */
30 padding: 8px;
31 border-radius: 8px;
32 children: [prompt, entry];
33}
34
35prompt {
36 enabled: true;
37 padding: 8px;
38 background-color: @selected;
39 text-color: #000000;
40 border-radius: 4px;
41}
42
43entry {
44 padding: 8px;
45 background-color: #444444; /* Slightly lighter gray for visibility */
46 text-color: #FFFFFF; /* White text to make typing visible */
47 placeholder: "Search...";
48 placeholder-color: rgba(255, 255, 255, 0.5);
49 border-radius: 6px;
50}
51
52listview {
53 layout: vertical;
54 spacing: 8px;
55 lines: 10;
56 background-color: @background; /* Consistent black background for list items */
57}
58
59element {
60 padding: 12px;
61 border-radius: 4px;
62 background-color: @background; /* Uniform color for each list item */
63 text-color: @foreground;
64}
65
66element normal.normal {
67 background-color: @background; /* Ensures no alternating color */
68}
69
70element selected.normal {
71 background-color: @selected;
72 text-color: #FFFFFF;
73}
74
75element-text {
76 background-color: transparent;
77 text-color: inherit;
78 vertical-align: 0.5;
79}
rofi/selectanimepreview.rasi added +118
@@ -0,0 +1,118 @@
1// Colours
2* {
3 background-color: transparent;
4 background: #1D2330;
5 background-transparent: #1D2330A0;
6 text-color: #BBBBBB;
7 text-color-selected: #FFFFFF;
8 primary: #BB77BB;
9 important: #BF616A;
10}
11
12configuration {
13 font: "Roboto 17";
14 show-icons: true;
15}
16
17window {
18 fullscreen: true;
19 height: 100%;
20 width: 100%;
21 transparency: "real";
22 background-color: @background-transparent;
23 border: 0px;
24 border-color: @primary;
25}
26
27mainbox {
28 children: [prompt, inputbar-box, listview];
29 padding: 0px;
30}
31
32prompt {
33 width: 100%;
34 margin: 10px 0px 0px 30px;
35 text-color: @important;
36 font: "Roboto Bold 27";
37}
38
39listview {
40 layout: vertical;
41 padding: 60px;
42 dynamic: true;
43 columns: 7;
44 spacing: 20px;
45 horizontal-align: center; /* Center the list items */
46}
47
48inputbar-box {
49 children: [dummy, inputbar, dummy];
50 orientation: horizontal;
51 expand: false;
52}
53
54inputbar {
55 children: [textbox-prompt, entry];
56 margin: 0px;
57 background-color: @primary;
58 border: 4px;
59 border-color: @primary;
60 border-radius: 8px;
61}
62
63textbox-prompt {
64 text-color: @background;
65 horizontal-align: 0.5;
66 vertical-align: 0.5;
67 expand: false;
68}
69
70entry {
71 expand: false;
72 padding: 8px;
73 margin: -6px;
74 horizontal-align: 0;
75 width: 300;
76 background-color: @background;
77 border: 6px;
78 border-color: @primary;
79 border-radius: 8px;
80 cursor: text;
81}
82
83element {
84 children: [dummy, element-box, dummy];
85 padding: 5px;
86 orientation: vertical;
87 border: 0px;
88 border-radius: 16px;
89 background-color: transparent; /* Default background */
90}
91
92element selected {
93 background-color: @primary; /* Solid color for selected item */
94}
95
96element-box {
97 children: [element-icon, element-text];
98 orientation: vertical;
99 expand: false;
100 cursor: pointer;
101}
102
103element-icon {
104 padding: 10px;
105 cursor: inherit;
106 size: 33%;
107 margin: 10px;
108}
109
110element-text {
111 horizontal-align: 0.5;
112 cursor: inherit;
113 text-color: @text-color;
114}
115
116element-text selected {
117 text-color: @text-color-selected;
118}
rofi/userinput.rasi added +51
@@ -0,0 +1,51 @@
1configuration {
2 font: "Sans 12";
3}
4
5* {
6 background-color: rgba(0, 0, 0, 0.7);
7 text-color: #FFFFFF;
8}
9
10window {
11 fullscreen: true;
12 transparency: "real";
13 background-color: @background-color;
14}
15
16mainbox {
17 children: [ message, listview, inputbar ];
18 padding: 40% 30%;
19}
20
21message {
22 border: 0;
23 padding: 10px;
24 margin: 0 0 20px 0;
25 font: "Sans Bold 24"; /* Increased font size and made it bold */
26}
27
28inputbar {
29 children: [ prompt, entry ];
30 background-color: rgba(255, 255, 255, 0.1);
31 padding: 8px;
32 border-radius: 4px;
33}
34
35prompt {
36 padding: 8px;
37}
38
39entry {
40 padding: 8px;
41}
42
43listview {
44 lines: 0;
45}
46
47/* Style for the message text specifically */
48textbox {
49 horizontal-align: 0.5; /* Center the text */
50 font: "Sans Bold 24"; /* Match message font */
51}\ No newline at end of file