internal/config.go
793 lines · 23713 bytes · executable
1package internal
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8
9 // "io"
10 "net/http"
11 "net/url"
12 "os"
13 "path/filepath"
14 "reflect"
15 "strconv"
16 "strings"
17 "time"
18)
19
20const (
21 anilistOAuthURL = "https://anilist.co/api/v2/oauth"
22 anilistClientID = "20686"
23 anilistClientSecret = "APfx41cOgSQVMvi88v7PbN7g6kzed2ZQRcxmACod"
24 anilistRedirectURI = "http://localhost:8000/oauth/callback"
25 anilistServerPort = 8000
26)
27
28// AnilistToken represents the OAuth token response from Anilist
29type AnilistToken struct {
30 AccessToken string `json:"access_token"`
31 TokenType string `json:"token_type"`
32 ExpiresIn int `json:"expires_in"`
33 RefreshToken string `json:"refresh_token"`
34 ExpiresAt time.Time `json:"expires_at"`
35}
36
37// CurdConfig struct with field names that match the config keys
38type CurdConfig struct {
39 Platform string `config:"-"`
40 Player string `config:"Player"`
41 MpvArgs []string `config:"MpvArgs"`
42 SubsLanguage string `config:"SubsLanguage"`
43 SubOrDub string `config:"SubOrDub"`
44 StoragePath string `config:"StoragePath"`
45 AnimeNameLanguage string `config:"AnimeNameLanguage"`
46 MenuOrder string `config:"MenuOrder"`
47 PercentageToMarkComplete int `config:"PercentageToMarkComplete"`
48 NextEpisodePrompt bool `config:"NextEpisodePrompt"`
49 SkipOp bool `config:"SkipOp"`
50 SkipEd bool `config:"SkipEd"`
51 SkipFiller bool `config:"SkipFiller"`
52 ImagePreview bool `config:"ImagePreview"`
53 SkipRecap bool `config:"SkipRecap"`
54 RofiSelection bool `config:"RofiSelection"`
55 CurrentCategory bool `config:"CurrentCategory"`
56 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
57 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
58 AddMissingOptions bool `config:"AddMissingOptions"`
59 AlternateScreen bool `config:"AlternateScreen"`
60 DiscordPresence bool `config:"DiscordPresence"`
61 DiscordClientId string `config:"DiscordClientId"`
62 AndroidPlayerPackage string `config:"AndroidPlayerPackage"`
63 AndroidPlayerActivity string `config:"AndroidPlayerActivity"`
64 AndroidPlayerMode string `config:"AndroidPlayerMode"`
65 AndroidPlayerIntentAction string `config:"AndroidPlayerIntentAction"`
66 AndroidUseTermuxAPI bool `config:"AndroidUseTermuxAPI"`
67 AndroidOpenLinksWith string `config:"AndroidOpenLinksWith"`
68 AndroidNotifications bool `config:"AndroidNotifications"`
69 AndroidWakeLock bool `config:"AndroidWakeLock"`
70 AndroidExtraIntentArgs []string `config:"AndroidExtraIntentArgs"`
71 AndroidPlayerSocketPath string `config:"AndroidPlayerSocketPath"`
72 AndroidDetectedCapability string `config:"AndroidDetectedCapability"`
73}
74
75type ConfigSchema struct {
76 platform Platform
77 keys []string
78 defaults map[string]string
79}
80
81func desktopConfigSchema() ConfigSchema {
82 defaults := map[string]string{
83 "Player": "mpv",
84 "MpvArgs": "[]",
85 "StoragePath": "$HOME/.local/share/curd",
86 "AnimeNameLanguage": "english",
87 "SubsLanguage": "english",
88 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST",
89 "SubOrDub": "sub",
90 "PercentageToMarkComplete": "85",
91 "NextEpisodePrompt": "false",
92 "SkipOp": "true",
93 "SkipEd": "true",
94 "SkipFiller": "true",
95 "SkipRecap": "true",
96 "RofiSelection": "false",
97 "ImagePreview": "false",
98 "CurrentCategory": "false",
99 "ScoreOnCompletion": "true",
100 "SaveMpvSpeed": "true",
101 "AddMissingOptions": "true",
102 "AlternateScreen": "true",
103 "DiscordPresence": "true",
104 "DiscordClientId": "1287457464148820089",
105 }
106
107 return ConfigSchema{
108 platform: PlatformDesktop,
109 keys: []string{
110 "Player",
111 "MpvArgs",
112 "StoragePath",
113 "AnimeNameLanguage",
114 "SubsLanguage",
115 "MenuOrder",
116 "SubOrDub",
117 "PercentageToMarkComplete",
118 "NextEpisodePrompt",
119 "SkipOp",
120 "SkipEd",
121 "SkipFiller",
122 "SkipRecap",
123 "RofiSelection",
124 "ImagePreview",
125 "CurrentCategory",
126 "ScoreOnCompletion",
127 "SaveMpvSpeed",
128 "AddMissingOptions",
129 "AlternateScreen",
130 "DiscordPresence",
131 "DiscordClientId",
132 },
133 defaults: defaults,
134 }
135}
136
137func androidConfigSchema() ConfigSchema {
138 defaults := map[string]string{
139 "StoragePath": "$HOME/.local/share/curd",
140 "AnimeNameLanguage": "english",
141 "SubsLanguage": "english",
142 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST",
143 "SubOrDub": "sub",
144 "PercentageToMarkComplete": "85",
145 "NextEpisodePrompt": "false",
146 "SkipOp": "true",
147 "SkipEd": "true",
148 "SkipFiller": "true",
149 "SkipRecap": "true",
150 "RofiSelection": "false",
151 "ImagePreview": "false",
152 "CurrentCategory": "false",
153 "ScoreOnCompletion": "true",
154 "SaveMpvSpeed": "true",
155 "AddMissingOptions": "true",
156 "AlternateScreen": "false",
157 "DiscordPresence": "false",
158 "AndroidPlayerPackage": "is.xyz.mpv",
159 "AndroidPlayerActivity": ".MPVActivity",
160 "AndroidPlayerMode": "intent",
161 "AndroidPlayerIntentAction": "android.intent.action.VIEW",
162 "AndroidUseTermuxAPI": "true",
163 "AndroidOpenLinksWith": "termux-open-url",
164 "AndroidNotifications": "false",
165 "AndroidWakeLock": "false",
166 "AndroidExtraIntentArgs": "[]",
167 "AndroidPlayerSocketPath": "",
168 "AndroidDetectedCapability": "intent",
169 }
170
171 return ConfigSchema{
172 platform: PlatformAndroid,
173 keys: []string{
174 "StoragePath",
175 "AnimeNameLanguage",
176 "SubsLanguage",
177 "MenuOrder",
178 "SubOrDub",
179 "PercentageToMarkComplete",
180 "NextEpisodePrompt",
181 "SkipOp",
182 "SkipEd",
183 "SkipFiller",
184 "SkipRecap",
185 "RofiSelection",
186 "ImagePreview",
187 "CurrentCategory",
188 "ScoreOnCompletion",
189 "SaveMpvSpeed",
190 "AddMissingOptions",
191 "AlternateScreen",
192 "DiscordPresence",
193 "AndroidPlayerPackage",
194 "AndroidPlayerActivity",
195 "AndroidPlayerMode",
196 "AndroidPlayerIntentAction",
197 "AndroidUseTermuxAPI",
198 "AndroidOpenLinksWith",
199 "AndroidNotifications",
200 "AndroidWakeLock",
201 "AndroidExtraIntentArgs",
202 "AndroidPlayerSocketPath",
203 "AndroidDetectedCapability",
204 },
205 defaults: defaults,
206 }
207}
208
209func configSchemaForPlatform(platform Platform) ConfigSchema {
210 if platform == PlatformAndroid {
211 return androidConfigSchema()
212 }
213
214 return desktopConfigSchema()
215}
216
217var globalConfig *CurdConfig
218
219func SetGlobalConfig(config *CurdConfig) {
220 globalConfig = config
221}
222
223func GetGlobalConfig() *CurdConfig {
224 return globalConfig
225}
226
227func (c *CurdConfig) IsAndroid() bool {
228 return c != nil && c.Platform == string(PlatformAndroid)
229}
230
231// Helper function to parse string array from config
232func parseStringArray(value string) []string {
233 // Remove brackets and split by comma
234 value = strings.TrimPrefix(value, "[")
235 value = strings.TrimSuffix(value, "]")
236 if value == "" {
237 return nil
238 }
239
240 // Split by comma and trim spaces and quotes from each element
241 parts := strings.Split(value, ",")
242 result := make([]string, 0, len(parts))
243 for _, part := range parts {
244 // Trim spaces and quotes
245 part = strings.TrimSpace(part)
246 part = strings.Trim(part, "\"")
247 if part != "" {
248 result = append(result, part)
249 }
250 }
251 return result
252}
253
254// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
255func LoadConfig(configPath string) (CurdConfig, error) {
256 platform := DetectPlatform()
257 if strings.TrimSpace(configPath) == "" {
258 configPath = DefaultConfigPathForPlatform(platform)
259 }
260 platform = InferPlatformForConfigPath(configPath, platform)
261
262 return LoadConfigForPlatform(configPath, platform)
263}
264
265func LoadConfigForPlatform(configPath string, platform Platform) (CurdConfig, error) {
266 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
267 schema := configSchemaForPlatform(platform)
268
269 // Check if config file exists
270 if _, err := os.Stat(configPath); os.IsNotExist(err) {
271 // Create the config file with default values if it doesn't exist
272 CurdOut("Config file not found. Creating default config...")
273 if err := createDefaultConfig(configPath, schema); err != nil {
274 return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
275 }
276 }
277
278 // Load the config from file
279 configMap, err := LoadConfigFromFile(configPath)
280 if err != nil {
281 return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
282 }
283
284 // Check AddMissingOptions setting first
285 addMissing := true
286 if val, exists := configMap["AddMissingOptions"]; exists {
287 addMissing, _ = strconv.ParseBool(val)
288 }
289
290 // Add missing fields to the config map
291 updated := false
292 for key, defaultValue := range schema.defaults {
293 if _, exists := configMap[key]; !exists {
294 configMap[key] = defaultValue
295 updated = true
296 }
297 }
298
299 // Write updated config back to file only if AddMissingOptions is true
300 if addMissing && updated {
301 if err := SaveConfigToFileWithSchema(configPath, configMap, schema); err != nil {
302 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
303 }
304 }
305
306 // Parse string arrays
307 if mpvArgs, exists := configMap["MpvArgs"]; exists {
308 configMap["MpvArgs"] = mpvArgs
309 }
310
311 // Populate the CurdConfig struct from the config map
312 config := PopulateConfig(configMap)
313 config.Platform = string(platform)
314
315 return config, nil
316}
317
318// Create a config file with default values in key=value format
319// Ensure the directory exists before creating the file
320func createDefaultConfig(path string, schema ConfigSchema) error {
321 // Ensure the directory exists
322 dir := filepath.Dir(path)
323 if err := os.MkdirAll(dir, 0755); err != nil {
324 return fmt.Errorf("error creating directory: %v", err)
325 }
326
327 file, err := os.Create(path)
328 if err != nil {
329 return fmt.Errorf("error creating file: %v", err)
330 }
331 defer file.Close()
332
333 writer := bufio.NewWriter(file)
334 for _, key := range schema.keys {
335 value := schema.defaults[key]
336 line := fmt.Sprintf("%s=%s\n", key, value)
337 if _, err := writer.WriteString(line); err != nil {
338 return fmt.Errorf("error writing to file: %v", err)
339 }
340 }
341 if err := writer.Flush(); err != nil {
342 return fmt.Errorf("error flushing writer: %v", err)
343 }
344 return nil
345}
346
347// authenticateWithBrowser performs OAuth authentication using browser
348func authenticateWithBrowser(tokenPath string, forceRefresh bool) (string, error) {
349 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
350 defer cancel()
351
352 // Try to load existing token first
353 if !forceRefresh {
354 if token, err := loadToken(tokenPath); err == nil && isTokenValid(token) {
355 return token.AccessToken, nil
356 }
357 }
358
359 if forceRefresh {
360 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
361 Log("Failed to remove existing token before refresh: " + err.Error())
362 }
363 }
364
365 // Start local server to handle OAuth callback
366 callbackCh := make(chan string, 1)
367 errCh := make(chan error, 1)
368 mux := http.NewServeMux()
369 srv := &http.Server{
370 Addr: fmt.Sprintf(":%d", anilistServerPort),
371 Handler: mux,
372 }
373
374 // Handle OAuth callback - for authorization code grant, code comes in query params
375 mux.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
376 code := r.URL.Query().Get("code")
377 errorParam := r.URL.Query().Get("error")
378
379 w.Header().Set("Content-Type", "text/html")
380
381 if errorParam != "" {
382 w.WriteHeader(http.StatusBadRequest)
383 html := fmt.Sprintf(`<!DOCTYPE html>
384<html>
385<head>
386 <title>Curd Authentication</title>
387 <style>
388 body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
389 .error { color: #f44336; font-size: 18px; margin-bottom: 20px; }
390 </style>
391</head>
392<body>
393 <div class="error">Authentication failed: %s</div>
394 <p>You can close this window and try again.</p>
395</body>
396</html>`, errorParam)
397 fmt.Fprint(w, html)
398 errCh <- fmt.Errorf("oauth error: %s", errorParam)
399 return
400 }
401
402 if code == "" {
403 w.WriteHeader(http.StatusBadRequest)
404 html := `<!DOCTYPE html>
405<html>
406<head>
407 <title>Curd Authentication</title>
408 <style>
409 body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
410 .error { color: #f44336; font-size: 18px; margin-bottom: 20px; }
411 </style>
412</head>
413<body>
414 <div class="error">No authorization code received</div>
415 <p>You can close this window and try again.</p>
416</body>
417</html>`
418 fmt.Fprint(w, html)
419 errCh <- fmt.Errorf("no authorization code received")
420 return
421 }
422
423 // Exchange authorization code for access token
424 go func() {
425 tokenURL := fmt.Sprintf("%s/token", anilistOAuthURL)
426 data := url.Values{
427 "grant_type": {"authorization_code"},
428 "client_id": {anilistClientID},
429 "client_secret": {anilistClientSecret},
430 "redirect_uri": {anilistRedirectURI},
431 "code": {code},
432 }
433
434 resp, err := http.PostForm(tokenURL, data)
435 if err != nil {
436 errCh <- fmt.Errorf("failed to exchange code for token: %w", err)
437 return
438 }
439 defer resp.Body.Close()
440
441 if resp.StatusCode != http.StatusOK {
442 errCh <- fmt.Errorf("token exchange failed with status: %d", resp.StatusCode)
443 return
444 }
445
446 var tokenResponse struct {
447 AccessToken string `json:"access_token"`
448 TokenType string `json:"token_type"`
449 ExpiresIn int `json:"expires_in"`
450 }
451
452 if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {
453 errCh <- fmt.Errorf("failed to parse token response: %w", err)
454 return
455 }
456
457 if tokenResponse.AccessToken == "" {
458 errCh <- fmt.Errorf("no access token in response")
459 return
460 }
461
462 callbackCh <- tokenResponse.AccessToken
463 }()
464
465 // Show success page immediately
466 html := `<!DOCTYPE html>
467<html>
468<head>
469 <title>Curd Authentication</title>
470 <style>
471 body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
472 .loading { color: #2196F3; font-size: 18px; margin-bottom: 20px; }
473 </style>
474</head>
475<body>
476 <div class="loading">Processing authentication...</div>
477 <p>Exchanging authorization code for token. You can close this window.</p>
478</body>
479</html>`
480 fmt.Fprint(w, html)
481 })
482
483 // Start server in background
484 go func() {
485 if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
486 errCh <- fmt.Errorf("failed to start server: %w", err)
487 }
488 }()
489 defer srv.Shutdown(ctx)
490
491 // Give server a moment to start
492 time.Sleep(100 * time.Millisecond)
493
494 // Open browser for authentication using Authorization Code Grant flow (response_type=code)
495 authURL := fmt.Sprintf("%s/authorize?client_id=%s&redirect_uri=%s&response_type=code",
496 anilistOAuthURL,
497 anilistClientID,
498 url.QueryEscape(anilistRedirectURI))
499
500 fmt.Println("Opening browser for AniList authentication...")
501 fmt.Printf("If the browser doesn't open automatically, visit: %s\n", authURL)
502
503 if err := OpenURL(authURL, GetGlobalConfig()); err != nil {
504 fmt.Printf("Failed to open browser automatically: %v\n", err)
505 fmt.Println("Please copy and paste the URL above into your browser")
506 }
507
508 // Wait for token
509 var accessToken string
510 select {
511 case accessToken = <-callbackCh:
512 case err := <-errCh:
513 return "", fmt.Errorf("authentication failed: %w", err)
514 case <-ctx.Done():
515 return "", fmt.Errorf("authentication timeout after 5 minutes")
516 }
517
518 // Create token object and save
519 token := &AnilistToken{
520 AccessToken: accessToken,
521 TokenType: "Bearer",
522 ExpiresIn: 31536000, // AniList tokens are valid for 1 year
523 ExpiresAt: time.Now().Add(365 * 24 * time.Hour),
524 }
525
526 // Save token to file
527 if err := saveToken(tokenPath, token); err != nil {
528 return "", fmt.Errorf("failed to save token: %w", err)
529 }
530
531 fmt.Println("Authentication successful!")
532 return token.AccessToken, nil
533}
534
535// loadToken loads the token from the token file
536func loadToken(tokenPath string) (*AnilistToken, error) {
537 data, err := os.ReadFile(tokenPath)
538 if err != nil {
539 return nil, fmt.Errorf("failed to read token file: %w", err)
540 }
541
542 var token AnilistToken
543 if err := json.Unmarshal(data, &token); err != nil {
544 return nil, fmt.Errorf("failed to parse token file: %w", err)
545 }
546
547 return &token, nil
548}
549
550// saveToken saves the token to the token file
551func saveToken(tokenPath string, token *AnilistToken) error {
552 // Ensure directory exists
553 if err := os.MkdirAll(filepath.Dir(tokenPath), 0755); err != nil {
554 return fmt.Errorf("failed to create directory: %w", err)
555 }
556
557 data, err := json.Marshal(token)
558 if err != nil {
559 return fmt.Errorf("failed to marshal token: %w", err)
560 }
561
562 return os.WriteFile(tokenPath, data, 0600)
563}
564
565// isTokenValid checks if the token is still valid
566func isTokenValid(token *AnilistToken) bool {
567 return token != nil && token.AccessToken != "" && time.Now().Before(token.ExpiresAt)
568}
569
570// GetTokenFromFile loads the token from the token file (supports both old text format and new JSON format)
571func GetTokenFromFile(tokenPath string) (string, error) {
572 data, err := os.ReadFile(tokenPath)
573 if err != nil {
574 return "", fmt.Errorf("failed to read token from file: %w", err)
575 }
576
577 // Try to parse as JSON first (new format)
578 var token AnilistToken
579 if err := json.Unmarshal(data, &token); err == nil {
580 // It's JSON format, check if token is valid
581 if isTokenValid(&token) {
582 return token.AccessToken, nil
583 }
584 return "", fmt.Errorf("token has expired")
585 }
586
587 // Fall back to plain text format (old format)
588 plainToken := strings.TrimSpace(string(data))
589 if plainToken == "" {
590 return "", fmt.Errorf("empty token file")
591 }
592
593 return plainToken, nil
594}
595
596func ChangeToken(config *CurdConfig, user *User) {
597 var err error
598 tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
599
600 // Try browser-based OAuth first
601 fmt.Println("Starting browser-based authentication...")
602 user.Token, err = authenticateWithBrowser(tokenPath, true)
603
604 if err != nil {
605 Log("Browser authentication failed: " + err.Error())
606 fmt.Printf("Browser authentication failed: %v\n", err)
607 fmt.Println("Falling back to manual token entry...")
608
609 // Simple CLI fallback
610 fmt.Println("Please visit: https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token&redirect_uri=http://localhost:8000/oauth/callback")
611 fmt.Print("Copy and paste your access token here: ")
612 fmt.Scanln(&user.Token)
613
614 if user.Token == "" {
615 ExitCurd(fmt.Errorf("no token provided"))
616 }
617
618 // Save the manually entered token as JSON format
619 token := &AnilistToken{
620 AccessToken: user.Token,
621 TokenType: "Bearer",
622 ExpiresIn: 31536000, // AniList tokens are valid for 1 year
623 ExpiresAt: time.Now().Add(365 * 24 * time.Hour),
624 }
625
626 if err := saveToken(tokenPath, token); err != nil {
627 ExitCurd(fmt.Errorf("failed to save token: %w", err))
628 }
629 }
630
631 if user.Token == "" {
632 ExitCurd(fmt.Errorf("no token provided"))
633 }
634
635 fmt.Println("Token saved successfully!")
636}
637
638// LoadConfigFromFile loads config file from disk into a map (key=value format)
639func LoadConfigFromFile(path string) (map[string]string, error) {
640 file, err := os.Open(path)
641 if err != nil {
642 return nil, err
643 }
644 defer file.Close()
645
646 configMap := make(map[string]string)
647 scanner := bufio.NewScanner(file)
648
649 for scanner.Scan() {
650 line := strings.TrimSpace(scanner.Text())
651 if line == "" || strings.HasPrefix(line, "#") {
652 continue // Skip empty lines and comments
653 }
654
655 parts := strings.SplitN(line, "=", 2)
656 if len(parts) == 2 {
657 key := strings.TrimSpace(parts[0])
658 value := strings.TrimSpace(parts[1])
659 configMap[key] = value
660 }
661 }
662
663 if err := scanner.Err(); err != nil {
664 return nil, err
665 }
666
667 return configMap, nil
668}
669
670// SaveConfigToFile saves updated config map to file in key=value format
671func SaveConfigToFile(path string, configMap map[string]string) error {
672 platform := InferPlatformForConfigPath(path, DetectPlatform())
673 return SaveConfigToFileWithSchema(path, configMap, configSchemaForPlatform(platform))
674}
675
676func SaveConfigToFileWithSchema(path string, configMap map[string]string, schema ConfigSchema) error {
677 file, err := os.Create(path)
678 if err != nil {
679 return err
680 }
681 defer file.Close()
682
683 writer := bufio.NewWriter(file)
684 written := make(map[string]bool, len(configMap))
685 for _, key := range schema.keys {
686 value, exists := configMap[key]
687 if !exists {
688 continue
689 }
690
691 line := fmt.Sprintf("%s=%s\n", key, value)
692 if _, err := writer.WriteString(line); err != nil {
693 return err
694 }
695 written[key] = true
696 }
697
698 for key, value := range configMap {
699 if written[key] {
700 continue
701 }
702 line := fmt.Sprintf("%s=%s\n", key, value)
703 if _, err := writer.WriteString(line); err != nil {
704 return err
705 }
706 }
707 return writer.Flush()
708}
709
710// PopulateConfig populates the CurdConfig struct from a map
711func PopulateConfig(configMap map[string]string) CurdConfig {
712 config := CurdConfig{}
713 configValue := reflect.ValueOf(&config).Elem()
714
715 for i := 0; i < configValue.NumField(); i++ {
716 field := configValue.Type().Field(i)
717 tag := field.Tag.Get("config")
718
719 if value, exists := configMap[tag]; exists {
720 fieldValue := configValue.FieldByName(field.Name)
721
722 if fieldValue.CanSet() {
723 switch fieldValue.Kind() {
724 case reflect.String:
725 fieldValue.SetString(value)
726 case reflect.Int:
727 intVal, _ := strconv.Atoi(value)
728 fieldValue.SetInt(int64(intVal))
729 case reflect.Bool:
730 boolVal, _ := strconv.ParseBool(value)
731 fieldValue.SetBool(boolVal)
732 }
733 }
734 }
735 }
736
737 // Handle MpvArgs specially
738 if mpvArgs, exists := configMap["MpvArgs"]; exists {
739 config.MpvArgs = parseStringArray(mpvArgs)
740 }
741 if androidExtraArgs, exists := configMap["AndroidExtraIntentArgs"]; exists {
742 config.AndroidExtraIntentArgs = parseStringArray(androidExtraArgs)
743 }
744
745 return config
746}
747
748func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
749 // Define the default categories and all available labels
750 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST"}
751 availableLabels := map[string]string{
752 "CURRENT": "Currently Watching",
753 "ALL": "Show All",
754 "UNTRACKED": "Untracked Watching",
755 "UPDATE": "Update (Episode, Status, Score)",
756 "CONTINUE_LAST": "Continue Last Session",
757 "PLANNING": "Plan to Watch",
758 "COMPLETED": "Completed",
759 "PAUSED": "Paused",
760 "DROPPED": "Dropped",
761 "REWATCHING": "Rewatching",
762 }
763
764 // Create ordered list to store final result
765 finalOrder := make([]string, 0)
766 seen := make(map[string]bool)
767
768 // If no menu order specified, use default order
769 if userCurdConfig.MenuOrder == "" {
770 finalOrder = defaultOrder
771 } else {
772 // Only show items explicitly specified by user
773 menuItems := strings.Split(userCurdConfig.MenuOrder, ",")
774 for _, key := range menuItems {
775 key = strings.TrimSpace(key)
776 if _, exists := availableLabels[key]; exists && !seen[key] {
777 finalOrder = append(finalOrder, key)
778 seen[key] = true
779 }
780 }
781 }
782
783 // Create the final ordered slice of SelectionOptions
784 orderedCategories := make([]SelectionOption, 0, len(finalOrder))
785 for _, key := range finalOrder {
786 orderedCategories = append(orderedCategories, SelectionOption{
787 Key: key,
788 Label: availableLabels[key],
789 })
790 }
791
792 return orderedCategories
793}