1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package cli
import (
"bufio"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/humdrum-tiv/dots-cli/internal/api"
"github.com/humdrum-tiv/dots-cli/internal/auth"
"github.com/humdrum-tiv/dots-cli/internal/config"
)
// RequireClient loads the stored token and returns a ready API client.
func RequireClient() (*api.Client, error) {
token, err := auth.LoadToken()
if err != nil {
return nil, fmt.Errorf("not linked — run `dots auth`")
}
return api.New(config.BaseURL(), token), nil
}
// Today returns the current date (YYYY-MM-DD) in the device timezone.
func Today() string {
return time.Now().Format("2006-01-02")
}
// TZ returns the device IANA timezone name. If the device timezone is not
// mappable to an IANA name, falls back to "UTC".
func TZ() string {
if loc := time.Local.String(); loc != "Local" {
return loc
}
return "UTC"
}
func openBrowser(url string) {
if runtime.GOOS == "darwin" {
exec.Command("open", url).Start()
} else {
exec.Command("xdg-open", url).Start()
}
}
func NewAuthCmd() *cobra.Command {
return &cobra.Command{
Use: "auth",
Short: "Link this machine to your Dots account",
RunE: func(cmd *cobra.Command, args []string) error {
pageURL := config.BaseURL() + "/cli"
fmt.Printf("Opening %s — generate a token there, then paste it here.\n", pageURL)
openBrowser(pageURL)
fmt.Print("Token: ")
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('\n')
token := strings.TrimSpace(line)
if token == "" {
return fmt.Errorf("no token entered")
}
client := api.New(config.BaseURL(), token)
if _, err := client.GetDay(Today(), TZ()); err != nil {
return fmt.Errorf("token check failed: %w", err)
}
if err := auth.SaveToken(token); err != nil {
return fmt.Errorf("could not store token: %w", err)
}
fmt.Println("Linked. Try `dots today`.")
return nil
},
}
}
|