### Example usage Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/cache.md Example usage of InitCache, Set for session storage, and Get with sentinel-miss handling. The error from InitCache is unreachable per comment in main.go. ```go cfg := cache.Config{DataDir: "./data"} store, err := cache.InitCache(ctx, cfg) if err != nil { /* unreachable per comment in main.go */ } // session store store.Set(ctx, "session:", sessionData, 30 * 24 * time.Hour) // cache read with sentinel-miss handling var v types.SessionData if err := store.Get(ctx, key, &v); err != nil { if err == cache.ErrKeyNotFound { /* normal miss */ } else { /* real failure */ } } ``` -------------------------------- ### Login and protected call example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Example of login and protected call flow. Shows POST /api/auth/login with credentials and GET /api/auth/userinfo with Bearer token, including expected responses. ```go // POST /api/auth/login // Body: {"username": "admin", "password": "password123"} // -> 200 sets cookie; body carries access_token for non-cookie clients // GET /api/auth/userinfo // Authorization: Bearer // -> 200 {"id":1,"username":"admin","email":"..."} ``` -------------------------------- ### Database usage example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Example Go code showing database initialization, finding a service by instance ID, and creating/updating a user. ```go ctx := context.Background() db, err := database.InitDBWithConfig(&cfg.Database) defer db.Close() // find one service by exact instance id svc, err := db.FindServiceBy(ctx, types.FindServiceParams{InstanceID: "sonarr-1"}) // create a user and set its password user := &types.User{Username: "admin", Email: "admin@example.com", PasswordHash: hash} db.CreateUser(ctx, user) db.UpdateUserPassword(ctx, user.ID, newHash) ``` -------------------------------- ### Example: creating BuiltinAuthHandler Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Example usage from server.go that creates a handler with the server's database and cache. ```go builtinAuthHandler := handlers.NewBuiltinAuthHandler(s.db, s.cache) ``` -------------------------------- ### Run dashbrr with Docker Compose Source: https://github.com/autobrr/dashbrr/blob/develop/README.md Start dashbrr with Docker Compose. The first command runs the basic setup, the second enables service discovery features. Both use PostgreSQL by default; to use SQLite, uncomment the SQLite lines and comment out the PostgreSQL ones in the chosen compose file. ```bash docker compose -f docker-compose/docker-compose.yml up -d ``` ```bash docker compose -f docker-compose/docker-compose.discovery.yml up -d ``` -------------------------------- ### Discovery manager usage example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/discovery.md Example usage of the discovery package: creates a manager, discovers all services, defers Close, and iterates over services, skipping any that fail validation. InstanceID is like "radarr-1" and APIKey is resolved from environment variables. ```go mgr, err := discovery.NewManager() services, err := mgr.DiscoverAll(ctx) defer mgr.Close() for _, svc := range services { if err := discovery.ValidateService(svc); err != nil { continue } // svc.InstanceID like "radarr-1"; svc.APIKey resolved from env } ``` -------------------------------- ### API client usage example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/web-frontend.md Example usage of the API client for fetching settings, posting a service config, updating UI preferences, and deleting a queue item. Demonstrates the auth-required pattern with automatic /api prefix and JSON handling. ```ts const configs = await api.get>("/settings"); const config: ServiceConfig = { url, displayName, apiKey }; await api.post(`/settings/${instanceId}`, config); await api.put(`/ui/preferences/collapse`, { key: "service-card", collapsed: true }); await api.delete(`/arr/queue/${queueId}?instanceId=${instanceId}&removeFromClient=true`); ``` -------------------------------- ### dashbrr CLI example commands Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/cli.md Example commands for the dashbrr CLI: serve with config and database file paths, create a user, add a Sonarr service with dry-run, discover config with Kubernetes and auto-confirm, check health with services and JSON output, and check version against GitHub. ```bash dashbrr serve --config=/etc/dashbrr/config.toml --db-file=/var/lib/dashbrr/dashbrr.db dashbrr user create admin 'password123' admin@example.com dashbrr service sonarr add http://localhost:8989 --dry-run dashbrr config discover --k8s --yes dashbrr health --services --json dashbrr version --check-github ``` -------------------------------- ### Creating a Server with NewServer Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/server.md Example usage from cmd/dashbrr/main.go that creates a new Server instance with the configuration, database, and cache store. ```go srv := api.NewServer(cfg, db, store) ``` -------------------------------- ### Example: Create service and check health Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/models-registry.md Example of creating a service registry and checking health for a service type. CreateService returns nil for unknown types, so the nil check is required before calling CheckHealth. ```go registry := models.NewServiceRegistry() checker := registry.CreateService("radarr") // RadarrService instance or nil if checker == nil { return // unknown type } health, status := checker.CheckHealth(ctx, url, apiKey) ``` -------------------------------- ### GET /api/auth/callback and GET /api/auth/oidc/callback Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Handles the OIDC callback, verifies the nonce, creates a session, and redirects to the frontend. ```APIDOC ## GET /api/auth/callback and GET /api/auth/oidc/callback ### Description Handles the OIDC callback after the user authenticates with the provider. Accepts `code` and `state` query parameters. Verifies the nonce from the ID token, stores a session (`oidc:session:`) with a 30-day TTL, sets a cookie, and redirects (307) to the stored `frontendUrl`. ### Method GET ### Endpoint /api/auth/callback and /api/auth/oidc/callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code from the provider. - **state** (string) - Required - The state parameter for CSRF protection. ### Response #### Success Response (307) Redirects to the stored `frontendUrl`. #### Failure Redirects - `/login?error=no_code` - Missing code. - `/login?error=timeout` - Operation timed out. - `/login?error=oidc_discovery_failed` - OIDC discovery failed. - `/login?error=invalid_state` - Invalid state. - `/login?error=exchange_failed` - Token exchange failed. - `/login?error=no_id_token` - No ID token. - `/login?error=invalid_nonce` - Invalid nonce. - `/login?error=session_failed` - Session creation failed. ``` -------------------------------- ### Handler creation example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/server.md Creates a new Server and obtains its handler. The first call builds the poller; subsequent calls reuse the existing poller. Use for custom integration where routes are not wired. ```go s := api.NewServer(cfg, db, store) handler := s.Handler() // builds poller; any number of calls after the first reuse s.poller ``` -------------------------------- ### Graceful shutdown example Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/server.md Calls Shutdown with a background context and logs an error and exits if shutdown fails. Use for graceful server termination. ```go if err := srv.Shutdown(context.Background()); err != nil { log.Error().Err(err).Msg("got error during graceful http shutdown") os.Exit(1) } ``` -------------------------------- ### GET /api/settings Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/handlers.md Retrieves all service configurations with sanitized API keys. Cached for 5 minutes. ```APIDOC ## GET /api/settings ### Description Retrieves all service configurations, with API keys sanitized (empty string). Results are cached for 5 minutes. Logs are throttled to 30 seconds. ### Method GET ### Endpoint /api/settings ### Response #### Success Response (200) - Returns a map of instance ID to sanitized service configuration. #### Response Example { "instanceId": { "apiKey": "", "url": "http://example.com" } } ``` -------------------------------- ### Set up dashbrr systemd service Source: https://github.com/autobrr/dashbrr/blob/develop/README.md Create and enable a systemd service for dashbrr. The service file uses a template unit with %i as the user/group and config path. After creating the file, enable and start the service for the current user. ```bash sudo nano /etc/systemd/system/dashbrr@.service ``` ```systemd [Unit] Description=dashbrr service for %i After=syslog.target network-online.target [Service] Type=simple User=%i Group=%i ExecStart=/usr/local/bin/dashbrr serve --config=/home/%i/.config/dashbrr/config.toml [Install] WantedBy=multi-user.target ``` ```bash sudo systemctl enable -q --now dashbrr@$USER ``` -------------------------------- ### Creating AuthHandler with NewAuthHandler Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Example usage from internal/api/server.go. It constructs an AuthConfig with issuer, client ID, client secret, and redirect URL, then creates a new AuthHandler with the cache store. ```go authConfig := &types.AuthConfig{ Issuer: oidc.Issuer, ClientID: oidc.ClientID, ClientSecret: oidc.ClientSecret, RedirectURL: redirectURL, } oidcAuthHandler = handlers.NewAuthHandler(authConfig, s.cache) ``` -------------------------------- ### Dashbrr user management commands Source: https://github.com/autobrr/dashbrr/blob/develop/docs/commands.md Shows the user management commands: creating a user with optional email and changing a user's password. Includes example invocations. ```bash # Create a new user dashbrr user create [email] Example: dashbrr user create admin password123 Example: dashbrr user create admin password123 admin@example.com # Change user password dashbrr user change-password Example: dashbrr user change-password admin newpassword123 ``` -------------------------------- ### YAML service configuration with environment variable API keys Source: https://github.com/autobrr/dashbrr/blob/develop/docs/config_management.md Example YAML configuration for defining services with their URLs, API keys (using environment variable references), and optional display names. The `name` field is optional, as shown for the Radarr service. ```yaml services: radarr: - url: "http://radarr:7878" apikey: "${RADARR_API_KEY}" name: "Movies" # Optional sonarr: - url: "http://sonarr:8989" apikey: "${SONARR_API_KEY}" name: "TV Shows" prowlarr: - url: "http://prowlarr:9696" apikey: "${PROWLARR_API_KEY}" ``` -------------------------------- ### DB Lifecycle Methods Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Methods to manage the database connection lifecycle: get the file path, open the database, and close it. ```APIDOC ## DB Lifecycle Methods ### Path ```go func (db *DB) Path() string ``` Returns the SQLite file path. ### Open ```go func (db *DB) Open() error ``` Opens the database connection. ### Close ```go func (db *DB) Close() error ``` Closes the database connection (calls `db.DB.Close()`). ``` -------------------------------- ### GET /api/v3/queue Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/services-arr.md Fetches the first page of the queue for a given arr application. ```APIDOC ## [GET] /api/v3/queue ### Description Fetches the first page of the queue for a given arr application. ### Method GET ### Endpoint /api/v3/queue ### Parameters #### Query Parameters - **url** (string) - Required - The base URL of the arr application. - **apiKey** (string) - Required - The API key for authentication. ### Response #### Success Response (200) - **totalRecords** (integer) - Total number of queue items. - **records** (array) - List of queue items on the first page. #### Response Example ```json { "totalRecords": 100, "records": [] } ``` #### Error Response - **ErrArr** - Contains operation "get_queue" and HTTP status code. ``` -------------------------------- ### GET /api/auth/oidc/callback Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Handles the OIDC callback, exchanges the code for tokens, and establishes a session. ```APIDOC ## [GET] /api/auth/oidc/callback ### Description Handles the OIDC callback after the user authenticates with the provider. Validates the state, exchanges the authorization code for tokens, verifies the nonce, creates a session, and redirects to the stored frontend URL. ### Method GET ### Endpoint /api/auth/oidc/callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code returned by the OIDC provider. - **state** (string) - Required - The state value that was sent in the login request. ### Response #### Success Response (307) Redirect to the stored `frontendUrl`. #### Error Responses Redirects to `/login?error=...` or `/login?error=...` with one of the following error codes: `no_code`, `timeout`, `oidc_discovery_failed`, `invalid_state`, `exchange_failed`, `no_id_token`, `invalid_nonce`, `session_failed`. ``` -------------------------------- ### GET /api/auth/config Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Returns the authentication configuration, including available methods and default method. ```APIDOC ## GET /api/auth/config ### Description Reports available authentication methods and configuration. ### Method GET ### Endpoint /api/auth/config ### Response #### Success Response (200) - **methods** (object) - Available auth methods. - **builtin** (boolean) - Whether built-in auth is available. - **oidc** (boolean) - Whether OIDC is configured. - **default** (string) - Default auth method ("builtin" or "oidc"). - **bypass** (boolean) - Whether auth bypass is enabled. #### Response Example { "methods": { "builtin": true, "oidc": false }, "default": "builtin", "bypass": false } ``` -------------------------------- ### Password validation error handling Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Error handling example for password policy validation. Returns 400 Bad Request with error message when password validation fails. ```go // error handling: password policy failure surfaces as a 400 var req types.RegisterRequest if err := utils.ValidatePassword(req.Password); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } ``` -------------------------------- ### Dashbrr TOML configuration file Source: https://github.com/autobrr/dashbrr/blob/develop/README.md Default configuration file for Dashbrr, located at ./config.toml. Sets the server listen address, SQLite database path, and log level. PostgreSQL and OIDC settings are provided as commented examples. ```toml [server] listen_addr = ":8080" # Optional: if UI is served from a different origin than the API # cors_origins = ["http://localhost:3000", "https://dash.example.com"] # cors_allow_credentials = true [database] type = "sqlite" path = "./data/dashbrr.db" # PostgreSQL can use a standard connection URI instead: # type = "postgres" # dsn = "postgres://dashbrr:password@postgres:5432/dashbrr?sslmode=require" [log] # trace, debug, info, warn, error, fatal, panic level = "info" # Optional: OpenID Connect. You can also set these with DASHBRR__OIDC_* variables. # [auth.oidc] # issuer = "https://your-provider.com" # client_id = "your-client-id" # client_secret = "your-client-secret" # redirect_url = "http://localhost:3000/api/auth/oidc/callback" ``` -------------------------------- ### ServeCommand and startServer functions Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/cli.md Defines the serve command and the startServer function. The serve command supports flags --config, --listen-addr, and --db-file with the specified defaults. startServer loads config, initializes the database, cache, and API server, then waits for signals or server errors before shutting down. ```go func ServeCommand() *cobra.Command // Flags: --config (default "config.toml"), --listen-addr (default ":8080"), --db-file (default "") func startServer(configPath string, listenAddr string, origDBPath string) error ``` -------------------------------- ### Shared Arr status and update functions Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/services-arr.md Shared implementations for Arr services. GetArrSystemStatusWithVersion calls GET /api//system/status and caches the version for 1 hour with key version:; non-200 returns ErrArr{HttpCode}. CheckArrForUpdatesWithVersion calls GET /api//update and returns true when any entry has !Installed && Installable. GetArrSystemStatus defaults apiVersion to "v3". ```go func GetArrSystemStatusWithVersion(ctx context.Context, service, apiVersion, url, apiKey string, getVersionFromCache func(context.Context, string) string, cacheVersion func(context.Context, string, string, time.Duration) error, ) (string, error) func GetArrSystemStatus(ctx context.Context, service, url, apiKey string, getVersionFromCache func(context.Context, string) string, cacheVersion func(context.Context, string, string, time.Duration) error, ) (string, error) // apiVersion "v3" func CheckArrForUpdatesWithVersion(ctx context.Context, service, apiVersion, url, apiKey string) (bool, error) func CheckArrForUpdates(ctx context.Context, service, url, apiKey string) (bool, error) func ExtractMessageField(body []byte) string ``` -------------------------------- ### CheckArrForUpdates Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/services-arr.md Checks for available updates on an *arr service. Returns true when any update entry has `!Installed && Installable`. ```APIDOC ## CheckArrForUpdates ### Description Checks for available updates on an *arr service. Returns true when any update entry has `!Installed && Installable`. ### Method `CheckArrForUpdates(ctx context.Context, service, url, apiKey string) (bool, error)` ### Parameters - **ctx** (context.Context) - Required - Context. - **service** (string) - Required - Service name. - **url** (string) - Required - Base URL. - **apiKey** (string) - Required - API key. ### Endpoint `GET /api/v3/update` ### Response Returns a boolean indicating whether updates are available. ``` -------------------------------- ### CheckArrForUpdatesWithVersion Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/services-arr.md Checks for available updates on an *arr service. Returns true when any update entry has `!Installed && Installable`. ```APIDOC ## CheckArrForUpdatesWithVersion ### Description Checks for available updates on an *arr service. Returns true when any update entry has `!Installed && Installable`. ### Method `CheckArrForUpdatesWithVersion(ctx context.Context, service, apiVersion, url, apiKey string) (bool, error)` ### Parameters - **ctx** (context.Context) - Required - Context. - **service** (string) - Required - Service name. - **apiVersion** (string) - Required - API version. - **url** (string) - Required - Base URL. - **apiKey** (string) - Required - API key. ### Endpoint `GET /api//update` ### Response Returns a boolean indicating whether updates are available. ``` -------------------------------- ### Dashbrr serve with custom config and database paths Source: https://github.com/autobrr/dashbrr/blob/develop/docs/commands.md Demonstrates using the --config flag to specify a custom config file location and how the database path is derived from it. Also shows overriding the database location with --db-file. ```bash # Using config in /etc/dashbrr dashbrr serve --config=/etc/dashbrr/config.toml # Database will be created at /etc/dashbrr/data/dashbrr.db # Override default database location dashbrr serve --config=/etc/dashbrr/config.toml --db-file=/var/lib/dashbrr/dashbrr.db ``` -------------------------------- ### GET /api/auth/verify Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Verifies the current session token. ```APIDOC ## [GET] /api/auth/verify ### Description Verifies the current session token. ### Method GET ### Endpoint /api/auth/verify ### Response #### Success Response (200) - **message** (string) - "Token is valid". - **user_id** (integer) - The user's ID. #### Response Example { "message": "Token is valid", "user_id": 1 } #### Error Responses - **401** - Session not found or expired. - **401** - Session expired. ``` -------------------------------- ### GET /api/auth/oidc/verify Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Verifies the current session token. ```APIDOC ## [GET] /api/auth/oidc/verify ### Description Verifies the current session token by checking the stored session in Redis. ### Method GET ### Endpoint /api/auth/oidc/verify ### Response #### Success Response (200) - **message** (string) - `"Token is valid"` #### Error Responses - **401** - `{ "error": "No session found" }` or `{ "error": "Session expired" }` - **504** - `{ "error": "Operation timed out" }` ``` -------------------------------- ### Dashbrr serve startup flags Source: https://github.com/autobrr/dashbrr/blob/develop/docs/commands.md Shows the startup flags for the Dashbrr serve command. By default, the config file is loaded from ./config.toml, the database is created at /data/dashbrr.db, and the server listens on port 8080. ```bash # Start Dashbrr with default settings dashbrr serve # Specify a custom config file location dashbrr serve --config=/path/to/config.toml # Specify a custom database location dashbrr serve --db-file=/path/to/database.db # Specify a custom listen address dashbrr serve --listen-addr=:8081 ``` -------------------------------- ### POST /api/settings/:instance Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/handlers.md Creates or updates a service configuration for a specific instance. API key is write-only. ```APIDOC ## POST /api/settings/:instance ### Description Creates or updates a service configuration for the specified instance. The API key is write-only: if empty on update, the existing key is kept. The service is initialized, cache is invalidated, and the poller is refreshed. ### Method POST ### Endpoint /api/settings/:instance ### Parameters #### Path Parameters - **instance** (string) - Required - The instance ID. #### Request Body - **apiKey** (string) - Optional - API key. If empty on update, existing key is kept. - **url** (string) - Optional - Service URL. Trailing slash is trimmed. - Other fields from `models.ServiceConfiguration` as needed. ### Request Example { "apiKey": "secret", "url": "http://example.com/" } ### Response #### Success Response (200) - Returns the created or updated configuration (sanitized). ``` -------------------------------- ### GET /api/auth/user Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Retrieves the current user's information. ```APIDOC ## [GET] /api/auth/user ### Description Retrieves the current user's information. ### Method GET ### Endpoint /api/auth/user ### Response #### Success Response (200) - **id** (integer) - User ID. - **username** (string) - Username. - **email** (string) - Email. #### Response Example { "id": 1, "username": "john_doe", "email": "john@example.com" } #### Error Responses - **401** - Session not found or user not found. - **500** - Internal server error. ``` -------------------------------- ### UI collapse preferences methods Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Go method signatures for retrieving and upserting UI collapse preferences, with the corresponding SQL queries shown as comments. ```go func (db *DB) GetUICollapsePreferences(ctx context.Context, userID int64) (map[string]bool, error) // SELECT preference_key, is_collapsed FROM ui_collapse_preferences WHERE user_id = ? func (db *DB) UpsertUICollapsePreference(ctx context.Context, userID int64, key string, collapsed bool) error // INSERT INTO ui_collapse_preferences (user_id, preference_key, is_collapsed, updated_at) // VALUES ($1,$2,$3,$4) ON CONFLICT (user_id, preference_key) DO UPDATE SET is_collapsed, updated_at ``` -------------------------------- ### GET /api/ui/preferences/collapse Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Retrieves UI collapse preferences for the authenticated user. ```APIDOC ## GET /api/ui/preferences/collapse ### Description Returns collapse preferences for the authenticated user. Requires a numeric user_id context value set by auth; OIDC sessions map to shared user 0. ### Method GET ### Endpoint /api/ui/preferences/collapse ### Response #### Success Response (200) - **** (bool) - Collapse preference value #### Response Example { "": true } #### Error Responses - **401** - `{ "error": "User context not found" }` - **500** - `{ "error": "Failed to load UI preferences" }` ``` -------------------------------- ### GET /api/auth/userinfo Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Returns the current user's profile information. ```APIDOC ## GET /api/auth/userinfo ### Description Returns the user's ID, username, and email for the current session. Loads the DB user for the session. ### Method GET ### Endpoint /api/auth/userinfo ### Response #### Success Response (200) - **id** (string) - The user's ID. - **username** (string) - The user's username. - **email** (string) - The user's email. #### Error Responses - **401** - `{ "error": "Session not found" }` or `{ "error": "User not found" }` - **500** - Internal error. ``` -------------------------------- ### Config constructors and DB initialization functions Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Function signatures for configuration and initialization. DefaultConfig returns a Config with sqlite driver and default path; NewConfig applies environment overrides; InitDBWithConfig builds and opens the DB; postgresDSN constructs a DSN string. ```go func DefaultConfig() *Config // Driver "sqlite", Path "./data/dashbrr.db", Host "localhost", Port 5432, // User "dashbrr", Password "dashbrr", DBName "dashbrr" func NewConfig() *Config // DefaultConfig + ApplyEnvOverrides func (config *Config) ApplyEnvOverrides() func InitDBWithConfig(config *Config) (*DB, error) func postgresDSN(config *Config) string ``` -------------------------------- ### GET /health Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Liveness probe endpoint that returns a simple status. ```APIDOC ## GET /health ### Description Liveness probe. No auth, no rate limit. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Always "ok". #### Response Example { "status": "ok" } ``` -------------------------------- ### GET /api/plex/auth/pin/:pinId Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Checks the authorization status of a Plex authentication PIN. ```APIDOC ## GET /api/plex/auth/pin/:pinId ### Description Checks the status of a Plex authentication PIN. Rate limited. ### Method GET ### Endpoint /api/plex/auth/pin/:pinId ### Parameters #### Path Parameters - **pinId** (int) - Required - The PIN ID #### Query Parameters - **code** (string) - Required - The PIN code - **clientIdentifier** (string) - Required - The client identifier - **product** (string) - Optional - Product name ### Response #### Success Response (200) - **authorized** (bool) - Whether the PIN is authorized - **authToken** (string) - Authentication token (omitted if empty) - **expiresIn** (int) - Expiration time in seconds #### Response Example { "authorized": true, "authToken": "string", "expiresIn": 600 } #### Error Responses - **400** - Invalid pin id / missing code / missing clientIdentifier - **502** - Upstream check failure ``` -------------------------------- ### Dashbrr version command with options Source: https://github.com/autobrr/dashbrr/blob/develop/docs/commands.md Shows the version command with its options: --check-github and --json. The command displays the current version, build commit hash, build date, and latest release information when using --check-github. ```bash # Display version information dashbrr version [--check-github] [--json] Options: --check-github Check for latest version on GitHub --json Output results in JSON format Example: dashbrr version --check-github Example: dashbrr version --json ``` -------------------------------- ### initializeDatabase function signature Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/cli.md Initializes the database for CLI commands. Uses database.InitDBWithConfig with a new config, which respects DASHBRR__DB_* environment variables or defaults. ```go func initializeDatabase() (*database.DB, error) // database.InitDBWithConfig(database.NewConfig()) — DASHBRR__DB_* env or defaults ``` -------------------------------- ### GET /api/auth/oidc/userinfo Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Returns the current user's ID and authentication type. ```APIDOC ## [GET] /api/auth/oidc/userinfo ### Description Returns the user ID and authentication type for the current session. ### Method GET ### Endpoint /api/auth/oidc/userinfo ### Response #### Success Response (200) - **user_id** (int64) - The user's ID. - **auth_type** (string) - `"oidc"` #### Error Responses - **401** - `{ "error": "No session found" }`, `{ "error": "Session expired" }`, or `{ "error": "Invalid session" }` - **504** - Timeout error ``` -------------------------------- ### GET /api/auth/oidc/logout Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Logs out the user and redirects to the OIDC provider's logout endpoint. ```APIDOC ## [GET] /api/auth/oidc/logout ### Description Logs out the current user by deleting the session and clearing the cookie, then redirects to the OIDC provider's logout URL. ### Method GET ### Endpoint /api/auth/oidc/logout ### Parameters #### Query Parameters - **frontendUrl** (string) - Required - The URL to redirect to after logout. ### Response #### Success Response (307) Redirect to the OIDC provider's logout URL. #### Error Responses - **400** - `{ "error": "Frontend URL is required" }` - **200** - `{ "message": "Already logged out" }` (when no session exists) - **504** - Timeout error ``` -------------------------------- ### Manager.DiscoverAll Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/discovery.md Discovers all services from all registered discoverers and returns their configurations. ```APIDOC ## DiscoverAll ### Description Discovers all services from all registered discoverers and returns their configurations. ### Method Function ### Signature `func (m *Manager) DiscoverAll(ctx context.Context) ([]models.ServiceConfiguration, error)` ### Parameters - `ctx` (context.Context) - Required - The context for the discovery operation ### Returns - `[]models.ServiceConfiguration` - List of discovered service configurations - `error` - Error if discovery fails ### Example ```go services, err := mgr.DiscoverAll(ctx) if err != nil { // handle error } ``` ``` -------------------------------- ### GET /api/events Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Streams service health updates and internal events via Server-Sent Events. ```APIDOC ## GET /api/events ### Description Server-Sent Events endpoint that streams service health updates and internal events. ### Method GET ### Endpoint /api/events ### Response #### Success Response (200) - **Content-Type**: `text/event-stream` - **Cache-Control**: `no-cache` - **Connection**: `keep-alive` - **Transfer-Encoding**: `chunked` - **X-Accel-Buffering**: `no` #### Event Format - First bytes: `retry: 5000\n\n` - On connect, replays `Broadcaster.Snapshot()` (latest ServiceHealth per service, sorted by serviceId) - Then pushes each published payload; every 15 s emits `: keepalive\n\n` comment - Each event is `data: \n\n` where the JSON is a merged `models.ServiceHealth` (eventType is "health" or "internal") - Encode fallback: `data: {"status":"error","message":"failed to encode event"}\n\n` ``` -------------------------------- ### GetAllServices Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Retrieves all service configurations. ```APIDOC ## GetAllServices ### Description Returns a list of all service configurations in the database. ### Method `func (db *DB) GetAllServices(ctx context.Context) ([]models.ServiceConfiguration, error)` ### Parameters - `ctx` (context.Context) - Required - The context for the operation. ### Returns - `[]models.ServiceConfiguration` - A slice of all service configurations. - `error` - Any error encountered during the operation. ``` -------------------------------- ### GET /api/auth/oidc/logout and POST /api/auth/oidc/logout Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Logs out the user and redirects to the provider's logout URL. ```APIDOC ## GET /api/auth/oidc/logout and POST /api/auth/oidc/logout ### Description Logs out the user by deleting the session, clearing the cookie, and redirecting (307) to the provider's logout URL built by `buildLogoutURL` (`/v2/logout?client_id=...&returnTo=...`). Requires a `frontendUrl` query parameter for GET requests. ### Method GET, POST ### Endpoint /api/auth/oidc/logout ### Parameters #### Query Parameters - **frontendUrl** (string) - Required (for GET) - The URL to redirect back to after logout. ### Response #### Success Response (307) Redirects to the provider's logout URL. #### Error Responses - **400** - `{ "error": "Frontend URL is required" }` - **200** - `{ "message": "Already logged out" }` when no session exists. ``` -------------------------------- ### Error handling in Go consumer Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Shows how to handle errors from ensureProviderConfig, returning a 504 timeout or 502 discovery failure based on context errors. ```go // error handling in a Go consumer err := h.ensureProviderConfig(ctx) if err != nil { if ctx.Err() != nil { c.JSON(504, {"error": "Operation timed out"}) } else { c.JSON(502, {"error": "OIDC provider discovery failed"}) } } ``` -------------------------------- ### GET /api/auth/registration-status Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Checks whether registration is enabled. Registration is enabled only while zero users exist. ```APIDOC ## [GET] /api/auth/registration-status ### Description Checks whether registration is enabled. Registration is enabled only while zero users exist. ### Method GET ### Endpoint /api/auth/registration-status ### Response #### Success Response (200) - **hasUsers** (bool) - Whether any users exist. - **registrationEnabled** (bool) - Whether registration is enabled. #### Response Example { "hasUsers": false, "registrationEnabled": true } #### Error Response (500) - **error** (string) - "Internal server error". ``` -------------------------------- ### GET /api/auth/oidc/login Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-oidc.md Initiates the OIDC login flow by redirecting to the provider's authorization endpoint. ```APIDOC ## [GET] /api/auth/oidc/login ### Description Initiates the OIDC login flow. Requires a `frontendUrl` query parameter, generates state and nonce, stores them in Redis, and redirects the user to the OIDC provider's authorization endpoint. ### Method GET ### Endpoint /api/auth/oidc/login ### Parameters #### Query Parameters - **frontendUrl** (string) - Required - The URL to redirect back to after login. ### Response #### Success Response (307) Redirect to the OIDC provider's authorization URL. #### Error Responses - **400** - `{ "error": "Frontend URL is required" }` - **502** - `{ "error": "OIDC provider discovery failed" }` - **504** - `{ "error": "Operation timed out" }` - **500** - `{ "error": "Internal server error" }` ``` -------------------------------- ### NewKubernetesDiscovery Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/discovery.md Creates a new Kubernetes discovery instance using the Kubernetes client-go library. ```APIDOC ## NewKubernetesDiscovery ### Description Creates a new Kubernetes discovery instance using the Kubernetes client-go library. ### Method Function ### Signature `func NewKubernetesDiscovery() (*KubernetesDiscovery, error)` ### Parameters None ### Returns - `*KubernetesDiscovery` - The Kubernetes discovery instance - `error` - Error if initialization fails ### Example ```go k8sDisc, err := discovery.NewKubernetesDiscovery() if err != nil { // handle error } ``` ``` -------------------------------- ### GET /api/health/:service Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/handlers.md Checks the health of a service. Supports ad-hoc configuration via query parameters. ```APIDOC ## GET /api/health/:service ### Description Checks the health of a service. The service type is extracted from the first `-` segment of the `:service` path parameter. If a `url` query parameter is provided, an ad-hoc configuration is built (falling back to the stored API key if missing). Otherwise, the configuration is loaded from the database (404 if absent). If the service is unconfigured (`url == ""`), returns 200 with status "unconfigured". ### Method GET ### Endpoint /api/health/:service?url=&apiKey= ### Parameters #### Path Parameters - **service** (string) - Required - Service identifier, e.g., `sonarr-instance`. #### Query Parameters - **url** (string) - Optional - Service URL. If provided, builds an ad-hoc config. - **apiKey** (string) - Optional - API key. Used if `url` is provided and the stored key is missing. ### Response #### Success Response (200) - If unconfigured: `{ "status": "unconfigured" }` - Otherwise, delegates to the service checker; see endpoints.md for status codes. #### Error Response (404) - Returned when no configuration exists and no `url` is provided. ``` -------------------------------- ### Using SonarrService with ServiceCore Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/service-core.md Shows how to use a service that embeds ServiceCore: set a timeout, build headers, call DoRequest, handle errors, and read the response body. The comment lists possible error types and notes that ReadBody builds a message from status and body. ```go service := &sonarr.SonarrService{} // embeds ServiceCore service.SetTimeout(core.DefaultTimeout) headers := map[string]string{"X-Api-Key": apiKey} resp, err := service.DoRequest(ctx, http.MethodGet, url, headers, nil) if err != nil { // ErrServiceNotConfigured | request failures | ErrNilResponse | 301/302 } if resp.StatusCode != http.StatusOK { // ReadBody builds a message from status + body } body, err := service.ReadBody(resp) // decode body into a types.* envelope ``` -------------------------------- ### NewBuiltinAuthHandler constructor Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/auth-builtin.md Constructor that returns a new handler instance. Takes the database and cache store used for user persistence and session management. ```go func NewBuiltinAuthHandler(db *database.DB, cache cache.Store) *BuiltinAuthHandler ``` -------------------------------- ### GET /api/health/:service Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/endpoints.md Checks the health of a service instance. Rate limited to 30 requests per minute. ```APIDOC ## GET /api/health/:service ### Description Checks the health of a service. Rate limited to 30/min. The :service path parameter is the instance ID; the leading dash-separated token is the service type. If url is supplied, it takes precedence; a missing apiKey falls back to the stored key for the instance. ### Method GET ### Endpoint /api/health/:service ### Parameters #### Path Parameters - **service** (string) - Required - The instance ID #### Query Parameters - **url** (string) - Optional - Service URL; overrides stored URL - **apiKey** (string) - Optional - API key; falls back to stored key if url is set ### Response #### Success Response (200) - **status** (string) - `online|offline|warning|error|unconfigured` - **responseTime** (number) - Response time in ms - **lastChecked** (string) - Last check timestamp - **message** (string, optional) - Status message - **version** (string, optional) - Service version - **updateAvailable** (bool, optional) - Whether update is available - **stats** (object, optional) - Service statistics - **details** (object, optional) - Additional details #### Response Example { "status": "online", "responseTime": 123, "lastChecked": "2023-01-01T00:00:00Z", "message": "string", "version": "string", "updateAvailable": false, "stats": {}, "details": {} } #### Error Responses - **400** - `{ "error": "Service ID is required" }` / `{ "error": "Invalid service ID format" }` / `{ "error": "Unsupported service type: " }` / `{ "status": "error", "message": "API key is required for this service type" }` - **404** - `{ "error": "Service not found" }` - **504** - `{ "error": "Operation timed out" }` / `{ "status": "error", "message": "Health check timed out" }` - Upstream failures: 401 → `{ "status": "error", "message": "Invalid API key" }`, 404 → `{ "status": "error", "message": "Service not found at the specified URL" }`, 503 → `{ "status": "error", "message": "Service is unavailable" }`, else `{ "status": "error", "message": "Failed to check service health" }` ``` -------------------------------- ### GetServiceByInstancePrefix Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Finds a service configuration by instance ID prefix. ```APIDOC ## GetServiceByInstancePrefix ### Description Retrieves a service configuration whose instance ID starts with the given prefix. Returns `(nil, nil)` if no service is found. ### Method `func (db *DB) GetServiceByInstancePrefix(ctx context.Context, prefix string) (*models.ServiceConfiguration, error)` ### Parameters - `ctx` (context.Context) - Required - The context for the operation. - `prefix` (string) - Required - The prefix to match against the instance ID. ### Behavior Executes a raw SQL query: `WHERE instance_id LIKE $1 || '%' LIMIT 1` (postgres) or `LIKE ? || '%' LIMIT 1` (sqlite). ### Returns - `*models.ServiceConfiguration` - The found service configuration, or `nil` if not found. - `error` - Any error encountered during the operation. ``` -------------------------------- ### CreateService Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md Creates a new service configuration. ```APIDOC ## CreateService ### Description Inserts a new service configuration record. The `id` field is populated from the database. ### Method `func (db *DB) CreateService(ctx context.Context, service *models.ServiceConfiguration) error` ### Parameters - `ctx` (context.Context) - Required - The context for the operation. - `service` (*models.ServiceConfiguration) - Required - The service configuration to insert. The `id` field will be set after insertion. ### Behavior Executes an `INSERT ... RETURNING id` and sets `service.ID` to the returned value. ``` -------------------------------- ### SQLite schema for users, service_configurations, and ui_collapse_preferences Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/database.md SQLite schema for users, service_configurations, and ui_collapse_preferences tables, as defined in internal/database/migrations/sqlite_schema.sql. ```sql CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL ); CREATE TABLE IF NOT EXISTS service_configurations ( id INTEGER PRIMARY KEY, instance_id TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL, url TEXT, api_key TEXT, access_url TEXT ); CREATE TABLE IF NOT EXISTS ui_collapse_preferences ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, preference_key TEXT NOT NULL, is_collapsed BOOLEAN NOT NULL DEFAULT FALSE, updated_at TIMESTAMP NOT NULL, UNIQUE(user_id, preference_key) ); ``` -------------------------------- ### Handling ListenAndServe errors Source: https://github.com/autobrr/dashbrr/blob/develop/_autodocs/api-reference/server.md Example of calling ListenAndServe and handling errors. It sends the error to an error channel unless the server was closed normally (http.ErrServerClosed). ```go if listenErr := srv.ListenAndServe(); listenErr != nil && !errors.Is(listenErr, http.ErrServerClosed) { errorChannel <- listenErr } ```