ente/cli/internal/api/client.go

98 lines
2.1 KiB
Go
Raw Normal View History

2023-09-07 03:23:25 +00:00
package api
import (
"context"
2023-09-07 03:23:25 +00:00
"github.com/go-resty/resty/v2"
2023-10-30 02:45:29 +00:00
"log"
"time"
2023-09-07 03:23:25 +00:00
)
2023-09-08 14:42:58 +00:00
const (
2023-09-13 08:49:56 +00:00
EnteAPIEndpoint = "https://api.ente.io"
TokenHeader = "X-Auth-Token"
TokenQuery = "token"
ClientPkgHeader = "X-Client-Package"
2023-09-08 14:42:58 +00:00
)
var (
RedactedHeaders = []string{TokenHeader, " X-Request-Id"}
)
var tokenMap map[string]string = make(map[string]string)
2023-09-08 14:42:58 +00:00
2023-09-07 03:23:25 +00:00
type Client struct {
restClient *resty.Client
2023-09-25 13:40:36 +00:00
// use separate client for downloading files
downloadClient *resty.Client
2023-09-08 14:42:58 +00:00
}
type Params struct {
Debug bool
Trace bool
2023-09-13 08:49:56 +00:00
Host string
2023-09-07 03:23:25 +00:00
}
func readValueFromContext(ctx context.Context, key string) interface{} {
value := ctx.Value(key)
return value
}
2023-09-21 12:07:18 +00:00
2023-09-08 14:42:58 +00:00
func NewClient(p Params) *Client {
enteAPI := resty.New()
2023-09-25 13:40:36 +00:00
2023-09-08 14:42:58 +00:00
if p.Trace {
enteAPI.EnableTrace()
2023-09-08 14:42:58 +00:00
}
enteAPI.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
app := readValueFromContext(req.Context(), "app")
if app == nil {
panic("app not set in context")
}
req.Header.Set(ClientPkgHeader, StringToApp(app.(string)).ClientPkg())
2023-09-25 13:40:36 +00:00
attachToken(req)
return nil
})
2023-09-08 14:42:58 +00:00
if p.Debug {
enteAPI.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
2023-09-08 14:42:58 +00:00
logRequest(req)
return nil
})
enteAPI.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
2023-09-08 14:42:58 +00:00
logResponse(resp)
return nil
})
}
2023-09-13 08:49:56 +00:00
if p.Host != "" {
enteAPI.SetBaseURL(p.Host)
2023-09-13 08:49:56 +00:00
} else {
enteAPI.SetBaseURL(EnteAPIEndpoint)
2023-09-13 08:49:56 +00:00
}
2023-09-07 03:23:25 +00:00
return &Client{
restClient: enteAPI,
downloadClient: resty.New().
SetRetryCount(3).
SetRetryWaitTime(5 * time.Second).
SetRetryMaxWaitTime(10 * time.Second).
AddRetryCondition(func(r *resty.Response, err error) bool {
shouldRetry := r.StatusCode() == 429 || r.StatusCode() > 500
if shouldRetry {
2023-10-30 02:45:29 +00:00
log.Printf("retrying download due to %d code", r.StatusCode())
}
return shouldRetry
}),
2023-09-25 13:40:36 +00:00
}
}
func attachToken(req *resty.Request) {
2023-10-04 03:01:24 +00:00
accountKey := readValueFromContext(req.Context(), "account_key")
if accountKey != nil && accountKey != "" {
if token, ok := tokenMap[accountKey.(string)]; ok {
2023-09-25 13:40:36 +00:00
req.SetHeader(TokenHeader, token)
}
2023-09-07 03:23:25 +00:00
}
}
func (c *Client) AddToken(id string, token string) {
tokenMap[id] = token
}