chore(publicip): less coupling with ipinfo.io

This commit is contained in:
Quentin McGaw
2024-02-13 11:11:10 +00:00
parent 6a6337b98f
commit cfca026621
14 changed files with 136 additions and 75 deletions

View File

@@ -0,0 +1,47 @@
package api
import (
"context"
"errors"
"fmt"
"net/http"
"net/netip"
"strings"
"github.com/qdm12/gluetun/internal/models"
)
type API interface {
FetchInfo(ctx context.Context, ip netip.Addr) (
result models.PublicIP, err error)
}
type Provider string
const (
IPInfo Provider = "ipinfo"
)
func New(provider Provider, client *http.Client, token string) ( //nolint:ireturn
a API, err error) {
switch provider {
case IPInfo:
return newIPInfo(client, token), nil
default:
panic("provider not valid: " + provider)
}
}
var (
ErrProviderNotValid = errors.New("API name is not valid")
)
func ParseProvider(s string) (provider Provider, err error) {
switch strings.ToLower(s) {
case "ipinfo":
return IPInfo, nil
default:
return "", fmt.Errorf(`%w: %q can only be "ipinfo" or "ip2location"`,
ErrProviderNotValid, s)
}
}

View File

@@ -0,0 +1,9 @@
package api
import "errors"
var (
ErrTokenNotValid = errors.New("token is not valid")
ErrTooManyRequests = errors.New("too many requests sent for this month")
ErrBadHTTPStatus = errors.New("bad HTTP status received")
)

View File

@@ -0,0 +1,13 @@
package api
import (
"context"
"net/netip"
"github.com/qdm12/gluetun/internal/models"
)
type Fetcher interface {
FetchInfo(ctx context.Context, ip netip.Addr) (
result models.PublicIP, err error)
}

View File

@@ -0,0 +1,100 @@
package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/netip"
"strings"
"github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
)
type ipInfo struct {
client *http.Client
token string
}
func newIPInfo(client *http.Client, token string) *ipInfo {
return &ipInfo{
client: client,
token: token,
}
}
// FetchInfo obtains information on the ip address provided
// using the ipinfo.io API. If the ip is the zero value, the public IP address
// of the machine is used as the IP.
func (i *ipInfo) FetchInfo(ctx context.Context, ip netip.Addr) (
result models.PublicIP, err error) {
url := "https://ipinfo.io/"
switch {
case ip.Is6():
url = "https://v6.ipinfo.io/" + ip.String()
case ip.Is4():
url = "https://ipinfo.io/" + ip.String()
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return result, err
}
request.Header.Set("Authorization", "Bearer "+i.token)
response, err := i.client.Do(request)
if err != nil {
return result, err
}
defer response.Body.Close()
if i.token != "" && response.StatusCode == http.StatusUnauthorized {
return result, fmt.Errorf("%w: %s", ErrTokenNotValid, response.Status)
}
switch response.StatusCode {
case http.StatusOK:
case http.StatusTooManyRequests, http.StatusForbidden:
return result, fmt.Errorf("%w from %s: %d %s",
ErrTooManyRequests, url, response.StatusCode, response.Status)
default:
return result, fmt.Errorf("%w from %s: %d %s",
ErrBadHTTPStatus, url, response.StatusCode, response.Status)
}
decoder := json.NewDecoder(response.Body)
var data struct {
IP netip.Addr `json:"ip,omitempty"`
Region string `json:"region,omitempty"`
Country string `json:"country,omitempty"`
City string `json:"city,omitempty"`
Hostname string `json:"hostname,omitempty"`
Loc string `json:"loc,omitempty"`
Org string `json:"org,omitempty"`
Postal string `json:"postal,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
if err := decoder.Decode(&data); err != nil {
return result, fmt.Errorf("decoding response: %w", err)
}
countryCode := strings.ToLower(data.Country)
country, ok := constants.CountryCodes()[countryCode]
if ok {
data.Country = country
}
result = models.PublicIP{
IP: data.IP,
Region: data.Region,
Country: data.Country,
City: data.City,
Hostname: data.Hostname,
Location: data.Loc,
Organization: data.Org,
PostalCode: data.Postal,
Timezone: data.Timezone,
}
return result, nil
}

View File

@@ -0,0 +1,56 @@
package api
import (
"context"
"net/netip"
"github.com/qdm12/gluetun/internal/models"
)
// FetchMultiInfo obtains the public IP address information for every IP
// addresses provided and returns a slice of results with the corresponding
// order as to the IP addresses slice order.
// If an error is encountered, all the operations are canceled and
// an error is returned, so the results returned should be considered
// incomplete in this case.
func FetchMultiInfo(ctx context.Context, fetcher Fetcher, ips []netip.Addr) (
results []models.PublicIP, err error) {
ctx, cancel := context.WithCancel(ctx)
type asyncResult struct {
index int
result models.PublicIP
err error
}
resultsCh := make(chan asyncResult)
for i, ip := range ips {
go func(index int, ip netip.Addr) {
aResult := asyncResult{
index: index,
}
aResult.result, aResult.err = fetcher.FetchInfo(ctx, ip)
resultsCh <- aResult
}(i, ip)
}
results = make([]models.PublicIP, len(ips))
for i := 0; i < len(ips); i++ {
aResult := <-resultsCh
if aResult.err != nil {
if err == nil {
// Cancel on the first error encountered
err = aResult.err
cancel()
}
continue // ignore errors after the first one
}
results[aResult.index] = aResult.result
}
close(resultsCh)
cancel()
return results, err
}