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