package client import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "os" "strings" "time" ) // Version is reported in the User-Agent so streamd's audit log can tell // agent builds apart. const Version = "2.0" type Client struct { BaseURL string Token string HTTP *http.Client UserAgent string // AgentID is sent as X-Agent-ID so streamd can attribute audit rows to // this agent rather than just to the API key it shares. AgentID string } // ErrUnauthorized is returned when streamd rejects this agent's credential. // It is checked by the worker so a bad key does not burn job attempts. var ErrUnauthorized = errors.New("unauthorized") func New(baseURL, token string) *Client { return &Client{ BaseURL: strings.TrimRight(baseURL, "/"), Token: token, HTTP: &http.Client{Timeout: 30 * time.Second}, UserAgent: "drm-agent/" + Version, } } // Stream is one row of GET /api/streams. // // Note there is no Key field. streamd redacts credentials from this response, // and the agent only ever writes keys, never reads them. Decisions that used // to be made here by inspecting the key are now made server-side and arrive // as NeedsCapture / KeyValid / DRMRequired. type Stream struct { ID int64 `json:"id"` Name string `json:"name"` Title string `json:"title"` App string `json:"app"` Channel string `json:"channel"` Tags string `json:"tags"` MPD string `json:"mpd"` Enabled bool `json:"enabled"` Health string `json:"health"` LastError string `json:"last_error"` PlaylistAgeS float64 `json:"playlist_age_s"` ClaimedBy string `json:"claimed_by"` // Credential state, without the credentials. HasKey bool `json:"has_key"` KeyValid bool `json:"key_valid"` DRMRequired bool `json:"drm_required"` // NeedsCapture is streamd's verdict on whether to refresh credentials. // This is the field the poller acts on. NeedsCapture bool `json:"needs_capture"` OnDemand bool `json:"on_demand"` Public bool `json:"public"` Outputs []Output `json:"outputs"` } // Output is one configured publish format, shown by `agent status`. type Output struct { ID string `json:"id"` Label string `json:"label"` Format string `json:"format"` Enabled bool `json:"enabled"` } // EnabledOutputs is a short label list for display, e.g. "HLS, DASH". func (s Stream) EnabledOutputs() string { var on []string for _, o := range s.Outputs { if o.Enabled { on = append(on, o.Label) } } return strings.Join(on, ",") } type Credentials struct { MPD string `json:"mpd"` Key string `json:"key"` PSSH string `json:"pssh,omitempty"` Auth string `json:"auth,omitempty"` PID string `json:"pid,omitempty"` } // Identity is the answer from GET /api/me. type Identity struct { Name string `json:"name"` Role string `json:"role"` ActorKind string `json:"actor_kind"` AgentID string `json:"agent_id,omitempty"` } func (c *Client) Health() error { _, err := c.do(http.MethodGet, "/api/health", nil) return err } // Me verifies this agent's credential and reports the role it was granted. // Called at startup so a missing, wrong or revoked key fails loudly instead // of silently failing every poll. func (c *Client) Me() (Identity, error) { body, err := c.do(http.MethodGet, "/api/me", nil) if err != nil { return Identity{}, err } var id Identity if err := json.Unmarshal(body, &id); err != nil { return Identity{}, err } return id, nil } func (c *Client) ListStreams() ([]Stream, error) { body, err := c.do(http.MethodGet, "/api/streams", nil) if err != nil { return nil, err } var wrap struct { Streams []Stream `json:"streams"` } if err := json.Unmarshal(body, &wrap); err != nil { return nil, err } return wrap.Streams, nil } func (c *Client) Claim(id int64, agentID string, ttlSec int) error { payload := map[string]any{"agent_id": agentID, "ttl_sec": ttlSec} _, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/claim", id), payload) return err } func (c *Client) ReleaseClaim(id int64, agentID string) error { payload := map[string]any{"agent_id": agentID} _, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/claim/release", id), payload) return err } func (c *Client) PostCredentials(id int64, cred Credentials) error { _, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/credentials", id), cred) return err } // Capture event kinds reported back to streamd, so a failing phone capture // shows up on the stream's timeline in the dashboard instead of only in this // agent's console. const ( EventCaptureStarted = "capture_started" EventCaptureOK = "capture_ok" EventCaptureFailed = "capture_failed" ) // PostEvent records an agent-authored event against a stream. Failures are // the caller's to ignore: losing a timeline entry must never fail a capture. func (c *Client) PostEvent(streamID int64, kind, message string, detail map[string]any) error { payload := map[string]any{"kind": kind, "message": message} if len(detail) > 0 { payload["detail"] = detail } _, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/events", streamID), payload) return err } // ModuleInfo is one modules// entry from GET /api/modules. type ModuleInfo struct { Name string `json:"name"` HasYAML bool `json:"has_yaml"` YAMLSHA256 string `json:"yaml_sha256,omitempty"` HasPackage bool `json:"has_package"` PackageSHA256 string `json:"package_sha256,omitempty"` Arches []string `json:"arches,omitempty"` SizeBytes int64 `json:"size_bytes,omitempty"` } func (c *Client) ListModules() ([]ModuleInfo, error) { body, err := c.do(http.MethodGet, "/api/modules", nil) if err != nil { return nil, err } var wrap struct { Modules []ModuleInfo `json:"modules"` } if err := json.Unmarshal(body, &wrap); err != nil { return nil, err } return wrap.Modules, nil } // GetModuleYAML downloads raw module.yaml bytes for name. func (c *Client) GetModuleYAML(name string) ([]byte, error) { req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil) if err != nil { return nil, err } c.setHeaders(req) resp, err := c.HTTP.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) if resp.StatusCode >= 300 { return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body) } return body, nil } // DownloadModulePackage writes the module zip to destPath. func (c *Client) DownloadModulePackage(name, destPath string) error { req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil) if err != nil { return err } c.setHeaders(req) resp, err := c.HTTP.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode >= 300 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body) } tmp := destPath + ".partial" f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { return err } _, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20)) closeErr := f.Close() if copyErr != nil { _ = os.Remove(tmp) return copyErr } if closeErr != nil { _ = os.Remove(tmp) return closeErr } _ = os.Remove(destPath) return os.Rename(tmp, destPath) } func (c *Client) setHeaders(req *http.Request) { ua := c.UserAgent if ua == "" { ua = "streamd-agent/" + Version } req.Header.Set("User-Agent", ua) if c.Token != "" { req.Header.Set("Authorization", "Bearer "+c.Token) } if c.AgentID != "" { req.Header.Set("X-Agent-ID", c.AgentID) } } func (c *Client) do(method, path string, payload any) ([]byte, error) { var rdr io.Reader if payload != nil { b, err := json.Marshal(payload) if err != nil { return nil, err } rdr = bytes.NewReader(b) } req, err := http.NewRequest(method, c.BaseURL+path, rdr) if err != nil { return nil, err } if payload != nil { req.Header.Set("Content-Type", "application/json") } c.setHeaders(req) resp, err := c.HTTP.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) if resp.StatusCode >= 300 { return nil, c.statusError(method, path, resp, body) } return body, nil } // statusError turns an HTTP failure into something actionable. A 401 or 403 // used to surface as a bare status line, which left an operator guessing why // a working agent had gone quiet. func (c *Client) statusError(method, path string, resp *http.Response, body []byte) error { msg := strings.TrimSpace(string(body)) if parsed := errorField(body); parsed != "" { msg = parsed } switch resp.StatusCode { case http.StatusUnauthorized: hint := "streamd rejected this agent's credential" if c.Token == "" { hint = "streamd requires a credential and none is configured" } return fmt.Errorf("%w: %s %s — %s. Set `token:` (or `api_key:`) in apps/agent/agent.yaml, "+ "or STREAMD_TOKEN, to an API key created in the streamd dashboard under "+ "Settings -> API keys (role: operator). Server said: %s", ErrUnauthorized, method, path, hint, msg) case http.StatusForbidden: return fmt.Errorf("%w: %s %s — this agent's API key lacks the needed role; "+ "it must be at least `operator`. Server said: %s", ErrUnauthorized, method, path, msg) case http.StatusTooManyRequests: return fmt.Errorf("%s %s: rate limited by streamd (retry-after %s) — %s", method, path, resp.Header.Get("Retry-After"), msg) } return fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, msg) } func errorField(body []byte) string { var wrap struct { Error string `json:"error"` } if json.Unmarshal(body, &wrap) == nil { return strings.TrimSpace(wrap.Error) } return "" }