api

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package api builds AudD API clients for the CLI: it resolves the token, configures the SDK's HTTP transport, heals a login-fetched token that the API rejects, and turns SDK errors into the CLI's error contract.

Index

Constants

View Source
const (
	APIDocsURL        = "https://docs.audd.io/"
	EnterpriseDocsURL = "https://docs.audd.io/enterprise"
)

APIDocsURL and EnterpriseDocsURL are the docs pages that list the API's errors, linked from errors AudD returned.

View Source
const DashboardURL = "https://dashboard.audd.io"

DashboardURL is where people get and manage API tokens.

View Source
const ExitInterrupted = 130

ExitInterrupted is the exit code after Ctrl-C (128 + SIGINT).

View Source
const NoTokenHint = "audd login, or audd config set token <your-api-token> (get one at " + DashboardURL + ")"

NoTokenHint is the fix shown with every no_token error.

View Source
const StandardTimeout = 60 * time.Second

StandardTimeout bounds one standard recognition request.

Variables

View Source
var EnterpriseParams = []string{"skip", "every", "skip_first_seconds", "use_timecode", "accurate_offsets"}

EnterpriseParams are the enterprise passthrough parameters (wire names) accepted in Request.EnterpriseOpts.

View Source
var Providers = []string{"apple_music", "spotify", "deezer", "musicbrainz"}

Providers are the metadata sources --return accepts.

Functions

func Clock

func Clock(sec float64) string

Clock formats seconds as "m:ss", or "h:mm:ss" from an hour on.

func Do

func Do[T any](ctx context.Context, a *app.App, call func(c *audd.Client) (T, error)) (T, error)

Do runs call with a client from a.APIClient. When the API rejects the token as invalid, and that token was fetched by `audd login`, Do fetches the current token from the account, stores it, and retries once (the API rejects a bad token before doing any metered work). Tokens given with --token, AUDD_API_TOKEN, or `audd config` are never replaced. Errors come back as *output.Error (see MapError).

func DoOnce

func DoOnce[T any](ctx context.Context, a *app.App, call func(c *audd.Client) (T, error)) (T, error)

DoOnce is Do with a client from a.APIClientOnce, which never retries a request on its own: for calls that may be billed or change the account even when the response is lost.

func Essential

func Essential(v app.ResultView) string

Essential is the one-line form of a result: "Artist — Title".

func HTTPClient

func HTTPClient(a *app.App) *http.Client

HTTPClient returns the HTTP client every AudD call uses: proxies from HTTPS_PROXY/NO_PROXY, the CLI user agent, and with --debug a log of each request on stderr (tokens redacted). It has no overall timeout; callers bound each call with a context or a per-call timeout.

func HealLogin

func HealLogin(ctx context.Context, a *app.App, c *audd.Client, err error) (bool, error)

HealLogin is the token healing Do performs, for long-running loops that hold their own client (the stream recorder): when err is the API rejecting a token fetched by audd login, it fetches the account's current token, stores it, and sets it on c. It reports whether c now has a different token to retry with. Tokens from --token, AUDD_API_TOKEN, or audd config are never replaced. It does not restart the background recorder.

func IsAuthRejected

func IsAuthRejected(err error) bool

IsAuthRejected reports whether the API rejected the token itself (invalid, missing, or disabled), as opposed to quota or plan limits.

func MapError

func MapError(err error, src config.TokenSource) error

MapError converts an SDK error into an *output.Error with the right exit code. src is where the token came from (for the hint on auth errors). *output.Error values pass through unchanged.

func MatchesJSON

func MatchesJSON(ms []audd.EnterpriseMatch) json.RawMessage

MatchesJSON renders enterprise matches with every API field plus the computed start_seconds and end_seconds (position in the file).

func NewClientFactory

func NewClientFactory(a *app.App, opts ...audd.Option) func() (*audd.Client, error)

NewClientFactory returns the App.APIClient factory. Each call resolves the token (--token > AUDD_API_TOKEN > audd config > audd login) and returns a client with the given extra options; with no token it returns a no_token error (exit 3).

func NormalizeReturn

func NormalizeReturn(s string) (string, error)

NormalizeReturn validates and canonicalizes a --return list ("spotify, apple_music" → "apple_music,spotify").

func PreUpload

func PreUpload(err error) bool

PreUpload reports a connection error that happened before any request bytes were sent (DNS, TCP or TLS dial, or a dial to the HTTPS_PROXY that failed), so nothing reached AudD.

