terraform-provider-interwebao/internal/client/api.go
2026-11-28 15:28:02 +02:00

453 lines
15 KiB
Go

package client
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
)
// Price is the price of one billing cycle.
type Price struct {
BillingCycle string `json:"billing_cycle"`
Months int64 `json:"months"`
Price float64 `json:"price"`
SetupFee float64 `json:"setup_fee"`
}
// Group is a product group.
type Group struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
// Product is one item of GET /v1/catalog/products.
type Product struct {
ID int64 `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Group Group `json:"group"`
Free bool `json:"free"`
Currency string `json:"currency"`
Prices []Price `json:"prices"`
Purchasable bool `json:"purchasable"`
}
// Choice is one choice of a configurable option.
type Choice struct {
ID int64 `json:"id"`
Name string `json:"name"`
Prices []Price `json:"prices"`
}
// ConfigOption is an option the buyer picks, such as the operating system or the data center.
type ConfigOption struct {
ID int64 `json:"id"`
Name string `json:"name"`
DefaultChoiceID int64 `json:"default_choice_id"`
Choices []Choice `json:"choices"`
}
// ProductDetail is GET /v1/catalog/products/{id}.
type ProductDetail struct {
ID int64 `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Group Group `json:"group"`
Currency string `json:"currency"`
BillingCycles []Price `json:"billing_cycles"`
ConfigOptions []ConfigOption `json:"config_options"`
AcceptsDomain bool `json:"accepts_domain"`
Purchasable bool `json:"purchasable"`
NotPurchasableReason *string `json:"not_purchasable_reason"`
}
// TLD is one domain extension with its prices by number of years.
type TLD struct {
Extension string `json:"extension"`
Currency string `json:"currency"`
Register map[string]float64 `json:"register"`
Renew map[string]float64 `json:"renew"`
Transfer map[string]float64 `json:"transfer"`
Features struct {
DNSManagement bool `json:"dns_management"`
EmailForwarding bool `json:"email_forwarding"`
IDProtection bool `json:"id_protection"`
TransferCodeRequired bool `json:"transfer_code_required"`
} `json:"features"`
}
// Availability is GET /v1/domains/availability.
type Availability struct {
Domain string `json:"domain"`
Extension string `json:"extension"`
Status string `json:"status"`
Available bool `json:"available"`
OneYearPrice struct {
Register *float64 `json:"register"`
Renew *float64 `json:"renew"`
Transfer *float64 `json:"transfer"`
} `json:"one_year_price"`
Currency string `json:"currency"`
PortalOnly bool `json:"portal_only"`
}
// Server is a VPS, from GET /v1/servers/{id}.
type Server struct {
ID int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Product string `json:"product"`
IP string `json:"ip"`
PowerState string `json:"power_state"`
NextDueDate *string `json:"next_due_date"`
AdditionalIPs []string `json:"additional_ips"`
OperatingSystem struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"operating_system"`
Location string `json:"location"`
Resources struct {
VCPU int64 `json:"vcpu"`
RAMGB int64 `json:"ram_gb"`
DiskGB int64 `json:"disk_gb"`
TrafficGB int64 `json:"traffic_gb"`
} `json:"resources"`
BillingCycle string `json:"billing_cycle"`
StateStale bool `json:"state_stale"`
}
// Purchase is the answer of POST /v1/services/purchase.
type Purchase struct {
ActionID string `json:"action_id"`
Status string `json:"status"`
Simulated bool `json:"simulated"`
Name string `json:"name"`
Kind string `json:"kind"`
OrderID int64 `json:"order_id"`
InvoiceID int64 `json:"invoice_id"`
ServiceID int64 `json:"service_id"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
}
// PowerAction is the answer of start, stop, restart and timezone changes.
type PowerAction struct {
ActionID string `json:"action_id"`
Status string `json:"status"`
Simulated bool `json:"simulated"`
}
// Domain is GET /v1/domains/{domain}.
type Domain struct {
ID int64 `json:"id"`
Domain string `json:"domain"`
Status string `json:"status"`
Type string `json:"type"`
RegisteredAt *string `json:"registered_at"`
ExpiresAt *string `json:"expires_at"`
NextDueDate *string `json:"next_due_date"`
PeriodYears int64 `json:"period_years"`
RenewalAmount float64 `json:"renewal_amount"`
Currency string `json:"currency"`
AutoRenew bool `json:"auto_renew"`
Premium bool `json:"premium"`
Features struct {
DNSManagement bool `json:"dns_management"`
} `json:"features"`
}
// Registration is the answer of POST /v1/domains/register.
type Registration struct {
ActionID string `json:"action_id"`
Status string `json:"status"`
Simulated bool `json:"simulated"`
Domain string `json:"domain"`
Years int64 `json:"years"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
Locked *bool `json:"locked"`
}
// DNSRecord is one record of a DNS zone.
type DNSRecord struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Value string `json:"value"`
TTL int64 `json:"ttl"`
Priority int64 `json:"priority"`
ReadOnly bool `json:"read_only"`
Simulated bool `json:"simulated"`
}
// DNSRecordInput is the body to create or change a record.
type DNSRecordInput struct {
Name string `json:"name"`
Type string `json:"type"`
Value string `json:"value"`
TTL int64 `json:"ttl"`
Priority int64 `json:"priority"`
}
func esc(s string) string { return url.PathEscape(strings.ToLower(strings.TrimSpace(s))) }
func currencyQuery(currency string) url.Values {
q := url.Values{}
if currency != "" {
q.Set("currency", currency)
}
return q
}
// ---------------------------------------------------------------- catalog
// Products lists the products for sale.
func (c *Client) Products(ctx context.Context, currency string) ([]Product, error) {
var all []Product
err := c.ListAll(ctx, "/v1/catalog/products", currencyQuery(currency), func(raw json.RawMessage) error {
var page []Product
if err := json.Unmarshal(raw, &page); err != nil {
return err
}
all = append(all, page...)
return nil
})
return all, err
}
// Product returns one product with its options.
func (c *Client) Product(ctx context.Context, id int64, currency string) (*ProductDetail, error) {
var p ProductDetail
_, err := c.Do(ctx, http.MethodGet, "/v1/catalog/products/"+strconv.FormatInt(id, 10), currencyQuery(currency), nil, "", &p)
return &p, err
}
// TLDs lists the domain extensions. extension filters one, such as ".co.ao".
func (c *Client) TLDs(ctx context.Context, extension, currency string) ([]TLD, error) {
q := currencyQuery(currency)
if extension != "" {
q.Set("extension", extension)
}
var all []TLD
err := c.ListAll(ctx, "/v1/catalog/tlds", q, func(raw json.RawMessage) error {
var page []TLD
if err := json.Unmarshal(raw, &page); err != nil {
return err
}
all = append(all, page...)
return nil
})
return all, err
}
// Availability checks one domain name.
func (c *Client) Availability(ctx context.Context, domain string) (*Availability, error) {
var a Availability
q := url.Values{}
q.Set("domain", strings.ToLower(strings.TrimSpace(domain)))
_, err := c.Do(ctx, http.MethodGet, "/v1/domains/availability", q, nil, "", &a)
return &a, err
}
// ---------------------------------------------------------------- servers
// Servers lists the servers of the account.
func (c *Client) Servers(ctx context.Context, status string) ([]Server, error) {
q := url.Values{}
if status != "" {
q.Set("status", status)
}
var all []Server
err := c.ListAll(ctx, "/v1/servers", q, func(raw json.RawMessage) error {
var page []Server
if err := json.Unmarshal(raw, &page); err != nil {
return err
}
all = append(all, page...)
return nil
})
return all, err
}
// Server returns one server.
func (c *Client) Server(ctx context.Context, id int64) (*Server, error) {
var s Server
_, err := c.Do(ctx, http.MethodGet, "/v1/servers/"+strconv.FormatInt(id, 10), nil, nil, "", &s)
return &s, err
}
// Purchase buys a plan of the catalog with credit. The Idempotency-Key is required.
func (c *Client) Purchase(ctx context.Context, body map[string]interface{}, idemKey string) (*Purchase, error) {
var p Purchase
res, err := c.Do(ctx, http.MethodPost, "/v1/services/purchase", nil, body, idemKey, &p)
if err == nil && res.Simulated {
p.Simulated = true
}
return &p, err
}
// Power starts, stops or restarts a server. action is "start", "stop" or "restart".
func (c *Client) Power(ctx context.Context, id int64, action string) (*PowerAction, error) {
var a PowerAction
res, err := c.Do(ctx, http.MethodPost, "/v1/servers/"+strconv.FormatInt(id, 10)+"/"+action, nil, nil, NewIdempotencyKey(), &a)
if err == nil && res.Simulated {
a.Simulated = true
}
return &a, err
}
// Timezone returns the saved time zone of a server ("" when none was chosen) and the ones available.
func (c *Client) Timezone(ctx context.Context, id int64) (string, []string, error) {
var out struct {
Timezone *string `json:"timezone"`
Available []string `json:"available"`
}
_, err := c.Do(ctx, http.MethodGet, "/v1/servers/"+strconv.FormatInt(id, 10)+"/timezone", nil, nil, "", &out)
tz := ""
if out.Timezone != nil {
tz = *out.Timezone
}
return tz, out.Available, err
}
// SetTimezone changes the time zone of a server.
func (c *Client) SetTimezone(ctx context.Context, id int64, tz string) (*PowerAction, error) {
var a PowerAction
res, err := c.Do(ctx, http.MethodPut, "/v1/servers/"+strconv.FormatInt(id, 10)+"/timezone", nil, map[string]string{"timezone": tz}, "", &a)
if err == nil && res.Simulated {
a.Simulated = true
}
return &a, err
}
// ReverseDNS returns the name of each IP of a server ("" while it is the default one).
func (c *Client) ReverseDNS(ctx context.Context, id int64) (map[string]string, error) {
var out struct {
Records []struct {
IP string `json:"ip"`
Hostname *string `json:"hostname"`
} `json:"records"`
}
_, err := c.Do(ctx, http.MethodGet, "/v1/servers/"+strconv.FormatInt(id, 10)+"/reverse-dns", nil, nil, "", &out)
m := map[string]string{}
for _, r := range out.Records {
h := ""
if r.Hostname != nil {
h = *r.Hostname
}
m[r.IP] = h
}
return m, err
}
// SetReverseDNS changes the name of the given IPs. An empty hostname clears it.
func (c *Client) SetReverseDNS(ctx context.Context, id int64, records map[string]string) error {
type rec struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
}
body := struct {
Records []rec `json:"records"`
}{}
for ip, h := range records {
body.Records = append(body.Records, rec{IP: ip, Hostname: h})
}
_, err := c.Do(ctx, http.MethodPut, "/v1/servers/"+strconv.FormatInt(id, 10)+"/reverse-dns", nil, body, "", nil)
return err
}
// ---------------------------------------------------------------- domains
// Domain returns one domain of the account, by name.
func (c *Client) Domain(ctx context.Context, name string) (*Domain, error) {
var d Domain
_, err := c.Do(ctx, http.MethodGet, "/v1/domains/"+esc(name), nil, nil, "", &d)
return &d, err
}
// Register registers a domain with credit. The Idempotency-Key is required.
func (c *Client) Register(ctx context.Context, body map[string]interface{}, idemKey string) (*Registration, error) {
var r Registration
res, err := c.Do(ctx, http.MethodPost, "/v1/domains/register", nil, body, idemKey, &r)
if err == nil && res.Simulated {
r.Simulated = true
}
return &r, err
}
// Nameservers returns the nameservers of a domain.
func (c *Client) Nameservers(ctx context.Context, name string) ([]string, error) {
var out struct {
Nameservers []string `json:"nameservers"`
}
_, err := c.Do(ctx, http.MethodGet, "/v1/domains/"+esc(name)+"/nameservers", nil, nil, "", &out)
return out.Nameservers, err
}
// SetNameservers changes the nameservers of a domain (2 to 5).
func (c *Client) SetNameservers(ctx context.Context, name string, ns []string) error {
_, err := c.Do(ctx, http.MethodPut, "/v1/domains/"+esc(name)+"/nameservers", nil, map[string][]string{"nameservers": ns}, "", nil)
return err
}
// Lock tells whether the transfer lock is on.
func (c *Client) Lock(ctx context.Context, name string) (bool, error) {
var out struct {
Locked bool `json:"locked"`
}
_, err := c.Do(ctx, http.MethodGet, "/v1/domains/"+esc(name)+"/lock", nil, nil, "", &out)
return out.Locked, err
}
// SetLock turns the transfer lock on or off.
func (c *Client) SetLock(ctx context.Context, name string, locked bool) error {
_, err := c.Do(ctx, http.MethodPut, "/v1/domains/"+esc(name)+"/lock", nil, map[string]bool{"locked": locked}, "", nil)
return err
}
// SetAutoRenew turns the renewal invoices on or off.
func (c *Client) SetAutoRenew(ctx context.Context, name string, on bool) error {
_, err := c.Do(ctx, http.MethodPut, "/v1/domains/"+esc(name)+"/auto-renew", nil, map[string]bool{"auto_renew": on}, "", nil)
return err
}
// ---------------------------------------------------------------- DNS
// DNSRecords lists the records of the zone of a domain.
func (c *Client) DNSRecords(ctx context.Context, domain string) ([]DNSRecord, error) {
var recs []DNSRecord
_, err := c.Do(ctx, http.MethodGet, "/v1/domains/"+esc(domain)+"/dns", nil, nil, "", &recs)
return recs, err
}
// CreateDNSRecord adds a record.
func (c *Client) CreateDNSRecord(ctx context.Context, domain string, in DNSRecordInput) (*DNSRecord, error) {
var r DNSRecord
res, err := c.Do(ctx, http.MethodPost, "/v1/domains/"+esc(domain)+"/dns", nil, in, "", &r)
if err == nil && res.Simulated {
r.Simulated = true
}
return &r, err
}
// UpdateDNSRecord changes a record. The id changes when the name, type, value or priority change.
func (c *Client) UpdateDNSRecord(ctx context.Context, domain, id string, in DNSRecordInput) (*DNSRecord, error) {
var r DNSRecord
res, err := c.Do(ctx, http.MethodPut, "/v1/domains/"+esc(domain)+"/dns/"+url.PathEscape(id), nil, in, "", &r)
if err == nil && res.Simulated {
r.Simulated = true
}
return &r, err
}
// DeleteDNSRecord deletes a record. A record that is already gone is not an error.
func (c *Client) DeleteDNSRecord(ctx context.Context, domain, id string) error {
_, err := c.Do(ctx, http.MethodDelete, "/v1/domains/"+esc(domain)+"/dns/"+url.PathEscape(id), nil, nil, "", nil)
if IsNotFound(err) {
return nil
}
return err
}