/
qrcode.go
92 lines (79 loc) · 2.09 KB
/
qrcode.go
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package adrive
import (
"context"
"fmt"
"os"
"time"
"github.com/isayme/go-alipanopen"
"github.com/isayme/go-ora"
"github.com/mdp/qrterminal/v3"
)
func (fs *FileSystem) authIfRequired(ctx context.Context) error {
if fs.accessToken != "" {
return nil
}
scopes := []string{alipanopen.SCOPE_USER_BASE, alipanopen.SCOPE_FILE_ALL_READ}
if !fs.readonly {
scopes = append(scopes, alipanopen.SCOPE_FILE_ALL_WRITE)
}
reqBody := &alipanopen.GetQrCodeReq{
ClientId: fs.clientId,
ClientSecret: fs.clientSecret,
Scopes: scopes,
}
qrCodeResp, err := fs.client.GetQrCode(ctx, reqBody)
if err != nil {
return err
}
qrCodeText := "https://www.aliyundrive.com/o/oauth/authorize?sid=" + qrCodeResp.Sid
qrterminal.GenerateWithConfig(qrCodeText, qrterminal.Config{
Level: qrterminal.L,
Writer: os.Stdout,
HalfBlocks: true,
BlackChar: qrterminal.BLACK_BLACK,
WhiteChar: qrterminal.WHITE_WHITE,
WhiteBlackChar: qrterminal.WHITE_BLACK,
BlackWhiteChar: qrterminal.BLACK_WHITE,
QuietZone: 2,
})
ora := ora.New()
defer ora.Stop()
ora.Start()
ora.Text("等待扫码...")
done := false
for {
if done {
break
}
qrCodeStatusResp, err := fs.client.GetQrCodeStatus(ctx, qrCodeResp.Sid)
if err != nil {
return err
}
switch qrCodeStatusResp.Status {
case alipanopen.QRCODE_STATUS_WAITLOGIN:
ora.Text("等待扫码...")
time.Sleep(time.Second)
case alipanopen.QRCODE_STATUS_SCANSUCCESS:
ora.Text("已扫码成功")
time.Sleep(time.Second)
case alipanopen.QRCODE_STATUS_LOGINSUCCESS:
ora.Succeed("已登录成功")
reqBody := &alipanopen.RefreshTokenReq{
ClientId: fs.clientId,
ClientSecret: fs.clientSecret,
GrantType: alipanopen.GRANT_TYPE_AUTHORIZATION_CODE,
Code: qrCodeStatusResp.AuthCode,
}
refreshTokenResp, err := fs.client.RefreshToken(ctx, reqBody)
if err != nil {
return err
}
fs.saveToken(refreshTokenResp)
done = true
case alipanopen.QRCODE_STATUS_QRCODEEXPIRED:
ora.Fail("二维码过期")
return fmt.Errorf("二维码过期")
}
}
return nil
}