|
| 1 | +// Package unifiapi provides the Ubiquiti UniFi API client producer. |
| 2 | +package unifiapi |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "crypto/tls" |
| 7 | + "crypto/x509" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/database64128/ddns-go/internal/httpreq" |
| 14 | + "github.com/database64128/ddns-go/jsoncfg" |
| 15 | + "github.com/database64128/ddns-go/producer" |
| 16 | + "github.com/database64128/ddns-go/producer/internal/poller" |
| 17 | + "github.com/database64128/ddns-go/tslog" |
| 18 | +) |
| 19 | + |
| 20 | +// Source obtains the IPv4 address of a device from the Ubiquiti UniFi API. |
| 21 | +// |
| 22 | +// Source implements [producer.Source]. |
| 23 | +type Source struct { |
| 24 | + client *Client |
| 25 | + siteID string |
| 26 | + deviceID string |
| 27 | +} |
| 28 | + |
| 29 | +// NewSource creates a new [Source]. |
| 30 | +// |
| 31 | +// - If client is nil, [http.DefaultClient] is used. |
| 32 | +// - If baseURL is empty, it defaults to "https://unifi.local". |
| 33 | +func NewSource(client *http.Client, baseURL, apiKey, siteID, deviceID string) (*Source, error) { |
| 34 | + c, err := NewClient(client, baseURL, apiKey) |
| 35 | + if err != nil { |
| 36 | + return nil, fmt.Errorf("failed to create UniFi API client: %w", err) |
| 37 | + } |
| 38 | + |
| 39 | + return &Source{ |
| 40 | + client: c, |
| 41 | + siteID: siteID, |
| 42 | + deviceID: deviceID, |
| 43 | + }, nil |
| 44 | +} |
| 45 | + |
| 46 | +var _ producer.Source = (*Source)(nil) |
| 47 | + |
| 48 | +// Snapshot returns the current IPv4 address of the device. |
| 49 | +// |
| 50 | +// Snapshot implements [producer.Source.Snapshot]. |
| 51 | +func (s *Source) Snapshot(ctx context.Context) (producer.Message, error) { |
| 52 | + addr, err := s.client.GetDeviceIPAddress(ctx, s.siteID, s.deviceID) |
| 53 | + if err != nil { |
| 54 | + return producer.Message{}, fmt.Errorf("failed to get device IP address: %w", err) |
| 55 | + } |
| 56 | + if !addr.Is4() { |
| 57 | + return producer.Message{}, fmt.Errorf("not an IPv4 address: %s", addr) |
| 58 | + } |
| 59 | + return producer.Message{IPv4: addr}, nil |
| 60 | +} |
| 61 | + |
| 62 | +// ProducerConfig contains configuration options for the Ubiquiti UniFi API producer. |
| 63 | +type ProducerConfig struct { |
| 64 | + // BaseURL is the base URL of the UniFi API endpoints. |
| 65 | + // |
| 66 | + // If empty, it defaults to "https://unifi.local". |
| 67 | + BaseURL string `json:"base_url,omitzero"` |
| 68 | + |
| 69 | + // APIKey is the API key for authenticating API requests. |
| 70 | + APIKey string `json:"api_key"` |
| 71 | + |
| 72 | + // SiteID is the site ID. |
| 73 | + SiteID string `json:"site_id"` |
| 74 | + |
| 75 | + // DeviceID is the device ID. |
| 76 | + DeviceID string `json:"device_id"` |
| 77 | + |
| 78 | + // RootCAPaths is a list of paths to PEM-encoded root CA certificates for verifying TLS server certificates. |
| 79 | + // |
| 80 | + // To trust the self-signed certificate, download the certificate and specify its path here. |
| 81 | + // |
| 82 | + // If empty, the system root CAs are used. |
| 83 | + RootCAPaths []string `json:"root_ca_paths,omitzero"` |
| 84 | + |
| 85 | + // ServerName is the server name to use when initializing a TLS connection. |
| 86 | + // |
| 87 | + // If empty, it is inferred from BaseURL. |
| 88 | + ServerName string `json:"server_name,omitzero"` |
| 89 | + |
| 90 | + // PollInterval is the interval between polling the UniFi API for the device IP address. |
| 91 | + // |
| 92 | + // If not positive, it defaults to 5 minutes. |
| 93 | + PollInterval jsoncfg.Duration `json:"poll_interval,omitzero"` |
| 94 | +} |
| 95 | + |
| 96 | +// NewProducer creates a new [producer.Producer] that monitors the IPv4 address of a device from the Ubiquiti UniFi API. |
| 97 | +func (cfg *ProducerConfig) NewProducer(client *http.Client, logger *tslog.Logger) (producer.Producer, error) { |
| 98 | + if client == nil && (len(cfg.RootCAPaths) > 0 || cfg.ServerName != "") { |
| 99 | + var rootCAs *x509.CertPool |
| 100 | + if len(cfg.RootCAPaths) > 0 { |
| 101 | + rootCAs = x509.NewCertPool() |
| 102 | + for _, path := range cfg.RootCAPaths { |
| 103 | + cert, err := os.ReadFile(path) |
| 104 | + if err != nil { |
| 105 | + return nil, fmt.Errorf("failed to read root CA file %q: %w", path, err) |
| 106 | + } |
| 107 | + if !rootCAs.AppendCertsFromPEM(cert) { |
| 108 | + return nil, fmt.Errorf("failed to append root CA from file %q", path) |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + transport := httpreq.DefaultHttpTransportClone() |
| 113 | + transport.TLSClientConfig = &tls.Config{ |
| 114 | + RootCAs: rootCAs, |
| 115 | + ServerName: cfg.ServerName, |
| 116 | + } |
| 117 | + client = &http.Client{ |
| 118 | + Transport: transport, |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + source, err := NewSource(client, cfg.BaseURL, cfg.APIKey, cfg.SiteID, cfg.DeviceID) |
| 123 | + if err != nil { |
| 124 | + return nil, fmt.Errorf("failed to create source: %w", err) |
| 125 | + } |
| 126 | + |
| 127 | + pollInterval := cfg.PollInterval.Value() |
| 128 | + if pollInterval <= 0 { |
| 129 | + pollInterval = 5 * time.Minute |
| 130 | + } |
| 131 | + |
| 132 | + return poller.New(pollInterval, source, logger), nil |
| 133 | +} |
0 commit comments