feat(admin): metadata-profile picker on integrations page

Persists the operator's metadata-profile choice alongside quality
profile + root folder. Defaults to the first profile Lidarr returns
(usually 'Standard' on a vanilla install) so the common case is
zero-click; operators with custom profiles like 'Singles only' can pick
explicitly.

Backend:
- Migration 0013: adds nullable default_metadata_profile_id to
  lidarr_config. Existing rows get NULL and the service falls back to
  fetch-and-pick-first until they save.
- Updated lidarr_config queries + sqlc + lidarrconfig.Config + admin
  view/put body to round-trip the new field.
- handlePutLidarrConfig requires it (along with QP and root folder)
  when enabled=true — matches the existing missing_defaults gate.
- New GET /api/admin/lidarr/metadata-profiles handler + lidarr.Client
  ListMetadataProfiles (GET /api/v1/metadataprofile, same shape as
  the quality-profile endpoint).
- lidarrrequests.Approve prefers cfg.DefaultMetadataProfileID; falls
  back to the fetch-list path only when 0 (back-compat for upgraders).

Frontend:
- LidarrConfig type + LidarrMetadataProfile type + qk.lidarrMetadataProfiles.
- listMetadataProfiles + createMetadataProfilesQuery client helpers.
- Integrations page: third <select> picker, auto-defaults to first
  profile when the saved value is 0, sends the new field on save and
  clears it on disconnect.
- Updated test fixtures + the duplicate 'Standard' option string in
  the dropdown-populates assertion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-02 00:09:13 -04:00
