| @@ -2,16 +2,40 @@ package internal |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 5 | 7 | "fmt" |
| 8 | |
| 9 | // "io" |
| 10 | "net/http" |
| 11 | "net/url" |
| 6 | 12 | "os" |
| 7 | | "os/exec" |
| 8 | 13 | "path/filepath" |
| 9 | 14 | "reflect" |
| 10 | | "runtime" |
| 11 | 15 | "strconv" |
| 12 | 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/pkg/browser" |
| 13 | 20 | ) |
| 14 | 21 | |
| 22 | const ( |
| 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 |
| 31 | type 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 | |
| 15 | 39 | // CurdConfig struct with field names that match the config keys |
| 16 | 40 | type CurdConfig struct { |
| 17 | 41 | Player string `config:"Player"` |
| @@ -181,74 +205,287 @@ func createDefaultConfig(path string) error { |
| 181 | 205 | return nil |
| 182 | 206 | } |
| 183 | 207 | |
| 184 | | func getTokenFromTempFile(isWindowsPlatform bool) (string, error) { |
| 185 | | // Create a temporary file for the token |
| 186 | | tempFile, err := os.CreateTemp("", "curd-token-*.txt") |
| 187 | | if err != nil { |
| 188 | | return "", fmt.Errorf("error creating temp file: %v", err) |
| 208 | // authenticateWithBrowser performs OAuth authentication using browser |
| 209 | func 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 |
| 189 | 216 | } |
| 190 | | tempPath := tempFile.Name() |
| 191 | | tempFile.Close() |
| 192 | 217 | |
| 193 | | // Write instructions to the temp file |
| 194 | | instructions := "Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token\n" + |
| 195 | | "Replace this text with your token and save the file.\n" |
| 196 | | if err := os.WriteFile(tempPath, []byte(instructions), 0644); err != nil { |
| 197 | | return "", fmt.Errorf("error writing instructions: %v", err) |
| 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, |
| 198 | 225 | } |
| 199 | 226 | |
| 200 | | // Open the file with appropriate editor |
| 201 | | var cmd *exec.Cmd |
| 202 | | if isWindowsPlatform { |
| 203 | | cmd = exec.Command("notepad.exe", tempPath) |
| 204 | | } else { |
| 205 | | editor := os.Getenv("EDITOR") |
| 206 | | if editor == "" { |
| 207 | | editor = "nano" // Default to nano if $EDITOR is not set |
| 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 |
| 208 | 253 | } |
| 209 | | cmd = exec.Command(editor, tempPath) |
| 210 | | cmd.Stdin = os.Stdin |
| 211 | | cmd.Stdout = os.Stdout |
| 212 | | cmd.Stderr = os.Stderr |
| 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), |
| 213 | 377 | } |
| 214 | 378 | |
| 215 | | if err := cmd.Run(); err != nil { |
| 216 | | return "", fmt.Errorf("error opening editor: %v", err) |
| 379 | // Save token to file |
| 380 | if err := saveToken(tokenPath, token); err != nil { |
| 381 | return "", fmt.Errorf("failed to save token: %w", err) |
| 217 | 382 | } |
| 218 | 383 | |
| 219 | | // Read the token from the file |
| 220 | | content, err := os.ReadFile(tempPath) |
| 384 | fmt.Println("Authentication successful!") |
| 385 | return token.AccessToken, nil |
| 386 | } |
| 387 | |
| 388 | // loadToken loads the token from the token file |
| 389 | func loadToken(tokenPath string) (*AnilistToken, error) { |
| 390 | data, err := os.ReadFile(tokenPath) |
| 221 | 391 | if err != nil { |
| 222 | | return "", fmt.Errorf("error reading token: %v", err) |
| 392 | return nil, fmt.Errorf("failed to read token file: %w", err) |
| 223 | 393 | } |
| 224 | 394 | |
| 225 | | // Clean up the temp file |
| 226 | | os.Remove(tempPath) |
| 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 | } |
| 227 | 399 | |
| 228 | | // Extract token (remove instructions and whitespace) |
| 229 | | return strings.TrimSpace(string(content)), nil |
| 400 | return &token, nil |
| 401 | } |
| 402 | |
| 403 | // saveToken saves the token to the token file |
| 404 | func 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 |
| 419 | func 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) |
| 424 | func 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 |
| 230 | 447 | } |
| 231 | 448 | |
| 232 | 449 | func ChangeToken(config *CurdConfig, user *User) { |
| 233 | 450 | var err error |
| 234 | | tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "token") |
| 235 | | |
| 236 | | switch { |
| 237 | | case runtime.GOOS == "darwin" || runtime.GOOS == "windows": |
| 238 | | user.Token, err = getTokenFromTempFile(runtime.GOOS == "windows") |
| 239 | | case config.RofiSelection: |
| 240 | | user.Token, err = GetTokenFromRofi() |
| 241 | | default: |
| 242 | | fmt.Println("Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token") |
| 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: ") |
| 243 | 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 | } |
| 244 | 482 | } |
| 245 | 483 | |
| 246 | | if err != nil { |
| 247 | | Log("Error getting user input: " + err.Error()) |
| 248 | | ExitCurd(err) |
| 484 | if user.Token == "" { |
| 485 | ExitCurd(fmt.Errorf("no token provided")) |
| 249 | 486 | } |
| 250 | 487 | |
| 251 | | WriteTokenToFile(user.Token, tokenPath) |
| 488 | fmt.Println("Token saved successfully!") |
| 252 | 489 | } |
| 253 | 490 | |
| 254 | 491 | // LoadConfigFromFile loads config file from disk into a map (key=value format) |