2022-10-27 02:54:49 +00:00
|
|
|
package alist_v3
|
2022-12-07 11:02:28 +00:00
|
|
|
|
|
|
|
import (
|
2023-04-23 09:48:26 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2022-12-07 11:02:28 +00:00
|
|
|
|
2023-04-23 09:48:26 +00:00
|
|
|
"github.com/alist-org/alist/v3/drivers/base"
|
|
|
|
"github.com/alist-org/alist/v3/internal/op"
|
|
|
|
"github.com/alist-org/alist/v3/pkg/utils"
|
2022-12-07 11:02:28 +00:00
|
|
|
"github.com/alist-org/alist/v3/server/common"
|
2023-04-23 09:48:26 +00:00
|
|
|
"github.com/go-resty/resty/v2"
|
2023-05-27 12:23:36 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2022-12-07 11:02:28 +00:00
|
|
|
)
|
|
|
|
|
2023-04-23 09:48:26 +00:00
|
|
|
func (d *AListV3) login() error {
|
2024-06-16 08:55:49 +00:00
|
|
|
if d.Username == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2023-04-23 09:48:26 +00:00
|
|
|
var resp common.Resp[LoginResp]
|
|
|
|
_, err := d.request("/auth/login", http.MethodPost, func(req *resty.Request) {
|
|
|
|
req.SetResult(&resp).SetBody(base.Json{
|
|
|
|
"username": d.Username,
|
|
|
|
"password": d.Password,
|
|
|
|
})
|
|
|
|
})
|
2022-12-07 11:02:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-04-23 09:48:26 +00:00
|
|
|
d.Token = resp.Data.Token
|
|
|
|
op.MustSaveDriverStorage(d)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *AListV3) request(api, method string, callback base.ReqCallback, retry ...bool) ([]byte, error) {
|
|
|
|
url := d.Address + "/api" + api
|
|
|
|
req := base.RestyClient.R()
|
|
|
|
req.SetHeader("Authorization", d.Token)
|
|
|
|
if callback != nil {
|
|
|
|
callback(req)
|
|
|
|
}
|
|
|
|
res, err := req.Execute(method, url)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-05-27 12:23:36 +00:00
|
|
|
log.Debugf("[alist_v3] response body: %s", res.String())
|
2023-04-23 09:48:26 +00:00
|
|
|
if res.StatusCode() >= 400 {
|
|
|
|
return nil, fmt.Errorf("request failed, status: %s", res.Status())
|
|
|
|
}
|
|
|
|
code := utils.Json.Get(res.Body(), "code").ToInt()
|
|
|
|
if code != 200 {
|
|
|
|
if (code == 401 || code == 403) && !utils.IsBool(retry...) {
|
|
|
|
err = d.login()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return d.request(api, method, callback, true)
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("request failed,code: %d, message: %s", code, utils.Json.Get(res.Body(), "message").ToString())
|
2022-12-07 11:02:28 +00:00
|
|
|
}
|
2023-04-23 09:48:26 +00:00
|
|
|
return res.Body(), nil
|
2022-12-07 11:02:28 +00:00
|
|
|
}
|