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