func Recognize

func Recognize(ctx context.Context, a *app.App, in media.Input, r Request) (json.RawMessage, error)

Recognize sends one input and returns the result in its cacheable form: the standard endpoint's result object ("null" for no match), or the enterprise matches as an array with start_seconds/end_seconds added.

func RecognizeWithCause

func RecognizeWithCause(ctx context.Context, a *app.App, in media.Input, r Request) (json.RawMessage, error)

RecognizeWithCause is Recognize for callers that need the SDK's own error as well as the CLI's: on failure it returns errors.Join(mapped, sdkErr), so errors.As finds the *output.Error first and the SDK error (which tells a connection that never opened from one that dropped after the upload) is still reachable.

func Redact

func Redact(s string) string

Redact hides token values in URLs and messages.

func TokenSource

func TokenSource(a *app.App) config.TokenSource

TokenSource reports where the API token in use comes from.

func Transport

func Transport() http.RoundTripper

Transport is the HTTP transport for AudD calls made outside the SDK (the stream recent-results endpoint and callback relays): proxies, the CLI user agent, and the test base URLs, read when each request is sent.

func UserAgent

func UserAgent() string

UserAgent identifies the CLI to AudD; the SDK's own agent follows it.

func View

func View(raw json.RawMessage, cached bool) (v app.ResultView, ok bool)

View flattens a standard result (as returned by Recognize) for display. ok is false for no match.

Types

type Match

type Match struct {
	Artist       string   `json:"artist"`
	Title        string   `json:"title"`
	Album        string   `json:"album"`
	Label        string   `json:"label"`
	ReleaseDate  string   `json:"release_date"`
	ISRC         string   `json:"isrc"`
	UPC          string   `json:"upc"`
	SongLink     string   `json:"song_link"`
	Timecode     string   `json:"timecode"`
	Score        int      `json:"score"`
	StartOffset  int      `json:"start_offset"`
	EndOffset    int      `json:"end_offset"`
	StartSeconds *float64 `json:"start_seconds"`
	EndSeconds   *float64 `json:"end_seconds"`
}

Match is an enterprise match read back from its JSON form.

func ParseMatches

func ParseMatches(raw json.RawMessage) []Match

ParseMatches reads matches from MatchesJSON output, leniently.

type Request

type Request struct {
	Enterprise     bool
	Return         string            // standard only; normalized provider list
	Limit          *int              // enterprise chunks; nil = no limit
	EnterpriseOpts map[string]string // EnterpriseParams, wire names and values
	// Offset is added to enterprise match positions: the start of a clip
	// (--at) within the original file, in seconds.
	Offset float64
}

Request describes one recognition of one input.

func (Request) CacheParams

func (r Request) CacheParams() map[string]string

CacheParams are the parameters that make a cached result reusable.

func (Request) Endpoint

func (r Request) Endpoint() string

Endpoint is the cache endpoint name.

func (Request) EnterpriseOptions

func (r Request) EnterpriseOptions() (*audd.EnterpriseOptions, error)

EnterpriseOptions builds the SDK options, validating the passthrough values.

type Track

type Track struct {
	Artist       string  `json:"artist"`
	Title        string  `json:"title"`
	Album        string  `json:"album,omitempty"`
	Label        string  `json:"label,omitempty"`
	ReleaseDate  string  `json:"release_date,omitempty"`
	ISRC         string  `json:"isrc,omitempty"`
	UPC          string  `json:"upc,omitempty"`
	SongLink     string  `json:"song_link,omitempty"`
	Score        int     `json:"score,omitempty"`
	Start        string  `json:"start"` // "h:mm:ss" or "m:ss"
	End          string  `json:"end"`
	StartSeconds float64 `json:"start_seconds"`
	EndSeconds   float64 `json:"end_seconds"`
	Matches      int     `json:"matches"`
	// contains filtered or unexported fields
}

Track is a song that plays across one or more enterprise chunks.

func Tracklist

func Tracklist(matches []Match, skip int) []Track

Tracklist merges enterprise matches into tracks. Matches of the same artist and title in consecutive chunks become one track, starting at the first match's start and ending at the last match's end. One chunk with no match of that song may sit in between (a quiet passage or a missed chunk); a chunk with a different song ends the track. Several songs matched in the same chunk are tracked side by side. skip is the enterprise skip parameter (chunks skipped between scanned ones), so chunks that were never scanned are not counted as gaps.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL