diff --git a/contracts/api/v2/fixtures/admin_requests_ok.json b/contracts/api/v2/fixtures/admin_requests_ok.json index 5a5689a62c..145d38ed61 100644 --- a/contracts/api/v2/fixtures/admin_requests_ok.json +++ b/contracts/api/v2/fixtures/admin_requests_ok.json @@ -12,6 +12,7 @@ "state": "approved", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", @@ -50,6 +51,7 @@ "state": "approved", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", @@ -88,6 +90,7 @@ "state": "approved", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", diff --git a/contracts/api/v2/fixtures/cancel_request_ok.json b/contracts/api/v2/fixtures/cancel_request_ok.json index 236bf729f1..8ea0510810 100644 --- a/contracts/api/v2/fixtures/cancel_request_ok.json +++ b/contracts/api/v2/fixtures/cancel_request_ok.json @@ -10,6 +10,7 @@ "state": "approved", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", diff --git a/contracts/api/v2/fixtures/create_request_ok.json b/contracts/api/v2/fixtures/create_request_ok.json index b05c1137cb..b78a035bb5 100644 --- a/contracts/api/v2/fixtures/create_request_ok.json +++ b/contracts/api/v2/fixtures/create_request_ok.json @@ -10,6 +10,7 @@ "state": "pending", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", diff --git a/contracts/api/v2/fixtures/list_my_requests_ok.json b/contracts/api/v2/fixtures/list_my_requests_ok.json index ad66ba543f..89ee27cbd4 100644 --- a/contracts/api/v2/fixtures/list_my_requests_ok.json +++ b/contracts/api/v2/fixtures/list_my_requests_ok.json @@ -12,6 +12,7 @@ "state": "pending", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", @@ -43,6 +44,7 @@ "state": "processing", "seasons": [], "season_progress": [], + "options": [], "source": "direct", "requested_by_user_id": "1", "requested_by_profile_id": "p-owner", diff --git a/contracts/api/v2/fixtures/request_status_ok.json b/contracts/api/v2/fixtures/request_status_ok.json index aed187cf57..92c53ef120 100644 --- a/contracts/api/v2/fixtures/request_status_ok.json +++ b/contracts/api/v2/fixtures/request_status_ok.json @@ -1,5 +1,5 @@ { - "revision": "e4c71a296c2a0ebb2a1bb4ac60ea47b3a1b10c7287b3f49195a62b79cbaebb4e", + "revision": "52622ce7e197840f90e9b123de0628ba95e7d2795a50323c9c7dbcba63c1db95", "state": "available", "allowed": true, "requests_enabled": true, @@ -11,5 +11,6 @@ "watchlist_titles_supported": false, "watchlist_requests": false, "discover_rows_supported": true, - "remove_failed_supported": true + "remove_failed_supported": true, + "request_options_supported": true } diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json index 84b4caf961..a4072f9065 100644 --- a/contracts/api/v2/openapi.json +++ b/contracts/api/v2/openapi.json @@ -18706,6 +18706,14 @@ "AdminRequestActionInputBody": { "additionalProperties": false, "properties": { + "options": { + "additionalProperties": { + "type": "string" + }, + "description": "Approve only: the admin's picks from listAdminRequestOptions, as option key to chosen value. A pick replaces the requester's for that option. A key or value that is not offered is refused with validation_failed. Omitted: the requester's picks and the download server's own settings apply", + "maxProperties": 16, + "type": "object" + }, "reason": { "type": "string" } @@ -35335,6 +35343,10 @@ "description": "Whether removeFailedRequest is available: a requester can delete their own failed request that delivered nothing.", "type": "boolean" }, + "request_options_supported": { + "description": "Whether the server has listRequestOptions and takes options on createRequest. Whether a given title offers any depends on its download server and that server's request plugin.", + "type": "boolean" + }, "requests_enabled": { "type": "boolean" }, @@ -35375,6 +35387,7 @@ "watchlist_requests", "discover_rows_supported", "remove_failed_supported", + "request_options_supported", "revision", "state", "allowed" @@ -39914,6 +39927,13 @@ ], "type": "string" }, + "options": { + "description": "What the requester chose from listRequestOptions when making the request, or the approving admin from listAdminRequestOptions, in the words it was offered in; empty when nothing was chosen", + "items": { + "$ref": "#/components/schemas/RequestOptionChoice" + }, + "type": "array" + }, "outcome": { "description": "active, declined, cancelled, failed", "examples": [ @@ -40045,6 +40065,7 @@ "state", "seasons", "season_progress", + "options", "source", "is_anime", "targets", @@ -40096,6 +40117,14 @@ ], "type": "string" }, + "options": { + "additionalProperties": { + "type": "string" + }, + "description": "The requester's picks from listRequestOptions for this title, as option key to chosen value. A key or value that is not offered is refused with validation_failed. Omitted: the download server's own settings apply", + "maxProperties": 16, + "type": "object" + }, "overview": { "type": "string" }, @@ -49489,6 +49518,124 @@ ], "type": "object" }, + "RequestOption": { + "additionalProperties": false, + "properties": { + "choices": { + "description": "The values on offer; never empty", + "items": { + "$ref": "#/components/schemas/RequestOptionValue" + }, + "type": "array" + }, + "default": { + "description": "The value to preselect; always one of choices. It is the download server's own setting when that is on offer, and the first choice otherwise, so send the selected value of every option, also when it is the default. A value that is the server's own setting is not stored as a pick", + "examples": [ + "default" + ], + "type": "string" + }, + "key": { + "description": "The key to send in createRequest's options", + "examples": [ + "radarr_profile_id" + ], + "type": "string" + }, + "label": { + "description": "The option's name", + "examples": [ + "Quality" + ], + "type": "string" + } + }, + "required": [ + "key", + "label", + "default", + "choices" + ], + "type": "object" + }, + "RequestOptionChoice": { + "additionalProperties": false, + "properties": { + "key": { + "description": "The option's key", + "examples": [ + "radarr_profile_id" + ], + "type": "string" + }, + "label": { + "description": "The option's name", + "examples": [ + "Quality" + ], + "type": "string" + }, + "value": { + "description": "The chosen value", + "examples": [ + "4" + ], + "type": "string" + }, + "value_label": { + "description": "The chosen value's name when it was chosen", + "examples": [ + "Ultra-HD" + ], + "type": "string" + } + }, + "required": [ + "key", + "label", + "value", + "value_label" + ], + "type": "object" + }, + "RequestOptionList": { + "additionalProperties": false, + "properties": { + "options": { + "description": "Empty, never null, when the title's download server offers no choice, or its choices cannot be read right now", + "items": { + "$ref": "#/components/schemas/RequestOption" + }, + "type": "array" + } + }, + "required": [ + "options" + ], + "type": "object" + }, + "RequestOptionValue": { + "additionalProperties": false, + "properties": { + "label": { + "examples": [ + "Ultra-HD" + ], + "type": "string" + }, + "value": { + "examples": [ + "4" + ], + "type": "string" + } + }, + "required": [ + "value", + "label" + ], + "type": "object" + }, "RequestSeasonProgress": { "additionalProperties": false, "properties": { @@ -123498,6 +123645,162 @@ "x-silo-service-backed": true } }, + "/api/v2/admin/requests/{id}/options": { + "get": { + "operationId": "listAdminRequestOptions", + "parameters": [ + { + "description": "Optional. When present, it must name the authenticated account's primary profile; an absent header is accepted.", + "in": "header", + "name": "X-Profile-Id", + "schema": { + "examples": [ + "1" + ], + "type": "string" + } + }, + { + "description": "Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked", + "in": "header", + "name": "X-Profile-Token", + "schema": { + "examples": [ + "pvt_5f3a9c1e7b2d4e8fa0c6" + ], + "type": "string" + } + }, + { + "description": "The request", + "in": "path", + "name": "id", + "required": true, + "schema": { + "description": "The request", + "examples": [ + "1834729" + ], + "minLength": 1, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestOptionList" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "406": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Acceptable" + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests" + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Manage media requests and their configuration.", + "tags": [ + "admin" + ], + "x-silo-class": "acting_admin", + "x-silo-service-backed": true + } + }, "/api/v2/admin/requests/{id}/retry": { "post": { "operationId": "adminRetryRequest", @@ -213598,6 +213901,191 @@ "x-silo-service-backed": true } }, + "/api/v2/requests/options/{media_type}/{tmdb_id}": { + "get": { + "operationId": "listRequestOptions", + "parameters": [ + { + "description": "The household profile acting for this request; it must belong to the authenticated account.", + "in": "header", + "name": "X-Profile-Id", + "required": true, + "schema": { + "examples": [ + "1" + ], + "type": "string" + } + }, + { + "description": "Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked", + "in": "header", + "name": "X-Profile-Token", + "schema": { + "examples": [ + "pvt_5f3a9c1e7b2d4e8fa0c6" + ], + "type": "string" + } + }, + { + "description": "The media type", + "in": "path", + "name": "media_type", + "required": true, + "schema": { + "description": "The media type", + "enum": [ + "movie", + "series" + ], + "examples": [ + "movie" + ], + "type": "string" + } + }, + { + "description": "TMDB identifier (external, not a Silo ID)", + "in": "path", + "name": "tmdb_id", + "required": true, + "schema": { + "description": "TMDB identifier (external, not a Silo ID)", + "examples": [ + 949 + ], + "format": "int64", + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestOptionList" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Bad Request" + }, + "401": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "406": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Acceptable" + }, + "409": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests" + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "List the download server settings the viewer may choose when requesting a title.", + "tags": [ + "requests" + ], + "x-silo-class": "profile_scoped", + "x-silo-service-backed": true + } + }, "/api/v2/requests/search": { "get": { "operationId": "searchRequestMedia", diff --git a/docs/architecture/api-contract.md b/docs/architecture/api-contract.md index a4e386f7e6..fdae9aea7d 100644 --- a/docs/architecture/api-contract.md +++ b/docs/architecture/api-contract.md @@ -2095,6 +2095,15 @@ series detail lists the regular seasons with availability and request coverage; requests carry `seasons`, `season_progress` and the `partially_available` state; `GET /api/v2/requests/status` advertises `season_requests_supported`. +A request can carry the requester's choice of download server settings +(`options` on `POST /api/v2/requests`), picked from +`GET /api/v2/requests/options/{media_type}/{tmdb_id}`. That operation asks the +title's download server, so a client calls it when the requester starts a +request, not per title shown. A key or value that is not offered answers +`validation_failed`. Requests carry what was chosen as `options`; +`GET /api/v2/requests/status` advertises `request_options_supported`. See +[Media requests](media-requests.md#requester-options). + While a request downloads, requests, their targets and the title detail's request state carry `download` (phase, percent, bytes, estimated completion, and when the server last heard from the download server), and diff --git a/docs/architecture/media-requests.md b/docs/architecture/media-requests.md index efe29e8ee0..9d64a7a5b2 100644 --- a/docs/architecture/media-requests.md +++ b/docs/architecture/media-requests.md @@ -351,6 +351,79 @@ The series detail lists each regular season with its availability (`missing`, has at most one open request: a second profile that wants the same series while a request is open follows it. +## Requester options + +A router plugin can let the requester, or the admin who approves, choose some +of a download server's settings for one request, such as a quality profile or +a root folder (`internal/requests/requester_options.go`). The plugin lists the +config fields in its manifest (`request_router.requester_options`): each names +a select field of its admin form, optionally a media type, a label, and a +second select in the same form in which an admin says per server who chooses: +`admin` (nobody; the saved value applies), `requester`, or `approver`. Because +it is a select, a routing rule can override it. The host reads the list from the +capability metadata stored at install, without launching the plugin. Whether a +server offers an option is the host's decision from that list and the server's +saved config; the plugin's RPCs are unchanged. + +`listRequestOptions` (`GET /api/v2/requests/options/{media_type}/{tmdb_id}`) +answers what the viewer may choose for a title. The host names the one server +the title would go to: the single usable connection when the media type has no +routes, otherwise the server routing sends the title's HD copy to (its 4K copy +when it gets no HD one), with that route's overrides applied. It then asks the +plugin's `ListConfigOptions` for that server and returns the offered fields +with their choices. It returns no options when no single server can be named +(several connections without routes, or rules that need TMDB facts it could not +read), when the server offers none, and when the plugin call fails, since a +title can always be requested without a pick. The call reaches the download +server, so clients make it when the requester opens the request control, never +per card. + +`createRequest` takes the picks as `options` (option key to value). The host +lists the offer again and refuses the request with `validation_failed` on +`options` unless every key is offered and every value is one of its choices; it +also refuses when the choices cannot be read. This check is the authority: a +pick reaches the download server as a setting, so only a value the plugin +listed for that server passes, and a plugin cannot offer a config key routing +sets itself. The picks are stored on the request (`requester_choices`) with the +labels they were offered under and the server they were offered on. + +An option's `default` is the value a form preselects. It is the server's own +setting when that is one of the choices, and the first choice otherwise (a +saved profile that was since deleted, say). A client therefore sends the +selected value of every option it showed, the default included, so what the +requester saw is what applies. A pick that is the server's own setting is not +stored: that setting applies anyway, and it keeps following the server. +Listing the options runs the same access check as creating a request, so an +account that may not request cannot read the choices. + +At submission the picks are set in that server's config, over the server's own +values and the route's overrides, and the plugin reads its config as always. +They apply only to the server they were offered on, and only while that server +still offers the option: picks for another server (routing changed since), or +for an option the server no longer leaves to whoever picked, are left out and the server's own +settings apply. A value is an id or a path of one server and may name +something else on another. The plugin checks the value again when it submits. + +A request shows its picks as `options`, to the requester and to admins. They +are the plugin's own words (a profile name, a folder path), which the +requester already saw when choosing. `GET /requests/status` advertises +`request_options_supported`. v1 does not carry options. Requests made from the +watchlist, from a result card, or by a client that does not know options carry +none. + +An admin approving a pending request chooses the options the server leaves to +the approver, and may change those it leaves to requesters. +`GET /admin/requests/{id}/options` (`listAdminRequestOptions`) lists both for +the server the request would go to, each defaulting to the requester's pick +when there is one. `adminApproveRequest` takes the admin's picks as `options` +and checks them the same way; a pick replaces the requester's for that option +and is stored as the admin's, unless it is the requester's own pick, which +stays theirs. The picks are stored in the same guarded update that approves +the request, so when two admins approve at once the one whose approval wins is +the one whose picks apply. A request that is approved automatically, or +with several others at once, gets no approver pick, so an option left to the +approver keeps the server's saved value there. + ## Following a title A profile that finds a title someone else already requested can follow it diff --git a/go.mod b/go.mod index 549064e510..5a058f05ed 100644 --- a/go.mod +++ b/go.mod @@ -174,3 +174,5 @@ require ( ) replace github.com/zishang520/webtransport-go => ./internal/compat/zishang520-webtransport-go + +replace github.com/Silo-Server/silo-plugin-sdk => github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415 diff --git a/go.sum b/go.sum index 3925190e3b..99418f9da4 100644 --- a/go.sum +++ b/go.sum @@ -14,8 +14,6 @@ github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0g github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI= github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s= github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA= -github.com/Silo-Server/silo-plugin-sdk v0.31.0 h1:lpDqlkpv/GxnhBEzX2WY8nw3qILIKUI1EvjY8Mw/pu8= -github.com/Silo-Server/silo-plugin-sdk v0.31.0/go.mod h1:+r4X2TAiB9Gk22sUj1gFWUj65lll1P1/dMS+Ncvy3Y0= github.com/TwiN/go-color v1.4.1 h1:mqG0P/KBgHKVqmtL5ye7K0/Gr4l6hTksPgTgMk3mUzc= github.com/TwiN/go-color v1.4.1/go.mod h1:WcPf/jtiW95WBIsEeY1Lc/b8aaWoiqQpu5cf8WFxu+s= github.com/abadojack/whatlanggo v1.0.1 h1:19N6YogDnf71CTHm3Mp2qhYfkRdyvbgwWdd2EPxJRG4= @@ -153,6 +151,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= +github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415 h1:Hd76ckWisVLd+q/+SCyVKACQrq128i+gQS1b+p3IyyE= +github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415/go.mod h1:+r4X2TAiB9Gk22sUj1gFWUj65lll1P1/dMS+Ncvy3Y0= github.com/h2non/bimg v1.1.9 h1:WH20Nxko9l/HFm4kZCA3Phbgu2cbHvYzxwxn9YROEGg= github.com/h2non/bimg v1.1.9/go.mod h1:R3+UiYwkK4rQl6KVFTOFJHitgLbZXBZNFh2cv3AEbp8= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= diff --git a/internal/api/handlers/requests.go b/internal/api/handlers/requests.go index 77f0ba5daa..9b778e430c 100644 --- a/internal/api/handlers/requests.go +++ b/internal/api/handlers/requests.go @@ -26,6 +26,8 @@ type RequestService interface { DiscoverRow(ctx context.Context, viewer mediarequests.Viewer, rowID string, page int) (*mediarequests.DiscoverySection, error) GetDetail(ctx context.Context, viewer mediarequests.Viewer, mediaType mediarequests.MediaType, tmdbID int) (*mediarequests.MediaDetail, error) CreateRequest(ctx context.Context, viewer mediarequests.Viewer, input mediarequests.CreateRequestInput) (*mediarequests.Request, error) + // RequesterOptions backs v2's listRequestOptions; v1 has no such route. + RequesterOptions(ctx context.Context, viewer mediarequests.Viewer, mediaType mediarequests.MediaType, tmdbID int) ([]mediarequests.RequesterOption, error) ListMine(ctx context.Context, viewer mediarequests.Viewer, filter mediarequests.ListFilter) ([]*mediarequests.Request, error) ListAdmin(ctx context.Context, viewer mediarequests.Viewer, filter mediarequests.ListFilter) ([]*mediarequests.Request, error) GetRequest(ctx context.Context, viewer mediarequests.Viewer, id string) (*mediarequests.Request, error) diff --git a/internal/api/requests_wiring.go b/internal/api/requests_wiring.go index ba2c06a37c..d6a66b2bd0 100644 --- a/internal/api/requests_wiring.go +++ b/internal/api/requests_wiring.go @@ -33,12 +33,32 @@ func (a PluginRequestRouterAdapter) RouterFeatures(ctx context.Context, installa if err != nil { return mediarequests.RouterFeatures{}, err } - return mediarequests.RouterFeatures{ + features := mediarequests.RouterFeatures{ SupportsSeasons: descriptor.GetSupportsSeasons(), ReportsDownloadProgress: descriptor.GetReportsDownloadProgress(), APIKeyOptional: descriptor.GetApiKeyOptional(), BaseURLOptional: descriptor.GetBaseUrlOptional(), - }, nil + } + if declared := descriptor.GetRequesterOptions(); len(declared) > 0 { + // An option without its own label takes the admin form field's. + labels, err := a.Svc.RequestRouterFieldLabels(ctx, installationID, capabilityID) + if err != nil { + return mediarequests.RouterFeatures{}, err + } + for _, option := range declared { + label := option.GetLabel() + if label == "" { + label = labels[option.GetField()] + } + features.RequesterOptions = append(features.RequesterOptions, mediarequests.RouterRequesterOption{ + Field: option.GetField(), + MediaType: mediarequests.MediaType(option.GetMediaType()), + Label: label, + ChooserField: option.GetChooserField(), + }) + } + } + return features, nil } // AttachRequestRouter wires the plugin-backed router provider onto a requests diff --git a/internal/api/testdata/media_routes.txt b/internal/api/testdata/media_routes.txt index 6e9af8af7d..306db52c7a 100644 --- a/internal/api/testdata/media_routes.txt +++ b/internal/api/testdata/media_routes.txt @@ -360,6 +360,7 @@ POST /api/v2/admin/requests/{id}/approve non-media POST /api/v2/admin/requests/{id}/cancel non-media POST /api/v2/admin/requests/{id}/decline non-media GET /api/v2/admin/requests/{id}/events non-media +GET /api/v2/admin/requests/{id}/options non-media POST /api/v2/admin/requests/{id}/retry non-media GET /api/v2/admin/sections non-media POST /api/v2/admin/sections non-media @@ -853,6 +854,7 @@ GET /api/v2/requests/discover/{section} non-media DELETE /api/v2/requests/follows/{media_type}/{tmdb_id} non-media PUT /api/v2/requests/follows/{media_type}/{tmdb_id} non-media GET /api/v2/requests/mine non-media +GET /api/v2/requests/options/{media_type}/{tmdb_id} non-media GET /api/v2/requests/search non-media GET /api/v2/requests/status non-media DELETE /api/v2/requests/{id} non-media @@ -1715,6 +1717,7 @@ POST /api/v2/admin/requests/{id}/approve non-media POST /api/v2/admin/requests/{id}/cancel non-media POST /api/v2/admin/requests/{id}/decline non-media GET /api/v2/admin/requests/{id}/events non-media +GET /api/v2/admin/requests/{id}/options non-media POST /api/v2/admin/requests/{id}/retry non-media GET /api/v2/admin/sections non-media POST /api/v2/admin/sections non-media @@ -2208,6 +2211,7 @@ GET /api/v2/requests/discover/{section} non-media DELETE /api/v2/requests/follows/{media_type}/{tmdb_id} non-media PUT /api/v2/requests/follows/{media_type}/{tmdb_id} non-media GET /api/v2/requests/mine non-media +GET /api/v2/requests/options/{media_type}/{tmdb_id} non-media GET /api/v2/requests/search non-media GET /api/v2/requests/status non-media DELETE /api/v2/requests/{id} non-media diff --git a/internal/apiv2/admin_requests.go b/internal/apiv2/admin_requests.go index 7a57f7234e..ac12c48247 100644 --- a/internal/apiv2/admin_requests.go +++ b/internal/apiv2/admin_requests.go @@ -20,6 +20,7 @@ const adminActionRetry = "retry" const adminRequestSort = "-created_at" const opGetAdminRequestCapabilities = "getAdminRequestCapabilities" const opAdminApproveRequest = "adminApproveRequest" +const opListAdminRequestOptions = "listAdminRequestOptions" const opAdminDeclineRequest = "adminDeclineRequest" const opAdminCancelRequest = "adminCancelRequest" const opAdminRetryRequest = "adminRetryRequest" @@ -164,8 +165,17 @@ type AdminRequestActionInput struct { MediaRequestGetInput Body struct { Reason string `json:"reason,omitempty"` + // Options are the approving admin's picks from listAdminRequestOptions. + Options map[string]string `json:"options,omitempty" maxProperties:"16" doc:"Approve only: the admin's picks from listAdminRequestOptions, as option key to chosen value. A pick replaces the requester's for that option. A key or value that is not offered is refused with validation_failed. Omitted: the requester's picks and the download server's own settings apply"` } } + +// adminRequestApprover is a request service that lets the approving admin +// choose download server settings. +type adminRequestApprover interface { + ApproverOptions(ctx context.Context, viewer mediarequests.Viewer, id string) ([]mediarequests.RequesterOption, error) + ApproveWithOptions(ctx context.Context, viewer mediarequests.Viewer, id string, picks map[string]string) (*mediarequests.Request, error) +} type AdminRequestCapabilitiesOutput struct { Status int ETag string `header:"ETag"` @@ -244,7 +254,11 @@ func registerAdminRequests(reg *Registry) { var err error switch action { case adminActionApprove: - r, err = s.Approve(ctx, v, string(in.ID)) + if approver, ok := s.(adminRequestApprover); ok && len(in.Body.Options) > 0 { + r, err = approver.ApproveWithOptions(ctx, v, string(in.ID), in.Body.Options) + } else { + r, err = s.Approve(ctx, v, string(in.ID)) + } case adminActionDecline: r, err = s.Decline(ctx, v, string(in.ID), in.Body.Reason) case adminActionCancel: @@ -262,6 +276,20 @@ func registerAdminRequests(reg *Registry) { return &MediaRequestOutput{Body: mediaRequestOf(r, v)}, nil }) } + Register(reg, op(http.MethodGet, "/admin/requests/{id}/options", opListAdminRequestOptions, false), func(ctx context.Context, in *MediaRequestGetInput) (*RequestOptionListOutput, error) { + s, p := reg.adminRequestService() + if p != nil { + return nil, p + } + var options []mediarequests.RequesterOption + if approver, ok := s.(adminRequestApprover); ok { + var err error + if options, err = approver.ApproverOptions(ctx, adminRequestViewer(ctx), string(in.ID)); err != nil { + return nil, requestProblem(err) + } + } + return &RequestOptionListOutput{Body: requestOptionListOf(options)}, nil + }) Register(reg, op(http.MethodGet, "/admin/request-settings", opGetAdminRequestSettings, false), reg.getAdminRequestSettings) Register(reg, op(http.MethodPut, "/admin/request-settings", opUpdateAdminRequestSettings, true), reg.updateAdminRequestSettings) Register(reg, op(http.MethodGet, "/admin/request-users/{user_id}/limit", opGetAdminRequestUserLimit, false), reg.getAdminRequestUserLimit) diff --git a/internal/apiv2/request_lifecycle.go b/internal/apiv2/request_lifecycle.go index e503492bcb..066c7246ad 100644 --- a/internal/apiv2/request_lifecycle.go +++ b/internal/apiv2/request_lifecycle.go @@ -67,6 +67,9 @@ type FeatureStatus struct { DiscoverRowsSupported bool `json:"discover_rows_supported" doc:"Whether the Discover page follows an admin-defined layout: listDiscoverSections may hold rows beyond the six built-in ones, in any order, and lists every row in row_order; getDiscoverRow pages any title row."` // RemoveFailedSupported advertises DELETE /requests/{id}. RemoveFailedSupported bool `json:"remove_failed_supported" doc:"Whether removeFailedRequest is available: a requester can delete their own failed request that delivered nothing."` + // RequestOptionsSupported advertises listRequestOptions, options on + // createRequest and options on requests. + RequestOptionsSupported bool `json:"request_options_supported" doc:"Whether the server has listRequestOptions and takes options on createRequest. Whether a given title offers any depends on its download server and that server's request plugin."` } type RequestFeatureStatusOutput struct { Status int @@ -233,7 +236,7 @@ func registerRequestLifecycle(reg *Registry, requests RequestLifecycleService, p return nil, requestProblem(err) } } - return &RequestFeatureStatusOutput{Body: FeatureStatus{Capability: Capability{State: enabledCapabilityState(status.RequestsEnabled), Allowed: &allowed}, RequestsEnabled: status.RequestsEnabled, RatingRestrictionsEnforced: status.RatingRestrictionsEnforced, FollowSupported: true, SeasonRequestsSupported: true, MissingSeasonsRequestable: status.MissingSeasonsRequestable, DownloadProgressSupported: true, DiscoverRowsSupported: true, RemoveFailedSupported: true, + return &RequestFeatureStatusOutput{Body: FeatureStatus{Capability: Capability{State: enabledCapabilityState(status.RequestsEnabled), Allowed: &allowed}, RequestsEnabled: status.RequestsEnabled, RatingRestrictionsEnforced: status.RatingRestrictionsEnforced, FollowSupported: true, SeasonRequestsSupported: true, MissingSeasonsRequestable: status.MissingSeasonsRequestable, DownloadProgressSupported: true, DiscoverRowsSupported: true, RemoveFailedSupported: true, RequestOptionsSupported: true, WatchlistTitlesSupported: status.RequestsEnabled && reg.deps.WatchlistTitles != nil && reg.deps.WatchlistRequests != nil, WatchlistRequests: status.WatchlistRequests && allowed}}, nil }) Register(reg, op(http.MethodPost, "/requests/{id}/cancel", "cancelRequest", "Cancel an accessible request."), func(ctx context.Context, in *RequestCancelInput) (*MediaRequestOutput, error) { diff --git a/internal/apiv2/request_options.go b/internal/apiv2/request_options.go new file mode 100644 index 0000000000..bf2738714d --- /dev/null +++ b/internal/apiv2/request_options.go @@ -0,0 +1,79 @@ +package apiv2 + +import ( + "context" + + mediarequests "github.com/Silo-Server/silo-server/internal/requests" +) + +// Requester options: the download server settings a requester or approving +// admin may choose for one request. Kept apart from requests.go to stay under +// the file size limit. + +// RequestOptionChoice is one setting the requester chose for a request. +type RequestOptionChoice struct { + Key string `json:"key" doc:"The option's key" example:"radarr_profile_id"` + Label string `json:"label" doc:"The option's name" example:"Quality"` + Value string `json:"value" doc:"The chosen value" example:"4"` + ValueLabel string `json:"value_label" doc:"The chosen value's name when it was chosen" example:"Ultra-HD"` +} + +func requestOptionChoicesOf(choices mediarequests.RequesterChoices) []RequestOptionChoice { + out := make([]RequestOptionChoice, 0, len(choices.Choices)) + for _, c := range choices.Choices { + out = append(out, RequestOptionChoice{Key: c.Key, Label: c.Label, Value: c.Value, ValueLabel: c.ValueLabel}) + } + return out +} + +// RequestOption is one download server setting the viewer may choose when +// requesting a title. +type RequestOption struct { + Key string `json:"key" doc:"The key to send in createRequest's options" example:"radarr_profile_id"` + Label string `json:"label" doc:"The option's name" example:"Quality"` + Default string `json:"default" doc:"The value to preselect; always one of choices. It is the download server's own setting when that is on offer, and the first choice otherwise, so send the selected value of every option, also when it is the default. A value that is the server's own setting is not stored as a pick" example:"default"` + Choices []RequestOptionValue `json:"choices" doc:"The values on offer; never empty"` +} + +// RequestOptionValue is one value of a RequestOption. +type RequestOptionValue struct { + Value string `json:"value" example:"4"` + Label string `json:"label" example:"Ultra-HD"` +} + +// RequestOptionList is the listRequestOptions response body. +type RequestOptionList struct { + Options []RequestOption `json:"options" doc:"Empty, never null, when the title's download server offers no choice, or its choices cannot be read right now"` +} + +// RequestOptionListOutput is the listRequestOptions response. +type RequestOptionListOutput struct { + Body RequestOptionList +} + +// listRequestOptions answers which download server settings the viewer may +// choose for a title. It asks the server's request plugin, so clients call it +// when the requester opens the request control, not for every title shown. +func (reg *Registry) listRequestOptions(ctx context.Context, in *RequestMediaDetailInput) (*RequestOptionListOutput, error) { + svc, viewer, p := reg.requestViewer(ctx) + if p != nil { + return nil, p + } + options, err := svc.RequesterOptions(ctx, viewer, mediarequests.MediaType(in.MediaType), in.TMDBID) + if err != nil { + return nil, requestProblem(err) + } + return &RequestOptionListOutput{Body: requestOptionListOf(options)}, nil +} + +func requestOptionListOf(options []mediarequests.RequesterOption) RequestOptionList { + out := RequestOptionList{Options: make([]RequestOption, 0, len(options))} + for _, option := range options { + values := make([]RequestOptionValue, 0, len(option.Choices)) + for _, choice := range option.Choices { + values = append(values, RequestOptionValue{Value: choice.Value, Label: choice.Label}) + } + out.Options = append(out.Options, RequestOption{Key: option.Key, Label: option.Label, Default: option.Default, Choices: values}) + } + return out +} diff --git a/internal/apiv2/requests.go b/internal/apiv2/requests.go index 77e19232b5..967d78e97c 100644 --- a/internal/apiv2/requests.go +++ b/internal/apiv2/requests.go @@ -225,6 +225,7 @@ type MediaRequest struct { State string `json:"state" doc:"The one state to show a user: pending, approved, processing, partially_available (some requested seasons are in the library), available (in the library), declined, cancelled or failed" example:"pending"` //nolint:misspell // the store's spelling Seasons []int `json:"seasons" doc:"Series: the requested season numbers; empty means the whole series (requests made through v1 or before season requests)"` SeasonProgress []RequestSeasonProgress `json:"season_progress" doc:"Series season requests: each requested season's episodes, once the series is in the library; empty otherwise"` + Options []RequestOptionChoice `json:"options" doc:"What the requester chose from listRequestOptions when making the request, or the approving admin from listAdminRequestOptions, in the words it was offered in; empty when nothing was chosen"` OutcomeReason string `json:"outcome_reason,omitempty" doc:"Why the request was declined or withdrawn, when a reason was given"` Source string `json:"source" doc:"What created the request: direct (the Request button or an API create) or watchlist (adding a title that is not in the library to a watchlist); more values may be added" example:"direct"` RequestedByUserID ID `json:"requested_by_user_id,omitempty" example:"1"` @@ -266,6 +267,8 @@ type MediaRequestCreate struct { PosterPath string `json:"poster_path,omitempty" doc:"TMDB image path"` BackdropPath string `json:"backdrop_path,omitempty" doc:"TMDB image path"` Seasons []int `json:"seasons,omitempty" maxItems:"200" doc:"Series only: the season numbers to request, starting at 1 (a season below 1 is refused). Omitted: every aired season not yet complete in the library" example:"[2,3]"` + // Options are the requester's picks from listRequestOptions. + Options map[string]string `json:"options,omitempty" maxProperties:"16" doc:"The requester's picks from listRequestOptions for this title, as option key to chosen value. A key or value that is not offered is refused with validation_failed. Omitted: the download server's own settings apply"` } // MediaRequestCreateInput is the createRequest request. @@ -365,6 +368,7 @@ const ( opGetRequest = "getRequest" opSearchRequestMedia = "searchRequestMedia" opGetRequestMediaDetail = "getRequestMediaDetail" + opListRequestOptions = "listRequestOptions" opListDiscoverSections = "listDiscoverSections" opGetDiscoverSection = "getDiscoverSection" opGetDiscoverRow = "getDiscoverRow" @@ -409,6 +413,11 @@ func registerRequests(reg *Registry) { detail.Errors = []int{http.StatusConflict} Register(reg, Operation{Operation: detail, Class: ClassProfileScoped, ServiceBacked: true}, reg.getRequestMediaDetail) + options := humaOp(http.MethodGet, Prefix+"/requests/options/{media_type}/{tmdb_id}", opListRequestOptions, requestsTag, + "List the download server settings the viewer may choose when requesting a title.") + options.Errors = []int{http.StatusConflict} + Register(reg, Operation{Operation: options, Class: ClassProfileScoped, ServiceBacked: true}, reg.listRequestOptions) + sections := humaOp(http.MethodGet, Prefix+"/requests/discover", opListDiscoverSections, requestsTag, "List the Discover page's rows in the admin's order, with each title row's first page.") sections.Errors = []int{http.StatusConflict} @@ -523,6 +532,7 @@ func (reg *Registry) createRequest(ctx context.Context, in *MediaRequestCreateIn PosterPath: in.Body.PosterPath, BackdropPath: in.Body.BackdropPath, Seasons: in.Body.Seasons, + Options: in.Body.Options, }) if err != nil { return nil, requestProblem(err) @@ -842,6 +852,7 @@ func mediaRequestOf(r *mediarequests.Request, viewer mediarequests.Viewer) Media State: string(r.State()), Seasons: NonNil(r.Seasons), SeasonProgress: requestSeasonProgressOf(r.SeasonProgress), + Options: requestOptionChoicesOf(r.RequesterChoices), OutcomeReason: r.OutcomeReason, Source: string(requestSourceOf(r.Source)), IsAnime: r.IsAnime, diff --git a/internal/apiv2/requests_test.go b/internal/apiv2/requests_test.go index 2a344228ee..9f342b91f5 100644 --- a/internal/apiv2/requests_test.go +++ b/internal/apiv2/requests_test.go @@ -21,6 +21,8 @@ type fakeRequests struct { err error // detailDownload is the download progress GetDetail reports. detailDownload *mediarequests.DownloadProgress + // options is what RequesterOptions offers. + options []mediarequests.RequesterOption lastViewer mediarequests.Viewer lastFilter mediarequests.ListFilter @@ -99,6 +101,13 @@ func (f *fakeRequests) GetDetail(_ context.Context, viewer mediarequests.Viewer, }, nil } +func (f *fakeRequests) RequesterOptions(_ context.Context, viewer mediarequests.Viewer, mediaType mediarequests.MediaType, tmdbID int) ([]mediarequests.RequesterOption, error) { + if err := f.record(viewer, "options", mediaType, tmdbID); err != nil { + return nil, err + } + return f.options, nil +} + func (f *fakeRequests) CreateRequest(_ context.Context, viewer mediarequests.Viewer, input mediarequests.CreateRequestInput) (*mediarequests.Request, error) { f.lastCreate = input if err := f.record(viewer, "create"); err != nil { diff --git a/internal/apiv2/router.go b/internal/apiv2/router.go index 8bd77036d3..064874eb75 100644 --- a/internal/apiv2/router.go +++ b/internal/apiv2/router.go @@ -1119,6 +1119,7 @@ type MediaRequestService interface { DiscoverRow(ctx context.Context, viewer mediarequests.Viewer, rowID string, page int) (*mediarequests.DiscoverySection, error) GetDetail(ctx context.Context, viewer mediarequests.Viewer, mediaType mediarequests.MediaType, tmdbID int) (*mediarequests.MediaDetail, error) CreateRequest(ctx context.Context, viewer mediarequests.Viewer, input mediarequests.CreateRequestInput) (*mediarequests.Request, error) + RequesterOptions(ctx context.Context, viewer mediarequests.Viewer, mediaType mediarequests.MediaType, tmdbID int) ([]mediarequests.RequesterOption, error) ListMine(ctx context.Context, viewer mediarequests.Viewer, filter mediarequests.ListFilter) ([]*mediarequests.Request, error) GetRequest(ctx context.Context, viewer mediarequests.Viewer, id string) (*mediarequests.Request, error) ListStudios(ctx context.Context, viewer mediarequests.Viewer) ([]mediarequests.DiscoverBrandCard, error) diff --git a/internal/plugins/request_router.go b/internal/plugins/request_router.go index 1f8e83902b..6b84a9e8b3 100644 --- a/internal/plugins/request_router.go +++ b/internal/plugins/request_router.go @@ -16,6 +16,36 @@ import ( // or one the installation does not declare, yields an empty descriptor: every // optional request-router feature off. func (s *Service) RequestRouterDescriptor(ctx context.Context, installationID int, capabilityID string) (*pluginv1.RequestRouterDescriptor, error) { + descriptor, err := s.requestRouterCapability(ctx, installationID, capabilityID) + if err != nil { + return nil, err + } + if router := descriptor.GetRequestRouter(); router != nil { + return router, nil + } + return &pluginv1.RequestRouterDescriptor{}, nil +} + +// RequestRouterFieldLabels returns the label of each field in the admin forms +// of an installation's request router capability, keyed by config key. Like +// RequestRouterDescriptor it reads stored metadata only. +func (s *Service) RequestRouterFieldLabels(ctx context.Context, installationID int, capabilityID string) (map[string]string, error) { + descriptor, err := s.requestRouterCapability(ctx, installationID, capabilityID) + if err != nil { + return nil, err + } + labels := map[string]string{} + for _, schema := range descriptor.GetConfigSchema() { + for _, field := range schema.GetAdminForm().GetFields() { + labels[field.GetKey()] = field.GetLabel() + } + } + return labels, nil +} + +// requestRouterCapability returns the stored descriptor of an installation's +// request router capability, or nil when the installation declares none. +func (s *Service) requestRouterCapability(ctx context.Context, installationID int, capabilityID string) (*pluginv1.CapabilityDescriptor, error) { if s == nil || s.installations == nil { return nil, errors.New("plugin installations are not configured") } @@ -31,10 +61,7 @@ func (s *Service) RequestRouterDescriptor(ctx context.Context, installationID in if err != nil { return nil, fmt.Errorf("decode request router capability %q of installation %d: %w", capabilityID, installationID, err) } - if router := descriptor.GetRequestRouter(); router != nil { - return router, nil - } - break + return descriptor, nil } - return &pluginv1.RequestRouterDescriptor{}, nil + return nil, nil } diff --git a/internal/requests/repository.go b/internal/requests/repository.go index 52ecd20a60..d28fc07560 100644 --- a/internal/requests/repository.go +++ b/internal/requests/repository.go @@ -371,25 +371,26 @@ func (r *Repository) insertRequest( if err != nil { return nil, err } + choices := encodeRequesterChoices(input.Choices) row := exec.QueryRow(ctx, ` INSERT INTO media_requests ( id, provider, media_type, tmdb_id, tvdb_id, imdb_id, title, year, overview, poster_path, backdrop_path, status, outcome, requested_by_user_id, requested_by_profile_id, is_anime, created_at, updated_at, approved_at, - routing_facts, seasons, source + routing_facts, seasons, source, requester_choices ) VALUES ( $1, 'tmdb', $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $16, $17, - $18, $19, $20 + $18, $19, $20, $21 ) RETURNING `+requestColumns(), input.ID, input.Input.MediaType, input.Input.TMDBID, tvdbID, strings.TrimSpace(input.Input.IMDbID), strings.TrimSpace(input.Input.Title), year, strings.TrimSpace(input.Input.Overview), strings.TrimSpace(input.Input.PosterPath), strings.TrimSpace(input.Input.BackdropPath), status, outcome, input.Requester.UserID, input.Requester.ProfileID, input.IsAnime, now, approvedAt, - facts, nonNilSeasons(input.Input.Seasons), requestSource(input.Input.Source)) + facts, nonNilSeasons(input.Input.Seasons), requestSource(input.Input.Source), choices) req, err := scanRequest(row) if err != nil { return nil, fmt.Errorf("insert request: %w", err) @@ -647,6 +648,19 @@ func guardMiss(ctx context.Context, exec requestExecutor, id string) error { } func (r *Repository) SetStatus(ctx context.Context, id string, from StateGuard, status Status, actor Viewer) (*Request, error) { + return r.setStatus(ctx, id, from, status, actor, nil) +} + +// ApproveWithRequesterChoices approves a pending request and replaces its +// picks in one guarded update, so of two admins approving at once the one +// whose approval wins also has their picks stored. +func (r *Repository) ApproveWithRequesterChoices(ctx context.Context, id string, choices RequesterChoices, actor Viewer) (*Request, error) { + return r.setStatus(ctx, id, guardPending, StatusApproved, actor, encodeRequesterChoices(choices)) +} + +// setStatus applies a guarded status transition. choices, when not nil, +// replaces the request's picks in the same update. +func (r *Repository) setStatus(ctx context.Context, id string, from StateGuard, status Status, actor Viewer, choices []byte) (*Request, error) { tx, err := r.pool.Begin(ctx) if err != nil { return nil, fmt.Errorf("begin request status transaction: %w", err) @@ -663,10 +677,11 @@ func (r *Repository) SetStatus(ctx context.Context, id string, from StateGuard, completed_at = CASE WHEN $5 = 'completed' AND completed_at IS NULL THEN now() ELSE completed_at END, submit_attempts = CASE WHEN $5 = 'approved' THEN 0 ELSE submit_attempts END, submit_lease_until = CASE WHEN $5 = 'approved' THEN NULL ELSE submit_lease_until END, - next_submit_at = CASE WHEN $5 = 'approved' THEN NULL ELSE next_submit_at END + next_submit_at = CASE WHEN $5 = 'approved' THEN NULL ELSE next_submit_at END, + requester_choices = COALESCE($6::jsonb, requester_choices) WHERE id = $1 AND `+guardCondition+` - RETURNING `+requestColumns(), id, statuses, outcomes, unsent, status)) + RETURNING `+requestColumns(), id, statuses, outcomes, unsent, status, choices)) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, guardMiss(ctx, tx, id) @@ -1482,7 +1497,8 @@ func requestColumns() string { overview, poster_path, backdrop_path, status, outcome, requested_by_user_id, requested_by_profile_id, is_anime, last_error, created_at, updated_at, approved_at, completed_at, - submit_attempts, submit_lease_until, next_submit_at, outcome_reason, routing_facts, seasons, source` + submit_attempts, submit_lease_until, next_submit_at, outcome_reason, routing_facts, seasons, source, + requester_choices` } type requestScanner interface { @@ -1493,7 +1509,7 @@ func scanRequest(row requestScanner) (*Request, error) { var req Request var tvdbID, year sql.NullInt64 var approvedAt, completedAt, submitLeaseUntil, nextSubmitAt sql.NullTime - var rawFacts []byte + var rawFacts, rawChoices []byte if err := row.Scan( &req.ID, &req.Provider, @@ -1523,9 +1539,15 @@ func scanRequest(row requestScanner) (*Request, error) { &rawFacts, &req.Seasons, &req.Source, + &rawChoices, ); err != nil { return nil, err } + choices, err := decodeRequesterChoices(rawChoices) + if err != nil { + return nil, err + } + req.RequesterChoices = choices facts, err := decodeRoutingFacts(rawFacts) if err != nil { return nil, err diff --git a/internal/requests/requester_choices_db_test.go b/internal/requests/requester_choices_db_test.go new file mode 100644 index 0000000000..a5b64151ae --- /dev/null +++ b/internal/requests/requester_choices_db_test.go @@ -0,0 +1,66 @@ +package requests + +import ( + "errors" + "reflect" + "testing" +) + +func TestRequesterChoicesDatabase(t *testing.T) { + repo, _ := lifecycleTestRepository(t) + ctx := t.Context() + first := RequesterChoices{ + IntegrationID: "seerr-1", + Choices: []RequesterChoice{{Key: "radarr_profile_id", Label: "Quality", Value: "4", ValueLabel: "HD-1080p"}}, + } + created, err := repo.CreateRequest(ctx, CreateRequestRecord{ + ID: "picked", + Input: CreateRequestInput{MediaType: MediaTypeMovie, TMDBID: 601, Title: "Picked"}, + Choices: first, + Status: StatusPending, + Outcome: OutcomeActive, + Requester: Viewer{UserID: 1, ProfileID: "profile"}, + }) + if err != nil { + t.Fatalf("create: %v", err) + } + if !reflect.DeepEqual(created.RequesterChoices, first) { + t.Fatalf("created choices = %+v, want %+v", created.RequesterChoices, first) + } + + // An admin approving replaces the picks in the same update that approves. + second := RequesterChoices{ + IntegrationID: "seerr-1", + Choices: []RequesterChoice{{Key: "radarr_profile_id", Label: "Quality", Value: "7", ValueLabel: "Ultra-HD", ByAdmin: true}}, + } + approved, err := repo.ApproveWithRequesterChoices(ctx, "picked", second, Viewer{UserID: 9, IsAdmin: true}) + if err != nil { + t.Fatalf("approve with choices: %v", err) + } + if approved.Status != StatusApproved || !reflect.DeepEqual(approved.RequesterChoices, second) { + t.Fatalf("approved = %s %+v, want approved with %+v", approved.Status, approved.RequesterChoices, second) + } + + // A second approval loses: the request is no longer pending, and the + // winner's picks stay. + if _, err := repo.ApproveWithRequesterChoices(ctx, "picked", first, Viewer{UserID: 8, IsAdmin: true}); !errors.Is(err, ErrInvalidState) { + t.Fatalf("second approval: err = %v, want ErrInvalidState", err) + } + got, err := repo.GetRequest(ctx, "picked") + if err != nil { + t.Fatalf("get: %v", err) + } + if !reflect.DeepEqual(got.RequesterChoices, second) { + t.Fatalf("stored choices = %+v, want the winner's %+v", got.RequesterChoices, second) + } + + // A plain status change leaves the picks alone. + insertLifecycleRequest(t, repo, "plain", 1, 602, StatusPending) + plain, err := repo.SetStatus(ctx, "plain", guardPending, StatusApproved, Viewer{UserID: 9, IsAdmin: true}) + if err != nil { + t.Fatalf("set status: %v", err) + } + if len(plain.RequesterChoices.Choices) != 0 { + t.Fatalf("plain approval choices = %+v, want none", plain.RequesterChoices) + } +} diff --git a/internal/requests/requester_options.go b/internal/requests/requester_options.go new file mode 100644 index 0000000000..8184c45ca1 --- /dev/null +++ b/internal/requests/requester_options.go @@ -0,0 +1,436 @@ +package requests + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "maps" + "slices" + "strings" + "time" + + "github.com/Silo-Server/silo-server/internal/logredact" +) + +// Requester options: a router plugin can let the requester choose some of a +// download server's settings for one request, such as a quality profile. The +// plugin lists the config fields in its manifest; the host offers the choices +// the plugin reports for the server the request would go to, checks a pick +// against them when the request is made, stores it, and at submission sets it +// in that server's config over the server's own value and a route's. The +// plugin reads its config as always. + +// RouterRequesterOption is a config field a router capability lets requesters +// choose, as its manifest declares it. +type RouterRequesterOption struct { + Field string + // MediaType limits the option to one media type; empty means both. + MediaType MediaType + // Label names the choice to requesters. + Label string + // ChooserField is the config select that says who chooses the option + // on a server; empty lets requesters choose on every server. + ChooserField string +} + +// RequesterOption is one setting a requester may choose for a title, with the +// values on offer. +type RequesterOption struct { + Key string + Label string + // Default is the value in effect when the requester picks nothing, when + // it is one of the choices; otherwise the first choice. + Default string + // DefaultIsSaved reports that Default is the server's own setting, which + // applies without a pick. It is false when that setting is not one of + // the choices and Default is only what a form shows first. + DefaultIsSaved bool + Choices []RouterOption +} + +// RequesterChoice is one pick, with the words it was offered in so it can be +// shown after the server's lists change. +type RequesterChoice struct { + Key string `json:"key"` + Label string `json:"label"` + Value string `json:"value"` + ValueLabel string `json:"value_label"` + // ByAdmin marks a pick an admin made when approving. It applies when the + // server leaves the option to the approver or to requesters. + ByAdmin bool `json:"by_admin,omitempty"` +} + +// RequesterChoices are a request's picks and the server they were offered on. +// They apply only to that server: a value is an id or a path of that server +// and may name something else on another. +type RequesterChoices struct { + IntegrationID string `json:"integration_id,omitempty"` + Choices []RequesterChoice `json:"choices,omitempty"` +} + +// maxRequesterChoices bounds a request's picks. A plugin declares a handful +// of options at most. +const maxRequesterChoices = 16 + +// requesterOptionsTimeout bounds the plugin call that lists a server's +// choices, so a download server that does not answer cannot hold a request +// dialog open. +const requesterOptionsTimeout = 15 * time.Second + +// encodeRequesterChoices writes the picks as JSON. The value holds only +// strings, so encoding cannot fail. +func encodeRequesterChoices(choices RequesterChoices) []byte { + raw, _ := json.Marshal(choices) + return raw +} + +func decodeRequesterChoices(raw []byte) (RequesterChoices, error) { + var choices RequesterChoices + if len(raw) == 0 { + return choices, nil + } + if err := json.Unmarshal(raw, &choices); err != nil { + return RequesterChoices{}, fmt.Errorf("decode requester choices: %w", err) + } + return choices, nil +} + +// Who chooses an option on a server: the values of its chooser select. +const ( + chooserAdmin = "admin" + chooserRequester = "requester" + chooserApprover = "approver" +) + +// chooserOf reads who chooses option on the server with config. Any value +// the host does not know, or none, leaves the admin's saved setting alone. +func chooserOf(option RouterRequesterOption, config map[string]any) string { + if option.ChooserField == "" { + return chooserRequester + } + switch value, _ := config[option.ChooserField].(string); strings.TrimSpace(value) { + case chooserRequester: + return chooserRequester + case chooserApprover: + return chooserApprover + } + return chooserAdmin +} + +// offeredRequesterOptions keeps the declared options a server offers for a +// media type: to requesters those they choose, and to an approving admin +// those as well as the admin's own. An option on a key routing sets itself +// is never offered. +func offeredRequesterOptions(declared []RouterRequesterOption, mediaType MediaType, config map[string]any, approver bool) []RouterRequesterOption { + var out []RouterRequesterOption + for _, option := range declared { + if option.Field == "" || slices.Contains(routingOwnedConfigKeys, option.Field) { + continue + } + if option.MediaType != "" && option.MediaType != mediaType { + continue + } + chooser := chooserOf(option, config) + if chooser == chooserRequester || (approver && chooser == chooserApprover) { + out = append(out, option) + } + } + return out +} + +// requesterDestination is the one server a request's HD copy (or its 4K copy, +// when it gets no HD one) would go to right now, with the route's overrides +// applied. ok is false when no single server can be named: nothing is +// configured, the plugin picks among several servers, or the routes cannot +// decide yet. +func (s *Service) requesterDestination(ctx context.Context, fc *fulfillContext, probe Request) (conn ResolvedRouterConnection, installationID int, capabilityID string, ok bool) { + routes := fc.routesFor(probe.MediaType) + if len(routes) == 0 { + conns, installationID, capabilityID, err := s.resolveRouterConnections(ctx, fc, probe.MediaType) + if err != nil || len(conns) != 1 { + return ResolvedRouterConnection{}, 0, "", false + } + return conns[0], installationID, capabilityID, true + } + if !probe.RoutingFacts.Captured() && !isStandardRouting(routes, probe.MediaType) && routesUseConditions(routes, probe.MediaType) { + // TMDB could not supply what the rules match on. + return ResolvedRouterConnection{}, 0, "", false + } + allowed, _ := s.allowedQualities(ctx, probe, fc.settings) + decisions := decideRoutes(routes, probe, allowed) + for _, q := range []Quality{Quality1080p, Quality2160p} { + decision, decided := decisions[q] + if !decided || decision.Skip { + continue + } + conn, installationID, capabilityID, err := s.routedConnection(ctx, fc, decision, probe.MediaType, q) + if err != nil { + return ResolvedRouterConnection{}, 0, "", false + } + return conn, installationID, capabilityID, true + } + return ResolvedRouterConnection{}, 0, "", false +} + +// requesterOffer lists what may be chosen for probe, and the server that +// offers it: what the server offers requesters, or an approving admin. No options, without an error, means there +// is nothing to choose. An error means the server's choices could not be read. +func (s *Service) requesterOffer(ctx context.Context, probe Request, approver bool) (integrationID string, options []RequesterOption, err error) { + if s.router == nil { + return "", nil, nil + } + fc, err := s.newFulfillContext(ctx) + if err != nil { + return "", nil, err + } + conn, installationID, capabilityID, ok := s.requesterDestination(ctx, fc, probe) + if !ok { + return "", nil, nil + } + features, err := s.routerFeatures(ctx, fc, installationID, capabilityID) + if err != nil { + return "", nil, err + } + offered := offeredRequesterOptions(features.RequesterOptions, probe.MediaType, conn.Config, approver) + if len(offered) == 0 { + return "", nil, nil + } + ctx, cancel := context.WithTimeout(ctx, requesterOptionsTimeout) + defer cancel() + lists, err := s.router.ListConfigOptions(ctx, installationID, capabilityID, conn) + if err != nil { + return "", nil, fmt.Errorf("list the download server's choices: %w", err) + } + for _, option := range offered { + choices := lists[option.Field] + if len(choices) == 0 { + continue + } + // The server's own value is the default when it is on offer. + // Otherwise the first choice is shown, and it is not what applies + // without a pick, so resolveChoices must keep a pick of it. + current := fmt.Sprint(conn.Config[option.Field]) + saved := slices.ContainsFunc(choices, func(c RouterOption) bool { return c.Value == current }) + if !saved { + current = choices[0].Value + } + label := option.Label + if label == "" { + label = option.Field + } + options = append(options, RequesterOption{Key: option.Field, Label: label, Default: current, DefaultIsSaved: saved, Choices: choices}) + } + return conn.ID, options, nil +} + +// requestProbe stands in for a request that does not exist yet, so routing +// can say where it would go. +func requestProbe(viewer Viewer, mediaType MediaType, tmdbID int, facts RoutingFacts) Request { + return Request{ + MediaType: mediaType, TMDBID: tmdbID, + RequestedByUserID: viewer.UserID, RequestedByProfileID: viewer.ProfileID, + RoutingFacts: facts, IsAnime: facts.Anime, + } +} + +// RequesterOptions returns the download server settings the viewer may choose +// when requesting a title. It is empty when the server the title would go to +// offers none, and also when its choices cannot be read: the request can +// still be made without a pick. +func (s *Service) RequesterOptions(ctx context.Context, viewer Viewer, mediaType MediaType, tmdbID int) ([]RequesterOption, error) { + if err := validateViewer(viewer); err != nil { + return nil, err + } + if s == nil || s.store == nil { + return nil, errors.New("request service is not configured") + } + if err := s.ensureRequestsEnabled(ctx); err != nil { + return nil, err + } + if err := s.ensureViewerRequestsAllowed(ctx, viewer.UserID); err != nil { + return nil, err + } + mediaType, err := normalizeMediaType(mediaType) + if err != nil { + return nil, err + } + if tmdbID <= 0 { + return nil, fmt.Errorf("%w: tmdb_id is required", ErrInvalidInput) + } + // The same access check as creating a request: someone who may not + // request must not read the server's choices, which can be folder paths. + policy, err := s.EffectivePolicy(ctx, viewer.UserID) + if err != nil { + return nil, err + } + if err := validateCreateAccess(policy); err != nil { + return nil, err + } + facts := s.routingFacts(ctx, s.requestDetail(ctx, mediaType, tmdbID)) + _, options, err := s.requesterOffer(ctx, requestProbe(viewer, mediaType, tmdbID, facts), false) + if err != nil { + slog.WarnContext(ctx, "requests: could not list requester options", "component", "requests", + "media_type", string(mediaType), "tmdb_id", tmdbID, "err", logredact.SanitizeText(err.Error())) + return nil, nil + } + return options, nil +} + +// errRequesterOptions refuses a request whose picks cannot be honored. +func errRequesterOptions(message string) error { + return &ValidationError{FieldErrors: map[string]string{"options": message}} +} + +// resolveRequesterChoices checks a new request's picks against what the +// server it would go to offers right now. A pick for an option that is not +// offered, or a value that is not one of its choices, refuses the request: +// the value reaches the download server as a setting, so only listed values +// may pass. +func (s *Service) resolveRequesterChoices(ctx context.Context, probe Request, picks map[string]string) (RequesterChoices, error) { + return s.resolveChoices(ctx, probe, picks, false) +} + +// resolveChoices checks picks against the requester's offer, or the approving +// admin's, and returns them in the words they were offered in. +func (s *Service) resolveChoices(ctx context.Context, probe Request, picks map[string]string, approver bool) (RequesterChoices, error) { + if len(picks) == 0 { + return RequesterChoices{}, nil + } + if len(picks) > maxRequesterChoices { + return RequesterChoices{}, errRequesterOptions("Too many options.") + } + integrationID, options, err := s.requesterOffer(ctx, probe, approver) + if err != nil { + slog.WarnContext(ctx, "requests: could not check requester options", "component", "requests", + "media_type", string(probe.MediaType), "tmdb_id", probe.TMDBID, "err", logredact.SanitizeText(err.Error())) + return RequesterChoices{}, errRequesterOptions("The download server's choices could not be read. Try again, or continue without choosing.") + } + out := RequesterChoices{IntegrationID: integrationID} + for _, key := range slices.Sorted(maps.Keys(picks)) { + i := slices.IndexFunc(options, func(o RequesterOption) bool { return o.Key == key }) + if i < 0 { + return RequesterChoices{}, errRequesterOptions("This title has no such option. Reload and try again.") + } + option := options[i] + j := slices.IndexFunc(option.Choices, func(c RouterOption) bool { return c.Value == picks[key] }) + if j < 0 { + return RequesterChoices{}, errRequesterOptions(fmt.Sprintf("That %s is no longer offered. Reload and try again.", strings.ToLower(option.Label))) + } + if option.DefaultIsSaved && picks[key] == option.Default { + // The server's own setting: it applies without a pick. + continue + } + out.Choices = append(out.Choices, RequesterChoice{ + Key: key, Label: option.Label, Value: option.Choices[j].Value, ValueLabel: option.Choices[j].Label, + ByAdmin: approver, + }) + } + return out, nil +} + +// ApproverOptions returns the download server settings an admin may choose +// when approving a pending request: the options the server leaves to the +// approver, and those it leaves to requesters. An option's default is +// the requester's pick, when there is one. It is empty when there is nothing +// to choose, and also when the server's choices cannot be read: the request +// can still be approved without a pick. +func (s *Service) ApproverOptions(ctx context.Context, viewer Viewer, id string) ([]RequesterOption, error) { + if !viewer.IsAdmin { + return nil, ErrForbidden + } + req, err := s.store.GetRequest(ctx, strings.TrimSpace(id)) + if err != nil { + return nil, err + } + integrationID, options, err := s.requesterOffer(ctx, *req, true) + if err != nil { + slog.WarnContext(ctx, "requests: could not list approver options", "component", "requests", + "request_id", req.ID, "err", logredact.SanitizeText(err.Error())) + return nil, nil + } + if req.RequesterChoices.IntegrationID != integrationID { + return options, nil + } + for i := range options { + for _, pick := range req.RequesterChoices.Choices { + if pick.Key == options[i].Key && slices.ContainsFunc(options[i].Choices, func(c RouterOption) bool { return c.Value == pick.Value }) { + options[i].Default = pick.Value + } + } + } + return options, nil +} + +// ApproveWithOptions approves a pending request with the admin's picks from +// ApproverOptions. A pick replaces the requester's for the same option; the +// requester's other picks stay. No picks is Approve. +func (s *Service) ApproveWithOptions(ctx context.Context, viewer Viewer, id string, picks map[string]string) (*Request, error) { + if !viewer.IsAdmin { + return nil, ErrForbidden + } + if len(picks) == 0 { + return s.Approve(ctx, viewer, id) + } + id = strings.TrimSpace(id) + req, err := s.store.GetRequest(ctx, id) + if err != nil { + return nil, err + } + chosen, err := s.resolveChoices(ctx, *req, picks, true) + if err != nil { + return nil, err + } + if req.RequesterChoices.IntegrationID == chosen.IntegrationID { + for _, earlier := range req.RequesterChoices.Choices { + // The admin's pick replaces the requester's, unless it is the + // same value: then the requester's stays as it was made. + if pick, replaced := picks[earlier.Key]; !replaced || pick == earlier.Value { + chosen.Choices = slices.DeleteFunc(chosen.Choices, func(c RequesterChoice) bool { return c.Key == earlier.Key }) + chosen.Choices = append(chosen.Choices, earlier) + } + } + slices.SortFunc(chosen.Choices, func(a, b RequesterChoice) int { return strings.Compare(a.Key, b.Key) }) + } + // One guarded update: of two admins approving at once, the one whose + // approval wins is the one whose picks are stored. + approved, err := s.store.ApproveWithRequesterChoices(ctx, id, chosen, viewer) + if err != nil { + return nil, err + } + return s.afterAdminApproval(ctx, viewer, approved), nil +} + +// applyRequesterChoices sets a request's picks in conn's config when conn is +// the server they were offered on and that server still offers the option. +// Picks for another server, or for an option the server no longer leaves to +// whoever picked, are left out, so the server's own settings apply. conn's +// config is copied before it is changed. +func (s *Service) applyRequesterChoices(ctx context.Context, fc *fulfillContext, req Request, conn *ResolvedRouterConnection, installationID int, capabilityID string) error { + picks := req.RequesterChoices + if len(picks.Choices) == 0 || picks.IntegrationID != conn.ID { + return nil + } + features, err := s.routerFeatures(ctx, fc, installationID, capabilityID) + if err != nil { + return err + } + offered := offeredRequesterOptions(features.RequesterOptions, req.MediaType, conn.Config, false) + toApprover := offeredRequesterOptions(features.RequesterOptions, req.MediaType, conn.Config, true) + config := maps.Clone(conn.Config) + if config == nil { + config = map[string]any{} + } + for _, pick := range picks.Choices { + allowed := offered + if pick.ByAdmin { + allowed = toApprover + } + if slices.ContainsFunc(allowed, func(o RouterRequesterOption) bool { return o.Field == pick.Key }) { + config[pick.Key] = pick.Value + } + } + conn.Config = config + return nil +} diff --git a/internal/requests/requester_options_test.go b/internal/requests/requester_options_test.go new file mode 100644 index 0000000000..78f83aa04d --- /dev/null +++ b/internal/requests/requester_options_test.go @@ -0,0 +1,292 @@ +package requests + +import ( + "context" + "errors" + "testing" +) + +// optionsService is a server with one Seerr-like connection whose plugin +// lets the movie quality profile be chosen by whoever the connection's +// profile_chosen_by select names. +func optionsService(config map[string]any) (*Service, *fakeStore, *fakeRouterProvider) { + store := newFakeStore() + store.settings.RequestsEnabled = true + store.settings.GlobalAutoApprovalEnabled = true + in := routerInst("seerr") + in.PluginConfig = config + store.integrations = []Integration{in} + service, router := newRoutedService(store) + router.requesterOptions = map[int][]RouterRequesterOption{1: { + {Field: "radarr_profile_id", MediaType: MediaTypeMovie, Label: "Quality", ChooserField: "profile_chosen_by"}, + {Field: "sonarr_profile_id", MediaType: MediaTypeSeries, Label: "Quality", ChooserField: "profile_chosen_by"}, + // A plugin must not be able to hand requesters a key routing owns. + {Field: configIs4K}, + }} + router.options = map[string][]RouterOption{ + "radarr_profile_id": {{Value: "default", Label: "Seerr default (HD-1080p)"}, {Value: "4", Label: "Ultra-HD"}}, + "sonarr_profile_id": {{Value: "default", Label: "Seerr default"}, {Value: "9", Label: "Series UHD"}}, + configIs4K: {{Value: "true", Label: "Yes"}}, + } + return service, store, router +} + +func TestRequesterOptionsOffersOnlyWhatTheServerAllows(t *testing.T) { + service, _, _ := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + options, err := service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550) + if err != nil { + t.Fatalf("RequesterOptions: %v", err) + } + if len(options) != 1 || options[0].Key != "radarr_profile_id" || options[0].Label != "Quality" || + options[0].Default != "default" || len(options[0].Choices) != 2 { + t.Fatalf("options = %+v, want the movie quality profile only", options) + } + + // The admin has not turned the choice on: nothing is offered, and the + // plugin is not asked. + service, _, router := optionsService(map[string]any{"profile_chosen_by": "admin"}) + router.optionsErr = errors.New("must not be called") + options, err = service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550) + if err != nil || len(options) != 0 { + t.Fatalf("options = %+v, err = %v; want none", options, err) + } + + // A download server that cannot list its choices offers none rather + // than failing the request dialog. + service, _, router = optionsService(map[string]any{"profile_chosen_by": "requester"}) + router.optionsErr = errors.New("seerr is down") + options, err = service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550) + if err != nil || len(options) != 0 { + t.Fatalf("options = %+v, err = %v; want none", options, err) + } +} + +func TestCreateRequestSendsTheRequestersPick(t *testing.T) { + service, store, router := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + input := fightClubInput + input.Options = map[string]string{"radarr_profile_id": "4"} + req, err := service.CreateRequest(context.Background(), testViewer(1), input) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + want := RequesterChoice{Key: "radarr_profile_id", Label: "Quality", Value: "4", ValueLabel: "Ultra-HD"} + stored := store.requests[req.ID].RequesterChoices + if stored.IntegrationID != "seerr" || len(stored.Choices) != 1 || stored.Choices[0] != want { + t.Fatalf("stored choices = %+v, want %+v on seerr", stored, want) + } + // Auto-approval submitted it: the plugin got the pick as its config. + if len(router.gotConns) != 1 || router.gotConns[0].Config["radarr_profile_id"] != "4" { + t.Fatalf("fulfill connections = %+v, want radarr_profile_id 4", router.gotConns) + } + // The saved server config is untouched. + if got := store.integrations[0].PluginConfig["radarr_profile_id"]; got != "default" { + t.Fatalf("server config radarr_profile_id = %v, want default", got) + } +} + +func TestCreateRequestRefusesPicksThatAreNotOffered(t *testing.T) { + for name, c := range map[string]struct { + config map[string]any + picks map[string]string + optionsErr error + }{ + "value not listed": {map[string]any{"profile_chosen_by": "requester"}, map[string]string{"radarr_profile_id": "7"}, nil}, + "other media type": {map[string]any{"profile_chosen_by": "requester"}, map[string]string{"sonarr_profile_id": "9"}, nil}, + "undeclared key": {map[string]any{"profile_chosen_by": "requester"}, map[string]string{"radarr_root_folder": "/etc"}, nil}, + "routing-owned key": {map[string]any{"profile_chosen_by": "requester"}, map[string]string{configIs4K: "true"}, nil}, + "choice turned off": {map[string]any{"profile_chosen_by": "admin"}, map[string]string{"radarr_profile_id": "4"}, nil}, + "choices cannot be read": {map[string]any{"profile_chosen_by": "requester"}, map[string]string{"radarr_profile_id": "4"}, errors.New("seerr is down")}, + } { + t.Run(name, func(t *testing.T) { + service, store, router := optionsService(c.config) + router.optionsErr = c.optionsErr + input := fightClubInput + input.Options = c.picks + _, err := service.CreateRequest(context.Background(), testViewer(1), input) + var validation *ValidationError + if !errors.As(err, &validation) || validation.FieldErrors["options"] == "" { + t.Fatalf("CreateRequest error = %v, want a validation error on options", err) + } + if len(store.created) != 0 || router.fulfillCalls != 0 { + t.Fatalf("created = %d, fulfill calls = %d; want nothing made or sent", len(store.created), router.fulfillCalls) + } + }) + } +} + +// A pick is an id or path of the server it was offered on. It must not reach +// another server, or one whose admin has since turned the choice off. +func TestSubmitLeavesOutPicksThatNoLongerApply(t *testing.T) { + pick := RequesterChoices{IntegrationID: "seerr", Choices: []RequesterChoice{{Key: "radarr_profile_id", Value: "4"}}} + for name, c := range map[string]struct { + config map[string]any + choices RequesterChoices + }{ + "choice turned off": {map[string]any{"profile_chosen_by": "admin", "radarr_profile_id": "default"}, pick}, + "another server": {map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}, + RequesterChoices{IntegrationID: "old-seerr", Choices: pick.Choices}}, + "option no longer declared": {map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}, + RequesterChoices{IntegrationID: "seerr", Choices: []RequesterChoice{{Key: "requester_mode", Value: "admin"}}}}, + } { + t.Run(name, func(t *testing.T) { + service, store, router := optionsService(c.config) + req := Request{ID: "r1", MediaType: MediaTypeMovie, TMDBID: 550, Status: StatusApproved, Outcome: OutcomeActive, + RequestedByUserID: 7, RequesterChoices: c.choices} + store.requests["r1"] = &req + if _, err := service.submitApprovedRequest(context.Background(), req, Viewer{UserID: 7, IsAdmin: true}, nil); err != nil { + t.Fatalf("submit: %v", err) + } + if len(router.gotConns) != 1 { + t.Fatalf("fulfill connections = %+v, want one", router.gotConns) + } + config := router.gotConns[0].Config + if config["radarr_profile_id"] != "default" { + t.Fatalf("radarr_profile_id = %v, want the server's own", config["radarr_profile_id"]) + } + if _, set := config["requester_mode"]; set { + t.Fatalf("config = %v, an undeclared key was set", config) + } + }) + } +} + +func TestApproveWithOptionsAppliesTheAdminsPick(t *testing.T) { + // Requesters are not offered the choice; the approving admin still is. + service, store, router := optionsService(map[string]any{"profile_chosen_by": "approver", "radarr_profile_id": "default"}) + store.settings.GlobalAutoApprovalEnabled = false + if options, err := service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550); err != nil || len(options) != 0 { + t.Fatalf("RequesterOptions = %+v, err = %v; want none for a requester", options, err) + } + req, err := service.CreateRequest(context.Background(), testViewer(1), fightClubInput) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + admin := Viewer{UserID: 9, ProfileID: "9", IsAdmin: true} + + if _, err := service.ApproverOptions(context.Background(), testViewer(1), req.ID); !errors.Is(err, ErrForbidden) { + t.Fatalf("ApproverOptions as a requester: err = %v, want ErrForbidden", err) + } + options, err := service.ApproverOptions(context.Background(), admin, req.ID) + if err != nil || len(options) != 1 || options[0].Key != "radarr_profile_id" || options[0].Default != "default" { + t.Fatalf("ApproverOptions = %+v, err = %v; want the movie quality profile", options, err) + } + + var invalid *ValidationError + if _, err := service.ApproveWithOptions(context.Background(), admin, req.ID, map[string]string{"radarr_profile_id": "77"}); !errors.As(err, &invalid) { + t.Fatalf("ApproveWithOptions with an unlisted value: err = %v, want a validation error", err) + } + if len(router.gotConns) != 0 { + t.Fatalf("a refused approval submitted the request: %+v", router.gotConns) + } + + if _, err := service.ApproveWithOptions(context.Background(), admin, req.ID, map[string]string{"radarr_profile_id": "4"}); err != nil { + t.Fatalf("ApproveWithOptions: %v", err) + } + want := RequesterChoice{Key: "radarr_profile_id", Label: "Quality", Value: "4", ValueLabel: "Ultra-HD", ByAdmin: true} + stored := store.requests[req.ID].RequesterChoices + if stored.IntegrationID != "seerr" || len(stored.Choices) != 1 || stored.Choices[0] != want { + t.Fatalf("stored choices = %+v, want %+v on seerr", stored, want) + } + if len(router.gotConns) != 1 || router.gotConns[0].Config["radarr_profile_id"] != "4" { + t.Fatalf("fulfill connections = %+v, want radarr_profile_id 4", router.gotConns) + } +} + +func TestApproverOptionsDefaultToTheRequestersPick(t *testing.T) { + service, store, _ := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + store.settings.GlobalAutoApprovalEnabled = false + input := fightClubInput + input.Options = map[string]string{"radarr_profile_id": "4"} + req, err := service.CreateRequest(context.Background(), testViewer(1), input) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + options, err := service.ApproverOptions(context.Background(), Viewer{UserID: 9, ProfileID: "9", IsAdmin: true}, req.ID) + if err != nil || len(options) != 1 || options[0].Default != "4" { + t.Fatalf("ApproverOptions = %+v, err = %v; want the requester's pick as the default", options, err) + } +} + +func TestApproverOptionsLeaveOutWhatTheAdminFixed(t *testing.T) { + service, store, router := optionsService(map[string]any{"profile_chosen_by": "admin", "radarr_profile_id": "default"}) + store.settings.GlobalAutoApprovalEnabled = false + req, err := service.CreateRequest(context.Background(), testViewer(1), fightClubInput) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + admin := Viewer{UserID: 9, ProfileID: "9", IsAdmin: true} + if options, err := service.ApproverOptions(context.Background(), admin, req.ID); err != nil || len(options) != 0 { + t.Fatalf("ApproverOptions = %+v, err = %v; want none", options, err) + } + var invalid *ValidationError + if _, err := service.ApproveWithOptions(context.Background(), admin, req.ID, map[string]string{"radarr_profile_id": "4"}); !errors.As(err, &invalid) { + t.Fatalf("ApproveWithOptions for a fixed option: err = %v, want a validation error", err) + } + if len(router.gotConns) != 0 { + t.Fatalf("a refused approval submitted the request: %+v", router.gotConns) + } +} + +func TestRequesterPickOfTheShownDefaultIsKeptWhenItIsNotTheSavedSetting(t *testing.T) { + // The saved profile is gone from the server, so the form shows the first + // choice. Sending that choice must apply it, not the stale saved value. + service, store, router := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "12"}) + options, err := service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550) + if err != nil || len(options) != 1 || options[0].Default != "default" || options[0].DefaultIsSaved { + t.Fatalf("options = %+v, err = %v; want the first choice shown, not as the saved setting", options, err) + } + input := fightClubInput + input.Options = map[string]string{"radarr_profile_id": "default"} + req, err := service.CreateRequest(context.Background(), testViewer(1), input) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + if stored := store.requests[req.ID].RequesterChoices; len(stored.Choices) != 1 || stored.Choices[0].Value != "default" { + t.Fatalf("stored choices = %+v, want the shown default kept", stored) + } + if len(router.gotConns) != 1 || router.gotConns[0].Config["radarr_profile_id"] != "default" { + t.Fatalf("fulfill connections = %+v, want radarr_profile_id default", router.gotConns) + } +} + +func TestRequesterPickOfTheSavedSettingIsNotStored(t *testing.T) { + service, store, _ := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + input := fightClubInput + input.Options = map[string]string{"radarr_profile_id": "default"} + req, err := service.CreateRequest(context.Background(), testViewer(1), input) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + if stored := store.requests[req.ID].RequesterChoices; len(stored.Choices) != 0 { + t.Fatalf("stored choices = %+v, want none for the server's own setting", stored) + } +} + +func TestRequesterOptionsRefuseABlockedAccount(t *testing.T) { + service, store, router := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + store.limit = &UserLimit{UserID: 1, LimitMode: LimitModeBlocked, ApprovalMode: ApprovalModeInherit} + router.optionsErr = errors.New("must not be called") + if _, err := service.RequesterOptions(context.Background(), testViewer(1), MediaTypeMovie, 550); !errors.Is(err, ErrUserBlocked) { + t.Fatalf("err = %v, want ErrUserBlocked", err) + } +} + +func TestApproveWithOptionsKeepsTheRequestersPickTheAdminLeft(t *testing.T) { + service, store, _ := optionsService(map[string]any{"profile_chosen_by": "requester", "radarr_profile_id": "default"}) + store.settings.GlobalAutoApprovalEnabled = false + input := fightClubInput + input.Options = map[string]string{"radarr_profile_id": "4"} + req, err := service.CreateRequest(context.Background(), testViewer(1), input) + if err != nil { + t.Fatalf("CreateRequest: %v", err) + } + admin := Viewer{UserID: 9, ProfileID: "9", IsAdmin: true} + // The approval form sends what it shows: the requester's pick, unchanged. + if _, err := service.ApproveWithOptions(context.Background(), admin, req.ID, map[string]string{"radarr_profile_id": "4"}); err != nil { + t.Fatalf("ApproveWithOptions: %v", err) + } + stored := store.requests[req.ID].RequesterChoices + if len(stored.Choices) != 1 || stored.Choices[0].Value != "4" || stored.Choices[0].ByAdmin { + t.Fatalf("stored choices = %+v, want the requester's pick as they made it", stored) + } +} diff --git a/internal/requests/router_seasons.go b/internal/requests/router_seasons.go index 2864f5cf64..8b742b1555 100644 --- a/internal/requests/router_seasons.go +++ b/internal/requests/router_seasons.go @@ -24,6 +24,9 @@ type RouterFeatures struct { // in a connection test of a saved server is tested as blank rather than // as the saved address (see blankURLMeansSaved). BaseURLOptional bool + // RequesterOptions are the connection settings a requester may choose + // for one request (see requester_options.go). + RequesterOptions []RouterRequesterOption } // RouterFeatureReader reads a router capability's declared features from the diff --git a/internal/requests/service.go b/internal/requests/service.go index 20b8160726..982a0b7124 100644 --- a/internal/requests/service.go +++ b/internal/requests/service.go @@ -850,6 +850,11 @@ func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input Create if err := validateCreateAccess(policy); err != nil { return nil, err } + // Last of the checks: it asks the download server for its choices. + choices, err := s.resolveRequesterChoices(ctx, requestProbe(viewer, normalized.MediaType, normalized.TMDBID, facts), normalized.Options) + if err != nil { + return nil, err + } id, err := idgen.NextID() if err != nil { @@ -870,6 +875,7 @@ func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input Create Facts: facts, Requester: viewer, Now: s.now(), + Choices: choices, // Re-requesting a title that failed for this user (e.g. a transient // integration error) replaces their failed row. ReplaceFailed: true, @@ -1110,8 +1116,13 @@ func (s *Service) Approve(ctx context.Context, viewer Viewer, id string) (*Reque if err != nil { return nil, err } + return s.afterAdminApproval(ctx, viewer, approved), nil +} + +// afterAdminApproval notifies about and submits a request an admin approved. +func (s *Service) afterAdminApproval(ctx context.Context, viewer Viewer, approved *Request) *Request { s.notifyApproval(ctx, *approved, ApprovalOriginAdmin) - return s.withLibraryContent(ctx, s.submitAfterCommit(ctx, *approved, viewer)), nil + return s.withLibraryContent(ctx, s.submitAfterCommit(ctx, *approved, viewer)) } // Decline rejects a request nothing has been sent for: a pending one, or an @@ -2262,6 +2273,11 @@ func (s *Service) submitClaimed(ctx context.Context, req Request, actor Viewer, return done, err } s.populateRequesterIdentity(ctx, &req) + for i := range conns { + if err := s.applyRequesterChoices(ctx, fc, req, &conns[i], installationID, capabilityID); err != nil { + return nil, err + } + } targets, msg, err := s.router.Fulfill(ctx, installationID, capabilityID, req, plan.want, conns) if err != nil { return nil, err @@ -2312,6 +2328,10 @@ func (s *Service) submitRouted(ctx context.Context, req Request, actor Viewer, f continue } conn, installationID, capabilityID, err := s.routedConnection(ctx, fc, decision, req.MediaType, q) + if err == nil { + // The requester's picks go over the route's overrides. + err = s.applyRequesterChoices(ctx, fc, req, &conn, installationID, capabilityID) + } if err != nil { if len(targets) == 0 { // The chosen server is gone, disabled or not set up: an diff --git a/internal/requests/service_test.go b/internal/requests/service_test.go index 9a04f12971..ca47c2d731 100644 --- a/internal/requests/service_test.go +++ b/internal/requests/service_test.go @@ -1442,6 +1442,7 @@ func (f *fakeStore) CreateRequest(_ context.Context, input CreateRequestRecord) IsAnime: input.IsAnime, RoutingFacts: input.Facts, Seasons: input.Input.Seasons, + RequesterChoices: input.Choices, RequestedByUserID: input.Requester.UserID, RequestedByProfileID: input.Requester.ProfileID, Source: requestSource(input.Input.Source), @@ -1692,6 +1693,26 @@ func (f *fakeStore) SetStatus(_ context.Context, id string, from StateGuard, sta return ©, nil } +func (f *fakeStore) ApproveWithRequesterChoices(_ context.Context, id string, choices RequesterChoices, _ Viewer) (*Request, error) { + f.mu.Lock() + defer f.mu.Unlock() + req := f.lookupLocked(id) + if req == nil { + return nil, ErrNotFound + } + if !f.guardAccepts(guardPending, req) { + return nil, ErrInvalidState + } + f.statusUpdates = append(f.statusUpdates, StatusApproved) + req.RequesterChoices = choices + req.Status = StatusApproved + req.SubmitAttempts = 0 + req.SubmitLeaseUntil = nil + req.NextSubmitAt = nil + approved := *req + return &approved, nil +} + func (f *fakeStore) SetOutcome(_ context.Context, id string, from StateGuard, outcome Outcome, _ Viewer, message string) (*Request, error) { f.mu.Lock() defer f.mu.Unlock() @@ -2599,8 +2620,11 @@ type fakeRouterProvider struct { // urlOptional marks the installations whose router declares // base_url_optional. urlOptional map[int]bool - featuresErr error - gotTVDBID *int + // requesterOptions are the requester options each installation's router + // declares. + requesterOptions map[int][]RouterRequesterOption + featuresErr error + gotTVDBID *int // CheckStatus behavior. statuses []RouterTargetStatus @@ -2645,6 +2669,7 @@ func (f *fakeRouterProvider) RouterFeatures(_ context.Context, installationID in ReportsDownloadProgress: f.progressCapable[installationID], APIKeyOptional: f.keyOptional[installationID], BaseURLOptional: f.urlOptional[installationID], + RequesterOptions: f.requesterOptions[installationID], }, f.featuresErr } diff --git a/internal/requests/store.go b/internal/requests/store.go index 39c4d68ae7..d790850e52 100644 --- a/internal/requests/store.go +++ b/internal/requests/store.go @@ -43,6 +43,10 @@ type Store interface { // Declining or withdrawing also clears the title's follows in the same // transaction. SetStatus(ctx context.Context, id string, from StateGuard, status Status, actor Viewer) (*Request, error) + // ApproveWithRequesterChoices approves a pending request and replaces + // its picks in one guarded update; any other request returns + // ErrInvalidState and keeps its picks. + ApproveWithRequesterChoices(ctx context.Context, id string, choices RequesterChoices, actor Viewer) (*Request, error) SetOutcome(ctx context.Context, id string, from StateGuard, outcome Outcome, actor Viewer, message string) (*Request, error) // ReopenFailed moves a failed request back to active + approved with a // fresh submission budget, in one guarded write. @@ -155,6 +159,9 @@ type CreateRequestRecord struct { Facts RoutingFacts Requester Viewer Now time.Time + // Choices are the requester's picks, already checked against what the + // server offers. + Choices RequesterChoices // Quota, when non-nil, instructs the store to atomically verify the // requester is below their per-user limit before inserting. The check // runs inside the same transaction as the insert with a per-user diff --git a/internal/requests/types.go b/internal/requests/types.go index dcd17cc50d..de6eb937c2 100644 --- a/internal/requests/types.go +++ b/internal/requests/types.go @@ -298,6 +298,9 @@ type Request struct { // season's episode counts once the series is in the library. Seasons []int `json:"-"` SeasonProgress []SeasonProgress `json:"-"` + // RequesterChoices are the download server settings the requester + // picked, with the server they were offered on. v2 only. + RequesterChoices RequesterChoices `json:"-"` // Followers are the profiles, other than the requester's, that asked to be // told when the title is available; loaded for the fulfilled notification. Followers []Follower `json:"-"` @@ -526,6 +529,9 @@ type CreateRequestInput struct { // Source records what created the request; empty means SourceDirect. // Set by the watchlist path, never read from a client body. Source Source `json:"-"` + // Options are the requester's picks, keyed by option key, from the ones + // RequesterOptions offers for the title. v2 only. + Options map[string]string `json:"-"` } // RequestPageKey identifies the last emitted request in descending creation order. diff --git a/migrations/sql/20261111012048_request_requester_choices.sql b/migrations/sql/20261111012048_request_requester_choices.sql new file mode 100644 index 0000000000..ff5aad29b6 --- /dev/null +++ b/migrations/sql/20261111012048_request_requester_choices.sql @@ -0,0 +1,9 @@ +-- +goose Up +-- The download server settings the requester picked for a request (for +-- example a quality profile), with the server they were offered on. Empty +-- means the requester picked nothing, as for every request before requester +-- options. +ALTER TABLE media_requests ADD COLUMN requester_choices jsonb NOT NULL DEFAULT '{}'; + +-- +goose Down +ALTER TABLE media_requests DROP COLUMN requester_choices; diff --git a/scripts/ci/db-contracts.txt b/scripts/ci/db-contracts.txt index 2fddacee52..2cf79f5752 100644 --- a/scripts/ci/db-contracts.txt +++ b/scripts/ci/db-contracts.txt @@ -405,6 +405,7 @@ ./internal/requests TestReplaceFailedIsScopedToRequesterDatabase ./internal/requests TestDeleteFailedRequestDatabase ./internal/requests TestListDownloadingRequestsOrderDatabase +./internal/requests TestRequesterChoicesDatabase ./internal/downloads TestConcurrentArtifactCreatesCannotBypassQuotaDB ./internal/downloads TestSubscriptionSyncPagePostgres ./internal/downloads TestMonitorSyncKeepsDeletedEpisodesDeletedPostgres diff --git a/web/src/api/types.ts b/web/src/api/types.ts index ed48596bb7..179b506527 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -2105,6 +2105,25 @@ export interface CreateMediaRequestInput { backdrop_path?: string; /** Series only: the seasons to request. Omitted: every aired season not yet in the library. */ seasons?: number[]; + /** The requester's picks from the title's request options, as option key to value. */ + options?: Record; +} + +/** A download server setting the viewer may choose when requesting a title. */ +export interface RequestOption { + key: string; + label: string; + /** The value in effect when the requester chooses nothing; one of choices. */ + default: string; + choices: { value: string; label: string }[]; +} + +/** One setting the requester chose, in the words it was offered in. */ +export interface RequestOptionChoice { + key: string; + label: string; + value: string; + value_label: string; } /** The download server details (integration_*, instance_name, route_name, external_*, last_error) reach admins only. */ @@ -2153,6 +2172,8 @@ export interface MediaRequest { seasons?: number[]; /** Series season requests: each requested season's episodes, once the series is in the library. */ season_progress?: RequestSeasonProgress[]; + /** What the requester chose from the title's request options; empty when nothing. */ + options?: RequestOptionChoice[]; targets?: RequestTarget[]; /** Over every server of the request: the phase that needs the most attention, the latest estimate. */ download?: RequestDownload; diff --git a/web/src/api/v2/adminRequests.ts b/web/src/api/v2/adminRequests.ts index b41b4adb54..def1a73cab 100644 --- a/web/src/api/v2/adminRequests.ts +++ b/web/src/api/v2/adminRequests.ts @@ -8,6 +8,7 @@ import type { LoadRequestIntegrationOptionsRequest, MediaRequest, RequestIntegration, + RequestOption, RequestMediaType, RequestSettings, RequestUserLimit, @@ -400,9 +401,17 @@ export function cancelAdminRequestV2(id: string, reason?: string) { mediaRequestFromV2, ); } -export function approveAdminRequestV2(id: string) { - return v2("POST /api/v2/admin/requests/{id}/approve", { path: { id }, body: {} }).then( - mediaRequestFromV2, +/** Approves a request, with the admin's picks from listAdminRequestOptionsV2 when there are any. */ +export function approveAdminRequestV2(id: string, options?: Record) { + return v2("POST /api/v2/admin/requests/{id}/approve", { + path: { id }, + body: options ? { options } : {}, + }).then(mediaRequestFromV2); +} +/** The download server settings an admin may choose when approving a request. */ +export function listAdminRequestOptionsV2(id: string): Promise { + return v2("GET /api/v2/admin/requests/{id}/options", { path: { id } }).then( + (list) => list.options, ); } export function retryAdminRequestV2(id: string) { diff --git a/web/src/api/v2/operations.ts b/web/src/api/v2/operations.ts index 56179028fd..61b7de4576 100644 --- a/web/src/api/v2/operations.ts +++ b/web/src/api/v2/operations.ts @@ -253,6 +253,7 @@ export const v2Operations = { "GET /api/v2/admin/requests/capabilities": "getAdminRequestCapabilities", "GET /api/v2/admin/requests/counts": "getAdminRequestCounts", "GET /api/v2/admin/requests/{id}/events": "listAdminRequestEvents", + "GET /api/v2/admin/requests/{id}/options": "listAdminRequestOptions", "GET /api/v2/admin/sections": "listAdminSections", "GET /api/v2/admin/sections/capabilities": "getAdminSectionCapabilities", "GET /api/v2/admin/sections/order": "getAdminSectionOrder", @@ -510,6 +511,7 @@ export const v2Operations = { "GET /api/v2/requests/discover/studios": "listDiscoverStudios", "GET /api/v2/requests/discover/{section}": "getDiscoverSection", "GET /api/v2/requests/mine": "listMyRequests", + "GET /api/v2/requests/options/{media_type}/{tmdb_id}": "listRequestOptions", "GET /api/v2/requests/search": "searchRequestMedia", "GET /api/v2/requests/status": "getRequestStatus", "GET /api/v2/requests/{id}": "getRequest", diff --git a/web/src/api/v2/requests.ts b/web/src/api/v2/requests.ts index 8e8760c211..7ec1fd5eda 100644 --- a/web/src/api/v2/requests.ts +++ b/web/src/api/v2/requests.ts @@ -12,6 +12,7 @@ import type { RequestMediaPage, RequestMediaResult, RequestMediaType, + RequestOption, RequestSearchMediaType, RequestTarget, RequestUserState, @@ -133,6 +134,18 @@ export function getRequestMediaDetailV2( ); } +// The download server settings the viewer may choose for a title. The server +// asks the title's request plugin, so this is read when the viewer starts a +// request, not for every title shown. +export function listRequestOptionsV2( + mediaType: RequestMediaType, + tmdbID: number, +): Promise { + return v2("GET /api/v2/requests/options/{media_type}/{tmdb_id}", { + path: { media_type: mediaType, tmdb_id: tmdbID }, + }).then((list) => list.options); +} + function discoverSectionFromV2(s: Schemas["DiscoverSection"]): RequestDiscoverySection { return { ...s, results: s.results.map(mediaResultFromV2) }; } diff --git a/web/src/api/v2/schema.ts b/web/src/api/v2/schema.ts index b02b7b7da4..78e5595343 100644 --- a/web/src/api/v2/schema.ts +++ b/web/src/api/v2/schema.ts @@ -4850,6 +4850,23 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v2/admin/requests/{id}/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Manage media requests and their configuration. */ + get: operations["listAdminRequestOptions"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v2/admin/requests/{id}/retry": { parameters: { query?: never; @@ -11583,6 +11600,23 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v2/requests/options/{media_type}/{tmdb_id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List the download server settings the viewer may choose when requesting a title. */ + get: operations["listRequestOptions"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v2/requests/search": { parameters: { query?: never; @@ -20599,6 +20633,10 @@ export interface components { status: "started"; }; AdminRequestActionInputBody: { + /** @description Approve only: the admin's picks from listAdminRequestOptions, as option key to chosen value. A pick replaces the requester's for that option. A key or value that is not offered is refused with validation_failed. Omitted: the requester's picks and the download server's own settings apply */ + options?: { + [key: string]: string; + }; reason?: string; }; AdminRequestCapabilitiesOutputBody: { @@ -27099,6 +27137,8 @@ export interface components { rating_restrictions_enforced: boolean; /** @description Whether removeFailedRequest is available: a requester can delete their own failed request that delivered nothing. */ remove_failed_supported: boolean; + /** @description Whether the server has listRequestOptions and takes options on createRequest. Whether a given title offers any depends on its download server and that server's request plugin. */ + request_options_supported: boolean; requests_enabled: boolean; /** @description Opaque revision of this document */ revision: string; @@ -29166,6 +29206,8 @@ export interface components { * @example movie */ media_type: string; + /** @description What the requester chose from listRequestOptions when making the request, or the approving admin from listAdminRequestOptions, in the words it was offered in; empty when nothing was chosen */ + options: components["schemas"]["RequestOptionChoice"][]; /** * @description active, declined, cancelled, failed * @example active @@ -29250,6 +29292,10 @@ export interface components { * @enum {string} */ media_type: "movie" | "series"; + /** @description The requester's picks from listRequestOptions for this title, as option key to chosen value. A key or value that is not offered is refused with validation_failed. Omitted: the download server's own settings apply */ + options?: { + [key: string]: string; + }; overview?: string; /** @description TMDB image path */ poster_path?: string; @@ -33251,6 +33297,57 @@ export interface components { */ status?: string; }; + RequestOption: { + /** @description The values on offer; never empty */ + choices: components["schemas"]["RequestOptionValue"][]; + /** + * @description The value to preselect; always one of choices. It is the download server's own setting when that is on offer, and the first choice otherwise, so send the selected value of every option, also when it is the default. A value that is the server's own setting is not stored as a pick + * @example default + */ + default: string; + /** + * @description The key to send in createRequest's options + * @example radarr_profile_id + */ + key: string; + /** + * @description The option's name + * @example Quality + */ + label: string; + }; + RequestOptionChoice: { + /** + * @description The option's key + * @example radarr_profile_id + */ + key: string; + /** + * @description The option's name + * @example Quality + */ + label: string; + /** + * @description The chosen value + * @example 4 + */ + value: string; + /** + * @description The chosen value's name when it was chosen + * @example Ultra-HD + */ + value_label: string; + }; + RequestOptionList: { + /** @description Empty, never null, when the title's download server offers no choice, or its choices cannot be read right now */ + options: components["schemas"]["RequestOption"][]; + }; + RequestOptionValue: { + /** @example Ultra-HD */ + label: string; + /** @example 4 */ + value: string; + }; RequestSeasonProgress: { /** * Format: int64 @@ -81301,6 +81398,115 @@ export interface operations { }; }; }; + listAdminRequestOptions: { + parameters: { + query?: never; + header?: { + /** @description Optional. When present, it must name the authenticated account's primary profile; an absent header is accepted. */ + "X-Profile-Id"?: string; + /** @description Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked */ + "X-Profile-Token"?: string; + }; + path: { + /** @description The request */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RequestOptionList"]; + }; + }; + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Acceptable */ + 406: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Too Many Requests */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Internal Server Error */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Service Unavailable */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + }; + }; adminRetryRequest: { parameters: { query?: never; @@ -139126,6 +139332,126 @@ export interface operations { }; }; }; + listRequestOptions: { + parameters: { + query?: never; + header: { + /** @description The household profile acting for this request; it must belong to the authenticated account. */ + "X-Profile-Id": string; + /** @description Verification proof for a PIN-locked profile, issued by POST /api/v2/profiles/{id}/verify-pin; required only when the declared profile is locked */ + "X-Profile-Token"?: string; + }; + path: { + /** @description The media type */ + media_type: "movie" | "series"; + /** @description TMDB identifier (external, not a Silo ID) */ + tmdb_id: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RequestOptionList"]; + }; + }; + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Not Acceptable */ + 406: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Too Many Requests */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Internal Server Error */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + /** @description Service Unavailable */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["Problem"]; + }; + }; + }; + }; searchRequestMedia: { parameters: { query: { diff --git a/web/src/components/RequestOptionFields.tsx b/web/src/components/RequestOptionFields.tsx new file mode 100644 index 0000000000..2cb6e38c5b --- /dev/null +++ b/web/src/components/RequestOptionFields.tsx @@ -0,0 +1,66 @@ +import { useId } from "react"; +import type { RequestOption } from "@/api/types"; +import type { RequestOptionPicks } from "@/lib/mediaRequests"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; + +interface RequestOptionFieldsProps { + options: readonly RequestOption[]; + picks: RequestOptionPicks; + onChange: (picks: RequestOptionPicks) => void; + disabled?: boolean; +} + +/** + * One select per download server setting the viewer may choose for a request, + * such as a quality profile. The labels come from the server's request plugin. + */ +export function RequestOptionFields({ + options, + picks, + onChange, + disabled, +}: RequestOptionFieldsProps) { + const baseID = useId(); + if (options.length === 0) return null; + return ( +
+ {options.map((option) => { + const id = `${baseID}-${option.key}`; + const picked = picks[option.key]; + const value = + picked !== undefined && option.choices.some((choice) => choice.value === picked) + ? picked + : option.default; + return ( +
+ + +
+ ); + })} +
+ ); +} diff --git a/web/src/components/RequestOptionsDialog.tsx b/web/src/components/RequestOptionsDialog.tsx new file mode 100644 index 0000000000..5d51df56ab --- /dev/null +++ b/web/src/components/RequestOptionsDialog.tsx @@ -0,0 +1,86 @@ +import { useState } from "react"; +import { Loader2 } from "lucide-react"; +import type { RequestMediaResult, RequestOption } from "@/api/types"; +import { RequestOptionFields } from "@/components/RequestOptionFields"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { useCreateMediaRequest } from "@/hooks/queries/useRequests"; +import { + requestInputFromMediaResult, + requestOptionsToSend, + type RequestOptionPicks, +} from "@/lib/mediaRequests"; +import { useT } from "@/i18n"; + +interface RequestOptionsDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + item: RequestMediaResult; + /** What the viewer may choose; the caller opens the dialog only when there is something. */ + options: readonly RequestOption[]; +} + +/** + * Asks for the download server settings a title's request may choose (a + * quality profile, a folder) before sending it. A series picks them in the + * seasons dialog instead. + */ +export function RequestOptionsDialog({ + open, + onOpenChange, + item, + options, +}: RequestOptionsDialogProps) { + const t = useT(); + const createRequest = useCreateMediaRequest(); + const [picks, setPicks] = useState({}); + + const close = (next: boolean) => { + if (!next) setPicks({}); + onOpenChange(next); + }; + const submit = () => { + const chosen = requestOptionsToSend(options, picks); + createRequest.mutate( + { ...requestInputFromMediaResult(item), ...(chosen && { options: chosen }) }, + { onSuccess: () => close(false) }, + ); + }; + + return ( + + + + + {item.media_type === "series" + ? t("web.detail.request.requestSeries") + : t("web.detail.request.requestMovie")} + + {item.title} + + + + + + + + + ); +} diff --git a/web/src/components/RequestSeasonsDialog.test.tsx b/web/src/components/RequestSeasonsDialog.test.tsx index 45fbdeb542..fbaccc4d96 100644 --- a/web/src/components/RequestSeasonsDialog.test.tsx +++ b/web/src/components/RequestSeasonsDialog.test.tsx @@ -1,15 +1,17 @@ import { fireEvent, render, screen, within } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { RequestMediaDetail, RequestMediaSeason } from "@/api/types"; +import type { RequestMediaDetail, RequestMediaSeason, RequestOption } from "@/api/types"; const mocks = vi.hoisted(() => ({ create: vi.fn(), loaded: { data: undefined as RequestMediaDetail | undefined, isFetching: false, isError: false }, + options: { data: [] as RequestOption[], isLoading: false }, })); vi.mock("@/hooks/queries/useRequests", () => ({ useCreateMediaRequest: () => ({ mutate: mocks.create, isPending: false }), useRequestMediaDetail: () => mocks.loaded, + useRequestOptions: () => mocks.options, })); import { RequestSeasonsDialog } from "./RequestSeasonsDialog"; @@ -50,6 +52,28 @@ describe("RequestSeasonsDialog", () => { beforeEach(() => { mocks.create.mockReset(); mocks.loaded = { data: undefined, isFetching: false, isError: false }; + mocks.options = { data: [], isLoading: false }; + }); + + it("sends the download server settings the dialog shows", () => { + mocks.options.data = [ + { + key: "sonarr_profile_id", + label: "Quality", + default: "default", + choices: [ + { value: "default", label: "Server default" }, + { value: "9", label: "Ultra-HD" }, + ], + }, + ]; + const dialog = open(series({ seasons: [season(1)] })); + expect(within(dialog).getByRole("combobox", { name: "Quality" })).toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole("button", { name: "Request Season 1" })); + // Untouched, the shown default is sent; the server leaves out its own setting. + expect(mocks.create.mock.calls[0]![0]).toMatchObject({ + options: { sonarr_profile_id: "default" }, + }); }); it("leaves an untouched pick to the server", () => { diff --git a/web/src/components/RequestSeasonsDialog.tsx b/web/src/components/RequestSeasonsDialog.tsx index 8107095dad..d134e43f87 100644 --- a/web/src/components/RequestSeasonsDialog.tsx +++ b/web/src/components/RequestSeasonsDialog.tsx @@ -1,6 +1,7 @@ import { useId, useState } from "react"; import { Loader2 } from "lucide-react"; import type { RequestMediaDetail, RequestMediaSeason } from "@/api/types"; +import { RequestOptionFields } from "@/components/RequestOptionFields"; import { Button } from "@/components/ui/button"; import { Dialog, @@ -11,7 +12,11 @@ import { DialogTitle, } from "@/components/ui/dialog"; import { Switch } from "@/components/ui/switch"; -import { useCreateMediaRequest, useRequestMediaDetail } from "@/hooks/queries/useRequests"; +import { + useCreateMediaRequest, + useRequestMediaDetail, + useRequestOptions, +} from "@/hooks/queries/useRequests"; import { defaultRequestSeasons, formatRequestReason, @@ -19,6 +24,8 @@ import { formatSeasonList, latestRequestSeason, requestInputFromMediaResult, + requestOptionsToSend, + type RequestOptionPicks, seasonHasAired, seasonRequestable, upcomingRequestSeasons, @@ -63,6 +70,10 @@ export function RequestSeasonsDialog({ const seasons = detail?.seasons ?? []; const requestable = detail?.request.requestable ?? false; + // What the download server lets the requester choose, such as a quality + // profile. Nothing on offer, or a failed read, shows no fields. + const requestOptions = useRequestOptions("series", tmdbID, { enabled: open && requestable }); + const [optionPicks, setOptionPicks] = useState({}); const choices = requestable ? seasons.filter(seasonRequestable) : []; const defaults = defaultRequestSeasons(choices); const selected = (picked ?? defaults).filter((number) => @@ -80,7 +91,10 @@ export function RequestSeasonsDialog({ const upcoming = upcomingRequestSeasons(choices); const close = (next: boolean) => { - if (!next) setPicked(null); + if (!next) { + setPicked(null); + setOptionPicks({}); + } onOpenChange(next); }; const toggle = (season: number, on: boolean) => @@ -89,8 +103,13 @@ export function RequestSeasonsDialog({ ); const submit = () => { if (!detail) return; + const options = requestOptionsToSend(requestOptions.data, optionPicks); createRequest.mutate( - { ...requestInputFromMediaResult(detail), ...(!serverChooses && { seasons: selected }) }, + { + ...requestInputFromMediaResult(detail), + ...(!serverChooses && { seasons: selected }), + ...(options && { options }), + }, { onSuccess: () => close(false) }, ); }; @@ -201,6 +220,15 @@ export function RequestSeasonsDialog({ )} + {requestable && requestOptions.data ? ( + + ) : null} + + + + + + ); +} diff --git a/web/src/pages/admin-requests/QueueCells.tsx b/web/src/pages/admin-requests/QueueCells.tsx new file mode 100644 index 0000000000..7515c47c27 --- /dev/null +++ b/web/src/pages/admin-requests/QueueCells.tsx @@ -0,0 +1,76 @@ +import type { MediaRequest } from "@/api/types"; +import { RequestDownloadProgress } from "@/components/RequestDownloadProgress"; +import { useT } from "@/i18n"; +import { cn } from "@/lib/utils"; +import { TargetStatusBadge } from "./queueParts"; +import { distinctTargets, requestOptionValue, targetServerName } from "./requestQueueModel"; + +const SEPARATOR = " · "; +const SPACE = " "; +const NO_VALUE = "—"; + +/** One cell per chosen-setting column of a queue row. */ +export function OptionCells({ + request, + columns, +}: { + request: MediaRequest; + columns: readonly string[]; +}) { + return columns.map((column) => { + const value = requestOptionValue(request, column); + return ( + // Below the wide layout there is no header row, so the cell names its + // setting, and an empty one is left out. +

+ + {column} + {SEPARATOR} + + {value ?? NO_VALUE} +

+ ); + }); +} + +export function TargetList({ request }: { request: MediaRequest }) { + const t = useT(); + const targets = distinctTargets(request.targets); + if (targets.length === 0) { + return

{t("web.admin.requests.queue.notSent")}

; + } + return ( +
    + {targets.map(({ target, shared }) => ( +
  • +
    + {shared ? null : ( + <> + {target.quality} + {SPACE} + + )} + {targetServerName(target)} + {SPACE} + +
    + {target.route_name ? ( +

    + {t("web.admin.requests.queue.byRoute", { route: target.route_name })} +

    + ) : null} + {target.download ? ( + + ) : null} + {target.last_error ? ( +

    {target.last_error}

    + ) : null} +
  • + ))} +
+ ); +} diff --git a/web/src/pages/admin-requests/RequestQueue.tsx b/web/src/pages/admin-requests/RequestQueue.tsx index fc2503df7b..9555b7f709 100644 --- a/web/src/pages/admin-requests/RequestQueue.tsx +++ b/web/src/pages/admin-requests/RequestQueue.tsx @@ -3,9 +3,8 @@ import type { MouseEvent } from "react"; import { Link, useSearchParams } from "react-router"; import { Maximize2, RefreshCw, Search, X } from "lucide-react"; import type { MediaRequest } from "@/api/types"; -import type { AdminRequestCounts } from "@/api/v2/adminRequests"; +import { listAdminRequestOptionsV2, type AdminRequestCounts } from "@/api/v2/adminRequests"; import { BulkSelectionCheckbox } from "@/components/BulkSelectionCheckbox"; -import { RequestDownloadProgress } from "@/components/RequestDownloadProgress"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -29,21 +28,23 @@ import { formatMediaType, formatSeasonList, requestDetailHref } from "@/lib/medi import { cn } from "@/lib/utils"; import { RequestActionButtons, type RequestQueueActionHandlers } from "./RequestActionButtons"; import { RequestQueueDialog } from "./RequestQueueDialog"; +import { ApproveOptionsDialog, type ApprovePrompt } from "./ApproveOptionsDialog"; import { BulkProgress } from "./BulkProgress"; +import { OptionCells, TargetList } from "./QueueCells"; import { EmptyPanel, ReasonDialog, RequestPoster, RequestStateSummary, RowsSkeleton, - TargetStatusBadge, } from "./queueParts"; import { defaultRequestQueueView, parseRequestQueueUser, parseRequestQueueView, + queueColumnsStyle, REQUEST_QUEUE_VIEWS, - targetServerName, + requestOptionColumns, type RequestQueueAction, type RequestQueueMediaFilter, type RequestQueueView, @@ -51,7 +52,6 @@ import { const SEARCH_DEBOUNCE_MS = 300; const SEPARATOR = " · "; -const SPACE = " "; const MEDIA_FILTERS: { value: RequestQueueMediaFilter; label: MessageKey }[] = [ { value: "all", label: "web.admin.requests.queue.media.all" }, @@ -123,6 +123,7 @@ export function RequestQueue() { : null; if (opened !== null && openRequest === null) setOpened(null); const [prompt, setPrompt] = useState(null); + const [approvePrompt, setApprovePrompt] = useState(null); const [busy, setBusy] = useState>(() => new Map()); const approve = useApproveMediaRequest(); const decline = useDeclineMediaRequest(); @@ -160,13 +161,30 @@ export function RequestQueue() { ); } + /** + * Approves a request, first asking for the download server settings when + * its server has any to choose. A server whose choices cannot be read is + * approved with its own settings. + */ + function approveRequest(request: MediaRequest) { + track(request, "approve", async () => { + const options = await listAdminRequestOptionsV2(request.id).catch(() => []); + if (!options || options.length === 0) return approve.mutateAsync({ id: request.id }); + // A prompt already open keeps the dialog: replacing it would put this + // request under settings chosen for the other. Approve is pressed + // again once that dialog closes. + setApprovePrompt((open) => open ?? { request, options }); + return request; + }); + } + const handlers: RequestQueueActionHandlers = { locked: bulk.isRunning, busyAction: (id) => busy.get(id), run: (action: RequestQueueAction, request: MediaRequest) => { switch (action) { case "approve": - return track(request, action, () => approve.mutateAsync(request.id)); + return approveRequest(request); case "retry": return track(request, action, () => retry.mutateAsync(request.id)); case "decline": @@ -311,6 +329,15 @@ export function RequestQueue() { if (!open) setOpened(null); }} /> + + track(request, "approve", () => approve.mutateAsync({ id: request.id, options })) + } + onOpenChange={(open) => { + if (!open) setApprovePrompt(null); + }} + /> queue.data?.pages.flatMap((page) => page.items) ?? [], [queue.data]); + // A column per setting someone chose for a request on this page, such as + // a quality profile; none when nothing was chosen. + const optionColumns = useMemo(() => requestOptionColumns(rows), [rows]); + const columnsStyle = queueColumnsStyle(optionColumns.length); const selectable = view === "needs_approval"; const [selected, setSelected] = useState>(() => new Set()); const selectedRows = rows.filter((row) => selected.has(row.id)); @@ -498,10 +529,15 @@ function QueueList({
{selectable ? : null} -
+
{t("web.admin.requests.queue.column.request")} {t("web.admin.requests.queue.column.state")} {t("web.admin.requests.queue.column.servers")} + {optionColumns.map((column) => ( + + {column} + + ))}
{t("web.admin.requests.queue.column.actions")} @@ -516,6 +552,7 @@ function QueueList({ key={request.id} request={request} requester={username(request.requested_by_user_id)} + optionColumns={optionColumns} selectable={selectable} selected={selected.has(request.id)} handlers={handlers} @@ -626,6 +663,7 @@ function fromControl(event: MouseEvent) { function QueueRow({ request, requester, + optionColumns, selectable, selected, handlers, @@ -635,6 +673,8 @@ function QueueRow({ }: { request: MediaRequest; requester?: string; + /** The chosen settings shown as columns, by label. */ + optionColumns: readonly string[]; selectable: boolean; selected: boolean; handlers: RequestQueueActionHandlers; @@ -665,7 +705,10 @@ function QueueRow({
) : null} -
+
+
@@ -728,39 +772,3 @@ function QueueRow({ ); } - -function TargetList({ request }: { request: MediaRequest }) { - const t = useT(); - const targets = request.targets ?? []; - if (targets.length === 0) { - return

{t("web.admin.requests.queue.notSent")}

; - } - return ( -
    - {targets.map((target) => ( -
  • -
    - {target.quality} - {SPACE} - {targetServerName(target)} -
    - {target.route_name ? ( -

    - {t("web.admin.requests.queue.byRoute", { route: target.route_name })} -

    - ) : null} - {target.download ? ( - - ) : null} - {target.last_error ? ( -

    {target.last_error}

    - ) : null} -
  • - ))} -
- ); -} diff --git a/web/src/pages/admin-requests/RequestQueueDialog.tsx b/web/src/pages/admin-requests/RequestQueueDialog.tsx index 4972382be0..f1b9953b7c 100644 --- a/web/src/pages/admin-requests/RequestQueueDialog.tsx +++ b/web/src/pages/admin-requests/RequestQueueDialog.tsx @@ -44,7 +44,12 @@ import { RoutePreviewResult } from "@/pages/admin-settings/RequestRoutePreview"; import { requestRouterInstallations } from "@/pages/admin-settings/requestServerModel"; import { RequestActionButtons, type RequestQueueActionHandlers } from "./RequestActionButtons"; import { RequestPoster, RequestStateSummary, TargetStatusBadge } from "./queueParts"; -import { formatRequestEventType, requestQueueView, targetServerName } from "./requestQueueModel"; +import { + distinctTargets, + formatRequestEventType, + requestQueueView, + targetServerName, +} from "./requestQueueModel"; const SEPARATOR = " · "; const SPACE = " "; @@ -177,6 +182,12 @@ function RequestDetail({ {formatDateTime(request.completed_at)} ) : null} + {/* What the requester chose for the download server, in the plugin's own words. */} + {request.options?.map((choice) => ( + + {choice.value_label} + + ))} {request.media_type === "series" ? ( {request.seasons?.length @@ -287,8 +298,12 @@ function TargetsTable({ request }: { request: MediaRequest }) { - {request.targets?.map((target) => ( - + {distinctTargets(request.targets).map((entry) => ( + ))} @@ -296,11 +311,17 @@ function TargetsTable({ request }: { request: MediaRequest }) { ); } -function TargetRows({ target }: { target: NonNullable[number] }) { +function TargetRows({ + target, + label, +}: { + target: NonNullable[number]; + label: string; +}) { return ( <> - {target.quality} + {label} {targetServerName(target)} {target.route_name || NO_ROUTE} diff --git a/web/src/pages/admin-requests/requestQueueModel.test.ts b/web/src/pages/admin-requests/requestQueueModel.test.ts index efdddb0809..8c0bd8c56a 100644 --- a/web/src/pages/admin-requests/requestQueueModel.test.ts +++ b/web/src/pages/admin-requests/requestQueueModel.test.ts @@ -4,10 +4,13 @@ import { describe, expect, it } from "vitest"; import type { MediaRequest } from "@/api/types"; import { defaultRequestQueueView, + distinctTargets, parseRequestQueueUser, parseRequestQueueView, requestQueueActions, requestQueueView, + requestOptionColumns, + requestOptionValue, } from "./requestQueueModel"; type Fields = Pick; @@ -60,3 +63,48 @@ describe("queue links", () => { } }); }); + +describe("distinctTargets", () => { + const target = (id: number, quality: string, external_id?: string, integration_id = "seerr") => + ({ id, quality, external_id, integration_id, status: "queued" }) as NonNullable< + MediaRequest["targets"] + >[number]; + + it("shows one download that serves both qualities once", () => { + const entries = distinctTargets([target(1, "1080p", "42"), target(2, "2160p", "42")]); + expect(entries.map((entry) => [entry.target.id, entry.shared])).toEqual([[1, true]]); + }); + + it("keeps separate downloads, and targets without an external id, apart", () => { + const entries = distinctTargets([ + target(1, "1080p", "42"), + target(2, "2160p", "43"), + target(3, "1080p", "42", "other"), + target(4, "1080p"), + target(5, "2160p"), + ]); + expect(entries.map((entry) => entry.target.id)).toEqual([1, 2, 3, 4, 5]); + expect(entries.every((entry) => !entry.shared)).toBe(true); + }); +}); + +describe("requestOptionColumns", () => { + const movie = { + options: [ + { key: "radarr_profile_id", label: "Quality", value: "4", value_label: "Ultra-HD" }, + { key: "radarr_root_folder", label: "Folder", value: "/m", value_label: "/movies" }, + ], + }; + const series = { + options: [ + { key: "sonarr_profile_id", label: "Quality", value: "9", value_label: "Series UHD" }, + ], + }; + + it("names each chosen setting once, and reads a request's value for it", () => { + expect(requestOptionColumns([{}, series, movie])).toEqual(["Quality", "Folder"]); + expect(requestOptionColumns([{}, { options: [] }])).toEqual([]); + expect(requestOptionValue(series, "Quality")).toBe("Series UHD"); + expect(requestOptionValue(series, "Folder")).toBeUndefined(); + }); +}); diff --git a/web/src/pages/admin-requests/requestQueueModel.ts b/web/src/pages/admin-requests/requestQueueModel.ts index de59d3a4b8..82be137120 100644 --- a/web/src/pages/admin-requests/requestQueueModel.ts +++ b/web/src/pages/admin-requests/requestQueueModel.ts @@ -1,3 +1,4 @@ +import type { CSSProperties } from "react"; import type { MediaRequest, RequestMediaType, RequestTarget } from "@/api/types"; import type { AdminRequestCounts, AdminRequestQueueView } from "@/api/v2/adminRequests"; import { t, type MessageKey } from "@/i18n"; @@ -132,6 +133,57 @@ export function targetServerName( ); } +/** + * A request's targets with those that are one copy on one server shown once. + * A server that decides the resolution itself (by a quality profile) answers + * Silo's HD and 4K versions with the same download, which comes back as two + * targets carrying one external id. + */ +export function distinctTargets( + targets: readonly RequestTarget[] | undefined, +): { target: RequestTarget; shared: boolean }[] { + const out: { target: RequestTarget; shared: boolean }[] = []; + const seen = new Map(); + for (const target of targets ?? []) { + const key = + target.integration_id && target.external_id + ? `${target.integration_id}\n${target.external_id}` + : undefined; + const earlier = key === undefined ? undefined : seen.get(key); + if (earlier !== undefined) { + const first = out[earlier]; + if (first) first.shared = true; + continue; + } + if (key !== undefined) seen.set(key, out.length); + out.push({ target, shared: false }); + } + return out; +} + +/** + * The settings chosen for the given requests (a quality profile, a folder), + * as the column names to show them under: each label once, in the order + * first seen. Movies and series name the same setting with the same label. + */ +export function requestOptionColumns(requests: readonly Pick[]): string[] { + const labels: string[] = []; + for (const request of requests) { + for (const choice of request.options ?? []) { + if (!labels.includes(choice.label)) labels.push(choice.label); + } + } + return labels; +} + +/** What a request chose for the setting a column names; undefined when nothing. */ +export function requestOptionValue( + request: Pick, + column: string, +): string | undefined { + return request.options?.find((choice) => choice.label === column)?.value_label; +} + /** The request's own closing reason, or the error that stopped it. */ export function requestProblemText( request: Pick, @@ -140,3 +192,10 @@ export function requestProblemText( if (request.outcome_reason) return { text: request.outcome_reason, error: false }; return null; } + +/** The queue's columns: request, state, servers, then one per chosen setting. */ +export function queueColumnsStyle(optionColumns: number) { + return { + "--queue-columns": `minmax(0,1.4fr) minmax(0,1fr) minmax(0,1.3fr)${" minmax(0,0.8fr)".repeat(optionColumns)}`, + } as CSSProperties; +}