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