File size: 1,897 Bytes
7107f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package kodbox

import (
	"fmt"
	"github.com/alist-org/alist/v3/drivers/base"
	"github.com/alist-org/alist/v3/pkg/utils"
	"github.com/go-resty/resty/v2"
	"strings"
)

func (d *KodBox) getToken() error {
	var authResp CommonResp
	res, err := base.RestyClient.R().
		SetResult(&authResp).
		SetQueryParams(map[string]string{
			"name":     d.UserName,
			"password": d.Password,
		}).
		Post(d.Address + "/?user/index/loginSubmit")
	if err != nil {
		return err
	}
	if res.StatusCode() >= 400 {
		return fmt.Errorf("get token failed: %s", res.String())
	}

	if res.StatusCode() == 200 && authResp.Code.(bool) == false {
		return fmt.Errorf("get token failed: %s", res.String())
	}

	d.authorization = fmt.Sprintf("%s", authResp.Info)
	return nil
}

func (d *KodBox) request(method string, pathname string, callback base.ReqCallback, noRedirect ...bool) ([]byte, error) {
	full := pathname
	if !strings.HasPrefix(pathname, "http") {
		full = d.Address + pathname
	}
	req := base.RestyClient.R()
	if len(noRedirect) > 0 && noRedirect[0] {
		req = base.NoRedirectClient.R()
	}
	req.SetFormData(map[string]string{
		"accessToken": d.authorization,
	})
	callback(req)

	var (
		res        *resty.Response
		commonResp *CommonResp
		err        error
		skip       bool
	)
	for i := 0; i < 2; i++ {
		if skip {
			break
		}
		res, err = req.Execute(method, full)
		if err != nil {
			return nil, err
		}

		err := utils.Json.Unmarshal(res.Body(), &commonResp)
		if err != nil {
			return nil, err
		}

		switch commonResp.Code.(type) {
		case bool:
			skip = true
		case string:
			if commonResp.Code.(string) == "10001" {
				err = d.getToken()
				if err != nil {
					return nil, err
				}
				req.SetFormData(map[string]string{"accessToken": d.authorization})
			}
		}
	}
	if commonResp.Code.(bool) == false {
		return nil, fmt.Errorf("request failed: %s", commonResp.Data)
	}
	return res.Body(), nil
}