2020-10-09 00:57:41 +00:00
|
|
|
package cliutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
logging "github.com/ipfs/go-log/v2"
|
|
|
|
"github.com/multiformats/go-multiaddr"
|
|
|
|
manet "github.com/multiformats/go-multiaddr/net"
|
|
|
|
)
|
|
|
|
|
|
|
|
var log = logging.Logger("cliutil")
|
|
|
|
|
|
|
|
var (
|
|
|
|
infoWithToken = regexp.MustCompile("^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?:.+$")
|
|
|
|
)
|
|
|
|
|
|
|
|
type APIInfo struct {
|
|
|
|
Addr string
|
|
|
|
Token []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseApiInfo(s string) APIInfo {
|
|
|
|
var tok []byte
|
2022-09-27 16:08:04 +00:00
|
|
|
|
2020-10-09 00:57:41 +00:00
|
|
|
if infoWithToken.Match([]byte(s)) {
|
|
|
|
sp := strings.SplitN(s, ":", 2)
|
|
|
|
tok = []byte(sp[0])
|
|
|
|
s = sp[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
return APIInfo{
|
|
|
|
Addr: s,
|
|
|
|
Token: tok,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-27 16:08:04 +00:00
|
|
|
func ParseApiInfoMulti(s string) []APIInfo {
|
|
|
|
var apiInfos []APIInfo
|
|
|
|
|
2022-10-18 19:53:42 +00:00
|
|
|
allAddrs := strings.SplitN(s, ",", -1)
|
2022-09-27 16:08:04 +00:00
|
|
|
|
2022-10-18 19:53:42 +00:00
|
|
|
for _, addr := range allAddrs {
|
2022-12-02 19:16:40 +00:00
|
|
|
apiInfos = append(apiInfos, ParseApiInfo(addr))
|
2022-09-27 16:08:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return apiInfos
|
|
|
|
}
|
|
|
|
|
2021-03-23 18:15:44 +00:00
|
|
|
func (a APIInfo) DialArgs(version string) (string, error) {
|
2020-10-09 00:57:41 +00:00
|
|
|
ma, err := multiaddr.NewMultiaddr(a.Addr)
|
|
|
|
if err == nil {
|
|
|
|
_, addr, err := manet.DialArgs(ma)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2021-03-23 18:15:44 +00:00
|
|
|
return "ws://" + addr + "/rpc/" + version, nil
|
2020-10-09 00:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
_, err = url.Parse(a.Addr)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-03-23 18:15:44 +00:00
|
|
|
return a.Addr + "/rpc/" + version, nil
|
2020-10-09 00:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (a APIInfo) Host() (string, error) {
|
|
|
|
ma, err := multiaddr.NewMultiaddr(a.Addr)
|
|
|
|
if err == nil {
|
|
|
|
_, addr, err := manet.DialArgs(ma)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return addr, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
spec, err := url.Parse(a.Addr)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return spec.Host, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a APIInfo) AuthHeader() http.Header {
|
|
|
|
if len(a.Token) != 0 {
|
|
|
|
headers := http.Header{}
|
|
|
|
headers.Add("Authorization", "Bearer "+string(a.Token))
|
|
|
|
return headers
|
|
|
|
}
|
|
|
|
log.Warn("API Token not set and requested, capabilities might be limited.")
|
|
|
|
return nil
|
|
|
|
}
|