parent 7d33166f23
commit c265b871c3
15 changed files with 236 additions and 85 deletions
+55 -23
View File
@@ -13,11 +13,12 @@ import (
// lidarrConfigView is the JSON shape returned by GET /api/admin/lidarr/config // lidarrConfigView is the JSON shape returned by GET /api/admin/lidarr/config
// and PUT /api/admin/lidarr/config. api_key is always masked as "***" when set. // and PUT /api/admin/lidarr/config. api_key is always masked as "***" when set.
type lidarrConfigView struct { type lidarrConfigView struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
APIKey string `json:"api_key"` APIKey string `json:"api_key"`
DefaultQualityProfileID int `json:"default_quality_profile_id"` DefaultQualityProfileID int `json:"default_quality_profile_id"`
DefaultRootFolderPath string `json:"default_root_folder_path"` DefaultMetadataProfileID int `json:"default_metadata_profile_id"`
DefaultRootFolderPath string `json:"default_root_folder_path"`
} }
// maskAPIKey converts an api_key for external response: non-empty keys become // maskAPIKey converts an api_key for external response: non-empty keys become
@@ -33,11 +34,12 @@ func maskAPIKey(key string) string {
// api_key masked. // api_key masked.
func configToView(cfg lidarrconfig.Config) lidarrConfigView { func configToView(cfg lidarrconfig.Config) lidarrConfigView {
return lidarrConfigView{ return lidarrConfigView{
Enabled: cfg.Enabled, Enabled: cfg.Enabled,
BaseURL: cfg.BaseURL, BaseURL: cfg.BaseURL,
APIKey: maskAPIKey(cfg.APIKey), APIKey: maskAPIKey(cfg.APIKey),
DefaultQualityProfileID: cfg.DefaultQualityProfileID, DefaultQualityProfileID: cfg.DefaultQualityProfileID,
DefaultRootFolderPath: cfg.DefaultRootFolderPath, DefaultMetadataProfileID: cfg.DefaultMetadataProfileID,
DefaultRootFolderPath: cfg.DefaultRootFolderPath,
} }
} }
@@ -55,11 +57,12 @@ func (h *handlers) handleGetLidarrConfig(w http.ResponseWriter, r *http.Request)
// putLidarrConfigBody is the decoded JSON body for PUT /api/admin/lidarr/config. // putLidarrConfigBody is the decoded JSON body for PUT /api/admin/lidarr/config.
type putLidarrConfigBody struct { type putLidarrConfigBody struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
APIKey string `json:"api_key"` APIKey string `json:"api_key"`
DefaultQualityProfileID int `json:"default_quality_profile_id"` DefaultQualityProfileID int `json:"default_quality_profile_id"`
DefaultRootFolderPath string `json:"default_root_folder_path"` DefaultMetadataProfileID int `json:"default_metadata_profile_id"`
DefaultRootFolderPath string `json:"default_root_folder_path"`
} }
// handlePutLidarrConfig implements PUT /api/admin/lidarr/config. // handlePutLidarrConfig implements PUT /api/admin/lidarr/config.
@@ -95,21 +98,24 @@ func (h *handlers) handlePutLidarrConfig(w http.ResponseWriter, r *http.Request)
return return
} }
// Defaults must be present so future Approve calls don't dispatch // Defaults must be present so future Approve calls don't dispatch
// invalid POST bodies to Lidarr (which produces 5xx with no useful // invalid POST bodies to Lidarr (which produces 4xx with field
// detail). The frontend pre-selects first values so this almost // errors). The frontend pre-selects first values so this almost
// never fires for non-malicious traffic, but it's the right gate. // never fires for non-malicious traffic, but it's the right gate.
if body.DefaultQualityProfileID == 0 || body.DefaultRootFolderPath == "" { if body.DefaultQualityProfileID == 0 ||
body.DefaultMetadataProfileID == 0 ||
body.DefaultRootFolderPath == "" {
writeAdminJSONErr(w, http.StatusBadRequest, "missing_defaults") writeAdminJSONErr(w, http.StatusBadRequest, "missing_defaults")
return return
} }
} }
cfg := lidarrconfig.Config{ cfg := lidarrconfig.Config{
Enabled: body.Enabled, Enabled: body.Enabled,
BaseURL: body.BaseURL, BaseURL: body.BaseURL,
APIKey: apiKey, APIKey: apiKey,
DefaultQualityProfileID: body.DefaultQualityProfileID, DefaultQualityProfileID: body.DefaultQualityProfileID,
DefaultRootFolderPath: body.DefaultRootFolderPath, DefaultMetadataProfileID: body.DefaultMetadataProfileID,
DefaultRootFolderPath: body.DefaultRootFolderPath,
} }
if err := h.lidarrCfg.Save(r.Context(), cfg); err != nil { if err := h.lidarrCfg.Save(r.Context(), cfg); err != nil {
h.logger.Error("admin: put lidarr config: save", "err", err) h.logger.Error("admin: put lidarr config: save", "err", err)
@@ -210,6 +216,32 @@ func (h *handlers) handleListQualityProfiles(w http.ResponseWriter, r *http.Requ
writeJSON(w, http.StatusOK, out) writeJSON(w, http.StatusOK, out)
} }
// metadataProfileView is the JSON shape for a single metadata profile in the
// GET /api/admin/lidarr/metadata-profiles response.
type metadataProfileView struct {
ID int `json:"id"`
Name string `json:"name"`
}
// handleListMetadataProfiles implements GET /api/admin/lidarr/metadata-profiles.
func (h *handlers) handleListMetadataProfiles(w http.ResponseWriter, r *http.Request) {
_, client, ok := h.lidarrClientFromConfig(w, r)
if !ok {
return
}
profiles, err := client.ListMetadataProfiles(r.Context())
if err != nil {
writeAdminJSONErr(w, http.StatusServiceUnavailable, lidarrErrCode(err))
return
}
out := make([]metadataProfileView, len(profiles))
for i, p := range profiles {
out[i] = metadataProfileView{ID: p.ID, Name: p.Name}
}
writeJSON(w, http.StatusOK, out)
}
// rootFolderView is the JSON shape for a single root folder in the // rootFolderView is the JSON shape for a single root folder in the
// GET /api/admin/lidarr/root-folders response. // GET /api/admin/lidarr/root-folders response.
type rootFolderView struct { type rootFolderView struct {
+1
View File
@@ -82,6 +82,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
admin.Put("/lidarr/config", h.handlePutLidarrConfig) admin.Put("/lidarr/config", h.handlePutLidarrConfig)
admin.Post("/lidarr/test", h.handleTestLidarrConnection) admin.Post("/lidarr/test", h.handleTestLidarrConnection)
admin.Get("/lidarr/quality-profiles", h.handleListQualityProfiles) admin.Get("/lidarr/quality-profiles", h.handleListQualityProfiles)
admin.Get("/lidarr/metadata-profiles", h.handleListMetadataProfiles)
admin.Get("/lidarr/root-folders", h.handleListRootFolders) admin.Get("/lidarr/root-folders", h.handleListRootFolders)
admin.Get("/requests", h.handleListAdminRequests) admin.Get("/requests", h.handleListAdminRequests)
admin.Post("/requests/{id}/approve", h.handleApproveRequest) admin.Post("/requests/{id}/approve", h.handleApproveRequest)
+50 -17
View File
@@ -7,24 +7,40 @@ package dbq
import ( import (
"context" "context"
"github.com/jackc/pgx/v5/pgtype"
) )
const getLidarrConfig = `-- name: GetLidarrConfig :one const getLidarrConfig = `-- name: GetLidarrConfig :one
SELECT id, enabled, base_url, api_key, default_quality_profile_id, SELECT id, enabled, base_url, api_key, default_quality_profile_id,
default_root_folder_path, created_at, updated_at default_metadata_profile_id, default_root_folder_path,
created_at, updated_at
FROM lidarr_config FROM lidarr_config
WHERE id = 1 WHERE id = 1
` `
func (q *Queries) GetLidarrConfig(ctx context.Context) (LidarrConfig, error) { type GetLidarrConfigRow struct {
ID int16
Enabled bool
BaseUrl *string
ApiKey *string
DefaultQualityProfileID *int32
DefaultMetadataProfileID *int32
DefaultRootFolderPath *string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) GetLidarrConfig(ctx context.Context) (GetLidarrConfigRow, error) {
row := q.db.QueryRow(ctx, getLidarrConfig) row := q.db.QueryRow(ctx, getLidarrConfig)
var i LidarrConfig var i GetLidarrConfigRow
err := row.Scan( err := row.Scan(
&i.ID, &i.ID,
&i.Enabled, &i.Enabled,
&i.BaseUrl, &i.BaseUrl,
&i.ApiKey, &i.ApiKey,
&i.DefaultQualityProfileID, &i.DefaultQualityProfileID,
&i.DefaultMetadataProfileID,
&i.DefaultRootFolderPath, &i.DefaultRootFolderPath,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
@@ -34,40 +50,57 @@ func (q *Queries) GetLidarrConfig(ctx context.Context) (LidarrConfig, error) {
const updateLidarrConfig = `-- name: UpdateLidarrConfig :one const updateLidarrConfig = `-- name: UpdateLidarrConfig :one
UPDATE lidarr_config UPDATE lidarr_config
SET enabled = $1, SET enabled = $1,
base_url = $2, base_url = $2,
api_key = $3, api_key = $3,
default_quality_profile_id = $4, default_quality_profile_id = $4,
default_root_folder_path = $5, default_metadata_profile_id = $5,
updated_at = now() default_root_folder_path = $6,
updated_at = now()
WHERE id = 1 WHERE id = 1
RETURNING id, enabled, base_url, api_key, default_quality_profile_id, RETURNING id, enabled, base_url, api_key, default_quality_profile_id,
default_root_folder_path, created_at, updated_at default_metadata_profile_id, default_root_folder_path,
created_at, updated_at
` `
type UpdateLidarrConfigParams struct { type UpdateLidarrConfigParams struct {
Enabled bool Enabled bool
BaseUrl *string BaseUrl *string
ApiKey *string ApiKey *string
DefaultQualityProfileID *int32 DefaultQualityProfileID *int32
DefaultRootFolderPath *string DefaultMetadataProfileID *int32
DefaultRootFolderPath *string
} }
func (q *Queries) UpdateLidarrConfig(ctx context.Context, arg UpdateLidarrConfigParams) (LidarrConfig, error) { type UpdateLidarrConfigRow struct {
ID int16
Enabled bool
BaseUrl *string
ApiKey *string
DefaultQualityProfileID *int32
DefaultMetadataProfileID *int32
DefaultRootFolderPath *string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) UpdateLidarrConfig(ctx context.Context, arg UpdateLidarrConfigParams) (UpdateLidarrConfigRow, error) {
row := q.db.QueryRow(ctx, updateLidarrConfig, row := q.db.QueryRow(ctx, updateLidarrConfig,
arg.Enabled, arg.Enabled,
arg.BaseUrl, arg.BaseUrl,
arg.ApiKey, arg.ApiKey,
arg.DefaultQualityProfileID, arg.DefaultQualityProfileID,
arg.DefaultMetadataProfileID,
arg.DefaultRootFolderPath, arg.DefaultRootFolderPath,
) )
var i LidarrConfig var i UpdateLidarrConfigRow
err := row.Scan( err := row.Scan(
&i.ID, &i.ID,
&i.Enabled, &i.Enabled,
&i.BaseUrl, &i.BaseUrl,
&i.ApiKey, &i.ApiKey,
&i.DefaultQualityProfileID, &i.DefaultQualityProfileID,
&i.DefaultMetadataProfileID,
&i.DefaultRootFolderPath, &i.DefaultRootFolderPath,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
+9 -8
View File
@@ -254,14 +254,15 @@ type GeneralLikesArtist struct {
} }
type LidarrConfig struct { type LidarrConfig struct {
ID int16 ID int16
Enabled bool Enabled bool
BaseUrl *string BaseUrl *string
ApiKey *string ApiKey *string
DefaultQualityProfileID *int32 DefaultQualityProfileID *int32
DefaultRootFolderPath *string DefaultRootFolderPath *string
CreatedAt pgtype.Timestamptz CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz
DefaultMetadataProfileID *int32
} }
type LidarrQuarantine struct { type LidarrQuarantine struct {
@@ -0,0 +1,2 @@
ALTER TABLE lidarr_config
DROP COLUMN default_metadata_profile_id;
@@ -0,0 +1,9 @@
-- M6a follow-up: persist the operator's metadata-profile choice alongside
-- quality profile + root folder. Lidarr POST /api/v1/artist requires
-- metadataProfileId; without storing it we'd refetch and pick first on
-- every Approve, denying the operator a choice. Nullable: existing rows
-- (and operators upgrading from before this migration) get NULL and the
-- service falls back to "fetch list and pick first" until they save.
ALTER TABLE lidarr_config
ADD COLUMN default_metadata_profile_id integer;
+11 -8
View File
@@ -1,17 +1,20 @@
-- name: GetLidarrConfig :one -- name: GetLidarrConfig :one
SELECT id, enabled, base_url, api_key, default_quality_profile_id, SELECT id, enabled, base_url, api_key, default_quality_profile_id,
default_root_folder_path, created_at, updated_at default_metadata_profile_id, default_root_folder_path,
created_at, updated_at
FROM lidarr_config FROM lidarr_config
WHERE id = 1; WHERE id = 1;
-- name: UpdateLidarrConfig :one -- name: UpdateLidarrConfig :one
UPDATE lidarr_config UPDATE lidarr_config
SET enabled = $1, SET enabled = $1,
base_url = $2, base_url = $2,
api_key = $3, api_key = $3,
default_quality_profile_id = $4, default_quality_profile_id = $4,
default_root_folder_path = $5, default_metadata_profile_id = $5,
updated_at = now() default_root_folder_path = $6,
updated_at = now()
WHERE id = 1 WHERE id = 1
RETURNING id, enabled, base_url, api_key, default_quality_profile_id, RETURNING id, enabled, base_url, api_key, default_quality_profile_id,
default_root_folder_path, created_at, updated_at; default_metadata_profile_id, default_root_folder_path,
created_at, updated_at;
+16 -10
View File
@@ -15,11 +15,12 @@ import (
// Config is the typed projection of lidarr_config (no NULL fields exposed // Config is the typed projection of lidarr_config (no NULL fields exposed
// to callers — empty strings / zero ints carry the "unset" meaning). // to callers — empty strings / zero ints carry the "unset" meaning).
type Config struct { type Config struct {
Enabled bool Enabled bool
BaseURL string BaseURL string
APIKey string APIKey string
DefaultQualityProfileID int DefaultQualityProfileID int
DefaultRootFolderPath string DefaultMetadataProfileID int
DefaultRootFolderPath string
} }
// Service reads and writes the singleton. // Service reads and writes the singleton.
@@ -44,6 +45,9 @@ func (s *Service) Get(ctx context.Context) (Config, error) {
if row.DefaultQualityProfileID != nil { if row.DefaultQualityProfileID != nil {
cfg.DefaultQualityProfileID = int(*row.DefaultQualityProfileID) cfg.DefaultQualityProfileID = int(*row.DefaultQualityProfileID)
} }
if row.DefaultMetadataProfileID != nil {
cfg.DefaultMetadataProfileID = int(*row.DefaultMetadataProfileID)
}
if row.DefaultRootFolderPath != nil { if row.DefaultRootFolderPath != nil {
cfg.DefaultRootFolderPath = *row.DefaultRootFolderPath cfg.DefaultRootFolderPath = *row.DefaultRootFolderPath
} }
@@ -57,14 +61,16 @@ func (s *Service) Save(ctx context.Context, cfg Config) error {
baseURL = strPtr(cfg.BaseURL) baseURL = strPtr(cfg.BaseURL)
apiKey = strPtr(cfg.APIKey) apiKey = strPtr(cfg.APIKey)
qpID = int32Ptr(cfg.DefaultQualityProfileID) qpID = int32Ptr(cfg.DefaultQualityProfileID)
mpID = int32Ptr(cfg.DefaultMetadataProfileID)
rootPath = strPtr(cfg.DefaultRootFolderPath) rootPath = strPtr(cfg.DefaultRootFolderPath)
) )
_, err := dbq.New(s.pool).UpdateLidarrConfig(ctx, dbq.UpdateLidarrConfigParams{ _, err := dbq.New(s.pool).UpdateLidarrConfig(ctx, dbq.UpdateLidarrConfigParams{
Enabled: cfg.Enabled, Enabled: cfg.Enabled,
BaseUrl: baseURL, BaseUrl: baseURL,
ApiKey: apiKey, ApiKey: apiKey,
DefaultQualityProfileID: qpID, DefaultQualityProfileID: qpID,
DefaultRootFolderPath: rootPath, DefaultMetadataProfileID: mpID,
DefaultRootFolderPath: rootPath,
}) })
if err != nil { if err != nil {
return fmt.Errorf("lidarrconfig: %w", err) return fmt.Errorf("lidarrconfig: %w", err)
+14 -13
View File
@@ -179,20 +179,21 @@ func (s *Service) Approve(ctx context.Context, requestID pgtype.UUID, adminID pg
} }
// Lidarr requires a metadata profile id on POST /api/v1/artist (and // Lidarr requires a metadata profile id on POST /api/v1/artist (and
// on /api/v1/album when it has to create the parent artist). We // on /api/v1/album when it has to create the parent artist). Prefer
// don't store this in lidarr_config yet — fetch the available // the operator's pinned choice from cfg; fall back to fetching the
// profiles per-Approve and pick the first as a sensible default. // list and using the first when nothing's been saved yet (operators
// Lidarr installs ship "Standard" at id=1 OOB, so this works for // upgrading from before metadata-profile support landed).
// vanilla setups; operators with custom profiles get whichever was mdProfileID := cfg.DefaultMetadataProfileID
// saved first. A picker on /admin/integrations is a follow-up. if mdProfileID == 0 {
mdProfiles, err := client.ListMetadataProfiles(ctx) mdProfiles, mdErr := client.ListMetadataProfiles(ctx)
if err != nil { if mdErr != nil {
return dbq.LidarrRequest{}, fmt.Errorf("approve: list metadata profiles: %w", err) return dbq.LidarrRequest{}, fmt.Errorf("approve: list metadata profiles: %w", mdErr)
}
if len(mdProfiles) == 0 {
return dbq.LidarrRequest{}, fmt.Errorf("approve: no metadata profiles configured in lidarr")
}
mdProfileID = mdProfiles[0].ID
} }
if len(mdProfiles) == 0 {
return dbq.LidarrRequest{}, fmt.Errorf("approve: no metadata profiles configured in lidarr")
}
mdProfileID := mdProfiles[0].ID
switch row.Kind { switch row.Kind {
case dbq.LidarrRequestKindArtist: case dbq.LidarrRequestKindArtist:
+1
View File
@@ -41,6 +41,7 @@ const baseConfig: LidarrConfig = {
base_url: 'http://lidarr.lan:8686', base_url: 'http://lidarr.lan:8686',
api_key: '***', api_key: '***',
default_quality_profile_id: 1, default_quality_profile_id: 1,
default_metadata_profile_id: 1,
default_root_folder_path: '/music' default_root_folder_path: '/music'
}; };
+13
View File
@@ -5,6 +5,7 @@ import type {
ActionResult, ActionResult,
AdminQuarantineRow, AdminQuarantineRow,
LidarrConfig, LidarrConfig,
LidarrMetadataProfile,
LidarrQualityProfile, LidarrQualityProfile,
LidarrQuarantineActionRow, LidarrQuarantineActionRow,
LidarrRequest, LidarrRequest,
@@ -36,6 +37,10 @@ export async function listQualityProfiles(): Promise<LidarrQualityProfile[]> {
return api.get<LidarrQualityProfile[]>('/api/admin/lidarr/quality-profiles'); return api.get<LidarrQualityProfile[]>('/api/admin/lidarr/quality-profiles');
} }
export async function listMetadataProfiles(): Promise<LidarrMetadataProfile[]> {
return api.get<LidarrMetadataProfile[]>('/api/admin/lidarr/metadata-profiles');
}
export async function listRootFolders(): Promise<LidarrRootFolder[]> { export async function listRootFolders(): Promise<LidarrRootFolder[]> {
return api.get<LidarrRootFolder[]>('/api/admin/lidarr/root-folders'); return api.get<LidarrRootFolder[]>('/api/admin/lidarr/root-folders');
} }
@@ -92,6 +97,14 @@ export function createQualityProfilesQuery(enabled: boolean = true) {
}); });
} }
export function createMetadataProfilesQuery(enabled: boolean = true) {
return createQuery({
queryKey: qk.lidarrMetadataProfiles(),
queryFn: listMetadataProfiles,
enabled
});
}
export function createRootFoldersQuery(enabled: boolean = true) { export function createRootFoldersQuery(enabled: boolean = true) {
return createQuery({ return createQuery({
queryKey: qk.lidarrRootFolders(), queryKey: qk.lidarrRootFolders(),
+3 -2
View File
@@ -24,8 +24,9 @@ export const qk = {
['lidarrSearch', { q, kind }] as const, ['lidarrSearch', { q, kind }] as const,
myRequests: () => ['myRequests'] as const, myRequests: () => ['myRequests'] as const,
lidarrConfig: () => ['lidarrConfig'] as const, lidarrConfig: () => ['lidarrConfig'] as const,
lidarrQualityProfiles: () => ['lidarrQualityProfiles'] as const, lidarrQualityProfiles: () => ['lidarrQualityProfiles'] as const,
lidarrRootFolders: () => ['lidarrRootFolders'] as const, lidarrMetadataProfiles: () => ['lidarrMetadataProfiles'] as const,
lidarrRootFolders: () => ['lidarrRootFolders'] as const,
adminRequests: (status?: string) => adminRequests: (status?: string) =>
['adminRequests', { status: status ?? 'all' }] as const, ['adminRequests', { status: status ?? 'all' }] as const,
myQuarantine: () => ['myQuarantine'] as const, myQuarantine: () => ['myQuarantine'] as const,
+6
View File
@@ -131,6 +131,7 @@ export type LidarrConfig = {
base_url: string; base_url: string;
api_key: string; api_key: string;
default_quality_profile_id: number; default_quality_profile_id: number;
default_metadata_profile_id: number;
default_root_folder_path: string; default_root_folder_path: string;
}; };
@@ -139,6 +140,11 @@ export type LidarrQualityProfile = {
name: string; name: string;
}; };
export type LidarrMetadataProfile = {
id: number;
name: string;
};
export type LidarrRootFolder = { export type LidarrRootFolder = {
path: string; path: string;
accessible: boolean; accessible: boolean;
+30 -2
View File
@@ -4,6 +4,7 @@
import { import {
createLidarrConfigQuery, createLidarrConfigQuery,
createQualityProfilesQuery, createQualityProfilesQuery,
createMetadataProfilesQuery,
createRootFoldersQuery, createRootFoldersQuery,
putLidarrConfig, putLidarrConfig,
testLidarrConnection testLidarrConnection
@@ -26,6 +27,7 @@
let baseUrl = $state(''); let baseUrl = $state('');
let apiKeyInput = $state(''); // intentionally never seeded with '***' let apiKeyInput = $state(''); // intentionally never seeded with '***'
let qualityId = $state<number>(0); let qualityId = $state<number>(0);
let metadataId = $state<number>(0);
let rootPath = $state<string>(''); let rootPath = $state<string>('');
let initialized = false; let initialized = false;
@@ -34,6 +36,7 @@
if (c && !initialized) { if (c && !initialized) {
baseUrl = c.base_url; baseUrl = c.base_url;
qualityId = c.default_quality_profile_id; qualityId = c.default_quality_profile_id;
metadataId = c.default_metadata_profile_id;
rootPath = c.default_root_folder_path; rootPath = c.default_root_folder_path;
initialized = true; initialized = true;
} }
@@ -41,13 +44,18 @@
// Auto-default to the first option Lidarr returns when the operator // Auto-default to the first option Lidarr returns when the operator
// hasn't picked one yet. Saves a click for the common case (one // hasn't picked one yet. Saves a click for the common case (one
// quality profile + one root folder, which is what most home setups // profile + one root folder, which is what most home setups have).
// have). The operator can still change either before saving. // The operator can still change any of them before saving.
$effect(() => { $effect(() => {
if (qualityId === 0 && profiles.data && profiles.data.length > 0) { if (qualityId === 0 && profiles.data && profiles.data.length > 0) {
qualityId = profiles.data[0].id; qualityId = profiles.data[0].id;
} }
}); });
$effect(() => {
if (metadataId === 0 && metadataProfiles.data && metadataProfiles.data.length > 0) {
metadataId = metadataProfiles.data[0].id;
}
});
$effect(() => { $effect(() => {
if (rootPath === '' && folders.data && folders.data.length > 0) { if (rootPath === '' && folders.data && folders.data.length > 0) {
rootPath = folders.data[0].path; rootPath = folders.data[0].path;
@@ -61,6 +69,9 @@
const profilesStore = $derived(createQualityProfilesQuery(profilesEnabled)); const profilesStore = $derived(createQualityProfilesQuery(profilesEnabled));
const profiles = $derived($profilesStore); const profiles = $derived($profilesStore);
const metadataProfilesStore = $derived(createMetadataProfilesQuery(profilesEnabled));
const metadataProfiles = $derived($metadataProfilesStore);
const foldersStore = $derived(createRootFoldersQuery(profilesEnabled)); const foldersStore = $derived(createRootFoldersQuery(profilesEnabled));
const folders = $derived($foldersStore); const folders = $derived($foldersStore);
@@ -78,6 +89,7 @@
base_url: baseUrl, base_url: baseUrl,
api_key: apiKeyInput, // empty string tells backend "preserve saved key" api_key: apiKeyInput, // empty string tells backend "preserve saved key"
default_quality_profile_id: qualityId, default_quality_profile_id: qualityId,
default_metadata_profile_id: metadataId,
default_root_folder_path: rootPath default_root_folder_path: rootPath
}; };
await putLidarrConfig(cfg); await putLidarrConfig(cfg);
@@ -86,6 +98,7 @@
await Promise.all([ await Promise.all([
client.invalidateQueries({ queryKey: qk.lidarrConfig() }), client.invalidateQueries({ queryKey: qk.lidarrConfig() }),
client.invalidateQueries({ queryKey: qk.lidarrQualityProfiles() }), client.invalidateQueries({ queryKey: qk.lidarrQualityProfiles() }),
client.invalidateQueries({ queryKey: qk.lidarrMetadataProfiles() }),
client.invalidateQueries({ queryKey: qk.lidarrRootFolders() }) client.invalidateQueries({ queryKey: qk.lidarrRootFolders() })
]); ]);
apiKeyInput = ''; apiKeyInput = '';
@@ -126,11 +139,13 @@
base_url: '', base_url: '',
api_key: '', api_key: '',
default_quality_profile_id: 0, default_quality_profile_id: 0,
default_metadata_profile_id: 0,
default_root_folder_path: '' default_root_folder_path: ''
}); });
await Promise.all([ await Promise.all([
client.invalidateQueries({ queryKey: qk.lidarrConfig() }), client.invalidateQueries({ queryKey: qk.lidarrConfig() }),
client.invalidateQueries({ queryKey: qk.lidarrQualityProfiles() }), client.invalidateQueries({ queryKey: qk.lidarrQualityProfiles() }),
client.invalidateQueries({ queryKey: qk.lidarrMetadataProfiles() }),
client.invalidateQueries({ queryKey: qk.lidarrRootFolders() }) client.invalidateQueries({ queryKey: qk.lidarrRootFolders() })
]); ]);
modalOpen = false; modalOpen = false;
@@ -212,6 +227,19 @@
</select> </select>
</label> </label>
<label class="block">
<span class="block text-sm text-text-secondary">Default metadata profile</span>
<select
bind:value={metadataId}
disabled={!profilesEnabled || metadataProfiles.isPending}
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50"
>
{#each metadataProfiles.data ?? [] as p (p.id)}
<option value={p.id}>{p.name}</option>
{/each}
</select>
</label>
<label class="block"> <label class="block">
<span class="block text-sm text-text-secondary">Default root folder</span> <span class="block text-sm text-text-secondary">Default root folder</span>
<select <select
@@ -13,6 +13,7 @@ vi.mock('@tanstack/svelte-query', async (orig) => {
vi.mock('$lib/api/admin', () => ({ vi.mock('$lib/api/admin', () => ({
createLidarrConfigQuery: vi.fn(), createLidarrConfigQuery: vi.fn(),
createQualityProfilesQuery: vi.fn(), createQualityProfilesQuery: vi.fn(),
createMetadataProfilesQuery: vi.fn(),
createRootFoldersQuery: vi.fn(), createRootFoldersQuery: vi.fn(),
putLidarrConfig: vi.fn(), putLidarrConfig: vi.fn(),
testLidarrConnection: vi.fn() testLidarrConnection: vi.fn()
@@ -22,6 +23,7 @@ import IntegrationsPage from './+page.svelte';
import { import {
createLidarrConfigQuery, createLidarrConfigQuery,
createQualityProfilesQuery, createQualityProfilesQuery,
createMetadataProfilesQuery,
createRootFoldersQuery, createRootFoldersQuery,
putLidarrConfig, putLidarrConfig,
testLidarrConnection testLidarrConnection
@@ -32,6 +34,7 @@ const cfgConnected: LidarrConfig = {
base_url: 'http://lidarr.local', base_url: 'http://lidarr.local',
api_key: '***', api_key: '***',
default_quality_profile_id: 1, default_quality_profile_id: 1,
default_metadata_profile_id: 1,
default_root_folder_path: '/music' default_root_folder_path: '/music'
}; };
@@ -40,6 +43,7 @@ const cfgUnset: LidarrConfig = {
base_url: '', base_url: '',
api_key: '', api_key: '',
default_quality_profile_id: 0, default_quality_profile_id: 0,
default_metadata_profile_id: 0,
default_root_folder_path: '' default_root_folder_path: ''
}; };
@@ -59,6 +63,14 @@ function setup(opts: { config?: LidarrConfig } = {}) {
] ]
}) })
); );
(createMetadataProfilesQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockQuery({
data: [
{ id: 1, name: 'Standard' },
{ id: 2, name: 'Singles only' }
]
})
);
(createRootFoldersQuery as ReturnType<typeof vi.fn>).mockReturnValue( (createRootFoldersQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockQuery({ data: [{ path: '/music', accessible: true, free_space: 0 }] }) mockQuery({ data: [{ path: '/music', accessible: true, free_space: 0 }] })
); );
@@ -164,10 +176,12 @@ describe('/admin/integrations', () => {
); );
}); });
test('Quality profile and root folder dropdowns populate from API', () => { test('Quality / metadata / root folder dropdowns populate from API', () => {
setup(); setup();
expect(screen.getByText('Standard')).toBeInTheDocument(); // 'Standard' appears in both quality + metadata fixtures, so use *AllBy*.
expect(screen.getAllByText('Standard').length).toBeGreaterThanOrEqual(2);
expect(screen.getByText('Lossless')).toBeInTheDocument(); expect(screen.getByText('Lossless')).toBeInTheDocument();
expect(screen.getByText('Singles only')).toBeInTheDocument();
expect(screen.getByText('/music')).toBeInTheDocument(); expect(screen.getByText('/music')).toBeInTheDocument();
}); });