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