Commit 6bb2b35e3f

6bb2b35e3fb217ead66e4e2d5d7b0e2763ca15e8

parent: ae75c9f7ed

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2025-08-26 21:41 UTC
committer: <noreply@github.com>

Add: Get token from browser automatically instead of pasting it manually (#68)

Layout: unified · split

cmd/curd/main.go +10 −10
@@ -38,9 +38,6 @@ func main() {
38 } 38 }
39 internal.SetGlobalConfig(&userCurdConfig) 39 internal.SetGlobalConfig(&userCurdConfig)
40 40
41 // Setup
42 internal.ClearScreen()
43 defer internal.RestoreScreen()
44 41
45 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log") 42 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
46 internal.SetGlobalLogFile(logFile) 43 internal.SetGlobalLogFile(logFile)
@@ -116,6 +113,10 @@ func main() {
116 return 113 return
117 } 114 }
118 115
116 // Setup screen for interactive mode (only if not changing token)
117 internal.ClearScreen()
118 defer internal.RestoreScreen()
119
119 if *currentCategory { 120 if *currentCategory {
120 userCurdConfig.CurrentCategory = true 121 userCurdConfig.CurrentCategory = true
121 } 122 }
@@ -149,7 +150,7 @@ func main() {
149 } 150 }
150 151
151 // Get the token from the token file 152 // Get the token from the token file
152 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token")) 153 user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "anilist_token.json"))
153 if err != nil { 154 if err != nil {
154 internal.Log("Error reading token") 155 internal.Log("Error reading token")
155 } 156 }
@@ -485,7 +486,7 @@ func main() {
485 if err != nil { 486 if err != nil {
486 internal.Log("Error updating local database on quit: " + err.Error()) 487 internal.Log("Error updating local database on quit: " + err.Error())
487 } 488 }
488 489
489 // Update Anilist progress if not rewatching 490 // Update Anilist progress if not rewatching
490 if !anime.Rewatching { 491 if !anime.Rewatching {
491 go func() { 492 go func() {
@@ -497,7 +498,7 @@ func main() {
497 } 498 }
498 }() 499 }()
499 } 500 }
500 501
501 internal.ExitCurd(nil) 502 internal.ExitCurd(nil)
502 } 503 }
503 } else { 504 } else {
@@ -591,7 +592,7 @@ func main() {
591 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection { 592 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
592 continue 593 continue
593 } 594 }
594 595
595 // Nothing is playing, check percentage watched 596 // Nothing is playing, check percentage watched
596 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 597 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
597 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n", 598 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n",
@@ -615,7 +616,7 @@ func main() {
615 if err != nil { 616 if err != nil {
616 internal.Log("Error updating local database on quit: " + err.Error()) 617 internal.Log("Error updating local database on quit: " + err.Error())
617 } 618 }
618 619
619 // Update Anilist progress if not rewatching 620 // Update Anilist progress if not rewatching
620 if !anime.Rewatching { 621 if !anime.Rewatching {
621 go func() { 622 go func() {
@@ -627,7 +628,7 @@ func main() {
627 } 628 }
628 }() 629 }()
629 } 630 }
630 631
631 internal.ExitCurd(nil) 632 internal.ExitCurd(nil)
632 } 633 }
633 } else { 634 } else {
@@ -808,4 +809,3 @@ func main() {
808 809
809 } 810 }
810} 811}
811
internal/config.go +285 −48
@@ -2,16 +2,40 @@ package internal
2 2
3import ( 3import (
4 "bufio" 4 "bufio"
5 "context"
6 "encoding/json"
5 "fmt" 7 "fmt"
8
9 // "io"
10 "net/http"
11 "net/url"
6 "os" 12 "os"
7 "os/exec"
8 "path/filepath" 13 "path/filepath"
9 "reflect" 14 "reflect"
10 "runtime"
11 "strconv" 15 "strconv"
12 "strings" 16 "strings"
17 "time"
18
19 "github.com/pkg/browser"
13) 20)
14 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
15// CurdConfig struct with field names that match the config keys 39// CurdConfig struct with field names that match the config keys
16type CurdConfig struct { 40type CurdConfig struct {
17 Player string `config:"Player"` 41 Player string `config:"Player"`
@@ -181,74 +205,287 @@ func createDefaultConfig(path string) error {
181 return nil 205 return nil
182} 206}
183 207
184func getTokenFromTempFile(isWindowsPlatform bool) (string, error) { 208// authenticateWithBrowser performs OAuth authentication using browser
185 // Create a temporary file for the token 209func authenticateWithBrowser(tokenPath string) (string, error) {
186 tempFile, err := os.CreateTemp("", "curd-token-*.txt") 210 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
187 if err != nil { 211 defer cancel()
188 return "", fmt.Errorf("error creating temp file: %v", err) 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 218 // Start local server to handle OAuth callback
194 instructions := "Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token\n" + 219 callbackCh := make(chan string, 1)
195 "Replace this text with your token and save the file.\n" 220 errCh := make(chan error, 1)
196 if err := os.WriteFile(tempPath, []byte(instructions), 0644); err != nil { 221 mux := http.NewServeMux()
197 return "", fmt.Errorf("error writing instructions: %v", err) 222 srv := &http.Server{
223 Addr: fmt.Sprintf(":%d", anilistServerPort),
224 Handler: mux,
198 } 225 }
199 226
200 // Open the file with appropriate editor 227 // Handle OAuth callback - for authorization code grant, code comes in query params
201 var cmd *exec.Cmd 228 mux.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
202 if isWindowsPlatform { 229 code := r.URL.Query().Get("code")
203 cmd = exec.Command("notepad.exe", tempPath) 230 errorParam := r.URL.Query().Get("error")
204 } else { 231
205 editor := os.Getenv("EDITOR") 232 w.Header().Set("Content-Type", "text/html")
206 if editor == "" { 233
207 editor = "nano" // Default to nano if $EDITOR is not set 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) 254
210 cmd.Stdin = os.Stdin 255 if code == "" {
211 cmd.Stdout = os.Stdout 256 w.WriteHeader(http.StatusBadRequest)
212 cmd.Stderr = os.Stderr 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 { 379 // Save token to file
216 return "", fmt.Errorf("error opening editor: %v", err) 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 384 fmt.Println("Authentication successful!")
220 content, err := os.ReadFile(tempPath) 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)
221 if err != nil { 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 395 var token AnilistToken
226 os.Remove(tempPath) 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) 400 return &token, nil
229 return strings.TrimSpace(string(content)), 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
230} 447}
231 448
232func ChangeToken(config *CurdConfig, user *User) { 449func ChangeToken(config *CurdConfig, user *User) {
233 var err error 450 var err error
234 tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "token") 451 tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
235 452
236 switch { 453 // Try browser-based OAuth first
237 case runtime.GOOS == "darwin" || runtime.GOOS == "windows": 454 fmt.Println("Starting browser-based authentication...")
238 user.Token, err = getTokenFromTempFile(runtime.GOOS == "windows") 455 user.Token, err = authenticateWithBrowser(tokenPath)
239 case config.RofiSelection: 456
240 user.Token, err = GetTokenFromRofi() 457 if err != nil {
241 default: 458 Log("Browser authentication failed: " + err.Error())
242 fmt.Println("Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token") 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 fmt.Scanln(&user.Token) 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 { 484 if user.Token == "" {
247 Log("Error getting user input: " + err.Error()) 485 ExitCurd(fmt.Errorf("no token provided"))
248 ExitCurd(err)
249 } 486 }
250 487
251 WriteTokenToFile(user.Token, tokenPath) 488 fmt.Println("Token saved successfully!")
252} 489}
253 490
254// LoadConfigFromFile loads config file from disk into a map (key=value format) 491// LoadConfigFromFile loads config file from disk into a map (key=value format)
internal/curd.go −12
@@ -19,18 +19,6 @@ import (
19 "github.com/gen2brain/beeep" 19 "github.com/gen2brain/beeep"
20) 20)
21 21
22func GetTokenFromFile(filePath string) (string, error) {
23 // Read the token from the file
24 data, err := os.ReadFile(filePath)
25 if err != nil {
26 return "", fmt.Errorf("failed to read token from file: %w", err)
27 }
28
29 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
30 token := strings.TrimSpace(string(data))
31
32 return token, nil
33}
34 22
35func EditConfig(configFilePath string) { 23func EditConfig(configFilePath string) {
36 // Get the user's preferred editor from the EDITOR environment variable 24 // Get the user's preferred editor from the EDITOR environment variable
internal/rofi.go +3 −3
@@ -10,8 +10,8 @@ import (
10) 10)
11 11
12func GetTokenFromRofi() (string, error) { 12func GetTokenFromRofi() (string, error) {
13 // The URL to open 13 // The URL to open - using authorization code flow for consistency
14 url := "https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token" 14 url := "https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=code&redirect_uri=http://localhost:8000/oauth/callback"
15 15
16 // Use rofi to display a prompt with the URL 16 // Use rofi to display a prompt with the URL
17 message := "Press enter to open the anilist token page in your browser" 17 message := "Press enter to open the anilist token page in your browser"
@@ -27,7 +27,7 @@ func GetTokenFromRofi() (string, error) {
27 } 27 }
28 28
29 // Use rofi again to get the token input from the user 29 // Use rofi again to get the token input from the user
30 token, err := GetUserInputFromRofi("Enter the token") 30 token, err := GetUserInputFromRofi("Enter the token (from the redirect URL after 'access_token=')")
31 if err != nil { 31 if err != nil {
32 return "", err 32 return "", err
33 } 33 }