diff --git a/.silo-translations b/.silo-translations
index c1b275f1062..023f2c8281e 100644
--- a/.silo-translations
+++ b/.silo-translations
@@ -1,3 +1,3 @@
platform=web
-version=2026.12.03-957f0eb
-sha256=391cb6012923fce2d4fd6f1b827c009bf48ea00748f91e169550a50619516ba6
+version=local-65c290042b51
+sha256=-
diff --git a/contracts/api/v2/fixtures/admin_account_profile_clear_pin.json b/contracts/api/v2/fixtures/admin_account_profile_clear_pin.json
index 9cd1bce1477..a9d1ce50900 100644
--- a/contracts/api/v2/fixtures/admin_account_profile_clear_pin.json
+++ b/contracts/api/v2/fixtures/admin_account_profile_clear_pin.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/fixtures/admin_account_profile_create.json b/contracts/api/v2/fixtures/admin_account_profile_create.json
index 9f9ba0bb241..31745fb4405 100644
--- a/contracts/api/v2/fixtures/admin_account_profile_create.json
+++ b/contracts/api/v2/fixtures/admin_account_profile_create.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/fixtures/admin_account_profile_get.json b/contracts/api/v2/fixtures/admin_account_profile_get.json
index 9cd1bce1477..a9d1ce50900 100644
--- a/contracts/api/v2/fixtures/admin_account_profile_get.json
+++ b/contracts/api/v2/fixtures/admin_account_profile_get.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/fixtures/admin_catalog_capabilities.json b/contracts/api/v2/fixtures/admin_catalog_capabilities.json
index 341578f452d..24c8cbcd144 100644
--- a/contracts/api/v2/fixtures/admin_catalog_capabilities.json
+++ b/contracts/api/v2/fixtures/admin_catalog_capabilities.json
@@ -1,5 +1,5 @@
{
- "revision": "87ed2f969d24f16ec7d7c81e2bf71e1f696803213b2b6badcc3b870a70e47304",
+ "revision": "82eac3785d46084df08afe3dd492e5747b69683c83b5a7a71d42a27b16ab76e4",
"state": "available",
"allowed": true,
"item_listing": true,
@@ -12,5 +12,6 @@
"item_posters": false,
"metadata_listing": true,
"image_slot_locks": true,
- "episode_stills": true
+ "episode_stills": true,
+ "custom_tags": true
}
diff --git a/contracts/api/v2/fixtures/create_profile_created.json b/contracts/api/v2/fixtures/create_profile_created.json
index 3c970a314d9..be7978f6042 100644
--- a/contracts/api/v2/fixtures/create_profile_created.json
+++ b/contracts/api/v2/fixtures/create_profile_created.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/fixtures/list_profiles_ok.json b/contracts/api/v2/fixtures/list_profiles_ok.json
index dd4a8b5d441..73912198e7e 100644
--- a/contracts/api/v2/fixtures/list_profiles_ok.json
+++ b/contracts/api/v2/fixtures/list_profiles_ok.json
@@ -13,6 +13,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
@@ -35,5 +36,6 @@
"avatar_upload_enabled": false,
"max_advisory_age_supported": true,
"require_advisory_age_supported": true,
- "requests_allowed_supported": true
+ "requests_allowed_supported": true,
+ "excluded_tags_supported": true
}
diff --git a/contracts/api/v2/fixtures/update_profile_ok.json b/contracts/api/v2/fixtures/update_profile_ok.json
index 9cd1bce1477..a9d1ce50900 100644
--- a/contracts/api/v2/fixtures/update_profile_ok.json
+++ b/contracts/api/v2/fixtures/update_profile_ok.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/fixtures/upload_profile_avatar_ok.json b/contracts/api/v2/fixtures/upload_profile_avatar_ok.json
index d61ed294983..87732c91197 100644
--- a/contracts/api/v2/fixtures/upload_profile_avatar_ok.json
+++ b/contracts/api/v2/fixtures/upload_profile_avatar_ok.json
@@ -11,6 +11,7 @@
"max_advisory_age": null,
"require_advisory_age": false,
"requests_allowed": true,
+ "excluded_tags": [],
"quality_preference": "auto",
"language": "en",
"preferred_metadata_language": "",
diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json
index 68dc52bc3a4..21fe8fe0fd6 100644
--- a/contracts/api/v2/openapi.json
+++ b/contracts/api/v2/openapi.json
@@ -5836,6 +5836,10 @@
"description": "Whether the current principal may use the capability",
"type": "boolean"
},
+ "custom_tags": {
+ "description": "updateAdminItemMetadata accepts custom_tags on a movie or series, item detail returns them to a metadata curator, and listCatalogCustomTags is served",
+ "type": "boolean"
+ },
"episode_stills": {
"description": "listAdminItemImages lists an episode's still choices and current still_url, and uploadAdminItemImage accepts type still for an episode",
"type": "boolean"
@@ -5908,6 +5912,7 @@
"metadata_listing",
"image_slot_locks",
"episode_stills",
+ "custom_tags",
"revision",
"state",
"allowed"
@@ -16714,6 +16719,19 @@
"null"
]
},
+ "custom_tags": {
+ "description": "Replaces a movie's or series' custom tags: free-text labels no metadata provider writes, so a refresh keeps them. A profile's excluded_tags hide every title carrying one of its tags. Each tag is trimmed with inner whitespace collapsed, and tags that differ only in case are kept once, in the first spelling. At most 50 tags of at most 64 characters; an empty array clears them. getAdminCatalogCapabilities reports custom_tags when this member is accepted",
+ "examples": [
+ [
+ "Gore"
+ ]
+ ],
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 50,
+ "type": "array"
+ },
"episode_number": {
"format": "int64",
"type": [
@@ -32343,6 +32361,31 @@
],
"type": "object"
},
+ "CatalogCustomTag": {
+ "additionalProperties": false,
+ "properties": {
+ "tag": {
+ "description": "The tag in its most used spelling; tags that differ only in case are one tag",
+ "examples": [
+ "Gore"
+ ],
+ "type": "string"
+ },
+ "title_count": {
+ "description": "How many movies and series the caller can see that carry the tag",
+ "examples": [
+ 11
+ ],
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "tag",
+ "title_count"
+ ],
+ "type": "object"
+ },
"CatalogEffectiveSort": {
"additionalProperties": false,
"properties": {
@@ -33076,6 +33119,13 @@
},
"type": "array"
},
+ "custom_tags": {
+ "description": "A movie's or series' custom tags, the free-text labels set through updateAdminItemMetadata. Returned only to a viewer who curates the item's metadata; omitted for everyone else and when the item has none",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"disc_url": {
"description": "Presigned, short-lived. Transparent disc art. Movies only",
"format": "uri-reference",
@@ -35937,6 +35987,26 @@
],
"type": "object"
},
+ "CollectionCatalogCustomTag": {
+ "additionalProperties": false,
+ "properties": {
+ "items": {
+ "description": "The page's items; empty, never null",
+ "items": {
+ "$ref": "#/components/schemas/CatalogCustomTag"
+ },
+ "type": "array"
+ },
+ "page": {
+ "$ref": "#/components/schemas/PageInfo",
+ "description": "Cursor state; absent for bounded unpaginated collections"
+ }
+ },
+ "required": [
+ "items"
+ ],
+ "type": "object"
+ },
"CollectionDisplayFilterPresets": {
"additionalProperties": false,
"properties": {
@@ -54965,6 +55035,18 @@
"patternDescription": "a non-zero RFC 3339 instant",
"type": "string"
},
+ "excluded_tags": {
+ "description": "Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager; empty means none",
+ "examples": [
+ [
+ "Gore"
+ ]
+ ],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"has_pin": {
"examples": [
false
@@ -55111,6 +55193,7 @@
"max_advisory_age",
"require_advisory_age",
"requests_allowed",
+ "excluded_tags",
"quality_preference",
"language",
"preferred_metadata_language",
@@ -55157,6 +55240,13 @@
],
"type": "boolean"
},
+ "excluded_tags_supported": {
+ "description": "Whether profiles accept excluded_tags and the server enforces it",
+ "examples": [
+ true
+ ],
+ "type": "boolean"
+ },
"items": {
"description": "The page's items; empty, never null",
"items": {
@@ -55204,6 +55294,7 @@
"max_advisory_age_supported",
"require_advisory_age_supported",
"requests_allowed_supported",
+ "excluded_tags_supported",
"items"
],
"type": "object"
@@ -55260,6 +55351,19 @@
],
"type": "string"
},
+ "excluded_tags": {
+ "description": "Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; omitted means none",
+ "examples": [
+ [
+ "Gore"
+ ]
+ ],
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 50,
+ "type": "array"
+ },
"is_child": {
"examples": [
false
@@ -55869,6 +55973,19 @@
"null"
]
},
+ "excluded_tags": {
+ "description": "Replaces the excluded tags. Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; an empty array clears them",
+ "examples": [
+ [
+ "Gore"
+ ]
+ ],
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 50,
+ "type": "array"
+ },
"is_child": {
"examples": [
false
@@ -62872,13 +62989,14 @@
"type": "string"
},
"state": {
- "description": "within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help",
+ "description": "within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help. hidden_by_tag: the title carries a custom tag the profile excludes, which no allowance lifts",
"enum": [
"within_limits",
"allowed",
"allowed_by_collection",
"above_limit",
- "no_library_access"
+ "no_library_access",
+ "hidden_by_tag"
],
"examples": [
"above_limit"
@@ -170575,6 +170693,149 @@
"x-silo-service-backed": true
}
},
+ "/api/v2/catalog/custom-tags": {
+ "get": {
+ "operationId": "listCatalogCustomTags",
+ "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"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CollectionCatalogCustomTag"
+ }
+ }
+ },
+ "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": "The custom tags on the movies and series the caller can see, most used first, for the metadata editor and a profile's excluded_tags.",
+ "tags": [
+ "catalog"
+ ],
+ "x-silo-class": "profile_scoped",
+ "x-silo-service-backed": true
+ }
+ },
"/api/v2/catalog/filters": {
"get": {
"operationId": "getCatalogFilters",
diff --git a/docs/admin-api.md b/docs/admin-api.md
index f55dfc8565b..fdc7b9a9155 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -4011,7 +4011,7 @@ identifies the acting administrator. Actor filters use
| `user.login_session_revoked` | `deleteSession`, `deleteAdminUserLoginSession` | `login_session_id` (before) |
| `user.login_sessions_revoked` | `deleteAdminUserLoginSessions` | `revoked_login_sessions` count; recorded when the call ended any login session or Audiobookshelf, Jellyfin-compatible or device sign-in |
| `api_key.created`, `api_key.updated`, `api_key.deleted` | `createAdminAPIKey`, `updateAdminAPIKeyTier`, `deleteAdminAPIKey`, `createPersonalAPIKey`, `revokePersonalAPIKey` | `user_id` (owner), `label`, `rate_tier`, `scopes` (an empty list is an unscoped key with its owner's full access) |
-| `profile.created`, `profile.updated`, `profile.deleted` | `createProfile`, `updateProfile`, `deleteProfile` | `name`, `is_child`, `is_primary`, `max_content_rating`, `max_advisory_age`, `require_advisory_age`, `library_restrictions_enabled`, `allowed_library_ids`, `max_playback_quality`, `pin` |
+| `profile.created`, `profile.updated`, `profile.deleted` | `createProfile`, `updateProfile`, `deleteProfile` | `name`, `is_child`, `is_primary`, `max_content_rating`, `max_advisory_age`, `require_advisory_age`, `excluded_tags`, `library_restrictions_enabled`, `allowed_library_ids`, `max_playback_quality`, `pin` |
| `profile.updated` | `allowTitle`, `disallowTitle`, `allowCollection`, `disallowCollection`, `allowCollectionTitles`; target is the profile the allowance is for | `allowed_title` or `allowed_collection` (the item or collection ID, after when allowed, before when removed); `allowed_titles_added` count for a copy |
| `direct_connection.enrolled` | `enrollDirectConnectionDevice`; target is the device ID; recorded for the first enrollment of a node key for a device (a key replacement included), not for a renewal of the same key | `device_id`, `node_key` (after); never the signaling ticket |
diff --git a/docs/architecture/backups.md b/docs/architecture/backups.md
index 01cdb5ba38f..85c201c89dd 100644
--- a/docs/architecture/backups.md
+++ b/docs/architecture/backups.md
@@ -1342,7 +1342,7 @@ backup. `is_owner` and `break_glass` are never carried.
**Profile fields:** name, avatar, `is_primary`, PIN hash, and every field the
access resolver (`internal/access/resolver.go`) reads to decide access:
`is_child`, `max_content_rating`, `max_advisory_age`, `require_advisory_age`,
-`requests_blocked`, `library_restrictions_enabled`, the allowed libraries
+`requests_blocked`, `excluded_tags`, `library_restrictions_enabled`, the allowed libraries
(`user_profile_allowed_libraries`), and `max_playback_quality`. The PIN
revision is not carried; a restored profile starts its own. A profile restored
as the account's primary drops its library limit, since the primary profile
@@ -2115,7 +2115,8 @@ neither list.
both sides have, a
protection or restriction lifted or loosened (its PIN, becoming the
primary profile, child profile, rating or advisory-age ceiling, block
- from requests, library restriction, playback-quality ceiling), or a
+ from requests, an excluded custom tag, library restriction,
+ playback-quality ceiling), or a
looser request policy
(requests at all, without limit, more titles or over a shorter window,
or with automatic approval, as `requests.LayeredPolicy` resolves it from
diff --git a/docs/architecture/title-allowances.md b/docs/architecture/title-allowances.md
index c9980f080ca..4e58ece7b09 100644
--- a/docs/architecture/title-allowances.md
+++ b/docs/architecture/title-allowances.md
@@ -21,7 +21,8 @@ would compare episode IDs with title IDs and hide allowed episodes. Extras have
their own and follow their title.
An allowance lifts only the profile's own maturity limits. Library access,
-hidden libraries and every other restriction still apply, and the API refuses
+hidden libraries, excluded custom tags (`MaturityLimits.ExcludedTags`, which
+`RatingActive` leaves out) and every other restriction still apply, and the API refuses
an allowance for a title the profile cannot reach through its libraries. Two
stricter limits also win over it:
diff --git a/docs/catalog-api.md b/docs/catalog-api.md
index 6291daa0b17..19383491f0c 100644
--- a/docs/catalog-api.md
+++ b/docs/catalog-api.md
@@ -853,8 +853,9 @@ answers `403` otherwise.
- `GET /api/v2/catalog/items/{id}/title-allowances` lists every other profile
on the account with its `state` for the movie or series: `within_limits`,
- `allowed`, `allowed_by_collection`, `above_limit` (can be allowed), or
- `no_library_access`.
+ `allowed`, `allowed_by_collection`, `above_limit` (can be allowed),
+ `no_library_access`, or `hidden_by_tag` (the title carries a custom tag the
+ profile excludes, which no allowance lifts).
- `PUT` and `DELETE /api/v2/profiles/{id}/allowed-titles/{item_id}` add and
remove one allowance; both answer `204` and repeat safely. `PUT` answers `422`
for an episode or season (allow the series), for a profile with no limit
@@ -1580,6 +1581,38 @@ discovery with `requests_allowed` (boolean, default `true`); see
[media requests](architecture/media-requests.md#who-can-request). Detect it with
`requests_allowed_supported` on the `listProfiles` response.
+### Custom tags
+
+Custom tags are free-text labels an admin puts on a movie or series. No
+metadata provider writes them, so a refresh, Reset to Provider, and a rematch
+to another provider id keep them; merging two items keeps the tags of both.
+
+- Write them with `custom_tags` on `updateAdminItemMetadata` (an array; an empty
+ array clears them). Each tag is trimmed with inner whitespace collapsed, and
+ tags that differ only in case are kept once, in the first spelling. At most 50
+ tags of at most 64 characters each. Seasons, episodes and other item types
+ have none. `getAdminCatalogCapabilities` reports `custom_tags` when the server
+ accepts the member.
+- The item detail carries `custom_tags` only for a viewer who curates metadata
+ (`ViewerCurates`), as it does other curator-only fields; it is absent when
+ the item has none.
+- `listCatalogCustomTags` (`GET /api/v2/catalog/custom-tags`) returns the tags
+ on the movies and series the active profile can see, one entry per tag
+ whatever its spelling, each with `title_count`, most used first. It feeds the
+ metadata editor's suggestions and the profile editor's tag picker.
+
+A household manager can hide every title carrying any of a profile's
+`excluded_tags` (an array on the v2 profile operations, with the same bounds).
+Tags match without regard to case. A series' tags hide its seasons and
+episodes. The limit applies everywhere the content-rating ceiling does, through
+`catalog.ApplyMaturityLimits`, and a title allowance never lifts it: an
+allowance lifts only the rating and advisory-age limits. Only a household
+manager can set or clear the field, and changing it bumps the account's access
+policy revision. Media-request discovery cannot apply it, because titles
+outside the library carry no tags. Detect support with
+`excluded_tags_supported` on the `listProfiles` response, and do not send the
+member to a server that does not report it.
+
## Ratings on title pages
Every client shows a title's external ratings the same way: the item detail
diff --git a/internal/access/household.go b/internal/access/household.go
index ed71defac60..a63ec13308a 100644
--- a/internal/access/household.go
+++ b/internal/access/household.go
@@ -13,7 +13,8 @@ import "github.com/Silo-Server/silo-server/internal/userstore"
// request names that profile, and a household that must not fall back to
// account scope gives the profile one of these limits.
func ProfileIsLimited(profile userstore.Profile) bool {
- maturity := MaturityLimits{MaxContentRating: profile.MaxContentRating, MaxAdvisoryAge: profile.MaxAdvisoryAge}
+ maturity := MaturityLimits{MaxContentRating: profile.MaxContentRating, MaxAdvisoryAge: profile.MaxAdvisoryAge}.
+ WithExcludedTags(profile.ExcludedTags)
_, libraryLimited := ProfileLibraryLimit(&profile)
return profile.PINHash != "" ||
maturity.Active() ||
diff --git a/internal/access/household_test.go b/internal/access/household_test.go
index 211e8b61df9..dd0aab53bc5 100644
--- a/internal/access/household_test.go
+++ b/internal/access/household_test.go
@@ -19,6 +19,7 @@ func TestProfileIsLimited(t *testing.T) {
// restriction, not the absence of one.
{"blank deny-all ceiling", userstore.Profile{ID: "p", MaxContentRating: " "}, true},
{"advisory limit", userstore.Profile{ID: "p", MaxAdvisoryAge: 12}, true},
+ {"excluded tag", userstore.Profile{ID: "p", ExcludedTags: []string{"Gore"}}, true},
{"library restriction", userstore.Profile{ID: "p", LibraryRestrictionsEnabled: true, AllowedLibraryIDs: []int{1}}, true},
{"empty library restriction", userstore.Profile{ID: "p", LibraryRestrictionsEnabled: true}, true},
// Library IDs without the restriction flag are ignored by the resolver.
diff --git a/internal/access/resolver.go b/internal/access/resolver.go
index 3345adee42f..ba00100be1b 100644
--- a/internal/access/resolver.go
+++ b/internal/access/resolver.go
@@ -276,7 +276,7 @@ func ProfileMaturity(profile *userstore.Profile, allowUnrated bool) MaturityLimi
AllowUnratedContent: allowUnrated,
MaxAdvisoryAge: profile.MaxAdvisoryAge,
RequireAdvisoryAge: profile.RequireAdvisoryAge && profile.MaxAdvisoryAge > 0,
- }.WithAllowedTitles(profile.AllowedTitleIDs)
+ }.WithExcludedTags(profile.ExcludedTags).WithAllowedTitles(profile.AllowedTitleIDs)
}
// ProfileLibraries is the libraries a profile may see under its account's
diff --git a/internal/access/tags.go b/internal/access/tags.go
new file mode 100644
index 00000000000..ae203f6c171
--- /dev/null
+++ b/internal/access/tags.go
@@ -0,0 +1,86 @@
+package access
+
+import (
+ "slices"
+ "strings"
+ "unicode/utf8"
+)
+
+// Custom tag bounds. A title or a profile holds at most MaxCustomTags tags of
+// at most MaxCustomTagLength characters each.
+const (
+ MaxCustomTags = 50
+ MaxCustomTagLength = 64
+)
+
+// NormalizeTag is a custom tag as stored: trimmed, with each run of
+// whitespace inside it collapsed to one space. "" means no tag.
+func NormalizeTag(tag string) string {
+ return strings.Join(strings.Fields(tag), " ")
+}
+
+// TagKey is the form tags are compared in: the normalized tag in lowercase,
+// so "Gore", "gore" and " GORE " are one tag.
+func TagKey(tag string) string {
+ return strings.ToLower(NormalizeTag(tag))
+}
+
+// NormalizeTags normalizes each tag, drops empty ones, and keeps the first
+// spelling of tags that share a TagKey, in the order given. It returns a
+// non-nil slice, and reports false when a tag is longer than
+// MaxCustomTagLength or more than MaxCustomTags remain.
+func NormalizeTags(tags []string) ([]string, bool) {
+ out := firstSpellings(tags)
+ if len(out) > MaxCustomTags {
+ return nil, false
+ }
+ for _, tag := range out {
+ if utf8.RuneCountInString(tag) > MaxCustomTagLength {
+ return nil, false
+ }
+ }
+ return out, true
+}
+
+// DistinctTags returns the normalized tags, the first spelling of each
+// TagKey, ordered by TagKey; nil when none remain. Catalog SQL matches them
+// with lower() on both sides, so Go's and the database's case folding never
+// have to agree.
+func DistinctTags(tags []string) []string {
+ out := firstSpellings(tags)
+ if len(out) == 0 {
+ return nil
+ }
+ slices.SortFunc(out, func(a, b string) int { return strings.Compare(strings.ToLower(a), strings.ToLower(b)) })
+ return out
+}
+
+// firstSpellings normalizes tags, drops empty ones and keeps the first
+// spelling of each TagKey, in the order given; never nil.
+func firstSpellings(tags []string) []string {
+ out := make([]string, 0, len(tags))
+ seen := make(map[string]struct{}, len(tags))
+ for _, tag := range tags {
+ tag = NormalizeTag(tag)
+ key := strings.ToLower(tag)
+ if _, dup := seen[key]; tag == "" || dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ out = append(out, tag)
+ }
+ return out
+}
+
+// TagKeys returns the TagKeys of tags, sorted and distinct, without empty
+// ones; nil when none remain.
+func TagKeys(tags []string) []string {
+ var keys []string
+ for _, tag := range tags {
+ if key := TagKey(tag); key != "" {
+ keys = append(keys, key)
+ }
+ }
+ slices.Sort(keys)
+ return slices.Compact(keys)
+}
diff --git a/internal/access/types.go b/internal/access/types.go
index 05377ce9aaf..83d4c4e904b 100644
--- a/internal/access/types.go
+++ b/internal/access/types.go
@@ -111,14 +111,30 @@ type MaturityLimits struct {
//
// omitempty for the same reason as MaxAdvisoryAge.
AllowedTitleIDs []string `json:",omitempty"`
+ // ExcludedTags are the profile's excluded custom tags, one spelling per
+ // TagKey (DistinctTags): a movie or series carrying any of them is hidden, and so
+ // is every season and episode of such a series. A title allowance does
+ // not lift it; allowances answer rating limits only. Build it with
+ // WithExcludedTags.
+ //
+ // omitempty for the same reason as MaxAdvisoryAge.
+ ExcludedTags []string `json:",omitempty"`
+}
+
+// WithExcludedTags returns the limits excluding tags, one spelling per
+// TagKey in TagKey order, so two spellings of one tag key and render alike.
+// The spellings are kept because the SQL lowercases both sides itself.
+func (m MaturityLimits) WithExcludedTags(tags []string) MaturityLimits {
+ m.ExcludedTags = DistinctTags(tags)
+ return m
}
// WithAllowedTitles returns the limits carrying ids as their allowed titles
-// when the limits restrict anything, and unchanged otherwise: an allowance
-// above no limit means nothing, and leaving it out keeps unrestricted scopes
+// when a rating limit is set (RatingActive), and unchanged otherwise: an
+// allowance above no rating limit means nothing, and leaving it out keeps unrestricted scopes
// and their cache keys exactly as they were.
func (m MaturityLimits) WithAllowedTitles(ids []string) MaturityLimits {
- if !m.Active() || len(ids) == 0 {
+ if !m.RatingActive() || len(ids) == 0 {
m.AllowedTitleIDs = nil
return m
}
@@ -136,6 +152,12 @@ func (m MaturityLimits) HidesUnadvised() bool {
// Active reports whether the limits restrict anything at all.
func (m MaturityLimits) Active() bool {
+ return m.RatingActive() || len(m.ExcludedTags) > 0
+}
+
+// RatingActive reports whether a rating limit is set: a content-rating
+// ceiling or an advisory-age limit, the limits a title allowance lifts.
+func (m MaturityLimits) RatingActive() bool {
return HasCeiling(m.MaxContentRating) || m.MaxAdvisoryAge > 0
}
diff --git a/internal/api/handlers/admin.go b/internal/api/handlers/admin.go
index 32a39092edc..6003b583fc5 100644
--- a/internal/api/handlers/admin.go
+++ b/internal/api/handlers/admin.go
@@ -759,6 +759,9 @@ type UpdateItemMetadataRequest struct {
SeasonNumber *int `json:"season_number"`
EpisodeNumber *int `json:"episode_number"`
LockedFields *[]int `json:"locked_fields"`
+ // CustomTags replaces a movie's or series' custom tags. /api/v1 is
+ // frozen, so only v2 sets it (json:"-").
+ CustomTags *[]string `json:"-"`
}
// --- Server Settings endpoints ---
diff --git a/internal/api/handlers/admin_item_metadata_service.go b/internal/api/handlers/admin_item_metadata_service.go
index 8820a009293..d956e3da217 100644
--- a/internal/api/handlers/admin_item_metadata_service.go
+++ b/internal/api/handlers/admin_item_metadata_service.go
@@ -104,6 +104,14 @@ func (h *AdminHandler) UpdateCatalogItemMetadata(ctx context.Context, contentID
}
}
+ if req.CustomTags != nil {
+ tags, apiErr := normalizeTagsField("custom_tags", *req.CustomTags)
+ if apiErr != nil {
+ return nil, apiErr
+ }
+ req.CustomTags = &tags
+ }
+
upd := catalog.MetadataUpdate{
Title: req.Title, SortTitle: req.SortTitle, OriginalTitle: req.OriginalTitle,
Overview: req.Overview, Tagline: req.Tagline, ContentRating: req.ContentRating,
@@ -117,6 +125,7 @@ func (h *AdminHandler) UpdateCatalogItemMetadata(ctx context.Context, contentID
ImdbID: req.ImdbID, TmdbID: req.TmdbID, TvdbID: req.TvdbID,
SeasonNumber: req.SeasonNumber, EpisodeNumber: req.EpisodeNumber,
LockedFields: req.LockedFields,
+ CustomTags: req.CustomTags,
Clear: cleared,
}
@@ -125,10 +134,17 @@ func (h *AdminHandler) UpdateCatalogItemMetadata(ctx context.Context, contentID
if errors.Is(err, access.ErrMetadataCurationScope) {
return nil, metadataCurationForbidden()
}
+ if errors.Is(err, catalog.ErrCustomTagsUnsupported) {
+ return nil, customTagsUnsupported()
+ }
if !errors.Is(err, catalog.ErrItemNotFound) {
slog.ErrorContext(ctx, "admin: update item metadata failed", "component", "api", "content_id", contentID, "error", err)
return nil, apiError(http.StatusInternalServerError, "internal_error", "Failed to update metadata")
}
+ // Seasons and episodes have no custom tags; their series' tags apply.
+ if upd.CustomTags != nil {
+ return nil, customTagsUnsupported()
+ }
if err := h.DetailSvc.UpdateSeasonMetadata(ctx, contentID, &upd); err != nil {
if !errors.Is(err, catalog.ErrSeasonNotFound) {
slog.ErrorContext(ctx, "admin: update season metadata failed", "component", "api", "content_id", contentID, "error", err)
@@ -158,5 +174,13 @@ func (h *AdminHandler) UpdateCatalogItemMetadata(ctx context.Context, contentID
slog.ErrorContext(ctx, "admin: fetch updated detail failed", "component", "api", "content_id", contentID, "error", err)
return nil, apiError(http.StatusInternalServerError, "internal_error", "Updated but failed to fetch result")
}
+ if err := h.DetailSvc.AttachCustomTags(ctx, detail); err != nil {
+ slog.ErrorContext(ctx, "admin: fetch updated custom tags failed", "component", "api", "content_id", contentID, "error", err)
+ return nil, apiError(http.StatusInternalServerError, "internal_error", "Updated but failed to fetch result")
+ }
return detail, nil
}
+
+func customTagsUnsupported() error {
+ return fieldError("custom_tags", "Only movies and series have custom tags")
+}
diff --git a/internal/api/handlers/catalog_resources.go b/internal/api/handlers/catalog_resources.go
index ce424e3e862..d46d7f94ba6 100644
--- a/internal/api/handlers/catalog_resources.go
+++ b/internal/api/handlers/catalog_resources.go
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"fmt"
+ "log/slog"
"strconv"
"github.com/jackc/pgx/v5"
@@ -165,6 +166,8 @@ func (h *CatalogResourceHandler) enrichItemDetail(ctx context.Context, v ItemVie
detail.ViewerCurates = curates
if !detail.ViewerCurates {
detail.HideFileIdentity()
+ } else if err := h.items.detailSvc.AttachCustomTags(ctx, detail); err != nil {
+ slog.WarnContext(ctx, "catalog: reading custom tags failed", "component", "api", "content_id", detail.ContentID, "error", err)
}
if batched {
diff --git a/internal/api/handlers/profiles.go b/internal/api/handlers/profiles.go
index 0d800f631ac..0d8d759aa24 100644
--- a/internal/api/handlers/profiles.go
+++ b/internal/api/handlers/profiles.go
@@ -133,20 +133,23 @@ type ProfileCreateRequest struct {
RequireAdvisoryAge bool `json:"-"`
// RequestsBlocked keeps the profile out of requests and request
// discovery. v2-only (json:"-"); v2 carries it as requests_allowed.
- RequestsBlocked bool `json:"-"`
- QualityPreference string `json:"quality_preference,omitempty"`
- Language string `json:"language,omitempty"`
- PreferredMetadataLanguage string `json:"preferred_metadata_language,omitempty"`
- SubtitleLanguage string `json:"subtitle_language,omitempty"`
- SubtitleMode string `json:"subtitle_mode,omitempty"`
- AutoSkipIntro bool `json:"auto_skip_intro"`
- AutoSkipCredits bool `json:"auto_skip_credits"`
- AutoSkipRecap bool `json:"auto_skip_recap"`
- AutoPlayNextPreview bool `json:"auto_play_next_preview"`
- ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty"`
- LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
- AllowedLibraryIDs []int `json:"allowed_library_ids"`
- MaxPlaybackQuality string `json:"max_playback_quality"`
+ RequestsBlocked bool `json:"-"`
+ // ExcludedTags are custom tags the profile may not see. v2-only
+ // (json:"-").
+ ExcludedTags []string `json:"-"`
+ QualityPreference string `json:"quality_preference,omitempty"`
+ Language string `json:"language,omitempty"`
+ PreferredMetadataLanguage string `json:"preferred_metadata_language,omitempty"`
+ SubtitleLanguage string `json:"subtitle_language,omitempty"`
+ SubtitleMode string `json:"subtitle_mode,omitempty"`
+ AutoSkipIntro bool `json:"auto_skip_intro"`
+ AutoSkipCredits bool `json:"auto_skip_credits"`
+ AutoSkipRecap bool `json:"auto_skip_recap"`
+ AutoPlayNextPreview bool `json:"auto_play_next_preview"`
+ ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty"`
+ LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
+ AllowedLibraryIDs []int `json:"allowed_library_ids"`
+ MaxPlaybackQuality string `json:"max_playback_quality"`
}
type ProfileUpdateRequest struct {
@@ -162,20 +165,23 @@ type ProfileUpdateRequest struct {
// RequireAdvisoryAge: nil leaves it untouched. v2-only (json:"-").
RequireAdvisoryAge *bool `json:"-"`
// RequestsBlocked: nil leaves it untouched. v2-only (json:"-").
- RequestsBlocked *bool `json:"-"`
- QualityPreference *string `json:"quality_preference,omitempty"`
- Language *string `json:"language,omitempty"`
- PreferredMetadataLanguage *string `json:"preferred_metadata_language,omitempty"`
- SubtitleLanguage *string `json:"subtitle_language,omitempty"`
- SubtitleMode *string `json:"subtitle_mode,omitempty"`
- AutoSkipIntro *bool `json:"auto_skip_intro,omitempty"`
- AutoSkipCredits *bool `json:"auto_skip_credits,omitempty"`
- AutoSkipRecap *bool `json:"auto_skip_recap,omitempty"`
- AutoPlayNextPreview *bool `json:"auto_play_next_preview,omitempty"`
- ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty"`
- LibraryRestrictionsEnabled *bool `json:"library_restrictions_enabled,omitempty"`
- AllowedLibraryIDs *[]int `json:"allowed_library_ids,omitempty"`
- MaxPlaybackQuality *string `json:"max_playback_quality,omitempty"`
+ RequestsBlocked *bool `json:"-"`
+ // ExcludedTags: nil leaves them untouched, and an empty list clears them.
+ // v2-only (json:"-").
+ ExcludedTags *[]string `json:"-"`
+ QualityPreference *string `json:"quality_preference,omitempty"`
+ Language *string `json:"language,omitempty"`
+ PreferredMetadataLanguage *string `json:"preferred_metadata_language,omitempty"`
+ SubtitleLanguage *string `json:"subtitle_language,omitempty"`
+ SubtitleMode *string `json:"subtitle_mode,omitempty"`
+ AutoSkipIntro *bool `json:"auto_skip_intro,omitempty"`
+ AutoSkipCredits *bool `json:"auto_skip_credits,omitempty"`
+ AutoSkipRecap *bool `json:"auto_skip_recap,omitempty"`
+ AutoPlayNextPreview *bool `json:"auto_play_next_preview,omitempty"`
+ ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty"`
+ LibraryRestrictionsEnabled *bool `json:"library_restrictions_enabled,omitempty"`
+ AllowedLibraryIDs *[]int `json:"allowed_library_ids,omitempty"`
+ MaxPlaybackQuality *string `json:"max_playback_quality,omitempty"`
}
type ProfileView struct {
@@ -194,22 +200,24 @@ type ProfileView struct {
// RequireAdvisoryAge hides titles with no advisory age. v2-only (json:"-").
RequireAdvisoryAge bool `json:"-"`
// RequestsBlocked keeps the profile out of requests. v2-only (json:"-").
- RequestsBlocked bool `json:"-"`
- QualityPreference string `json:"quality_preference,omitempty"`
- Language string `json:"language,omitempty"`
- PreferredMetadataLanguage string `json:"preferred_metadata_language,omitempty"`
- SubtitleLanguage string `json:"subtitle_language,omitempty"`
- SubtitleMode string `json:"subtitle_mode,omitempty"`
- AutoSkipIntro bool `json:"auto_skip_intro"`
- AutoSkipCredits bool `json:"auto_skip_credits"`
- AutoSkipRecap bool `json:"auto_skip_recap"`
- AutoPlayNextPreview bool `json:"auto_play_next_preview"`
- ShowForcedSubtitles bool `json:"show_forced_subtitles"`
- LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
- AllowedLibraryIDs []int `json:"allowed_library_ids"`
- MaxPlaybackQuality string `json:"max_playback_quality"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ RequestsBlocked bool `json:"-"`
+ // ExcludedTags are custom tags the profile may not see. v2-only (json:"-").
+ ExcludedTags []string `json:"-"`
+ QualityPreference string `json:"quality_preference,omitempty"`
+ Language string `json:"language,omitempty"`
+ PreferredMetadataLanguage string `json:"preferred_metadata_language,omitempty"`
+ SubtitleLanguage string `json:"subtitle_language,omitempty"`
+ SubtitleMode string `json:"subtitle_mode,omitempty"`
+ AutoSkipIntro bool `json:"auto_skip_intro"`
+ AutoSkipCredits bool `json:"auto_skip_credits"`
+ AutoSkipRecap bool `json:"auto_skip_recap"`
+ AutoPlayNextPreview bool `json:"auto_play_next_preview"`
+ ShowForcedSubtitles bool `json:"show_forced_subtitles"`
+ LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
+ AllowedLibraryIDs []int `json:"allowed_library_ids"`
+ MaxPlaybackQuality string `json:"max_playback_quality"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
}
// ProfileListView is the v1 GET /profiles response.
@@ -281,6 +289,18 @@ func (h *ProfileHandler) householdProfileLimit(ctx context.Context, userID int)
return effective.MaxProfiles, nil
}
+// normalizeTagsField normalizes custom tags for storage
+// (access.NormalizeTags), refusing a list past the tag bounds as an error on
+// field.
+func normalizeTagsField(field string, tags []string) ([]string, *APIError) {
+ normalized, ok := access.NormalizeTags(tags)
+ if !ok {
+ return nil, fieldError(field, fmt.Sprintf(
+ "%s holds at most %d tags of at most %d characters", field, access.MaxCustomTags, access.MaxCustomTagLength))
+ }
+ return normalized, nil
+}
+
// invalidAdvisoryAgeLimit is the field error for an advisory-age limit outside
// the storable range.
func invalidAdvisoryAgeLimit() *APIError {
@@ -292,9 +312,10 @@ func invalidAdvisoryAgeLimit() *APIError {
// only touches fields the user is allowed to change on their own profiles.
// Admin-only fields (access policy: library restrictions, content rating,
// advisory-age limit and its strictness, playback-quality cap, child-profile
-// flag, requests block) must be rejected for non-admins.
+// flag, requests block, excluded tags) must be rejected for non-admins.
func isAllowedSelfServiceProfileUpdate(req ProfileUpdateRequest) bool {
return req.IsChild == nil &&
+ req.ExcludedTags == nil &&
req.MaxContentRating == nil &&
req.MaxAdvisoryAge == nil &&
req.RequireAdvisoryAge == nil &&
@@ -455,6 +476,10 @@ func (h *ProfileHandler) CreateProfile(ctx context.Context, cmd ProfileCreateCom
if req.MaxAdvisoryAge != 0 && !access.ValidAdvisoryAgeLimit(req.MaxAdvisoryAge) {
return none, invalidAdvisoryAgeLimit()
}
+ excludedTags, apiErr := normalizeTagsField("excluded_tags", req.ExcludedTags)
+ if apiErr != nil {
+ return none, apiErr
+ }
// Planned before anything is written: a preference value the canonical
// store would refuse must fail the request while it is still a no-op.
@@ -492,7 +517,7 @@ func (h *ProfileHandler) CreateProfile(ctx context.Context, cmd ProfileCreateCom
// admin bootstrap creations must leave those fields at their defaults.
if isBootstrap && !apimw.IsAdmin(ctx) &&
(req.IsChild || req.MaxContentRating != "" || req.MaxAdvisoryAge != 0 || req.RequireAdvisoryAge ||
- req.RequestsBlocked ||
+ req.RequestsBlocked || len(excludedTags) > 0 ||
req.LibraryRestrictionsEnabled || len(req.AllowedLibraryIDs) > 0 ||
req.MaxPlaybackQuality != "") {
return none, apiError(http.StatusForbidden, "forbidden", "Profile access settings require the primary profile or admin access")
@@ -551,6 +576,7 @@ func (h *ProfileHandler) CreateProfile(ctx context.Context, cmd ProfileCreateCom
MaxAdvisoryAge: req.MaxAdvisoryAge,
RequireAdvisoryAge: req.RequireAdvisoryAge,
RequestsBlocked: req.RequestsBlocked,
+ ExcludedTags: excludedTags,
QualityPreference: req.QualityPreference,
Language: req.Language,
PreferredMetadataLanguage: req.PreferredMetadataLanguage,
@@ -639,6 +665,13 @@ func (h *ProfileHandler) UpdateProfile(ctx context.Context, cmd ProfileUpdateCom
if req.MaxAdvisoryAge != nil && *req.MaxAdvisoryAge != 0 && !access.ValidAdvisoryAgeLimit(*req.MaxAdvisoryAge) {
return none, invalidAdvisoryAgeLimit()
}
+ if req.ExcludedTags != nil {
+ normalized, apiErr := normalizeTagsField("excluded_tags", *req.ExcludedTags)
+ if apiErr != nil {
+ return none, apiErr
+ }
+ req.ExcludedTags = &normalized
+ }
store, err := h.storeProvider.ForUser(ctx, userID)
if err != nil {
@@ -712,6 +745,7 @@ func (h *ProfileHandler) UpdateProfile(ctx context.Context, cmd ProfileUpdateCom
MaxAdvisoryAge: req.MaxAdvisoryAge,
RequireAdvisoryAge: req.RequireAdvisoryAge,
RequestsBlocked: req.RequestsBlocked,
+ ExcludedTags: req.ExcludedTags,
QualityPreference: req.QualityPreference,
Language: req.Language,
PreferredMetadataLanguage: req.PreferredMetadataLanguage,
@@ -1117,6 +1151,7 @@ func (h *ProfileHandler) profileResponseWith(
MaxAdvisoryAge: p.MaxAdvisoryAge,
RequireAdvisoryAge: p.RequireAdvisoryAge,
RequestsBlocked: p.RequestsBlocked,
+ ExcludedTags: p.ExcludedTags,
QualityPreference: p.QualityPreference,
Language: prefs.AudioLanguage,
PreferredMetadataLanguage: prefs.MetadataLanguage,
diff --git a/internal/api/handlers/profiles_audit.go b/internal/api/handlers/profiles_audit.go
index 977b6f9dcd5..e9120971332 100644
--- a/internal/api/handlers/profiles_audit.go
+++ b/internal/api/handlers/profiles_audit.go
@@ -29,12 +29,16 @@ func profileAuditValues(p *userstore.Profile) map[string]any {
if libraries == nil {
libraries = []int{}
}
+ excludedTags := p.ExcludedTags
+ if excludedTags == nil {
+ excludedTags = []string{}
+ }
return map[string]any{
auditFieldProfileName: strings.TrimSpace(p.Name), "is_child": p.IsChild, "is_primary": p.IsPrimary,
"max_content_rating": p.MaxContentRating, "max_advisory_age": p.MaxAdvisoryAge,
"require_advisory_age": p.RequireAdvisoryAge, "requests_blocked": p.RequestsBlocked,
"library_restrictions_enabled": p.LibraryRestrictionsEnabled, "allowed_library_ids": libraries,
- "max_playback_quality": p.MaxPlaybackQuality, auditFieldPIN: p.PINHash != "",
+ "max_playback_quality": p.MaxPlaybackQuality, "excluded_tags": excludedTags, auditFieldPIN: p.PINHash != "",
}
}
diff --git a/internal/api/handlers/profiles_excluded_tags_test.go b/internal/api/handlers/profiles_excluded_tags_test.go
new file mode 100644
index 00000000000..ee944ed0a30
--- /dev/null
+++ b/internal/api/handlers/profiles_excluded_tags_test.go
@@ -0,0 +1,75 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/Silo-Server/silo-server/internal/userstore"
+)
+
+// Excluded tags are an access limit: only the household manager sets them,
+// they are stored normalized, a tag past the length bound is refused, and a
+// change rebuilds the profile's recommendations like its other limits.
+func TestProfileExcludedTags(t *testing.T) {
+ store := newProfileTestStore(t)
+ ctx := context.Background()
+ if err := store.CreateProfile(ctx, userstore.Profile{ID: "kid", Name: "Kid"}); err != nil {
+ t.Fatal(err)
+ }
+ n := &recordingScopeNotifier{}
+ h := NewProfileHandler(testUserStoreProvider{store: store})
+ h.RecWorker = n
+ update := func(actingAs string, tags []string) error {
+ t.Helper()
+ _, err := h.UpdateProfile(profileServiceContext(actingAs), ProfileUpdateCommand{
+ UserID: 1, ProfileID: "kid", ActiveProfileID: actingAs,
+ Request: ProfileUpdateRequest{ExcludedTags: &tags}, VerifyProfile: noProfileVerification,
+ })
+ return err
+ }
+ stored := func(id string) []string {
+ t.Helper()
+ p, err := store.GetProfile(ctx, id)
+ if err != nil || p == nil {
+ t.Fatalf("GetProfile(%s) = %+v, %v", id, p, err)
+ }
+ return p.ExcludedTags
+ }
+
+ // The manager (profile-1, the primary) sets them; spellings of one tag
+ // collapse to the first, and blanks drop.
+ if err := update("profile-1", []string{" gore ", "Late night", "GORE", " "}); err != nil {
+ t.Fatal(err)
+ }
+ if got := stored("kid"); !slices.Equal(got, []string{"gore", "Late night"}) {
+ t.Fatalf("stored excluded tags = %v", got)
+ }
+ if !slices.Equal(n.profiles, []string{"kid"}) {
+ t.Fatalf("rebuilt %v, want kid after its tags changed", n.profiles)
+ }
+
+ // The kid cannot lift its own limit.
+ requireAPIStatus(t, update("kid", nil), http.StatusForbidden)
+ if got := stored("kid"); len(got) != 2 {
+ t.Fatalf("a refused self-update changed the tags to %v", got)
+ }
+
+ apiErr := requireAPIStatus(t, update("profile-1", []string{strings.Repeat("x", 65)}), http.StatusBadRequest)
+ if apiErr.Field != "excluded_tags" {
+ t.Fatalf("too-long tag rejected on field %q, want excluded_tags", apiErr.Field)
+ }
+
+ created, err := h.CreateProfile(profileServiceContext("profile-1"), ProfileCreateCommand{
+ UserID: 1, ActiveProfileID: "profile-1", VerifyProfile: noProfileVerification,
+ Request: ProfileCreateRequest{Name: "Teen", ExcludedTags: []string{"Gore", "gore"}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := stored(created.ID); !slices.Equal(got, []string{"Gore"}) {
+ t.Fatalf("created excluded tags = %v", got)
+ }
+}
diff --git a/internal/api/handlers/recommendation_scope.go b/internal/api/handlers/recommendation_scope.go
index 22564a6fd93..357a7f1c29a 100644
--- a/internal/api/handlers/recommendation_scope.go
+++ b/internal/api/handlers/recommendation_scope.go
@@ -43,7 +43,7 @@ func notifyScopeSettingChanged(ctx context.Context, notifier SignalsChangedNotif
// update's writer lock, where an overlapping update can change it, and a
// rebuild of one profile is cheap.
func profileScopeSet(req ProfileUpdateRequest) bool {
- return req.MaxContentRating != nil || req.MaxAdvisoryAge != nil || req.RequireAdvisoryAge != nil ||
+ return req.MaxContentRating != nil || req.MaxAdvisoryAge != nil || req.RequireAdvisoryAge != nil || req.ExcludedTags != nil ||
req.LibraryRestrictionsEnabled != nil || req.AllowedLibraryIDs != nil
}
diff --git a/internal/api/handlers/title_allowances.go b/internal/api/handlers/title_allowances.go
index 193fbe601f7..8243597e632 100644
--- a/internal/api/handlers/title_allowances.go
+++ b/internal/api/handlers/title_allowances.go
@@ -107,6 +107,9 @@ const (
AllowanceStateAllowedByCollection = "allowed_by_collection"
AllowanceStateAboveLimit = "above_limit"
AllowanceStateNoLibraryAccess = "no_library_access"
+ // AllowanceStateHiddenByTag: the title carries a custom tag the profile
+ // excludes, which no allowance lifts.
+ AllowanceStateHiddenByTag = "hidden_by_tag"
)
// ProfileAllowanceState is one household profile's standing for a title.
@@ -376,6 +379,13 @@ func (h *TitleAllowanceHandler) stateFor(ctx context.Context, userID int, profil
if ok, err := visible(filter); err != nil || !ok {
return AllowanceStateNoLibraryAccess, err
}
+ if len(scope.ExcludedTags) > 0 {
+ tagged := filter
+ tagged.MaturityLimits = access.MaturityLimits{}.WithExcludedTags(scope.ExcludedTags)
+ if ok, err := visible(tagged); err != nil || !ok {
+ return AllowanceStateHiddenByTag, err
+ }
+ }
limits := scope.MaturityLimits
limits.AllowedTitleIDs = nil
filter.MaturityLimits = limits
diff --git a/internal/api/handlers/title_allowances_test.go b/internal/api/handlers/title_allowances_test.go
index 8cd30556f1b..ee24efe7fff 100644
--- a/internal/api/handlers/title_allowances_test.go
+++ b/internal/api/handlers/title_allowances_test.go
@@ -81,22 +81,24 @@ func (s *memoryAllowances) AllowTitles(_ context.Context, _ userstore.AllowanceM
}
// libraryScopes resolves every profile to one library, and the kid to a PG
-// ceiling.
+// ceiling that also hides the "gore" tag.
type libraryScopes struct{ libraries map[string][]int }
func (s libraryScopes) Resolve(_ context.Context, in access.ResolveInput) (access.Scope, error) {
scope := access.Scope{ProfileID: in.ProfileID, AllowedLibraryIDs: s.libraries[in.ProfileID]}
if in.ProfileID == "kid" {
scope.MaxContentRating = "PG"
+ scope.MaturityLimits = scope.WithExcludedTags([]string{"gore"})
}
return scope, nil
}
-// libraryItemRepo is a markItemRepo that answers access by library and by an
-// "R" rating the PG ceiling hides.
+// libraryItemRepo is a markItemRepo that answers access by library, by an
+// "R" rating the PG ceiling hides, and by excluded tags.
type libraryItemRepo struct {
markItemRepo
library map[string]int
+ tags map[string][]string
}
func (r libraryItemRepo) EnsureAccessible(ctx context.Context, id string, filter catalog.AccessFilter) error {
@@ -115,6 +117,11 @@ func (r libraryItemRepo) EnsureAccessible(ctx context.Context, id string, filter
if filter.MaxContentRating != "" && r.items[id].ContentRating == "R" {
return catalog.ErrItemNotFound
}
+ for _, tag := range r.tags[id] {
+ if slices.Contains(access.TagKeys(filter.ExcludedTags), access.TagKey(tag)) {
+ return catalog.ErrItemNotFound
+ }
+ }
return nil
}
@@ -148,9 +155,11 @@ func TestTitleAllowanceAuthority(t *testing.T) {
"movie:r": {ContentID: "movie:r", Type: "movie", ContentRating: "R"},
"movie:pg": {ContentID: "movie:pg", Type: "movie", ContentRating: "PG"},
"movie:other": {ContentID: "movie:other", Type: "movie", ContentRating: "R"},
+ "movie:gore": {ContentID: "movie:gore", Type: "movie", ContentRating: "PG"},
"episode:r-1x1": {ContentID: "episode:r-1x1", Type: "episode", ContentRating: "R"},
}},
- library: map[string]int{"movie:r": 1, "movie:pg": 1, "movie:other": 2, "episode:r-1x1": 1},
+ library: map[string]int{"movie:r": 1, "movie:pg": 1, "movie:other": 2, "movie:gore": 1, "episode:r-1x1": 1},
+ tags: map[string][]string{"movie:gore": {"Gore"}},
}
h := NewTitleAllowanceHandler(
NewPersonalDataHandler(testUserStoreProvider{store: base}, repo),
@@ -197,7 +206,7 @@ func TestTitleAllowanceAuthority(t *testing.T) {
}
states := map[string]map[string]string{}
- for _, item := range []string{"movie:r", "movie:pg", "movie:other"} {
+ for _, item := range []string{"movie:r", "movie:pg", "movie:other", "movie:gore"} {
got, err := h.TitleAllowanceStates(ctx, actor("parent"), item)
if err != nil {
t.Fatalf("states(%s): %v", item, err)
@@ -211,6 +220,8 @@ func TestTitleAllowanceAuthority(t *testing.T) {
"movie:r": {"kid": AllowanceStateAllowed, "teen": AllowanceStateWithinLimits},
"movie:pg": {"kid": AllowanceStateWithinLimits, "teen": AllowanceStateWithinLimits},
"movie:other": {"kid": AllowanceStateNoLibraryAccess, "teen": AllowanceStateWithinLimits},
+ // An allowance never lifts a tag, so the title page offers none.
+ "movie:gore": {"kid": AllowanceStateHiddenByTag, "teen": AllowanceStateWithinLimits},
}
for item, byProfile := range want {
for profile, state := range byProfile {
diff --git a/internal/api/router.go b/internal/api/router.go
index cf7c0a4f0d6..aab7197eac1 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -3277,6 +3277,9 @@ func newChiRouter(deps Dependencies) chi.Router {
v2deps.AdminResourceSampler = deps.ResourceSampler
v2deps.AdminCatalogSearch = adminHandler
v2deps.AdminItemMetadata = adminHandler
+ if itemRepo != nil {
+ v2deps.CatalogCustomTags = itemRepo
+ }
if orders, ok := deps.MetadataService.(apiv2.AdminEpisodeOrderService); ok {
v2deps.AdminEpisodeOrders = orders
}
diff --git a/internal/api/testdata/media_routes.txt b/internal/api/testdata/media_routes.txt
index 296abbca1f9..5d55dc603a6 100644
--- a/internal/api/testdata/media_routes.txt
+++ b/internal/api/testdata/media_routes.txt
@@ -638,6 +638,7 @@ GET /api/v2/catalog non-media
GET /api/v2/catalog/audiobook-groups non-media
GET /api/v2/catalog/box-sets non-media
GET /api/v2/catalog/box-sets/{id} non-media
+GET /api/v2/catalog/custom-tags non-media
GET /api/v2/catalog/filters non-media
GET /api/v2/catalog/filters/search non-media
GET /api/v2/catalog/items/{id} non-media
@@ -1773,6 +1774,7 @@ GET /api/v2/catalog non-media
GET /api/v2/catalog/audiobook-groups non-media
GET /api/v2/catalog/box-sets non-media
GET /api/v2/catalog/box-sets/{id} non-media
+GET /api/v2/catalog/custom-tags non-media
GET /api/v2/catalog/filters non-media
GET /api/v2/catalog/filters/search non-media
GET /api/v2/catalog/items/{id} non-media
diff --git a/internal/apiv2/admin_catalog_item_metadata.go b/internal/apiv2/admin_catalog_item_metadata.go
index 61e0ef2787e..1eaf8c85aa9 100644
--- a/internal/apiv2/admin_catalog_item_metadata.go
+++ b/internal/apiv2/admin_catalog_item_metadata.go
@@ -56,6 +56,7 @@ type AdminItemMetadataUpdate struct {
SeasonNumber *int `json:"season_number,omitempty" nullable:"true"`
EpisodeNumber *int `json:"episode_number,omitempty" nullable:"true"`
LockedFields *[]int `json:"locked_fields,omitempty" nullable:"true"`
+ CustomTags *[]string `json:"custom_tags,omitempty" nullable:"false" maxItems:"50" doc:"Replaces a movie's or series' custom tags: free-text labels no metadata provider writes, so a refresh keeps them. A profile's excluded_tags hide every title carrying one of its tags. Each tag is trimmed with inner whitespace collapsed, and tags that differ only in case are kept once, in the first spelling. At most 50 tags of at most 64 characters; an empty array clears them. getAdminCatalogCapabilities reports custom_tags when this member is accepted" example:"[\"Gore\"]"`
}
type AdminItemMetadataUpdateInput struct {
ID string `path:"id" minLength:"1" maxLength:"512"`
diff --git a/internal/apiv2/admin_catalog_items.go b/internal/apiv2/admin_catalog_items.go
index 0db1eb5b30d..bf403566ba1 100644
--- a/internal/apiv2/admin_catalog_items.go
+++ b/internal/apiv2/admin_catalog_items.go
@@ -111,6 +111,7 @@ type AdminCatalogCapabilities struct {
MetadataListing bool `json:"metadata_listing" doc:"listAdminMetadataItems is served: movies and series with lock counts and missing-artwork flags, filterable by locked and missing_artwork"`
ImageSlotLocks bool `json:"image_slot_locks" doc:"locked_fields accepts one lock per image (14 poster, 15 backdrop, 16 logo, 17 episode still), and choosing or uploading an image locks only that image on its own item, season or episode"`
EpisodeStills bool `json:"episode_stills" doc:"listAdminItemImages lists an episode's still choices and current still_url, and uploadAdminItemImage accepts type still for an episode"`
+ CustomTags bool `json:"custom_tags" doc:"updateAdminItemMetadata accepts custom_tags on a movie or series, item detail returns them to a metadata curator, and listCatalogCustomTags is served"`
}
type AdminCatalogCapabilitiesOutput struct {
Status int
@@ -132,6 +133,7 @@ func registerAdminCatalogItems(reg *Registry) {
ItemMatchHints: reg.deps.AdminCatalogMatch != nil,
ItemMetadata: served,
ItemMetadataReset: reg.deps.AdminItemMetadata != nil,
+ CustomTags: reg.deps.AdminItemMetadata != nil && reg.deps.CatalogCustomTags != nil,
ItemFilePaths: served && adminCatalogFilePathsAllowed(ctx),
ItemPosters: served && reg.deps.ItemPosters != nil,
MetadataListing: reg.deps.AdminMetadataItems != nil,
diff --git a/internal/apiv2/catalog_custom_tags.go b/internal/apiv2/catalog_custom_tags.go
new file mode 100644
index 00000000000..beafde74568
--- /dev/null
+++ b/internal/apiv2/catalog_custom_tags.go
@@ -0,0 +1,51 @@
+package apiv2
+
+import (
+ "context"
+ "net/http"
+
+ catalogpkg "github.com/Silo-Server/silo-server/internal/catalog"
+ "github.com/Silo-Server/silo-server/internal/imagesize"
+)
+
+// CatalogCustomTagService lists the custom tags on the titles a viewer can
+// see. *catalog.ItemRepository implements it.
+type CatalogCustomTagService interface {
+ ListCustomTags(context.Context, catalogpkg.AccessFilter) ([]catalogpkg.CustomTagCount, error)
+}
+
+// CatalogCustomTag is one custom tag and how many titles carry it.
+type CatalogCustomTag struct {
+ Tag string `json:"tag" doc:"The tag in its most used spelling; tags that differ only in case are one tag" example:"Gore"`
+ TitleCount int `json:"title_count" doc:"How many movies and series the caller can see that carry the tag" example:"11"`
+}
+
+// CatalogCustomTagCollectionOutput is the listCatalogCustomTags response.
+type CatalogCustomTagCollectionOutput struct {
+ Body Collection[CatalogCustomTag]
+}
+
+func registerCatalogCustomTags(reg *Registry) {
+ op := viewerOperation(humaOp(http.MethodGet, Prefix+"/catalog/custom-tags", "listCatalogCustomTags", "catalog",
+ "The custom tags on the movies and series the caller can see, most used first, for the metadata editor and a profile's excluded_tags."))
+ Register(reg, op, reg.listCatalogCustomTags)
+}
+
+func (reg *Registry) listCatalogCustomTags(ctx context.Context, _ *struct{}) (*CatalogCustomTagCollectionOutput, error) {
+ if reg.deps.CatalogCustomTags == nil {
+ return nil, unavailable("custom tags")
+ }
+ viewer, p := reg.itemViewer(ctx, imagesize.Request{}, "", "")
+ if p != nil {
+ return nil, p
+ }
+ tags, err := reg.deps.CatalogCustomTags.ListCustomTags(ctx, viewer.Access)
+ if err != nil {
+ return nil, err
+ }
+ items := make([]CatalogCustomTag, len(tags))
+ for i, tag := range tags {
+ items[i] = CatalogCustomTag{Tag: tag.Tag, TitleCount: tag.TitleCount}
+ }
+ return &CatalogCustomTagCollectionOutput{Body: NewCollection(items)}, nil
+}
diff --git a/internal/apiv2/catalog_items.go b/internal/apiv2/catalog_items.go
index 95ec9bcebc8..d886b44121f 100644
--- a/internal/apiv2/catalog_items.go
+++ b/internal/apiv2/catalog_items.go
@@ -409,6 +409,7 @@ type CatalogItemDetail struct {
Cast []catalogpkg.CastCredit `json:"cast" doc:"Empty, never null"`
Crew []catalogpkg.CrewCredit `json:"crew" doc:"Empty, never null"`
Countries []string `json:"countries,omitempty" doc:"Production countries, normally ISO 3166-1 alpha-2 codes (US); NFO files and manual edits can store country names"`
+ CustomTags []string `json:"custom_tags,omitempty" doc:"A movie's or series' custom tags, the free-text labels set through updateAdminItemMetadata. Returned only to a viewer who curates the item's metadata; omitted for everyone else and when the item has none"`
LockedFields []int `json:"locked_fields,omitempty" doc:"Metadata fields an editor pinned"`
FirstAirDate *string `json:"first_air_date,omitempty" format:"date" doc:"Calendar date, YYYY-MM-DD"`
AirTime *string `json:"air_time,omitempty"`
@@ -1497,7 +1498,7 @@ func catalogItemDetailOf(d *catalogpkg.ItemDetail, sel ratingsources.Selection)
out := CatalogItemDetail{
CatalogItem: card, PlaySeasonNumber: d.PlaySeasonNumber,
SortTitle: d.SortTitle, OriginalTitle: d.OriginalTitle, Tagline: d.Tagline,
- Cast: NonNil(d.Cast), Crew: NonNil(d.Crew), Countries: d.Countries, LockedFields: d.LockedFields,
+ Cast: NonNil(d.Cast), Crew: NonNil(d.Crew), Countries: d.Countries, CustomTags: curatorCustomTags(d), LockedFields: d.LockedFields,
BannerURL: d.BannerURL, BannerThumbhash: d.BannerThumbhash, ThumbURL: d.ThumbURL, ThumbThumbhash: d.ThumbThumbhash,
ClearArtURL: d.ClearArtURL, DiscURL: d.DiscURL, BackdropURLs: d.BackdropURLs,
FirstAirDate: calendarDatePtr(d.FirstAirDate), AirTime: d.AirTime, AirTimezone: d.AirTimezone, SeasonCount: d.SeasonCount, EpisodeCount: d.EpisodeCount,
@@ -1580,3 +1581,12 @@ type SeriesEpisodeOrder struct {
FileOrder string `json:"file_order" doc:"tvdb or tmdb when the files are named in that provider's default order rather than the series provider's; order when they are named in the chosen order_id itself; empty otherwise. Treat an unknown value as empty" example:""`
CustomArrangement bool `json:"custom_arrangement" doc:"Arranged seasons place an episode elsewhere than the provider's default order does; false for seasons that were only renamed or described" example:"false"`
}
+
+// curatorCustomTags is the item's custom tags for a viewer who curates its
+// metadata, and nothing for anyone else.
+func curatorCustomTags(d *catalogpkg.ItemDetail) []string {
+ if !d.ViewerCurates {
+ return nil
+ }
+ return d.CustomTags
+}
diff --git a/internal/apiv2/cursor.go b/internal/apiv2/cursor.go
index e945edd1f8c..3e8b7f34493 100644
--- a/internal/apiv2/cursor.go
+++ b/internal/apiv2/cursor.go
@@ -7,9 +7,12 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/json"
+ "fmt"
"slices"
"strconv"
"strings"
+
+ "github.com/Silo-Server/silo-server/internal/access"
)
// tiebreakerItemID is the CursorScope tiebreaker of a keyset that ends on
@@ -95,6 +98,10 @@ func viewerScopeDigest(ctx context.Context) string {
if len(scope.AllowedTitleIDs) > 0 {
parts = append(parts, "allowed="+strings.Join(scope.AllowedTitleIDs, ","))
}
+ // Same rule: excluding a tag changes which rows a page holds.
+ if len(scope.ExcludedTags) > 0 {
+ parts = append(parts, "excludedtags="+fmt.Sprintf("%q", access.TagKeys(scope.ExcludedTags)))
+ }
canonical := strings.Join(parts, "\x00")
sum := sha256.Sum256([]byte(canonical))
return hex.EncodeToString(sum[:8])
diff --git a/internal/apiv2/cursor_scope_digest_test.go b/internal/apiv2/cursor_scope_digest_test.go
index d439b0eda46..8191d0d4ef5 100644
--- a/internal/apiv2/cursor_scope_digest_test.go
+++ b/internal/apiv2/cursor_scope_digest_test.go
@@ -20,6 +20,7 @@ func TestViewerScopeDigestCoversMaturityLimits(t *testing.T) {
"content rating": {MaxContentRating: "PG"},
"unrated": {AllowUnratedContent: true},
"advisory age": {MaxAdvisoryAge: 10},
+ "excluded tag": {ExcludedTags: []string{"gore"}},
} {
if digest(limits) == base {
t.Errorf("setting the %s limit does not change the cursor scope digest", name)
@@ -36,4 +37,8 @@ func TestViewerScopeDigestCoversMaturityLimits(t *testing.T) {
if digest(access.MaturityLimits{RequireAdvisoryAge: true}) != base {
t.Error("a require flag with no limit changed the cursor scope digest")
}
+ // Tags are free text, so a separator inside one must not collide with two.
+ if digest(access.MaturityLimits{ExcludedTags: []string{"a,b"}}) == digest(access.MaturityLimits{ExcludedTags: []string{"a", "b"}}) {
+ t.Error("excluding \"a,b\" and excluding \"a\" and \"b\" must digest differently")
+ }
}
diff --git a/internal/apiv2/document.go b/internal/apiv2/document.go
index c29cf32e619..152438e4cf9 100644
--- a/internal/apiv2/document.go
+++ b/internal/apiv2/document.go
@@ -704,6 +704,7 @@ func registerAll(reg *Registry) {
registerAdminCatalogPeople(reg)
registerAdminCatalogTranslation(reg)
registerAdminCatalogItemMetadata(reg)
+ registerCatalogCustomTags(reg)
registerAdminEpisodeOrder(reg)
registerAdminCustomSeasons(reg)
registerAdminCatalogIntro(reg)
diff --git a/internal/apiv2/fixtures_test.go b/internal/apiv2/fixtures_test.go
index 6d6fe953503..b95299fdce3 100644
--- a/internal/apiv2/fixtures_test.go
+++ b/internal/apiv2/fixtures_test.go
@@ -2212,6 +2212,7 @@ func fixtureDeps() Dependencies {
deps.AdminPeople = &fakeAdminPeople{}
deps.AdminMetadataTranslation = &fakeAdminTranslation{}
deps.AdminItemMetadata = &fakeAdminItemMetadata{}
+ deps.CatalogCustomTags = fakeCatalogCustomTags{}
deps.AdminEpisodeOrders = &fakeAdminEpisodeOrders{}
deps.AdminCustomSeasons = fakeAdminCustomSeasons{}
deps.AdminEpisodeMarkers = &fakeAdminIntro{}
@@ -2528,3 +2529,11 @@ func (f *fixtureAdminCollectionJobs) GetByID(ctx context.Context, id string) (*m
}
return &models.AdminJob{ID: id, JobType: adminjob.JobTypeTemplateBundleApply, Status: adminjob.StatusCompleted, RequestedAt: fixedTime(), StartedAt: new(fixedTime()), CompletedAt: new(fixedTime()), ResultPayload: json.RawMessage(`{"bundle_id":"bundle","created":[{"template_id":"recent","template_title":"Recently added","library_id":1,"library_name":"Movies","collection_id":"c1"}],"skipped":[{"template_id":"existing","template_title":"Existing","library_id":1,"library_name":"Movies","reason":"A collection from this template already exists"}]}`)}, nil
}
+
+// fakeCatalogCustomTags serves an empty tag list, so capability discovery
+// reports custom tags as available.
+type fakeCatalogCustomTags struct{}
+
+func (fakeCatalogCustomTags) ListCustomTags(context.Context, catalogsvc.AccessFilter) ([]catalogsvc.CustomTagCount, error) {
+ return nil, nil
+}
diff --git a/internal/apiv2/profiles.go b/internal/apiv2/profiles.go
index dd84443c939..34bb41d0832 100644
--- a/internal/apiv2/profiles.go
+++ b/internal/apiv2/profiles.go
@@ -30,28 +30,29 @@ type Profile struct {
ID ID `json:"id" example:"1"`
Name string `json:"name" example:"Alice"`
ProfileAvatar
- HasPIN bool `json:"has_pin" example:"false"`
- IsChild bool `json:"is_child" example:"false"`
- IsPrimary bool `json:"is_primary" doc:"The household parent (not the server admin role)" example:"true"`
- MaxContentRating string `json:"max_content_rating" doc:"Content-rating ceiling; empty means none" example:"PG-13"`
- MaxAdvisoryAge *int `json:"max_advisory_age" nullable:"true" minimum:"1" maximum:"21" doc:"Advisory-age limit: titles whose advisory age (for example Common Sense Media's 13+) is above it are hidden from the profile. Titles with no advisory age are limited by max_content_rating alone unless require_advisory_age is set; null means no limit" example:"12"`
- RequireAdvisoryAge bool `json:"require_advisory_age" doc:"Hide titles with no advisory age as well, so the profile sees only titles an advisory service rated at or under max_advisory_age. Advisory ages are looked up over time, so on a large library a profile with this set starts with few titles. No effect without max_advisory_age" example:"false"`
- RequestsAllowed bool `json:"requests_allowed" doc:"Whether the profile may make and follow requests and use request discovery. False keeps it out of those even when the account may request; it can still list, read and cancel the requests it made before. The account's own requests switch still applies on top. Set by the household manager" example:"true"`
- QualityPreference string `json:"quality_preference" doc:"Free-form until the vocabulary is ratified (#135). Canonical values today: auto, 720p, 1080p, 2160p, 4k; original is a deprecated alias of auto; empty when unset" example:"auto"`
- Language string `json:"language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Preferred audio language: BCP 47 tag, ISO 639-1 where one exists (en, pt-BR), or x-silo-original for each item's original language; empty inherits" example:"en"`
- PreferredMetadataLanguage string `json:"preferred_metadata_language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Metadata language: BCP 47 tag (en, pt-BR), or x-silo-original for each item's original language; empty inherits the library's" example:"en"`
- SubtitleLanguage string `json:"subtitle_language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Preferred subtitle language: BCP 47 tag, ISO 639-1 where one exists (en, pt-BR); empty inherits" example:"en"`
- SubtitleMode string `json:"subtitle_mode" doc:"Free-form until the vocabulary is ratified (#135). Canonical values today: auto, always, off, default, forced_only; empty when unset" example:"auto"`
- AutoSkipIntro bool `json:"auto_skip_intro" example:"true"`
- AutoSkipCredits bool `json:"auto_skip_credits" example:"false"`
- AutoSkipRecap bool `json:"auto_skip_recap" example:"false"`
- AutoPlayNextPreview bool `json:"auto_play_next_preview" example:"false"`
- ShowForcedSubtitles bool `json:"show_forced_subtitles" example:"false"`
- LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled" doc:"Whether the profile is limited to allowed_library_ids within its account's libraries. The primary profile is never limited: it sees every library its account can access and hides libraries through its settings instead" example:"false"`
- AllowedLibraryIDs []ID `json:"allowed_library_ids" doc:"Libraries the profile may see when restrictions are enabled" example:"[\"1\",\"2\"]"`
- MaxPlaybackQuality string `json:"max_playback_quality" doc:"Playback ceiling. Canonical values: 1080p, 2160p; empty means none. Older profiles may carry other stored values" example:"1080p"`
- CreatedAt Instant `json:"created_at" example:"2026-01-02T03:04:05.000Z"`
- UpdatedAt Instant `json:"updated_at" example:"2026-01-02T03:04:05.000Z"`
+ HasPIN bool `json:"has_pin" example:"false"`
+ IsChild bool `json:"is_child" example:"false"`
+ IsPrimary bool `json:"is_primary" doc:"The household parent (not the server admin role)" example:"true"`
+ MaxContentRating string `json:"max_content_rating" doc:"Content-rating ceiling; empty means none" example:"PG-13"`
+ MaxAdvisoryAge *int `json:"max_advisory_age" nullable:"true" minimum:"1" maximum:"21" doc:"Advisory-age limit: titles whose advisory age (for example Common Sense Media's 13+) is above it are hidden from the profile. Titles with no advisory age are limited by max_content_rating alone unless require_advisory_age is set; null means no limit" example:"12"`
+ RequireAdvisoryAge bool `json:"require_advisory_age" doc:"Hide titles with no advisory age as well, so the profile sees only titles an advisory service rated at or under max_advisory_age. Advisory ages are looked up over time, so on a large library a profile with this set starts with few titles. No effect without max_advisory_age" example:"false"`
+ RequestsAllowed bool `json:"requests_allowed" doc:"Whether the profile may make and follow requests and use request discovery. False keeps it out of those even when the account may request; it can still list, read and cancel the requests it made before. The account's own requests switch still applies on top. Set by the household manager" example:"true"`
+ ExcludedTags []string `json:"excluded_tags" doc:"Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager; empty means none" example:"[\"Gore\"]"`
+ QualityPreference string `json:"quality_preference" doc:"Free-form until the vocabulary is ratified (#135). Canonical values today: auto, 720p, 1080p, 2160p, 4k; original is a deprecated alias of auto; empty when unset" example:"auto"`
+ Language string `json:"language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Preferred audio language: BCP 47 tag, ISO 639-1 where one exists (en, pt-BR), or x-silo-original for each item's original language; empty inherits" example:"en"`
+ PreferredMetadataLanguage string `json:"preferred_metadata_language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Metadata language: BCP 47 tag (en, pt-BR), or x-silo-original for each item's original language; empty inherits the library's" example:"en"`
+ SubtitleLanguage string `json:"subtitle_language" pattern:"^(?:[a-z]{2,3}(?:-[0-9A-Za-z]{1,8})*|x(?:-[0-9A-Za-z]{1,8})+)?$" doc:"Preferred subtitle language: BCP 47 tag, ISO 639-1 where one exists (en, pt-BR); empty inherits" example:"en"`
+ SubtitleMode string `json:"subtitle_mode" doc:"Free-form until the vocabulary is ratified (#135). Canonical values today: auto, always, off, default, forced_only; empty when unset" example:"auto"`
+ AutoSkipIntro bool `json:"auto_skip_intro" example:"true"`
+ AutoSkipCredits bool `json:"auto_skip_credits" example:"false"`
+ AutoSkipRecap bool `json:"auto_skip_recap" example:"false"`
+ AutoPlayNextPreview bool `json:"auto_play_next_preview" example:"false"`
+ ShowForcedSubtitles bool `json:"show_forced_subtitles" example:"false"`
+ LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled" doc:"Whether the profile is limited to allowed_library_ids within its account's libraries. The primary profile is never limited: it sees every library its account can access and hides libraries through its settings instead" example:"false"`
+ AllowedLibraryIDs []ID `json:"allowed_library_ids" doc:"Libraries the profile may see when restrictions are enabled" example:"[\"1\",\"2\"]"`
+ MaxPlaybackQuality string `json:"max_playback_quality" doc:"Playback ceiling. Canonical values: 1080p, 2160p; empty means none. Older profiles may carry other stored values" example:"1080p"`
+ CreatedAt Instant `json:"created_at" example:"2026-01-02T03:04:05.000Z"`
+ UpdatedAt Instant `json:"updated_at" example:"2026-01-02T03:04:05.000Z"`
}
// ProfileUpdate is the updateProfile body. Every member is optional: omitted
@@ -65,6 +66,7 @@ type ProfileUpdate struct {
MaxAdvisoryAge Patch[int] `json:"max_advisory_age,omitzero" minimum:"1" maximum:"21" doc:"Advisory-age limit: titles whose advisory age (for example Common Sense Media's 13+) is above it are hidden from the profile. Titles with no advisory age are limited by max_content_rating alone unless require_advisory_age is set; null removes it" example:"12"`
RequireAdvisoryAge *bool `json:"require_advisory_age,omitempty" nullable:"false" doc:"Hide titles with no advisory age as well, so the profile sees only titles an advisory service rated at or under max_advisory_age. Advisory ages are looked up over time, so on a large library a profile with this set starts with few titles. No effect without max_advisory_age" example:"true"`
RequestsAllowed *bool `json:"requests_allowed,omitempty" nullable:"false" doc:"Whether the profile may make and follow requests and use request discovery. False keeps it out of those even when the account may request; it can still list, read and cancel the requests it made before. The account's own requests switch still applies on top. Set by the household manager" example:"false"`
+ ExcludedTags *[]string `json:"excluded_tags,omitempty" nullable:"false" maxItems:"50" doc:"Replaces the excluded tags. Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; an empty array clears them" example:"[\"Gore\"]"`
QualityPreference *string `json:"quality_preference,omitempty" nullable:"false" maxLength:"32" doc:"Free-form until the vocabulary is ratified (#135); v1 never validated it. Canonical values today: auto, 720p, 1080p, 2160p, 4k; original is a deprecated alias of auto" example:"auto"`
Language Patch[string] `json:"language,omitzero" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Preferred audio language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; null inherits" example:"en"`
PreferredMetadataLanguage Patch[string] `json:"preferred_metadata_language,omitzero" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Metadata language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; null inherits the library's" example:"en"`
@@ -141,6 +143,8 @@ type ProfileCollection struct {
RequireAdvisoryAgeSupported bool `json:"require_advisory_age_supported" doc:"Whether profiles accept require_advisory_age and the server enforces it" example:"true"`
// RequestsAllowedSupported is the same kind of flag for requests_allowed.
RequestsAllowedSupported bool `json:"requests_allowed_supported" doc:"Whether profiles accept requests_allowed and the server enforces it" example:"true"`
+ // ExcludedTagsSupported is the same kind of flag for excluded_tags.
+ ExcludedTagsSupported bool `json:"excluded_tags_supported" doc:"Whether profiles accept excluded_tags and the server enforces it" example:"true"`
// MaxProfiles is the household limit createProfile enforces, so a client
// can stop offering a new profile the server would refuse.
MaxProfiles *int `json:"max_profiles,omitempty" nullable:"false" minimum:"1" doc:"How many profiles this account may have, from its effective access policy; createProfile answers 409 once the household holds this many. Omitted on a remote-playback handoff, which lists only its own profile and cannot create one, and when the server could not read the limit; in that second case a client keeps offering new profiles and createProfile stays the check" example:"5"`
@@ -156,27 +160,28 @@ type ProfileCollectionOutput struct {
// else off or empty). No member admits null: there is nothing to clear on a
// profile that does not exist yet.
type ProfileCreate struct {
- Name string `json:"name" minLength:"1" maxLength:"64" doc:"Display name; leading and trailing spaces are trimmed" example:"Alice"`
- Avatar *string `json:"avatar,omitempty" nullable:"false" doc:"Preset avatar reference" example:"preset:fox"`
- PIN *string `json:"pin,omitempty" nullable:"false" minLength:"1" maxLength:"72" doc:"PIN, 1 to 72 bytes" example:"1234"`
- IsChild *bool `json:"is_child,omitempty" nullable:"false" example:"false"`
- MaxContentRating *string `json:"max_content_rating,omitempty" nullable:"false" doc:"Content-rating ceiling" example:"PG-13"`
- MaxAdvisoryAge *int `json:"max_advisory_age,omitempty" nullable:"false" minimum:"1" maximum:"21" doc:"Advisory-age limit: titles whose advisory age (for example Common Sense Media's 13+) is above it are hidden from the profile. Titles with no advisory age are limited by max_content_rating alone unless require_advisory_age is set" example:"12"`
- RequireAdvisoryAge *bool `json:"require_advisory_age,omitempty" nullable:"false" doc:"Hide titles with no advisory age as well, so the profile sees only titles an advisory service rated at or under max_advisory_age. Advisory ages are looked up over time, so on a large library a profile with this set starts with few titles. No effect without max_advisory_age" example:"true"`
- RequestsAllowed *bool `json:"requests_allowed,omitempty" nullable:"false" doc:"Whether the profile may make and follow requests and use request discovery. False keeps it out of those even when the account may request; it can still list, read and cancel the requests it made before. The account's own requests switch still applies on top. Set by the household manager. Omitted means allowed" example:"false"`
- QualityPreference *string `json:"quality_preference,omitempty" nullable:"false" maxLength:"32" doc:"Free-form until the vocabulary is ratified (#135); v1 never validated it. Canonical values today: auto, 720p, 1080p, 2160p, 4k; original is a deprecated alias of auto" example:"auto"`
- Language *string `json:"language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Preferred audio language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; omitted or empty inherits" example:"en"`
- PreferredMetadataLanguage *string `json:"preferred_metadata_language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Metadata language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; omitted or empty inherits the library's" example:"en"`
- SubtitleLanguage *string `json:"subtitle_language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Preferred subtitle language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; omitted or empty inherits" example:"en"`
- SubtitleMode *string `json:"subtitle_mode,omitempty" nullable:"false" maxLength:"32" doc:"Free-form until the vocabulary is ratified (#135); v1 never validated it. Canonical values today: auto, always, off, default, forced_only" example:"auto"`
- AutoSkipIntro *bool `json:"auto_skip_intro,omitempty" nullable:"false" example:"true"`
- AutoSkipCredits *bool `json:"auto_skip_credits,omitempty" nullable:"false" example:"false"`
- AutoSkipRecap *bool `json:"auto_skip_recap,omitempty" nullable:"false" example:"false"`
- AutoPlayNextPreview *bool `json:"auto_play_next_preview,omitempty" nullable:"false" example:"false"`
- ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty" nullable:"false" doc:"Defaults to true when omitted" example:"true"`
- LibraryRestrictionsEnabled *bool `json:"library_restrictions_enabled,omitempty" nullable:"false" doc:"Limits the profile to allowed_library_ids. Must be false or omitted on an account's first profile, which becomes its primary profile" example:"false"`
- AllowedLibraryIDs *[]ID `json:"allowed_library_ids,omitempty" nullable:"false" doc:"Unique library identifiers the profile may see when restrictions are enabled. Must be empty on an account's first profile, which becomes its primary profile, even with restrictions off" example:"[\"1\",\"2\"]"`
- MaxPlaybackQuality *string `json:"max_playback_quality,omitempty" nullable:"false" enum:"1080p,2160p" doc:"Playback ceiling" example:"1080p"`
+ Name string `json:"name" minLength:"1" maxLength:"64" doc:"Display name; leading and trailing spaces are trimmed" example:"Alice"`
+ Avatar *string `json:"avatar,omitempty" nullable:"false" doc:"Preset avatar reference" example:"preset:fox"`
+ PIN *string `json:"pin,omitempty" nullable:"false" minLength:"1" maxLength:"72" doc:"PIN, 1 to 72 bytes" example:"1234"`
+ IsChild *bool `json:"is_child,omitempty" nullable:"false" example:"false"`
+ MaxContentRating *string `json:"max_content_rating,omitempty" nullable:"false" doc:"Content-rating ceiling" example:"PG-13"`
+ MaxAdvisoryAge *int `json:"max_advisory_age,omitempty" nullable:"false" minimum:"1" maximum:"21" doc:"Advisory-age limit: titles whose advisory age (for example Common Sense Media's 13+) is above it are hidden from the profile. Titles with no advisory age are limited by max_content_rating alone unless require_advisory_age is set" example:"12"`
+ RequireAdvisoryAge *bool `json:"require_advisory_age,omitempty" nullable:"false" doc:"Hide titles with no advisory age as well, so the profile sees only titles an advisory service rated at or under max_advisory_age. Advisory ages are looked up over time, so on a large library a profile with this set starts with few titles. No effect without max_advisory_age" example:"true"`
+ RequestsAllowed *bool `json:"requests_allowed,omitempty" nullable:"false" doc:"Whether the profile may make and follow requests and use request discovery. False keeps it out of those even when the account may request; it can still list, read and cancel the requests it made before. The account's own requests switch still applies on top. Set by the household manager. Omitted means allowed" example:"false"`
+ ExcludedTags []string `json:"excluded_tags,omitempty" nullable:"false" maxItems:"50" doc:"Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; omitted means none" example:"[\"Gore\"]"`
+ QualityPreference *string `json:"quality_preference,omitempty" nullable:"false" maxLength:"32" doc:"Free-form until the vocabulary is ratified (#135); v1 never validated it. Canonical values today: auto, 720p, 1080p, 2160p, 4k; original is a deprecated alias of auto" example:"auto"`
+ Language *string `json:"language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Preferred audio language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; omitted or empty inherits" example:"en"`
+ PreferredMetadataLanguage *string `json:"preferred_metadata_language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Metadata language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; x-silo-original picks each item's original language; omitted or empty inherits the library's" example:"en"`
+ SubtitleLanguage *string `json:"subtitle_language,omitempty" nullable:"false" pattern:"^[\\s\\v\\x85\\p{Z}]*(?:[A-Za-z]{2,3}(?:[-_][0-9A-Za-z]{1,8})*|[XxIi](?:[-_][0-9A-Za-z]{1,8})+)?[\\s\\v\\x85\\p{Z}]*$" doc:"Preferred subtitle language: BCP 47 tag or ISO 639 code, any case (en, eng, pt-BR), stored in canonical form; omitted or empty inherits" example:"en"`
+ SubtitleMode *string `json:"subtitle_mode,omitempty" nullable:"false" maxLength:"32" doc:"Free-form until the vocabulary is ratified (#135); v1 never validated it. Canonical values today: auto, always, off, default, forced_only" example:"auto"`
+ AutoSkipIntro *bool `json:"auto_skip_intro,omitempty" nullable:"false" example:"true"`
+ AutoSkipCredits *bool `json:"auto_skip_credits,omitempty" nullable:"false" example:"false"`
+ AutoSkipRecap *bool `json:"auto_skip_recap,omitempty" nullable:"false" example:"false"`
+ AutoPlayNextPreview *bool `json:"auto_play_next_preview,omitempty" nullable:"false" example:"false"`
+ ShowForcedSubtitles *bool `json:"show_forced_subtitles,omitempty" nullable:"false" doc:"Defaults to true when omitted" example:"true"`
+ LibraryRestrictionsEnabled *bool `json:"library_restrictions_enabled,omitempty" nullable:"false" doc:"Limits the profile to allowed_library_ids. Must be false or omitted on an account's first profile, which becomes its primary profile" example:"false"`
+ AllowedLibraryIDs *[]ID `json:"allowed_library_ids,omitempty" nullable:"false" doc:"Unique library identifiers the profile may see when restrictions are enabled. Must be empty on an account's first profile, which becomes its primary profile, even with restrictions off" example:"[\"1\",\"2\"]"`
+ MaxPlaybackQuality *string `json:"max_playback_quality,omitempty" nullable:"false" enum:"1080p,2160p" doc:"Playback ceiling" example:"1080p"`
}
// ProfileCreateInput is the createProfile request.
@@ -701,6 +706,7 @@ func (reg *Registry) listProfiles(ctx context.Context, _ *struct{}) (*ProfileCol
MaxAdvisoryAgeSupported: true,
RequireAdvisoryAgeSupported: true,
RequestsAllowedSupported: true,
+ ExcludedTagsSupported: true,
MaxProfiles: maxProfiles,
}}, nil
}
@@ -784,6 +790,7 @@ func (c ProfileCreate) toRequest() (handlers.ProfileCreateRequest, *Problem) {
MaxAdvisoryAge: number(c.MaxAdvisoryAge),
RequireAdvisoryAge: flag(c.RequireAdvisoryAge),
RequestsBlocked: c.RequestsAllowed != nil && !*c.RequestsAllowed,
+ ExcludedTags: c.ExcludedTags,
QualityPreference: str(c.QualityPreference),
Language: str(c.Language),
PreferredMetadataLanguage: str(c.PreferredMetadataLanguage),
@@ -953,6 +960,7 @@ func (u ProfileUpdate) toRequest() (handlers.ProfileUpdateRequest, *Problem) {
MaxAdvisoryAge: advisoryAgePatch(u.MaxAdvisoryAge),
RequireAdvisoryAge: u.RequireAdvisoryAge,
RequestsBlocked: negate(u.RequestsAllowed),
+ ExcludedTags: u.ExcludedTags,
QualityPreference: u.QualityPreference,
Language: clear(u.Language),
PreferredMetadataLanguage: clear(u.PreferredMetadataLanguage),
@@ -1045,6 +1053,7 @@ func profileOf(v handlers.ProfileView) (Profile, *Problem) {
MaxAdvisoryAge: advisoryAgeOf(v.MaxAdvisoryAge),
RequireAdvisoryAge: v.RequireAdvisoryAge,
RequestsAllowed: !v.RequestsBlocked,
+ ExcludedTags: NonNil(v.ExcludedTags),
QualityPreference: v.QualityPreference,
Language: v.Language,
PreferredMetadataLanguage: v.PreferredMetadataLanguage,
diff --git a/internal/apiv2/profiles_test.go b/internal/apiv2/profiles_test.go
index bed5124b605..4fa8f70e5a9 100644
--- a/internal/apiv2/profiles_test.go
+++ b/internal/apiv2/profiles_test.go
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "slices"
"strings"
"testing"
"time"
@@ -193,7 +194,7 @@ func TestListProfiles(t *testing.T) {
if rec.Code != 200 {
t.Fatal(rec.Body.String())
}
- want := `{"items":[{"id":"p-owner","name":"Laura","avatar":"preset:fox","avatar_url":"/avatars/presets/fox.png","avatar_source":"preset","has_pin":false,"is_child":false,"is_primary":true,"max_content_rating":"","max_advisory_age":null,"require_advisory_age":false,"requests_allowed":true,"quality_preference":"auto","language":"en","preferred_metadata_language":"","subtitle_language":"","subtitle_mode":"auto","auto_skip_intro":true,"auto_skip_credits":false,"auto_skip_recap":false,"auto_play_next_preview":false,"show_forced_subtitles":false,"library_restrictions_enabled":false,"allowed_library_ids":["3"],"max_playback_quality":"1080p","created_at":"2026-01-02T03:04:05.000Z","updated_at":"2026-01-02T03:04:05.000Z"}],"avatar_upload_enabled":true,"max_advisory_age_supported":true,"require_advisory_age_supported":true,"requests_allowed_supported":true}` + "\n"
+ want := `{"items":[{"id":"p-owner","name":"Laura","avatar":"preset:fox","avatar_url":"/avatars/presets/fox.png","avatar_source":"preset","has_pin":false,"is_child":false,"is_primary":true,"max_content_rating":"","max_advisory_age":null,"require_advisory_age":false,"requests_allowed":true,"excluded_tags":[],"quality_preference":"auto","language":"en","preferred_metadata_language":"","subtitle_language":"","subtitle_mode":"auto","auto_skip_intro":true,"auto_skip_credits":false,"auto_skip_recap":false,"auto_play_next_preview":false,"show_forced_subtitles":false,"library_restrictions_enabled":false,"allowed_library_ids":["3"],"max_playback_quality":"1080p","created_at":"2026-01-02T03:04:05.000Z","updated_at":"2026-01-02T03:04:05.000Z"}],"avatar_upload_enabled":true,"max_advisory_age_supported":true,"require_advisory_age_supported":true,"requests_allowed_supported":true,"excluded_tags_supported":true}` + "\n"
if rec.Body.String() != want {
t.Fatalf("body = %s", rec.Body.String())
}
@@ -489,3 +490,46 @@ func TestProfileRequestsAllowed(t *testing.T) {
t.Fatalf("create with requests_allowed false: %d %s", rec.Code, rec.Body.String())
}
}
+
+// excluded_tags always renders as an array; on update omitted leaves the
+// tags alone, an array replaces them, [] clears them, and null is rejected.
+// listProfiles reports the capability.
+func TestProfileExcludedTags(t *testing.T) {
+ view := fixtureProfileView()
+ view.ExcludedTags = []string{"Gore"}
+ profiles := &fakeProfiles{view: view}
+ h := newTestHandler(t, pilotDeps(nil, profiles))
+ auth := bearer(memberToken)
+
+ rec := do(t, h, http.MethodPatch, "/api/v2/profiles/p-owner", `{"is_child":true}`, auth)
+ if rec.Code != 200 || profiles.last.Request.ExcludedTags != nil {
+ t.Fatalf("omitted excluded_tags: %d, request %v", rec.Code, profiles.last.Request.ExcludedTags)
+ }
+ if !strings.Contains(rec.Body.String(), `"excluded_tags":["Gore"],`) {
+ t.Fatalf("stored tags not rendered: %s", rec.Body.String())
+ }
+ for body, want := range map[string][]string{`{"excluded_tags":["Gore","Late night"]}`: {"Gore", "Late night"}, `{"excluded_tags":[]}`: {}} {
+ rec = do(t, h, http.MethodPatch, "/api/v2/profiles/p-owner", body, auth)
+ if got := profiles.last.Request.ExcludedTags; rec.Code != 200 || got == nil || !slices.Equal(*got, want) {
+ t.Fatalf("%s: %d, request %v", body, rec.Code, got)
+ }
+ }
+ for _, body := range []string{`{"excluded_tags":null}`, `{"excluded_tags":"Gore"}`} {
+ p := requireProblem(t, do(t, h, http.MethodPatch, "/api/v2/profiles/p-owner", body, auth), TypeValidationFailed)
+ if len(p.Errors) != 1 || p.Errors[0].Location != "body.excluded_tags" {
+ t.Errorf("%s: errors = %+v", body, p.Errors)
+ }
+ }
+
+ rec = do(t, h, http.MethodPost, "/api/v2/profiles", `{"name":"Kid","excluded_tags":["Gore"]}`, with(auth, "X-Profile-Id", "p-owner"))
+ if rec.Code != 201 || !slices.Equal(profiles.lastCreate.Request.ExcludedTags, []string{"Gore"}) {
+ t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
+ }
+
+ view.ExcludedTags = nil
+ profiles.view = view
+ rec = do(t, h, http.MethodGet, "/api/v2/profiles", "", auth)
+ if !strings.Contains(rec.Body.String(), `"excluded_tags":[],`) || !strings.Contains(rec.Body.String(), `"excluded_tags_supported":true`) {
+ t.Fatalf("list: %s", rec.Body.String())
+ }
+}
diff --git a/internal/apiv2/router.go b/internal/apiv2/router.go
index 2df28cae5ff..3ea877ae618 100644
--- a/internal/apiv2/router.go
+++ b/internal/apiv2/router.go
@@ -211,6 +211,7 @@ type Dependencies struct {
EbookConfig EbookConfigService
EbookProgress EbookProgressService
AdminItemMetadata AdminItemMetadataService
+ CatalogCustomTags CatalogCustomTagService
AdminEpisodeOrders AdminEpisodeOrderService
AdminCustomSeasons AdminCustomSeasonsService
AdminImagePresigner AdminImagePresigner
diff --git a/internal/apiv2/title_allowances.go b/internal/apiv2/title_allowances.go
index c966c07f2eb..9608dbf7493 100644
--- a/internal/apiv2/title_allowances.go
+++ b/internal/apiv2/title_allowances.go
@@ -85,7 +85,7 @@ type TitleAllowanceProfile struct {
Name string `json:"name" example:"Emma"`
MaxContentRating string `json:"max_content_rating" doc:"The profile's content-rating ceiling; empty means none" example:"PG"`
MaxAdvisoryAge *int `json:"max_advisory_age" nullable:"true" doc:"The profile's advisory-age limit; null means none" example:"10"`
- State string `json:"state" enum:"within_limits,allowed,allowed_by_collection,above_limit,no_library_access" doc:"within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help" example:"above_limit"`
+ State string `json:"state" enum:"within_limits,allowed,allowed_by_collection,above_limit,no_library_access,hidden_by_tag" doc:"within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help. hidden_by_tag: the title carries a custom tag the profile excludes, which no allowance lifts" example:"above_limit"`
}
// TitleAllowanceProfileCollection lists every other profile on the account.
diff --git a/internal/backup/credentials_authority.go b/internal/backup/credentials_authority.go
index 603ca49711f..9905317ec34 100644
--- a/internal/backup/credentials_authority.go
+++ b/internal/backup/credentials_authority.go
@@ -36,7 +36,7 @@ type accountAuthority struct {
// profileLimits are a profile's protections and restrictions: its PIN,
// whether it manages the household (the primary profile), a child
-// profile, its rating and advisory-age ceilings, its block from requests, its library restriction,
+// profile, its rating and advisory-age ceilings, its block from requests, its excluded tags, its library restriction,
// its playback-quality ceiling, and the titles allowed above its ceilings.
type profileLimits struct {
pin bool
@@ -46,9 +46,11 @@ type profileLimits struct {
advisoryAge *int
requireAdvisoryAge bool
requestsBlocked bool
- restricted bool
- libraries []int
- quality string
+ // excludedTags are the custom tags the profile may not see.
+ excludedTags []string
+ restricted bool
+ libraries []int
+ quality string
// allowedTitles are the titles the profile may watch above its
// ceilings: its title allowances and the titles of its live-allowed
// collections, resolved as the access scope resolves them.
@@ -133,9 +135,16 @@ func readProfileLimits(ctx context.Context, tx pgx.Tx, userID int) (map[string]p
} else if has {
requestsBlocked = "p.requests_blocked"
}
+ // Likewise a backup taken before custom tags excludes none.
+ excludedTags := "'{}'::text[]"
+ if has, err := columnExists(ctx, tx, tableUserProfiles, "excluded_tags"); err != nil {
+ return nil, err
+ } else if has {
+ excludedTags = "p.excluded_tags"
+ }
rows, err := tx.Query(ctx, `
SELECT p.id, coalesce(p.pin_hash, '') <> '', p.is_primary, p.is_child, coalesce(p.max_content_rating, ''), p.max_advisory_age::int,
- p.require_advisory_age, `+requestsBlocked+`, p.library_restrictions_enabled,
+ p.require_advisory_age, `+requestsBlocked+`, `+excludedTags+`, p.library_restrictions_enabled,
coalesce((SELECT array_agg(a.library_id ORDER BY a.library_id) FROM user_profile_allowed_libraries a WHERE a.user_id = p.user_id AND a.profile_id = p.id), '{}'),
coalesce(p.max_playback_quality, ''),
`+allowedTitles+`, `+directTitles+`, `+allowedCollections+`, `+collectionTitles+`
@@ -148,7 +157,7 @@ func readProfileLimits(ctx context.Context, tx pgx.Tx, userID int) (map[string]p
for rows.Next() {
var id string
var p profileLimits
- if err := rows.Scan(&id, &p.pin, &p.primary, &p.child, &p.ceiling, &p.advisoryAge, &p.requireAdvisoryAge, &p.requestsBlocked, &p.restricted, &p.libraries,
+ if err := rows.Scan(&id, &p.pin, &p.primary, &p.child, &p.ceiling, &p.advisoryAge, &p.requireAdvisoryAge, &p.requestsBlocked, &p.excludedTags, &p.restricted, &p.libraries,
&p.quality, &p.allowedTitles, &p.directTitles, &p.allowedCollections, &p.collectionTitles); err != nil {
return nil, err
}
@@ -256,6 +265,11 @@ func (p profileLimits) looserThan(live profileLimits) bool {
}
}
}
+ // A tag live excludes and the restored profile does not shows the
+ // titles carrying it.
+ if hasOther(access.TagKeys(live.excludedTags), access.TagKeys(p.excludedTags)) {
+ return true
+ }
return hasOther(p.allowedTitles, live.allowedTitles) || hasOther(p.directTitles, live.directTitles) ||
hasOther(p.allowedCollections, live.allowedCollections) || hasOther(p.collectionTitles, live.collectionTitles)
}
diff --git a/internal/backup/credentials_authority_test.go b/internal/backup/credentials_authority_test.go
index 6fd275fadf9..50095d06be0 100644
--- a/internal/backup/credentials_authority_test.go
+++ b/internal/backup/credentials_authority_test.go
@@ -94,7 +94,7 @@ func TestAuthorityComparisonCoversEveryField(t *testing.T) {
func TestProfileComparisonCoversEveryField(t *testing.T) {
profileColumns := map[string]string{
"PINHash": "pin", "IsPrimary": "primary", "IsChild": "child", "MaxContentRating": "ceiling", "MaxAdvisoryAge": "advisoryAge",
- "RequireAdvisoryAge": "requireAdvisoryAge", "RequestsBlocked": "requestsBlocked", "LibraryRestrictionsEnabled": "restricted", "AllowedLibraryIDs": "libraries",
+ "RequireAdvisoryAge": "requireAdvisoryAge", "RequestsBlocked": "requestsBlocked", "ExcludedTags": "excludedTags", "LibraryRestrictionsEnabled": "restricted", "AllowedLibraryIDs": "libraries",
"MaxPlaybackQuality": "quality", "AllowedTitleIDs": "allowedTitles",
}
notAuthority := map[string]string{
@@ -126,7 +126,7 @@ func TestProfileComparisonCoversEveryField(t *testing.T) {
// Each protection, lifted, widens the account.
quality, age := "1080p", 12
strict := profileLimits{pin: true, child: true, ceiling: "PG", advisoryAge: &age, requireAdvisoryAge: true, requestsBlocked: true,
- restricted: true, libraries: []int{1}, quality: quality}
+ excludedTags: []string{"Gore"}, restricted: true, libraries: []int{1}, quality: quality}
profileWidenings := map[string]func(*profileLimits){
"pin": func(p *profileLimits) { p.pin = false },
"primary": func(p *profileLimits) { p.primary = true },
@@ -135,6 +135,7 @@ func TestProfileComparisonCoversEveryField(t *testing.T) {
"advisoryAge": func(p *profileLimits) { p.advisoryAge = nil },
"requireAdvisoryAge": func(p *profileLimits) { p.requireAdvisoryAge = false },
"requestsBlocked": func(p *profileLimits) { p.requestsBlocked = false },
+ "excludedTags": func(p *profileLimits) { p.excludedTags = nil },
"restricted": func(p *profileLimits) { p.restricted = false },
"libraries": func(p *profileLimits) { p.libraries = []int{1, 2} },
"quality": func(p *profileLimits) { p.quality = "" },
@@ -143,6 +144,10 @@ func TestProfileComparisonCoversEveryField(t *testing.T) {
"directTitles": func(p *profileLimits) { p.directTitles = []string{"movie-r"} },
"collectionTitles": func(p *profileLimits) { p.collectionTitles = []string{"movie-r"} },
}
+ // Excluding the same tags in another spelling is not looser.
+ if respelled := strict; func() bool { respelled.excludedTags = []string{" gore "}; return respelled.looserThan(strict) }() {
+ t.Error("looserThan counts a respelled excluded tag as lifted")
+ }
for _, f := range reflect.VisibleFields(reflect.TypeFor[profileLimits]()) {
widen, ok := profileWidenings[f.Name]
if !ok {
diff --git a/internal/backup/profile_transfer.go b/internal/backup/profile_transfer.go
index b748adb0fc8..40d9d6e4002 100644
--- a/internal/backup/profile_transfer.go
+++ b/internal/backup/profile_transfer.go
@@ -84,7 +84,7 @@ var accessFieldNames = func() map[string]bool {
out := map[string]bool{}
for _, name := range strings.Fields(`account accounts profiles profile username email password_hash pin_hash role
permissions policy group effective_policy library_ids allowed_library_ids library_restrictions_enabled
- max_content_rating max_advisory_age require_advisory_age requests_blocked max_playback_quality is_child is_primary is_owner`) {
+ max_content_rating max_advisory_age require_advisory_age requests_blocked excluded_tags max_playback_quality is_child is_primary is_owner`) {
out[name] = true
}
return out
diff --git a/internal/backup/restoreset_users.go b/internal/backup/restoreset_users.go
index 4bce7531568..609d29d964a 100644
--- a/internal/backup/restoreset_users.go
+++ b/internal/backup/restoreset_users.go
@@ -122,19 +122,22 @@ type EffectivePolicy struct {
// hash, and every field the access resolver reads, with the profile's data
// by data type.
type ProfileEntry struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Avatar string `json:"avatar"`
- IsPrimary bool `json:"is_primary"`
- PINHash string `json:"pin_hash"`
- IsChild bool `json:"is_child"`
- MaxContentRating string `json:"max_content_rating"`
- MaxAdvisoryAge int `json:"max_advisory_age"`
- RequireAdvisoryAge bool `json:"require_advisory_age"`
- RequestsBlocked bool `json:"requests_blocked"`
- LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
- AllowedLibraryIDs []int `json:"allowed_library_ids"`
- MaxPlaybackQuality string `json:"max_playback_quality"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Avatar string `json:"avatar"`
+ IsPrimary bool `json:"is_primary"`
+ PINHash string `json:"pin_hash"`
+ IsChild bool `json:"is_child"`
+ MaxContentRating string `json:"max_content_rating"`
+ MaxAdvisoryAge int `json:"max_advisory_age"`
+ RequireAdvisoryAge bool `json:"require_advisory_age"`
+ RequestsBlocked bool `json:"requests_blocked"`
+ // ExcludedTags are the custom tags whose titles the profile may not
+ // see; absent from a backup taken before custom tags.
+ ExcludedTags []string `json:"excluded_tags,omitempty"`
+ LibraryRestrictionsEnabled bool `json:"library_restrictions_enabled"`
+ AllowedLibraryIDs []int `json:"allowed_library_ids"`
+ MaxPlaybackQuality string `json:"max_playback_quality"`
// Data holds each data type's document by data type id.
// Data is each type's own document, which the type bounds itself
// (userdata.DecodeStrict).
@@ -472,7 +475,7 @@ func exportUser(ctx context.Context, tx pgx.Tx, account AccountEntry) (UserDocum
func readBackupProfiles(ctx context.Context, tx pgx.Tx, userID int) ([]ProfileEntry, error) {
rows, err := tx.Query(ctx, `
SELECT p.id, p.name, p.avatar, p.is_primary, p.pin_hash, p.is_child, p.max_content_rating, COALESCE(p.max_advisory_age, 0),
- p.require_advisory_age, p.requests_blocked, p.library_restrictions_enabled, p.max_playback_quality,
+ p.require_advisory_age, p.requests_blocked, p.excluded_tags, p.library_restrictions_enabled, p.max_playback_quality,
COALESCE((SELECT array_agg(l.library_id ORDER BY l.library_id) FROM user_profile_allowed_libraries l
WHERE l.user_id = p.user_id AND l.profile_id = p.id), '{}')
FROM user_profiles p WHERE p.user_id = $1 ORDER BY p.created_at, p.id`, userID)
@@ -484,7 +487,7 @@ func readBackupProfiles(ctx context.Context, tx pgx.Tx, userID int) ([]ProfileEn
for rows.Next() {
var p ProfileEntry
if err := rows.Scan(&p.ID, &p.Name, &p.Avatar, &p.IsPrimary, &p.PINHash, &p.IsChild, &p.MaxContentRating, &p.MaxAdvisoryAge,
- &p.RequireAdvisoryAge, &p.RequestsBlocked, &p.LibraryRestrictionsEnabled, &p.MaxPlaybackQuality, &p.AllowedLibraryIDs); err != nil {
+ &p.RequireAdvisoryAge, &p.RequestsBlocked, &p.ExcludedTags, &p.LibraryRestrictionsEnabled, &p.MaxPlaybackQuality, &p.AllowedLibraryIDs); err != nil {
return nil, err
}
out = append(out, p)
diff --git a/internal/backup/users_apply.go b/internal/backup/users_apply.go
index 729e27c4707..66b08f3bf00 100644
--- a/internal/backup/users_apply.go
+++ b/internal/backup/users_apply.go
@@ -552,7 +552,8 @@ func (a *applier) createProfile(ctx context.Context, tx pgx.Tx, doc *UserDocumen
primary, err := pgstore.CreateRestoredProfileInTx(ctx, tx, plan.localID, pgstore.RestoredProfile{
ID: id, Name: e.Name, Avatar: avatar, IsPrimary: e.IsPrimary, PINHash: e.PINHash, IsChild: e.IsChild,
MaxContentRating: e.MaxContentRating, MaxAdvisoryAge: e.MaxAdvisoryAge, RequireAdvisoryAge: e.RequireAdvisoryAge,
- RequestsBlocked: e.RequestsBlocked, LibraryRestrictionsEnabled: e.LibraryRestrictionsEnabled, AllowedLibraryIDs: pp.allowed, MaxPlaybackQuality: e.MaxPlaybackQuality,
+ RequestsBlocked: e.RequestsBlocked, ExcludedTags: restoredExcludedTags(e.ExcludedTags),
+ LibraryRestrictionsEnabled: e.LibraryRestrictionsEnabled, AllowedLibraryIDs: pp.allowed, MaxPlaybackQuality: e.MaxPlaybackQuality,
})
if err != nil {
return false, err
@@ -660,3 +661,13 @@ func (a *applier) lookUpPluginInstallation(ctx context.Context, q queryer, insta
local, err := strconv.Atoi(ids[0])
return local, err == nil
}
+
+// restoredExcludedTags is a backed-up profile's excluded tags as this server
+// stores them. A list past the tag bounds still restores whole, one entry per
+// tag: dropping a tag would show the titles it hides.
+func restoredExcludedTags(tags []string) []string {
+ if out, ok := access.NormalizeTags(tags); ok {
+ return out
+ }
+ return access.TagKeys(tags)
+}
diff --git a/internal/backup/users_postgres_test.go b/internal/backup/users_postgres_test.go
index ce596df1d56..d702d501da8 100644
--- a/internal/backup/users_postgres_test.go
+++ b/internal/backup/users_postgres_test.go
@@ -980,7 +980,8 @@ func TestUserRestoreSameServerDB(t *testing.T) {
testProfile(t, f.pool, account, gone, "Gone", false, fakeHash("pin"))
// The child profile's ceiling hides the R-rated movie, though it once
// watched it: a restore gives it no data about a title it may not see.
- dbExec(t, f.pool, `UPDATE user_profiles SET is_child = true, max_content_rating = 'PG' WHERE user_id = $1 AND id = $2`, account, gone)
+ // Its excluded tags come back with it.
+ dbExec(t, f.pool, `UPDATE user_profiles SET is_child = true, max_content_rating = 'PG', excluded_tags = '{Gore}' WHERE user_id = $1 AND id = $2`, account, gone)
for _, p := range []string{keep, gone} {
for _, m := range []string{movie, mature} {
dbExec(t, f.pool, `INSERT INTO user_watch_progress (user_id, profile_id, media_item_id, position_seconds, duration_seconds, updated_at) VALUES ($1, $2, $3, 30, 300, now())`, account, p, m)
@@ -1011,7 +1012,7 @@ func TestUserRestoreSameServerDB(t *testing.T) {
t.Fatalf("same-server restore = %+v %+v", restored, restored.Account)
}
newGone := restored.Account.Profiles[1].LocalID
- if newGone == gone || countRows(t, f.pool, `SELECT count(*) FROM user_profiles WHERE user_id = $1 AND id = $2 AND pin_hash = $3`, account, newGone, fakeHash("pin")) != 1 ||
+ if newGone == gone || countRows(t, f.pool, `SELECT count(*) FROM user_profiles WHERE user_id = $1 AND id = $2 AND pin_hash = $3 AND excluded_tags = '{Gore}'`, account, newGone, fakeHash("pin")) != 1 ||
countRows(t, f.pool, `SELECT count(*) FROM user_watch_progress WHERE user_id = $1`, account) != 3 ||
countRows(t, f.pool, `SELECT count(*) FROM user_watch_progress WHERE user_id = $1 AND profile_id = $2 AND media_item_id = $3`, account, newGone, mature) != 0 {
t.Fatalf("restored profile %s: its progress is missing, or it gained the R-rated movie", newGone)
diff --git a/internal/catalog/access_cache_key.go b/internal/catalog/access_cache_key.go
index 21c2c1df53a..656b1fd2652 100644
--- a/internal/catalog/access_cache_key.go
+++ b/internal/catalog/access_cache_key.go
@@ -20,7 +20,7 @@ import (
//
// Included: AllowedLibraryIDs, DisabledLibraryIDs, every MaturityLimits field
// (MaxContentRating, AllowUnratedContent, MaxAdvisoryAge, RequireAdvisoryAge,
-// AllowedTitleIDs),
+// AllowedTitleIDs, ExcludedTags),
// ExcludedMediaTypes,
// NamePrefix, AllowedContentIDs. AllowedLibraryIDs and
// AllowedContentIDs preserve the nil (unrestricted) vs empty (restrict to
@@ -66,6 +66,14 @@ func (f AccessFilter) WriteAccessScopeCacheKey(b *strings.Builder) {
b.WriteString("|allowedtitles=")
b.WriteString(hashOptionalStringsKey(f.AllowedTitleIDs))
+ // Keyed as TagKeys, the form the predicate binds, so spellings of one
+ // tag share an entry. Each is quoted: a tag is free text and may hold
+ // the separators the other members rely on.
+ b.WriteString("|excludedtags=")
+ for _, tag := range access.TagKeys(f.ExcludedTags) {
+ b.WriteString(strconv.Quote(tag))
+ }
+
b.WriteString("|excludedtypes=")
writeSortedStringsKey(b, f.ExcludedMediaTypes)
diff --git a/internal/catalog/access_cache_key_test.go b/internal/catalog/access_cache_key_test.go
index 65e9559f0d3..adc8b64af4b 100644
--- a/internal/catalog/access_cache_key_test.go
+++ b/internal/catalog/access_cache_key_test.go
@@ -91,6 +91,17 @@ func TestAccessScopeCacheKeyCoversEveryMaturityLimit(t *testing.T) {
scopeKey(AccessFilter{MaturityLimits: access.MaturityLimits{MaxAdvisoryAge: 13}}) {
t.Error("advisory limits 10 and 13 must key separately")
}
+ // Tags are free text: a separator inside one tag must not key like two
+ // tags, while spellings of one tag render the same SQL and share a key.
+ tags := func(tags ...string) string {
+ return scopeKey(AccessFilter{MaturityLimits: access.MaturityLimits{ExcludedTags: tags}})
+ }
+ if tags("a,b") == tags("a", "b") || tags("a|excludedtypes=movie") == tags("a") {
+ t.Error("a tag holding a key separator collides with another scope")
+ }
+ if tags("Gore", "Late night") != tags(" late NIGHT ", "gore") {
+ t.Error("spellings of the same tags must share a key")
+ }
}
type namedMaturityLimits struct {
diff --git a/internal/catalog/access_filter.go b/internal/catalog/access_filter.go
index 1fdb91f7b00..82edaeab189 100644
--- a/internal/catalog/access_filter.go
+++ b/internal/catalog/access_filter.go
@@ -221,10 +221,37 @@ func ApplyEpisodeMaturityLimits(alias string, filter AccessFilter, conditions *[
applyMaturityLimits(alias, alias+".series_id", filter.MaturityLimits, conditions, args, argIdx)
}
+// excludedTagsSQL hides the title whose media_items row is titleKey (the
+// item itself, or an episode's series) when it carries a custom tag whose
+// lowercase matches one in the array bound at argIdx. Tags are looked up on the
+// title's own row rather than on alias, so episode read models that copy the
+// series' ratings need no copy of its tags, and a tag edit applies at once.
+//
+// The subquery does not depend on the outer row: Postgres builds the set of
+// excluded titles once per query, from the partial index on tagged titles,
+// and each row costs one hash lookup.
+func excludedTagsSQL(titleKey string, argIdx int) string {
+ return fmt.Sprintf(`%s NOT IN (
+ SELECT tagged.content_id FROM media_items tagged
+ WHERE tagged.custom_tags <> '{}'
+ AND EXISTS (
+ SELECT 1 FROM unnest(tagged.custom_tags) AS tag
+ WHERE lower(tag) IN (SELECT lower(excluded) FROM unnest($%d::text[]) AS excluded)
+ )
+ )`, titleKey, argIdx)
+}
+
// matchNothingSQL is the predicate an unusable maturity ceiling renders.
const matchNothingSQL = "1 = 0"
func applyMaturityLimits(alias, allowedKey string, limits access.MaturityLimits, conditions *[]string, args *[]any, argIdx *int) {
+ // Outside the allowance below: a title allowance lifts rating limits,
+ // never an excluded tag.
+ if tags := access.DistinctTags(limits.ExcludedTags); len(tags) > 0 {
+ *conditions = append(*conditions, excludedTagsSQL(allowedKey, *argIdx))
+ *args = append(*args, tags)
+ *argIdx = *argIdx + 1
+ }
limitConds := maturityLimitConditions(alias, limits, args, argIdx)
if len(limitConds) == 0 {
return
diff --git a/internal/catalog/custom_tags.go b/internal/catalog/custom_tags.go
new file mode 100644
index 00000000000..ea2b369a630
--- /dev/null
+++ b/internal/catalog/custom_tags.go
@@ -0,0 +1,53 @@
+package catalog
+
+import (
+ "context"
+ "fmt"
+ "strings"
+)
+
+// customTagListLimit bounds the tag list. Tags are typed by curators, so a
+// server holds tens of them; the bound only keeps a runaway list cheap.
+const customTagListLimit = 1000
+
+// CustomTagCount is one custom tag and how many movies and series the viewer
+// can see that carry it.
+type CustomTagCount struct {
+ Tag string
+ TitleCount int
+}
+
+// ListCustomTags lists the custom tags on the movies and series filter can
+// see, most used first. Spellings that differ only in case are one tag,
+// shown in its most used spelling.
+func (r *ItemRepository) ListCustomTags(ctx context.Context, filter AccessFilter) ([]CustomTagCount, error) {
+ conditions := []string{"mi.custom_tags <> '{}'", "mi.type IN ('movie', 'series')", InSomeLibraryWhere("mi.content_id")}
+ var args []any
+ argIdx := 1
+ if _, none := filter.LibraryScope(nil); none {
+ return []CustomTagCount{}, nil
+ }
+ appendLibraryAccessConditions("mi.content_id", filter, &conditions, &args, &argIdx)
+ applyAccessFilter("mi", filter, &conditions, &args, &argIdx)
+ query := fmt.Sprintf(`
+ SELECT mode() WITHIN GROUP (ORDER BY tag COLLATE "C"), COUNT(DISTINCT mi.content_id)
+ FROM media_items mi, unnest(mi.custom_tags) AS tag
+ WHERE %s
+ GROUP BY lower(tag)
+ ORDER BY 2 DESC, lower(tag)
+ LIMIT %d`, strings.Join(conditions, " AND "), customTagListLimit)
+ rows, err := r.pool.Query(ctx, query, args...)
+ if err != nil {
+ return nil, fmt.Errorf("listing custom tags: %w", err)
+ }
+ defer rows.Close()
+ out := []CustomTagCount{}
+ for rows.Next() {
+ var tag CustomTagCount
+ if err := rows.Scan(&tag.Tag, &tag.TitleCount); err != nil {
+ return nil, fmt.Errorf("scanning custom tag: %w", err)
+ }
+ out = append(out, tag)
+ }
+ return out, rows.Err()
+}
diff --git a/internal/catalog/custom_tags_access_db_test.go b/internal/catalog/custom_tags_access_db_test.go
new file mode 100644
index 00000000000..2e6bfa122d1
--- /dev/null
+++ b/internal/catalog/custom_tags_access_db_test.go
@@ -0,0 +1,220 @@
+package catalog
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/Silo-Server/silo-server/internal/access"
+ "github.com/Silo-Server/silo-server/internal/models"
+)
+
+// A profile's excluded custom tags hide every movie and series carrying one
+// of them, matched without regard to case, and every episode of a hidden
+// series. A title allowance lifts the rating limits only, never a tag.
+func TestExcludedCustomTagsHideTitlesPostgres(t *testing.T) {
+ dsn := os.Getenv("SILO_TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("SILO_TEST_DATABASE_URL is not set")
+ }
+ ctx := t.Context()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+
+ prefix := fmt.Sprintf("custom-tags-%d", time.Now().UnixNano())
+ id := func(name string) string { return prefix + "-" + name }
+ var library int
+ if err := pool.QueryRow(ctx, `INSERT INTO media_folders(type,name,enabled) VALUES('movies',$1,true) RETURNING id`, prefix).Scan(&library); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ cleanup := context.Background()
+ _, _ = pool.Exec(cleanup, `DELETE FROM media_items WHERE content_id LIKE $1`, prefix+"%")
+ _, _ = pool.Exec(cleanup, `DELETE FROM media_folders WHERE id=$1`, library)
+ })
+ exec := func(sql string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql, args...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, item := range []struct {
+ name, kind string
+ tags []string
+ }{
+ {"gory-movie", "movie", []string{"Gore", "Late night"}},
+ {"plain-movie", "movie", []string{}},
+ {"other-tag-movie", "movie", []string{"Comfort"}},
+ {"gory-series", "series", []string{"gore"}},
+ {"plain-series", "series", nil},
+ } {
+ tags := item.tags
+ if tags == nil {
+ tags = []string{}
+ }
+ exec(`INSERT INTO media_items(content_id,type,title,content_rating,content_rating_age,custom_tags) VALUES($1,$2,$1,'PG',8,$3)`, id(item.name), item.kind, tags)
+ exec(`INSERT INTO media_item_libraries(content_id,media_folder_id) VALUES($1,$2)`, id(item.name), library)
+ }
+ for _, series := range []string{"gory-series", "plain-series"} {
+ exec(`INSERT INTO episodes(content_id,series_id,season_number,episode_number,title) VALUES($1,$2,1,1,'Pilot')`, id(series+"-e1"), id(series))
+ }
+
+ everything := []string{id("gory-movie"), id("plain-movie"), id("other-tag-movie"), id("gory-series"), id("plain-series"), id("gory-series-e1"), id("plain-series-e1")}
+ visible := func(limits access.MaturityLimits) []string {
+ t.Helper()
+ got, err := filterAccessibleContentIDs(ctx, pool, everything, nil, nil, limits)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for contentID := range got {
+ out = append(out, strings.TrimPrefix(contentID, prefix+"-"))
+ }
+ slices.Sort(out)
+ return out
+ }
+ unrestricted := []string{"gory-movie", "gory-series", "gory-series-e1", "other-tag-movie", "plain-movie", "plain-series", "plain-series-e1"}
+ withoutGore := []string{"other-tag-movie", "plain-movie", "plain-series", "plain-series-e1"}
+
+ for _, tc := range []struct {
+ name string
+ limits access.MaturityLimits
+ want []string
+ }{
+ {"no tags", access.MaturityLimits{}, unrestricted},
+ {"case-insensitive tag", access.MaturityLimits{ExcludedTags: []string{"GORE"}}, withoutGore},
+ {"tag no title carries", access.MaturityLimits{ExcludedTags: []string{"Absent"}}, unrestricted},
+ {"two tags", access.MaturityLimits{ExcludedTags: []string{"gore", "comfort"}}, []string{"plain-movie", "plain-series", "plain-series-e1"}},
+ {"with a rating ceiling", access.MaturityLimits{MaxContentRating: "PG-13", ExcludedTags: []string{"Gore"}}, withoutGore},
+ {"allowance does not lift a tag", access.MaturityLimits{MaxContentRating: "G", ExcludedTags: []string{"Gore"}}.WithAllowedTitles([]string{id("gory-movie"), id("plain-movie")}), []string{"plain-movie"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := visible(tc.limits); !slices.Equal(got, tc.want) {
+ t.Fatalf("visible = %v, want %v", got, tc.want)
+ }
+ })
+ }
+
+ checkTaggedItemListing(t, pool, prefix)
+ checkCustomTagList(t, pool, library)
+}
+
+// checkTaggedItemListing: every catalog read applies the limits through
+// ApplyMaturityLimits over a media_items alias; an item listing is the
+// plainest of them.
+func checkTaggedItemListing(t *testing.T, pool *pgxpool.Pool, prefix string) {
+ t.Helper()
+ ctx := t.Context()
+ conditions := []string{"mi.content_id LIKE $1"}
+ args := []any{prefix + "%"}
+ argIdx := 2
+ ApplyMaturityLimits("mi", AccessFilter{MaturityLimits: access.MaturityLimits{ExcludedTags: []string{" gore "}}}, &conditions, &args, &argIdx)
+ rows, err := pool.Query(ctx, "SELECT mi.content_id FROM media_items mi WHERE "+strings.Join(conditions, " AND ")+" ORDER BY 1", args...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var listed []string
+ for rows.Next() {
+ var contentID string
+ if err := rows.Scan(&contentID); err != nil {
+ t.Fatal(err)
+ }
+ listed = append(listed, strings.TrimPrefix(contentID, prefix+"-"))
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{"other-tag-movie", "plain-movie", "plain-series"}; !slices.Equal(listed, want) {
+ t.Fatalf("listed = %v, want %v", listed, want)
+ }
+
+}
+
+// checkCustomTagList: the tag list counts the titles the viewer can see under
+// each tag, one entry per tag whatever its spelling, most used first.
+func checkCustomTagList(t *testing.T, pool *pgxpool.Pool, library int) {
+ t.Helper()
+ ctx := t.Context()
+ repo := NewItemRepository(pool)
+ for _, tc := range []struct {
+ name string
+ filter AccessFilter
+ want []CustomTagCount
+ }{
+ {"every title", AccessFilter{AllowedLibraryIDs: []int{library}}, []CustomTagCount{{"Gore", 2}, {"Comfort", 1}, {"Late night", 1}}},
+ {"hidden titles do not count", AccessFilter{AllowedLibraryIDs: []int{library}, MaturityLimits: access.MaturityLimits{ExcludedTags: []string{"comfort"}}}, []CustomTagCount{{"Gore", 2}, {"Late night", 1}}},
+ {"another library", AccessFilter{AllowedLibraryIDs: []int{library + 1_000_000}}, []CustomTagCount{}},
+ } {
+ t.Run("list "+tc.name, func(t *testing.T) {
+ got, err := repo.ListCustomTags(ctx, tc.filter)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got, tc.want) {
+ t.Fatalf("ListCustomTags = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// A metadata edit stores a movie's custom tags, and a provider refresh, which
+// rewrites the item through Upsert, leaves them alone: no provider owns them.
+// Other item types take none.
+func TestCustomTagsSurviveMetadataRefreshPostgres(t *testing.T) {
+ dsn := os.Getenv("SILO_TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("SILO_TEST_DATABASE_URL is not set")
+ }
+ ctx := t.Context()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ contentID := fmt.Sprintf("custom-tags-refresh-%d", time.Now().UnixNano())
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM media_items WHERE content_id LIKE $1`, contentID+"%")
+ })
+
+ repo := NewItemRepository(pool)
+ item := &models.MediaItem{ContentID: contentID, Type: "movie", Title: "Before", Genres: []string{"Drama"}}
+ if err := repo.Upsert(ctx, item); err != nil {
+ t.Fatal(err)
+ }
+ details := NewDetailService(repo, NewEpisodeRepository(pool), NewSeasonRepository(pool), NewPersonRepository(pool), noFileVersions{})
+ tags := []string{"Gore", "Late night"}
+ if err := details.UpdateMediaItemMetadata(ctx, contentID, &MetadataUpdate{CustomTags: &tags}); err != nil {
+ t.Fatal(err)
+ }
+ book := &models.MediaItem{ContentID: contentID + "-book", Type: "audiobook", Title: "Book"}
+ if err := repo.Upsert(ctx, book); err != nil {
+ t.Fatal(err)
+ }
+ if err := details.UpdateMediaItemMetadata(ctx, book.ContentID, &MetadataUpdate{CustomTags: &tags}); !errors.Is(err, ErrCustomTagsUnsupported) {
+ t.Fatalf("custom tags on an audiobook: err = %v, want ErrCustomTagsUnsupported", err)
+ }
+ item.Title, item.Genres = "After", []string{"Horror"}
+ if err := repo.Upsert(ctx, item); err != nil {
+ t.Fatal(err)
+ }
+ got, err := repo.CustomTags(ctx, contentID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got, tags) {
+ t.Fatalf("custom tags after a refresh = %v, want %v", got, tags)
+ }
+ if refreshed, err := repo.GetByID(ctx, contentID); err != nil || refreshed.Title != "After" {
+ t.Fatalf("the refresh did not land: %+v, %v", refreshed, err)
+ }
+}
diff --git a/internal/catalog/detail.go b/internal/catalog/detail.go
index d5f3e0e0fc4..723555c5533 100644
--- a/internal/catalog/detail.go
+++ b/internal/catalog/detail.go
@@ -235,13 +235,17 @@ type ItemDetail struct {
Studios []string `json:"studios"`
Networks []string `json:"networks"`
Countries []string `json:"countries,omitempty"`
- LockedFields []int `json:"locked_fields,omitempty"`
- FirstAirDate *string `json:"first_air_date,omitempty"`
- LastAirDate *string `json:"last_air_date,omitempty"`
- ReleaseDate *string `json:"release_date,omitempty"`
- AirTime *string `json:"air_time,omitempty"`
- AirTimezone *string `json:"air_timezone,omitempty"`
- ShowStatus string `json:"show_status,omitempty"`
+ // CustomTags are the movie's or series' custom tags. Only a viewer who
+ // curates the item's metadata gets them (AttachCustomTags), and /api/v1
+ // never does (json:"-").
+ CustomTags []string `json:"-"`
+ LockedFields []int `json:"locked_fields,omitempty"`
+ FirstAirDate *string `json:"first_air_date,omitempty"`
+ LastAirDate *string `json:"last_air_date,omitempty"`
+ ReleaseDate *string `json:"release_date,omitempty"`
+ AirTime *string `json:"air_time,omitempty"`
+ AirTimezone *string `json:"air_timezone,omitempty"`
+ ShowStatus string `json:"show_status,omitempty"`
// Presigned image URLs.
PosterURL string `json:"poster_url,omitempty"`
@@ -5780,3 +5784,17 @@ func (s *DetailService) episodeOrderSummary(ctx context.Context, seriesID string
}
return &o
}
+
+// AttachCustomTags loads a movie's or series' custom tags into detail, for a
+// viewer who curates its metadata. Other item types carry none.
+func (s *DetailService) AttachCustomTags(ctx context.Context, detail *ItemDetail) error {
+ if s == nil || s.itemRepo == nil || detail == nil || (detail.Type != AdminCatalogTypeMovie && detail.Type != AdminCatalogTypeSeries) {
+ return nil
+ }
+ tags, err := s.itemRepo.CustomTags(ctx, detail.ContentID)
+ if err != nil {
+ return err
+ }
+ detail.CustomTags = tags
+ return nil
+}
diff --git a/internal/catalog/episode_catalog_count_db_test.go b/internal/catalog/episode_catalog_count_db_test.go
index bf93724d838..f2ff7f649ac 100644
--- a/internal/catalog/episode_catalog_count_db_test.go
+++ b/internal/catalog/episode_catalog_count_db_test.go
@@ -56,6 +56,10 @@ func TestEpisodeCatalogCountsMatchCursorPagesPostgres(t *testing.T) {
a.MaturityLimits = access.MaturityLimits{MaxContentRating: "TV-14"}
return a
}, want: 3},
+ {name: "unwatched excluded tag", rules: unwatched, access: func(a AccessFilter) AccessFilter {
+ a.MaturityLimits = access.MaturityLimits{ExcludedTags: []string{"gore"}}
+ return a
+ }, want: 3},
{name: "unwatched disabled library", rules: unwatched, access: func(a AccessFilter) AccessFilter { a.DisabledLibraryIDs = []int{disabled}; return a }, want: 5},
{name: "episodes excluded", rules: unwatched, access: func(a AccessFilter) AccessFilter { a.ExcludedMediaTypes = []string{"episode"}; return a }, want: 0},
{name: "audio language", rules: []QueryRule{{Field: "audio_language", Op: "is", Value: "EN"}}, want: 1},
@@ -142,6 +146,10 @@ func seedEpisodeCountLibrary(t *testing.T, pool *pgxpool.Pool) episodeCountLibra
t.Fatal(err)
}
}
+ // Only bravo carries the tag, so excluding it hides bravo's episodes.
+ if _, err := pool.Exec(ctx, `UPDATE media_items SET custom_tags=ARRAY['Gore'] WHERE content_id=$1`, bravo); err != nil {
+ t.Fatal(err)
+ }
id := func(title string) string { return prefix + "-" + title }
for i, episode := range []struct {
series, title string
diff --git a/internal/catalog/item_repo.go b/internal/catalog/item_repo.go
index 25ab3f93437..5fb96da085d 100644
--- a/internal/catalog/item_repo.go
+++ b/internal/catalog/item_repo.go
@@ -870,6 +870,20 @@ func nonNilStringSlice(values []string) []string {
return values
}
+// CustomTags returns the item's custom tags; none for an item that has none
+// or does not exist.
+func (r *ItemRepository) CustomTags(ctx context.Context, contentID string) ([]string, error) {
+ var tags []string
+ err := r.pool.QueryRow(ctx, `SELECT custom_tags FROM media_items WHERE content_id = $1`, contentID).Scan(&tags)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("reading custom tags of %s: %w", contentID, err)
+ }
+ return tags, nil
+}
+
// GetByID retrieves a media item by its content ID.
func (r *ItemRepository) GetByID(ctx context.Context, contentID string) (*models.MediaItem, error) {
query := `SELECT ` + itemColumns + ` FROM media_items WHERE content_id = $1`
@@ -3006,6 +3020,7 @@ func (r *ItemRepository) UpdateMetadataTx(ctx context.Context, tx pgx.Tx, conten
addStringArray("studios", upd.Studios)
addStringArray("networks", upd.Networks)
addStringArray("countries", upd.Countries)
+ addStringArray("custom_tags", upd.CustomTags)
addString("release_date", upd.ReleaseDate)
addString("first_air_date", upd.FirstAirDate)
addString("last_air_date", upd.LastAirDate)
diff --git a/internal/catalog/personal_collection_access.go b/internal/catalog/personal_collection_access.go
index cd19f414583..a29bec30b55 100644
--- a/internal/catalog/personal_collection_access.go
+++ b/internal/catalog/personal_collection_access.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "slices"
"strings"
"github.com/Silo-Server/silo-server/internal/access"
@@ -86,6 +87,8 @@ func intersectMaturityLimits(viewer, owner access.MaturityLimits) access.Maturit
}
out.RequireAdvisoryAge = viewer.HidesUnadvised() || owner.HidesUnadvised()
out.AllowedTitleIDs = intersectAllowedTitles(viewer, owner)
+ // Either side's excluded tags hide a title.
+ out.ExcludedTags = access.DistinctTags(append(slices.Clone(viewer.ExcludedTags), owner.ExcludedTags...))
return out
}
@@ -96,9 +99,9 @@ func intersectMaturityLimits(viewer, owner access.MaturityLimits) access.Maturit
// wider, so one profile's allowance cannot lift the other profile's limit.
func intersectAllowedTitles(viewer, owner access.MaturityLimits) []string {
switch {
- case !owner.Active():
+ case !owner.RatingActive():
return viewer.AllowedTitleIDs
- case !viewer.Active():
+ case !viewer.RatingActive():
return owner.AllowedTitleIDs
}
ownerAllowed := make(map[string]struct{}, len(owner.AllowedTitleIDs))
diff --git a/internal/catalog/personal_collection_access_test.go b/internal/catalog/personal_collection_access_test.go
index 01035279c72..bb77bb98854 100644
--- a/internal/catalog/personal_collection_access_test.go
+++ b/internal/catalog/personal_collection_access_test.go
@@ -115,6 +115,18 @@ func TestIntersectAccessMaturityLimits(t *testing.T) {
access.MaturityLimits{MaxContentRating: "PG-13", AllowedTitleIDs: []string{"b", "c"}},
access.MaturityLimits{MaxContentRating: "PG", AllowedTitleIDs: []string{"b"}},
},
+ {
+ "either side's excluded tags apply",
+ access.MaturityLimits{ExcludedTags: []string{"gore"}},
+ access.MaturityLimits{ExcludedTags: []string{"Late night", "Gore"}},
+ access.MaturityLimits{ExcludedTags: []string{"gore", "Late night"}},
+ },
+ {
+ "an owner excluding only tags keeps the viewer's allowances",
+ access.MaturityLimits{MaxContentRating: "PG", AllowedTitleIDs: []string{"a"}},
+ access.MaturityLimits{ExcludedTags: []string{"gore"}},
+ access.MaturityLimits{MaxContentRating: "PG", AllowedTitleIDs: []string{"a"}, ExcludedTags: []string{"gore"}},
+ },
{
"the unrated policy is the viewer's",
access.MaturityLimits{AllowUnratedContent: false},
diff --git a/internal/catalog/update.go b/internal/catalog/update.go
index 4fed8f1b6a9..fddeb9ea0e8 100644
--- a/internal/catalog/update.go
+++ b/internal/catalog/update.go
@@ -2,6 +2,7 @@ package catalog
import (
"context"
+ "errors"
"log/slog"
"slices"
"strings"
@@ -64,18 +65,21 @@ type MetadataUpdate struct {
// cleared field's pointer stays nil.
Clear []string
- Title *string
- SortTitle *string
- OriginalTitle *string
- Overview *string
- Tagline *string
- ContentRating *string
- Year *int
- Runtime *int
- Genres *[]string
- Studios *[]string
- Networks *[]string
- Countries *[]string
+ Title *string
+ SortTitle *string
+ OriginalTitle *string
+ Overview *string
+ Tagline *string
+ ContentRating *string
+ Year *int
+ Runtime *int
+ Genres *[]string
+ Studios *[]string
+ Networks *[]string
+ Countries *[]string
+ // CustomTags replaces a movie's or series' custom tags, already
+ // normalized (access.NormalizeTags). No provider writes them.
+ CustomTags *[]string
ReleaseDate *string
FirstAirDate *string
LastAirDate *string
@@ -140,12 +144,15 @@ func (u *MetadataUpdate) clearedRatingSources() []string {
// UpdateMediaItemMetadata updates specific metadata fields on a media_items row.
func (s *DetailService) UpdateMediaItemMetadata(ctx context.Context, contentID string, upd *MetadataUpdate) error {
relinkWork := false
- if s.workLinker != nil && upd.Title != nil {
+ if (s.workLinker != nil && upd.Title != nil) || upd.CustomTags != nil {
item, err := s.itemRepo.GetByID(ctx, contentID)
if err != nil {
return err
}
- relinkWork = item.Type == searchTypeEbook || item.Type == detailTypeAudiobook
+ relinkWork = s.workLinker != nil && upd.Title != nil && (item.Type == searchTypeEbook || item.Type == detailTypeAudiobook)
+ if upd.CustomTags != nil && item.Type != AdminCatalogTypeMovie && item.Type != AdminCatalogTypeSeries {
+ return ErrCustomTagsUnsupported
+ }
}
if err := applyDefaultSortTitleOnAdminUpdate(ctx, s.itemRepo, contentID, upd); err != nil {
return err
@@ -214,3 +221,7 @@ func titleLockedForAdminUpdate(item *models.MediaItem, upd *MetadataUpdate) bool
}
return slices.Contains(item.LockedFields, fieldNameLocked)
}
+
+// ErrCustomTagsUnsupported refuses custom tags on an item other than a movie
+// or series: no access check or listing reads them there.
+var ErrCustomTagsUnsupported = errors.New("custom tags belong to movies and series")
diff --git a/internal/metadata/identify_sticky_db_test.go b/internal/metadata/identify_sticky_db_test.go
index b676fe2fa67..55c328a536c 100644
--- a/internal/metadata/identify_sticky_db_test.go
+++ b/internal/metadata/identify_sticky_db_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "slices"
"strings"
"testing"
"time"
@@ -19,7 +20,8 @@ import (
// Merging an item an admin identified onto its canonical row keeps the
// Identify choice on the survivor (the canonicalization step that merges the
-// item row's own columns).
+// item row's own columns), and the survivor carries both rows' custom tags,
+// so a tag that hides the title from a profile cannot vanish in a merge.
func TestCanonicalizeKeepsIdentityChoicePostgres(t *testing.T) {
pool := chainBuiltinTestPool(t)
ctx := context.Background()
@@ -31,8 +33,8 @@ func TestCanonicalizeKeepsIdentityChoicePostgres(t *testing.T) {
suffix := uuid.NewString()
source, canonical := "identity-choice-source-"+suffix, "identity-choice-canonical-"+suffix
- if _, err := tx.Exec(ctx, `INSERT INTO media_items (content_id, type, title, status, identity_chosen_at)
- VALUES ($1, 'movie', 'Source', 'matched', NOW()), ($2, 'movie', 'Canonical', 'matched', NULL)`, source, canonical); err != nil {
+ if _, err := tx.Exec(ctx, `INSERT INTO media_items (content_id, type, title, status, identity_chosen_at, custom_tags)
+ VALUES ($1, 'movie', 'Source', 'matched', NOW(), ARRAY['gore', 'Late night']), ($2, 'movie', 'Canonical', 'matched', NULL, ARRAY['Gore'])`, source, canonical); err != nil {
t.Fatalf("seed items: %v", err)
}
ran := false
@@ -55,6 +57,13 @@ func TestCanonicalizeKeepsIdentityChoicePostgres(t *testing.T) {
if !chosen {
t.Error("canonical item lost the Identify choice of the item merged onto it")
}
+ var tags []string
+ if err := tx.QueryRow(ctx, `SELECT custom_tags FROM media_items WHERE content_id = $1`, canonical).Scan(&tags); err != nil {
+ t.Fatalf("read canonical tags: %v", err)
+ }
+ if want := []string{"Gore", "Late night"}; !slices.Equal(tags, want) {
+ t.Errorf("canonical custom tags = %v, want %v", tags, want)
+ }
}
// An Identify's mark commits in the transaction that writes the identity:
diff --git a/internal/metadata/provider_id_integrity.go b/internal/metadata/provider_id_integrity.go
index 51e4a64b611..2b669f33a1b 100644
--- a/internal/metadata/provider_id_integrity.go
+++ b/internal/metadata/provider_id_integrity.go
@@ -753,6 +753,16 @@ func mergeStepArgs(sql, sourceID, canonicalID string) []any {
}
}
+// mergedCustomTagsSQL is the custom tags of the rows dest and src together:
+// dest's first, then src's that dest has in no spelling. A merge keeps both
+// rows' tags so a tag that hides the title from a profile survives it.
+const mergedCustomTagsSQL = `ARRAY(
+ SELECT tag FROM (
+ SELECT DISTINCT ON (lower(tag)) tag, ord
+ FROM unnest(dest.custom_tags || src.custom_tags) WITH ORDINALITY AS t(tag, ord)
+ ORDER BY lower(tag), ord
+ ) merged ORDER BY ord)`
+
var mediaItemMergeSteps = []mediaItemMergeStep{
// A provider ID is unique per (provider, provider_id, item_type), so the
// source row itself blocks inserting a copy for the canonical item. Move
@@ -778,6 +788,7 @@ var mediaItemMergeSteps = []mediaItemMergeStep{
tmdb_id = COALESCE(NULLIF(dest.tmdb_id, ''), src.tmdb_id),
tvdb_id = COALESCE(NULLIF(dest.tvdb_id, ''), src.tvdb_id),
identity_chosen_at = GREATEST(dest.identity_chosen_at, src.identity_chosen_at),
+ custom_tags = ` + mergedCustomTagsSQL + `,
updated_at = NOW()
FROM media_items src
WHERE dest.content_id = $2 AND src.content_id = $1`},
diff --git a/internal/metadata/service.go b/internal/metadata/service.go
index 4bd064be163..e680ba444a8 100644
--- a/internal/metadata/service.go
+++ b/internal/metadata/service.go
@@ -9385,6 +9385,20 @@ func (s *MetadataService) rebindItemOnto(ctx context.Context, fromContentID, toC
`,
args: []any{fromContentID, toContentID},
},
+ {
+ // Custom tags are curator data no provider restores, and a
+ // profile's excluded tags read them: the survivor keeps both
+ // rows' tags.
+ name: "keep custom tags",
+ sql: `
+ UPDATE media_items dest
+ SET custom_tags = ` + mergedCustomTagsSQL + `
+ FROM media_items src
+ WHERE dest.content_id = $2 AND src.content_id = $1
+ AND src.custom_tags <> '{}'
+ `,
+ args: []any{fromContentID, toContentID},
+ },
{
name: "delete orphaned skeleton",
sql: `
diff --git a/internal/policy/viewer_resolver.go b/internal/policy/viewer_resolver.go
index 191895834d6..4de72ab1aac 100644
--- a/internal/policy/viewer_resolver.go
+++ b/internal/policy/viewer_resolver.go
@@ -328,9 +328,12 @@ func (r *ViewerResolver) ResolveFacts(ctx context.Context, input access.ResolveI
requireAdvisory := profile != nil && profile.RequireAdvisoryAge && decision.MaxAdvisoryAge > 0
var pinRevision int64
- var allowedTitles []string
+ var allowedTitles, excludedTags []string
if profile != nil {
pinRevision = profile.PINRevision
+ // Read off the profile like RequireAdvisoryAge: excluding a tag only
+ // ever hides more, so no policy override needs to loosen it.
+ excludedTags = profile.ExcludedTags
// A household's allowances lift the profile's own limits only. When
// a custom scope policy tightens them, the administrator's limit
// wins and no allowance applies.
@@ -351,7 +354,7 @@ func (r *ViewerResolver) ResolveFacts(ctx context.Context, input access.ResolveI
AllowUnratedContent: allowUnrated,
MaxAdvisoryAge: decision.MaxAdvisoryAge,
RequireAdvisoryAge: requireAdvisory,
- }.WithAllowedTitles(allowedTitles),
+ }.WithExcludedTags(excludedTags).WithAllowedTitles(allowedTitles),
MaxPlaybackQuality: decision.MaxPlaybackQuality,
MaxRemoteStreamBitrateKbps: effective.MaxRemoteStreamBitrateKbps,
MaxLocalStreamBitrateKbps: effective.MaxLocalStreamBitrateKbps,
diff --git a/internal/policy/viewer_resolver_test.go b/internal/policy/viewer_resolver_test.go
index 52f977b9e23..81c539e6431 100644
--- a/internal/policy/viewer_resolver_test.go
+++ b/internal/policy/viewer_resolver_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"reflect"
+ "slices"
"testing"
"time"
@@ -40,7 +41,20 @@ func TestViewerResolverParityWithLegacyResolver(t *testing.T) {
wantMaxAdvisoryAge int
// wantRequireAdvisory pins the strict flag the same way.
wantRequireAdvisory bool
+ // wantExcludedTags pins the excluded tags, as TagKeys, the same way.
+ wantExcludedTags []string
}{
+ {
+ name: "profile excludes custom tags",
+ user: &models.User{ID: 1, AccessPolicyRevision: 5},
+ profile: &userstore.Profile{
+ ID: "prof-1",
+ ExcludedTags: []string{"Late night", "Gore"},
+ },
+ input: access.ResolveInput{UserID: 1, SessionID: "sess-1", ProfileID: "prof-1"},
+ wantNilAllowed: true,
+ wantExcludedTags: []string{"Gore", "Late night"},
+ },
{
// Hidden libraries are profile-scoped, so a request without a
// profile hides nothing; the frozen legacy account value the
@@ -379,6 +393,9 @@ func TestViewerResolverParityWithLegacyResolver(t *testing.T) {
if policyScope.RequireAdvisoryAge != tt.wantRequireAdvisory {
t.Fatalf("RequireAdvisoryAge = %v, want %v", policyScope.RequireAdvisoryAge, tt.wantRequireAdvisory)
}
+ if !slices.Equal(policyScope.ExcludedTags, tt.wantExcludedTags) {
+ t.Fatalf("ExcludedTags = %v, want %v", policyScope.ExcludedTags, tt.wantExcludedTags)
+ }
if policyScope.PreferredMetadataLanguage != tt.wantMetadataLang {
t.Fatalf("PreferredMetadataLanguage = %q, want %q", policyScope.PreferredMetadataLanguage, tt.wantMetadataLang)
}
diff --git a/internal/recommendations/engine.go b/internal/recommendations/engine.go
index d9fdf7ea643..b4693f9dccd 100644
--- a/internal/recommendations/engine.go
+++ b/internal/recommendations/engine.go
@@ -237,7 +237,7 @@ func (e *Engine) profileAccessFilter(ctx context.Context, userID int, profileID
// show those titles.
filter.AllowUnratedContent = e.unrated.AllowUnratedContent(ctx)
}
- filter.MaturityLimits = filter.WithAllowedTitles(profile.AllowedTitleIDs)
+ filter.MaturityLimits = filter.WithExcludedTags(profile.ExcludedTags).WithAllowedTitles(profile.AllowedTitleIDs)
if libraryIDs, limited := access.ProfileLibraryLimit(profile); limited {
filter.AllowedLibraryIDs = append([]int{}, libraryIDs...)
}
diff --git a/internal/userdb/conformance_test.go b/internal/userdb/conformance_test.go
index ca3ad59aedb..8ef384ad070 100644
--- a/internal/userdb/conformance_test.go
+++ b/internal/userdb/conformance_test.go
@@ -58,6 +58,10 @@ func TestSQLiteProfilePINRevision(t *testing.T) {
storetest.RunProfilePINRevision(t, newConformanceStore)
}
+func TestSQLiteProfileExcludedTags(t *testing.T) {
+ storetest.RunProfileExcludedTags(t, newConformanceStore)
+}
+
func TestSQLiteProfilePINRevisionTransactions(t *testing.T) {
storetest.RunProfilePINRevisionTransactions(t, newConformanceStore)
}
diff --git a/internal/userdb/migrate.go b/internal/userdb/migrate.go
index 69462e97aba..d9c34be3009 100644
--- a/internal/userdb/migrate.go
+++ b/internal/userdb/migrate.go
@@ -6,7 +6,7 @@ import (
"fmt"
)
-const schemaVersion = 38
+const schemaVersion = 39
func runMigrations(db *sql.DB) error {
version, err := userVersion(db)
@@ -411,6 +411,14 @@ WHERE key = 'ui.card_presentation'
return err
}
}
+ if version < 39 {
+ if err := addProfileExcludedTags(tx); err != nil {
+ return fmt.Errorf("migration v39 failed: %w", err)
+ }
+ if _, err := tx.ExecContext(context.Background(), "PRAGMA user_version = 39"); err != nil {
+ return err
+ }
+ }
if _, err := tx.Exec(profilePINRevisionSchema); err != nil {
return fmt.Errorf("creating profile PIN revision trigger: %w", err)
}
@@ -801,3 +809,15 @@ func addProfileRequestsBlocked(tx *sql.Tx) error {
_, err := tx.ExecContext(context.Background(), `ALTER TABLE profiles ADD COLUMN requests_blocked BOOLEAN NOT NULL DEFAULT false`)
return err
}
+
+// addProfileExcludedTags adds profiles.excluded_tags, a JSON array of the
+// custom tags the profile may not see. Same reasoning as v27: a fresh
+// profiles table already has the column. The Postgres store adds the same
+// column in 20261203082703_add_custom_tags.sql.
+func addProfileExcludedTags(tx *sql.Tx) error {
+ if columnExists(tx, "profiles", "excluded_tags") {
+ return nil
+ }
+ _, err := tx.ExecContext(context.Background(), `ALTER TABLE profiles ADD COLUMN excluded_tags TEXT NOT NULL DEFAULT '[]'`)
+ return err
+}
diff --git a/internal/userdb/profile_requests_blocked_test.go b/internal/userdb/profile_requests_blocked_test.go
index 75f02e6d0f1..aaa683279f7 100644
--- a/internal/userdb/profile_requests_blocked_test.go
+++ b/internal/userdb/profile_requests_blocked_test.go
@@ -42,3 +42,35 @@ func TestMigrateToV38AddsProfileRequestsBlocked(t *testing.T) {
t.Fatalf("migrated profile = %+v, %v; want not blocked", old, err)
}
}
+
+// An existing v38 store gains profiles.excluded_tags, empty for every
+// profile it already holds.
+func TestMigrateToV39AddsProfileExcludedTags(t *testing.T) {
+ db, err := sql.Open("sqlite3", ":memory:")
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ t.Cleanup(func() { _ = db.Close() })
+ if err := InitSchema(db); err != nil {
+ t.Fatalf("InitSchema: %v", err)
+ }
+ store := NewSQLiteUserStore(db)
+ ctx := context.Background()
+ if err := store.CreateProfile(ctx, userstore.Profile{ID: "old", Name: "Old"}); err != nil {
+ t.Fatalf("seed profile: %v", err)
+ }
+ if _, err := db.Exec(`ALTER TABLE profiles DROP COLUMN excluded_tags`); err != nil {
+ t.Fatalf("drop column: %v", err)
+ }
+ if _, err := db.Exec("PRAGMA user_version = 38"); err != nil {
+ t.Fatalf("set user_version: %v", err)
+ }
+
+ if err := runMigrations(db); err != nil {
+ t.Fatalf("runMigrations: %v", err)
+ }
+ old, err := store.GetProfile(ctx, "old")
+ if err != nil || old == nil || len(old.ExcludedTags) != 0 {
+ t.Fatalf("migrated profile = %+v, %v; want no excluded tags", old, err)
+ }
+}
diff --git a/internal/userdb/profiles.go b/internal/userdb/profiles.go
index 45bcf4714c2..af12b6bec9e 100644
--- a/internal/userdb/profiles.go
+++ b/internal/userdb/profiles.go
@@ -61,14 +61,14 @@ func createProfile(exec preferenceSettingsExecutor, p Profile) error {
_, err := exec.Exec(`
INSERT INTO profiles (
id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, max_advisory_age,
- require_advisory_age, requests_blocked,
+ require_advisory_age, requests_blocked, excluded_tags,
quality_preference, language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview,
show_forced_subtitles,
library_restrictions_enabled, max_playback_quality, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, NULLIF(?, 0), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, NULLIF(?, 0), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.ID, p.Name, p.Avatar, p.PINHash, p.IsChild, p.IsPrimary, p.MaxContentRating, p.MaxAdvisoryAge,
- p.RequireAdvisoryAge, p.RequestsBlocked,
+ p.RequireAdvisoryAge, p.RequestsBlocked, tagsJSON{&p.ExcludedTags},
p.QualityPreference, p.Language, p.SubtitleLanguage, p.SubtitleMode,
p.AutoSkipIntro, p.AutoSkipCredits, p.AutoSkipRecap, p.AutoPlayNextPreview,
p.ShowForcedSubtitles, p.LibraryRestrictionsEnabled,
@@ -89,14 +89,14 @@ func GetProfile(db *sql.DB, id string) (*Profile, error) {
var p Profile
err := db.QueryRow(`
SELECT id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, COALESCE(max_advisory_age, 0),
- require_advisory_age, requests_blocked,
+ require_advisory_age, requests_blocked, excluded_tags,
quality_preference, language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview, show_forced_subtitles,
library_restrictions_enabled, max_playback_quality, pin_revision, created_at, updated_at
FROM profiles WHERE id = ?`, id,
).Scan(
&p.ID, &p.Name, &p.Avatar, &p.PINHash, &p.IsChild, &p.IsPrimary, &p.MaxContentRating, &p.MaxAdvisoryAge,
- &p.RequireAdvisoryAge, &p.RequestsBlocked,
+ &p.RequireAdvisoryAge, &p.RequestsBlocked, tagsJSON{&p.ExcludedTags},
&p.QualityPreference, &p.Language, &p.SubtitleLanguage, &p.SubtitleMode,
&p.AutoSkipIntro, &p.AutoSkipCredits, &p.AutoSkipRecap, &p.AutoPlayNextPreview, &p.ShowForcedSubtitles,
&p.LibraryRestrictionsEnabled, &p.MaxPlaybackQuality, &p.PINRevision, &p.CreatedAt, &p.UpdatedAt,
@@ -118,7 +118,7 @@ func GetProfile(db *sql.DB, id string) (*Profile, error) {
func ListProfiles(db *sql.DB) ([]Profile, error) {
rows, err := db.Query(`
SELECT id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, COALESCE(max_advisory_age, 0),
- require_advisory_age, requests_blocked,
+ require_advisory_age, requests_blocked, excluded_tags,
quality_preference, language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview, show_forced_subtitles,
library_restrictions_enabled, max_playback_quality, pin_revision, created_at, updated_at
@@ -133,7 +133,7 @@ func ListProfiles(db *sql.DB) ([]Profile, error) {
var p Profile
if err := rows.Scan(
&p.ID, &p.Name, &p.Avatar, &p.PINHash, &p.IsChild, &p.IsPrimary, &p.MaxContentRating, &p.MaxAdvisoryAge,
- &p.RequireAdvisoryAge, &p.RequestsBlocked,
+ &p.RequireAdvisoryAge, &p.RequestsBlocked, tagsJSON{&p.ExcludedTags},
&p.QualityPreference, &p.Language, &p.SubtitleLanguage, &p.SubtitleMode,
&p.AutoSkipIntro, &p.AutoSkipCredits, &p.AutoSkipRecap, &p.AutoPlayNextPreview, &p.ShowForcedSubtitles,
&p.LibraryRestrictionsEnabled, &p.MaxPlaybackQuality, &p.PINRevision, &p.CreatedAt, &p.UpdatedAt,
@@ -206,6 +206,10 @@ func updateProfile(exec preferenceSettingsExecutor, id string, u UpdateProfileIn
setClauses = append(setClauses, "requests_blocked = ?")
args = append(args, *u.RequestsBlocked)
}
+ if u.ExcludedTags != nil {
+ setClauses = append(setClauses, "excluded_tags = ?")
+ args = append(args, tagsJSON{u.ExcludedTags})
+ }
if u.QualityPreference != nil {
setClauses = append(setClauses, "quality_preference = ?")
args = append(args, *u.QualityPreference)
diff --git a/internal/userdb/schema.go b/internal/userdb/schema.go
index 3c4278a468b..1faecb12f6d 100644
--- a/internal/userdb/schema.go
+++ b/internal/userdb/schema.go
@@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS profiles (
max_advisory_age INTEGER CHECK (max_advisory_age BETWEEN 1 AND 21),
require_advisory_age BOOLEAN NOT NULL DEFAULT false,
requests_blocked BOOLEAN NOT NULL DEFAULT false,
+ excluded_tags TEXT NOT NULL DEFAULT '[]',
quality_preference TEXT DEFAULT '1080p',
language TEXT DEFAULT 'en',
subtitle_language TEXT,
diff --git a/internal/userdb/tags_json.go b/internal/userdb/tags_json.go
new file mode 100644
index 00000000000..6a87342bf0e
--- /dev/null
+++ b/internal/userdb/tags_json.go
@@ -0,0 +1,44 @@
+package userdb
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+ "fmt"
+)
+
+// tagsJSON stores a tag list in a TEXT column as a JSON array: it binds
+// *tags as one, never null, and scans one back into *tags (nil for an empty
+// array).
+type tagsJSON struct{ tags *[]string }
+
+func (t tagsJSON) Value() (driver.Value, error) {
+ if t.tags == nil || len(*t.tags) == 0 {
+ return "[]", nil
+ }
+ b, _ := json.Marshal(*t.tags) // a []string always marshals
+ return string(b), nil
+}
+
+func (t tagsJSON) Scan(src any) error {
+ var raw []byte
+ switch v := src.(type) {
+ case nil:
+ *t.tags = nil
+ return nil
+ case string:
+ raw = []byte(v)
+ case []byte:
+ raw = v
+ default:
+ return fmt.Errorf("scanning tags: unsupported type %T", src)
+ }
+ var tags []string
+ if err := json.Unmarshal(raw, &tags); err != nil {
+ return fmt.Errorf("scanning tags: %w", err)
+ }
+ if len(tags) == 0 {
+ tags = nil
+ }
+ *t.tags = tags
+ return nil
+}
diff --git a/internal/userstore/pgstore/profile_pin_revision_test.go b/internal/userstore/pgstore/profile_pin_revision_test.go
index 86c9d637c40..f4d1e8544ec 100644
--- a/internal/userstore/pgstore/profile_pin_revision_test.go
+++ b/internal/userstore/pgstore/profile_pin_revision_test.go
@@ -19,6 +19,13 @@ func TestPostgresProfilePINRevision(t *testing.T) {
})
}
+func TestPostgresProfileExcludedTags(t *testing.T) {
+ storetest.RunProfileExcludedTags(t, func(t *testing.T) userstore.UserStore {
+ pool, userID := newConstraintTestUser(t)
+ return newStore(pool, userID)
+ })
+}
+
func TestPostgresProfilePINRevisionTransactions(t *testing.T) {
storetest.RunProfilePINRevisionTransactions(t, func(t *testing.T) userstore.UserStore {
pool, userID := newConstraintTestUser(t)
@@ -55,6 +62,14 @@ func TestPostgresProfileEditsStillBumpAccountRevision(t *testing.T) {
if got := accountRevision(); got != before+1 {
t.Fatalf("kid rating edit: account revision = %d, want %d", got, before+1)
}
+ tags := []string{"Gore"}
+ if err := store.UpdateProfile(ctx, "kid", userstore.UpdateProfileInput{ExcludedTags: &tags}); err != nil {
+ t.Fatal(err)
+ }
+ if got := accountRevision(); got != before+2 {
+ t.Fatalf("kid excluded tags edit: account revision = %d, want %d", got, before+2)
+ }
+ before++
if err := store.UpdateProfile(ctx, "parent", userstore.UpdateProfileInput{PINHash: str("hash-of-1234")}); err != nil {
t.Fatal(err)
}
diff --git a/internal/userstore/pgstore/profiles.go b/internal/userstore/pgstore/profiles.go
index 024dede84bb..23adf74aad6 100644
--- a/internal/userstore/pgstore/profiles.go
+++ b/internal/userstore/pgstore/profiles.go
@@ -25,7 +25,7 @@ func scanProfile(scanner interface {
var createdAt, updatedAt time.Time
err := scanner.Scan(append([]any{
&p.ID, &p.Name, &p.Avatar, &p.PINHash, &p.IsChild, &p.IsPrimary, &p.MaxContentRating, &p.MaxAdvisoryAge,
- &p.RequireAdvisoryAge, &p.RequestsBlocked,
+ &p.RequireAdvisoryAge, &p.RequestsBlocked, &p.ExcludedTags,
&p.QualityPreference, &p.Language, &p.PreferredMetadataLanguage, &p.SubtitleLanguage, &p.SubtitleMode,
&p.AutoSkipIntro, &p.AutoSkipCredits, &p.AutoSkipRecap, &p.AutoPlayNextPreview,
&p.LibraryRestrictionsEnabled,
@@ -85,14 +85,14 @@ func createProfile(
quality_preference, language, preferred_metadata_language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview,
library_restrictions_enabled,
- show_forced_subtitles, max_playback_quality, created_at, updated_at
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULLIF($9::smallint, 0), $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25)`,
+ show_forced_subtitles, max_playback_quality, created_at, updated_at, excluded_tags
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULLIF($9::smallint, 0), $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26)`,
p.ID, userID, p.Name, p.Avatar, p.PINHash, p.IsChild, p.IsPrimary, p.MaxContentRating, p.MaxAdvisoryAge,
p.RequireAdvisoryAge, p.RequestsBlocked,
p.QualityPreference, p.Language, p.PreferredMetadataLanguage, p.SubtitleLanguage, p.SubtitleMode,
p.AutoSkipIntro, p.AutoSkipCredits, p.AutoSkipRecap, p.AutoPlayNextPreview,
p.LibraryRestrictionsEnabled,
- p.ShowForcedSubtitles, p.MaxPlaybackQuality, p.CreatedAt, p.UpdatedAt,
+ p.ShowForcedSubtitles, p.MaxPlaybackQuality, p.CreatedAt, p.UpdatedAt, nonNilTags(p.ExcludedTags),
)
if err != nil {
return fmt.Errorf("inserting profile %s: %w", p.ID, err)
@@ -130,7 +130,7 @@ func QueueProfile(batch *pgx.Batch, userID int, id string) func(pgx.BatchResults
// ascending id order, so a profile costs one statement.
var profileByIDQuery = `
SELECT id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, COALESCE(max_advisory_age, 0),
- require_advisory_age, requests_blocked,
+ require_advisory_age, requests_blocked, excluded_tags,
quality_preference, language, preferred_metadata_language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview, library_restrictions_enabled,
show_forced_subtitles, max_playback_quality, pin_revision, created_at, updated_at,
@@ -214,7 +214,7 @@ func profileFromRow(row pgx.Row, id string) (*userstore.Profile, error) {
func (s *PostgresUserStore) ListProfiles(ctx context.Context) ([]userstore.Profile, error) {
rows, err := s.pool.Query(ctx, `
SELECT id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, COALESCE(max_advisory_age, 0),
- require_advisory_age, requests_blocked,
+ require_advisory_age, requests_blocked, excluded_tags,
quality_preference, language, preferred_metadata_language, subtitle_language, subtitle_mode,
auto_skip_intro, auto_skip_credits, auto_skip_recap, auto_play_next_preview, library_restrictions_enabled,
show_forced_subtitles, max_playback_quality, pin_revision, created_at, updated_at
@@ -261,6 +261,7 @@ func updateProfile(
u.MaxAdvisoryAge != nil ||
u.RequireAdvisoryAge != nil ||
u.RequestsBlocked != nil ||
+ u.ExcludedTags != nil ||
u.LibraryRestrictionsEnabled != nil ||
u.AllowedLibraryIDs != nil ||
u.MaxPlaybackQuality != nil
@@ -305,6 +306,9 @@ func updateProfile(
if u.RequestsBlocked != nil {
addArg("requests_blocked", *u.RequestsBlocked)
}
+ if u.ExcludedTags != nil {
+ addArg("excluded_tags", nonNilTags(*u.ExcludedTags))
+ }
if u.QualityPreference != nil {
addArg("quality_preference", *u.QualityPreference)
}
@@ -660,6 +664,7 @@ type RestoredProfile struct {
MaxAdvisoryAge int
RequireAdvisoryAge bool
RequestsBlocked bool
+ ExcludedTags []string
LibraryRestrictionsEnabled bool
AllowedLibraryIDs []int
MaxPlaybackQuality string
@@ -702,11 +707,20 @@ func CreateRestoredProfileInTx(ctx context.Context, tx pgx.Tx, userID int, p Res
}
if _, err := tx.Exec(ctx, `
INSERT INTO user_profiles (id, user_id, name, avatar, pin_hash, is_child, is_primary, max_content_rating, max_advisory_age,
- require_advisory_age, requests_blocked, library_restrictions_enabled, max_playback_quality)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULLIF($9::smallint, 0), $10, $11, $12, $13)`,
+ require_advisory_age, requests_blocked, library_restrictions_enabled, max_playback_quality, excluded_tags)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULLIF($9::smallint, 0), $10, $11, $12, $13, $14)`,
p.ID, userID, p.Name, p.Avatar, p.PINHash, p.IsChild, primary, p.MaxContentRating, p.MaxAdvisoryAge,
- p.RequireAdvisoryAge, p.RequestsBlocked, p.LibraryRestrictionsEnabled, p.MaxPlaybackQuality); err != nil {
+ p.RequireAdvisoryAge, p.RequestsBlocked, p.LibraryRestrictionsEnabled, p.MaxPlaybackQuality, nonNilTags(p.ExcludedTags)); err != nil {
return false, fmt.Errorf("inserting restored profile: %w", err)
}
return primary, replaceProfileAllowedLibraries(ctx, tx, userID, p.ID, p.AllowedLibraryIDs)
}
+
+// nonNilTags binds tags as a text[]: the column is NOT NULL, and pgx binds a
+// nil slice as NULL.
+func nonNilTags(tags []string) []string {
+ if tags == nil {
+ return []string{}
+ }
+ return tags
+}
diff --git a/internal/userstore/storetest/profile_excluded_tags.go b/internal/userstore/storetest/profile_excluded_tags.go
new file mode 100644
index 00000000000..329d17e1c6f
--- /dev/null
+++ b/internal/userstore/storetest/profile_excluded_tags.go
@@ -0,0 +1,68 @@
+package storetest
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/Silo-Server/silo-server/internal/userstore"
+)
+
+// RunProfileExcludedTags checks that a profile's excluded custom tags
+// round-trip through create, get, list and update, and that an update to
+// an empty list clears them.
+func RunProfileExcludedTags(t *testing.T, newStore func(*testing.T) userstore.UserStore) {
+ const parent, kid, scary = "tags-parent", "tags-kid", "Scary"
+ ctx := t.Context()
+ store := newStore(t)
+ if err := store.CreateProfile(ctx, userstore.Profile{ID: parent, Name: "Tags parent"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.CreateProfile(ctx, userstore.Profile{ID: kid, Name: "Kid", ExcludedTags: []string{"Gore", "Late night"}}); err != nil {
+ t.Fatal(err)
+ }
+ tagsOf := func(id string) []string {
+ t.Helper()
+ p, err := store.GetProfile(ctx, id)
+ if err != nil || p == nil {
+ t.Fatalf("GetProfile(%s) = %+v, %v", id, p, err)
+ }
+ return p.ExcludedTags
+ }
+ if got := tagsOf(parent); len(got) != 0 {
+ t.Fatalf("a profile created without tags excludes %v", got)
+ }
+ if got := tagsOf(kid); !slices.Equal(got, []string{"Gore", "Late night"}) {
+ t.Fatalf("created excluded tags = %v", got)
+ }
+ listed, err := store.ListProfiles(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range listed {
+ if want := p.ID == kid; (len(p.ExcludedTags) == 2) != want {
+ t.Fatalf("ListProfiles = %+v; want only the kid excluding two tags", listed)
+ }
+ }
+
+ for _, want := range [][]string{{scary}, {}} {
+ tags := want
+ if err := store.UpdateProfile(ctx, kid, userstore.UpdateProfileInput{ExcludedTags: &tags}); err != nil {
+ t.Fatal(err)
+ }
+ if got := tagsOf(kid); !slices.Equal(got, want) && (len(got) != 0 || len(want) != 0) {
+ t.Fatalf("excluded tags after update to %v = %v", want, got)
+ }
+ }
+ // An update that leaves the member out keeps the tags.
+ tags := []string{scary}
+ if err := store.UpdateProfile(ctx, kid, userstore.UpdateProfileInput{ExcludedTags: &tags}); err != nil {
+ t.Fatal(err)
+ }
+ name := "Kiddo"
+ if err := store.UpdateProfile(ctx, kid, userstore.UpdateProfileInput{Name: &name}); err != nil {
+ t.Fatal(err)
+ }
+ if got := tagsOf(kid); !slices.Equal(got, []string{scary}) {
+ t.Fatalf("a rename changed the excluded tags to %v", got)
+ }
+}
diff --git a/internal/userstore/types.go b/internal/userstore/types.go
index 76256405ac0..f7e201b9ffe 100644
--- a/internal/userstore/types.go
+++ b/internal/userstore/types.go
@@ -34,7 +34,11 @@ type Profile struct {
// RequestsBlocked keeps the profile out of requests and request discovery
// even when its account may request. Stored as a block, not an allow, so
// the zero value of a profile built anywhere keeps today's behavior.
- RequestsBlocked bool
+ RequestsBlocked bool
+ // ExcludedTags are custom tags the profile may not see: a movie or series
+ // carrying one is hidden from it (see access.MaturityLimits.ExcludedTags).
+ // Stored as normalized by access.NormalizeTags; empty means none.
+ ExcludedTags []string
QualityPreference string
Language string
PreferredMetadataLanguage string // ISO 639-1; "" = inherit library metadata language
@@ -98,7 +102,9 @@ type UpdateProfileInput struct {
// RequireAdvisoryAge: nil leaves it untouched.
RequireAdvisoryAge *bool
// RequestsBlocked: nil leaves it untouched.
- RequestsBlocked *bool
+ RequestsBlocked *bool
+ // ExcludedTags: nil leaves them untouched, and an empty list clears them.
+ ExcludedTags *[]string
QualityPreference *string
Language *string
PreferredMetadataLanguage *string
diff --git a/migrations/sql/20261203082703_add_custom_tags.sql b/migrations/sql/20261203082703_add_custom_tags.sql
new file mode 100644
index 00000000000..b4bfdfd44a9
--- /dev/null
+++ b/migrations/sql/20261203082703_add_custom_tags.sql
@@ -0,0 +1,37 @@
+-- +goose NO TRANSACTION
+
+-- +goose Up
+-- Custom tags are free-text labels a metadata curator puts on a movie or
+-- series. No metadata provider writes them, so a refresh never changes them.
+-- A profile's excluded_tags hide every title carrying one of those tags (and
+-- every season and episode of such a series); tags match without regard to
+-- case.
+--
+-- Constant defaults are catalog-only changes and rewrite no row, so existing
+-- titles carry no tags and existing profiles exclude none.
+--
+-- The file runs without a wrapping transaction so the index builds
+-- concurrently while the catalog keeps serving reads. Every statement is safe
+-- to re-run after a partial failure.
+ALTER TABLE public.media_items
+ ADD COLUMN IF NOT EXISTS custom_tags text[] NOT NULL DEFAULT '{}';
+
+ALTER TABLE public.user_profiles
+ ADD COLUMN IF NOT EXISTS excluded_tags text[] NOT NULL DEFAULT '{}';
+
+-- The tag list reads only tagged titles, which are few next to the catalog,
+-- so a partial index keeps it from scanning every item.
+-- A failed concurrent build leaves an invalid index, so drop before building.
+DROP INDEX CONCURRENTLY IF EXISTS public.idx_media_items_custom_tags;
+CREATE INDEX CONCURRENTLY idx_media_items_custom_tags
+ON public.media_items USING btree (content_id)
+WHERE custom_tags <> '{}';
+
+-- +goose Down
+DROP INDEX CONCURRENTLY IF EXISTS public.idx_media_items_custom_tags;
+
+ALTER TABLE public.user_profiles
+ DROP COLUMN IF EXISTS excluded_tags;
+
+ALTER TABLE public.media_items
+ DROP COLUMN IF EXISTS custom_tags;
diff --git a/scripts/ci/db-contracts.txt b/scripts/ci/db-contracts.txt
index 67683e085e8..081669aed50 100644
--- a/scripts/ci/db-contracts.txt
+++ b/scripts/ci/db-contracts.txt
@@ -3,6 +3,8 @@
# skipping. Run against a disposable, migrated database with make test-db-contracts.
# Library visibility, rating ceilings, mixed catalogs, and section results.
+./internal/catalog TestExcludedCustomTagsHideTitlesPostgres
+./internal/catalog TestCustomTagsSurviveMetadataRefreshPostgres
./internal/catalog TestDualLibraryItemDeniedByDisabledLibraryDB
./internal/catalog TestEpisodeOpensUnderEveryLibraryOfItsSeriesDB
./internal/catalog TestGetBySeriesAndFileNumberDB
@@ -1522,6 +1524,7 @@
# Household PIN proof must still match when the protected write transaction starts.
./internal/userstore/pgstore TestPostgresProfilePINRevisionTransactions
+./internal/userstore/pgstore TestPostgresProfileExcludedTags
# Personal collection list reads remember counts and collages with no source
# until the membership revision or the viewer's access changes.
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index cee7c88b52a..424dacdfb07 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -257,6 +257,11 @@ export interface Profile {
* server that predates the switch, which allows every profile.
*/
requests_allowed?: boolean;
+ /**
+ * Custom tags whose titles the profile cannot see. Absent on a server that
+ * predates custom tags.
+ */
+ excluded_tags?: string[];
quality_preference: string;
language: string;
preferred_metadata_language?: string;
@@ -1292,6 +1297,8 @@ export interface ItemDetail {
studios: string[];
networks: string[];
countries: string[];
+ /** A movie's or series' custom tags; sent only to metadata curators. */
+ custom_tags?: string[];
locked_fields?: number[];
release_date: string | null;
first_air_date: string | null;
diff --git a/web/src/api/v2/catalog.ts b/web/src/api/v2/catalog.ts
index 2e1439a54fb..65222781051 100644
--- a/web/src/api/v2/catalog.ts
+++ b/web/src/api/v2/catalog.ts
@@ -323,6 +323,7 @@ export function catalogItemDetailFromV2(item: CatalogItemDetailV2): ItemDetail {
studios: item.studios ?? [],
networks: item.networks ?? [],
countries: item.countries ?? [],
+ custom_tags: item.custom_tags,
locked_fields: item.locked_fields,
release_date: item.release_date ?? null,
first_air_date: item.first_air_date ?? null,
diff --git a/web/src/api/v2/operations.ts b/web/src/api/v2/operations.ts
index 75438416f47..f25f3f6d0fb 100644
--- a/web/src/api/v2/operations.ts
+++ b/web/src/api/v2/operations.ts
@@ -387,6 +387,7 @@ export const v2Operations = {
"GET /api/v2/catalog/audiobook-groups": "listAudiobookGroups",
"GET /api/v2/catalog/box-sets": "searchCatalogBoxSets",
"GET /api/v2/catalog/box-sets/{id}": "getCatalogBoxSet",
+ "GET /api/v2/catalog/custom-tags": "listCatalogCustomTags",
"GET /api/v2/catalog/filters": "getCatalogFilters",
"GET /api/v2/catalog/filters/search": "searchCatalogFacet",
"GET /api/v2/catalog/items/{id}": "getCatalogItem",
diff --git a/web/src/api/v2/schema.ts b/web/src/api/v2/schema.ts
index f0beaf19404..03865e2d9ba 100644
--- a/web/src/api/v2/schema.ts
+++ b/web/src/api/v2/schema.ts
@@ -7947,6 +7947,23 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/v2/catalog/custom-tags": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** The custom tags on the movies and series the caller can see, most used first, for the metadata editor and a profile's excluded_tags. */
+ get: operations["listCatalogCustomTags"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v2/catalog/filters": {
parameters: {
query?: never;
@@ -16809,6 +16826,8 @@ export interface components {
AdminCatalogCapabilities: {
/** @description Whether the current principal may use the capability */
allowed: boolean;
+ /** @description updateAdminItemMetadata accepts custom_tags on a movie or series, item detail returns them to a metadata curator, and listCatalogCustomTags is served */
+ custom_tags: boolean;
/** @description listAdminItemImages lists an episode's still choices and current still_url, and uploadAdminItemImage accepts type still for an episode */
episode_stills: boolean;
/** @description locked_fields accepts one lock per image (14 poster, 15 backdrop, 16 logo, 17 episode still), and choosing or uploading an image locks only that image on its own item, season or episode */
@@ -21351,6 +21370,13 @@ export interface components {
content_rating?: string | null;
/** @description Country codes, ISO 3166-1 alpha-2 by convention (US); stored as sent; null clears */
countries?: string[] | null;
+ /**
+ * @description Replaces a movie's or series' custom tags: free-text labels no metadata provider writes, so a refresh keeps them. A profile's excluded_tags hide every title carrying one of its tags. Each tag is trimmed with inner whitespace collapsed, and tags that differ only in case are kept once, in the first spelling. At most 50 tags of at most 64 characters; an empty array clears them. getAdminCatalogCapabilities reports custom_tags when this member is accepted
+ * @example [
+ * "Gore"
+ * ]
+ */
+ custom_tags?: string[];
/** Format: int64 */
episode_number?: number | null;
/** @description Null clears the stored date */
@@ -27414,6 +27440,19 @@ export interface components {
/** @description Opaque seed for subsequent explicit window jumps; carries query scope and the initial insertion fence */
window_cursor: string;
};
+ CatalogCustomTag: {
+ /**
+ * @description The tag in its most used spelling; tags that differ only in case are one tag
+ * @example Gore
+ */
+ tag: string;
+ /**
+ * Format: int64
+ * @description How many movies and series the caller can see that carry the tag
+ * @example 11
+ */
+ title_count: number;
+ };
CatalogEffectiveSort: {
/** @example title */
field: string;
@@ -27762,6 +27801,8 @@ export interface components {
credits?: components["schemas"]["Marker"];
/** @description Empty, never null */
crew: components["schemas"]["CrewCredit"][];
+ /** @description A movie's or series' custom tags, the free-text labels set through updateAdminItemMetadata. Returned only to a viewer who curates the item's metadata; omitted for everyone else and when the item has none */
+ custom_tags?: string[];
/**
* Format: uri-reference
* @description Presigned, short-lived. Transparent disc art. Movies only
@@ -28865,6 +28906,12 @@ export interface components {
*/
sync_schedule_editable: boolean;
};
+ CollectionCatalogCustomTag: {
+ /** @description The page's items; empty, never null */
+ items: components["schemas"]["CatalogCustomTag"][];
+ /** @description Cursor state; absent for bounded unpaginated collections */
+ page?: components["schemas"]["PageInfo"];
+ };
CollectionDisplayFilterPresets: {
/**
* @example [
@@ -36872,6 +36919,13 @@ export interface components {
* @example 2026-01-02T03:04:05.000Z
*/
created_at: string;
+ /**
+ * @description Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager; empty means none
+ * @example [
+ * "Gore"
+ * ]
+ */
+ excluded_tags: string[];
/** @example false */
has_pin: boolean;
/**
@@ -36966,6 +37020,11 @@ export interface components {
* @example true
*/
avatar_upload_enabled: boolean;
+ /**
+ * @description Whether profiles accept excluded_tags and the server enforces it
+ * @example true
+ */
+ excluded_tags_supported: boolean;
/** @description The page's items; empty, never null */
items: components["schemas"]["Profile"][];
/**
@@ -37014,6 +37073,13 @@ export interface components {
* @example preset:fox
*/
avatar?: string;
+ /**
+ * @description Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; omitted means none
+ * @example [
+ * "Gore"
+ * ]
+ */
+ excluded_tags?: string[];
/** @example false */
is_child?: boolean;
/**
@@ -37320,6 +37386,13 @@ export interface components {
* @example preset:fox
*/
avatar?: string | null;
+ /**
+ * @description Replaces the excluded tags. Custom tags the profile may not see: a movie or series carrying any of them is hidden from it, with its seasons and episodes, whatever its rating and whatever title allowances say. Matched without regard to case. Each tag is trimmed, and tags that differ only in case are kept once. Set by the household manager. At most 50 tags of at most 64 characters; an empty array clears them
+ * @example [
+ * "Gore"
+ * ]
+ */
+ excluded_tags?: string[];
/** @example false */
is_child?: boolean;
/**
@@ -40224,7 +40297,7 @@ export interface components {
*/
profile_id: string;
/**
- * @description within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help
+ * @description within_limits: the profile sees the title without an allowance. allowed: the profile has its own allowance for it. allowed_by_collection: an allowed collection holds it. above_limit: the title is above the profile's limits and can be allowed. no_library_access: the profile cannot see the title's library, so an allowance would not help. hidden_by_tag: the title carries a custom tag the profile excludes, which no allowance lifts
* @example above_limit
* @enum {string}
*/
@@ -40233,7 +40306,8 @@ export interface components {
| "allowed"
| "allowed_by_collection"
| "above_limit"
- | "no_library_access";
+ | "no_library_access"
+ | "hidden_by_tag";
};
TitleAllowanceProfileCollection: {
/** @description The page's items; empty, never null */
@@ -111974,6 +112048,112 @@ export interface operations {
};
};
};
+ listCatalogCustomTags: {
+ 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?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["CollectionCatalogCustomTag"];
+ };
+ };
+ /** @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"];
+ };
+ };
+ };
+ };
getCatalogFilters: {
parameters: {
query?: {
diff --git a/web/src/components/EditMetadataDialog.form.ts b/web/src/components/EditMetadataDialog.form.ts
index e7f00c999b2..7f605e3820c 100644
--- a/web/src/components/EditMetadataDialog.form.ts
+++ b/web/src/components/EditMetadataDialog.form.ts
@@ -107,6 +107,7 @@ export function initFormState(item: ItemDetail) {
studios: item.studios ?? [],
networks: item.networks ?? [],
countries: item.countries ?? [],
+ custom_tags: item.custom_tags ?? [],
release_date: item.release_date ?? "",
first_air_date: item.first_air_date ?? "",
last_air_date: item.last_air_date ?? "",
diff --git a/web/src/components/EditMetadataDialog.test.tsx b/web/src/components/EditMetadataDialog.test.tsx
index ac76fb73b25..d67803fc1b7 100644
--- a/web/src/components/EditMetadataDialog.test.tsx
+++ b/web/src/components/EditMetadataDialog.test.tsx
@@ -135,4 +135,40 @@ describe("EditMetadataPanel", () => {
expect(screen.queryByRole("button", { name: "Save Changes" })).not.toBeInTheDocument();
expect(v2Recorder.writes()).toHaveLength(0);
});
+
+ it("saves custom tags with no lock, offering the tags already in use", async () => {
+ v2Recorder.answer("GET /api/v2/catalog/custom-tags", {
+ items: [
+ { tag: "Gore", title_count: 3 },
+ { tag: "Late night", title_count: 1 },
+ ],
+ });
+ v2Recorder.answer("PATCH /api/v2/admin/items/{id}/metadata", movie);
+ render(
+
+
+ ,
+ );
+ const field = screen.getByLabelText("Custom tags");
+ fireEvent.focus(field);
+ expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual([
+ "Gore",
+ "Late night",
+ ]);
+ // Picking a suggestion adds it; typed text is added with Enter.
+ fireEvent.change(field, { target: { value: "go" } });
+ fireEvent.click(screen.getByRole("option", { name: "Gore" }));
+ fireEvent.change(field, { target: { value: "Comfort" } });
+ fireEvent.keyDown(field, { key: "Enter" });
+ fireEvent.click(await screen.findByRole("button", { name: "Save Changes" }));
+
+ await vi.waitFor(() =>
+ expect(v2Recorder.callsOf("PATCH /api/v2/admin/items/{id}/metadata")).toHaveLength(1),
+ );
+ expect(v2Recorder.callsOf("PATCH /api/v2/admin/items/{id}/metadata")[0]?.body).toEqual({
+ custom_tags: ["Gore", "Comfort"],
+ });
+ });
});
diff --git a/web/src/components/EditMetadataDialog.tsx b/web/src/components/EditMetadataDialog.tsx
index b33252a2d11..4e8c400ce08 100644
--- a/web/src/components/EditMetadataDialog.tsx
+++ b/web/src/components/EditMetadataDialog.tsx
@@ -20,6 +20,7 @@ import {
type UpdateItemMetadataRequest,
} from "@/hooks/queries/items";
import { useEpisodeOrder } from "@/hooks/queries/episodeOrder";
+import { useCatalogCustomTags } from "@/hooks/queries/customTags";
import { useIsActingAdmin } from "@/hooks/useIsActingAdmin";
import { useReportUnsavedChanges } from "@/hooks/useUnsavedChanges";
import { useMediaQuery } from "@/hooks/useMediaQuery";
@@ -183,6 +184,9 @@ function EditMetadataForm({
// Seasons order by number, so a sort title would do nothing.
const ownsSortTitle = item.type !== "season";
const fieldLockMap = FIELD_LOCK_MAPS[item.type];
+ // Movies and series carry custom tags, which no provider writes, so they
+ // have no lock. The tags already in use are the suggestions.
+ const hasCustomTags = item.type === "movie" || item.type === "series";
// An audiobook's fields mostly come from its file tags, which no provider
// supplies, so a reset would empty them rather than restore them.
const canResetToProvider = fieldLockMap !== undefined && item.type !== "audiobook";
@@ -256,6 +260,8 @@ function EditMetadataForm({
data.networks = form.networks;
if (JSON.stringify(form.countries) !== JSON.stringify(originalForm.countries))
data.countries = form.countries;
+ if (JSON.stringify(form.custom_tags) !== JSON.stringify(originalForm.custom_tags))
+ data.custom_tags = form.custom_tags;
if (form.release_date !== originalForm.release_date)
data.release_date = form.release_date || null;
if (form.first_air_date !== originalForm.first_air_date)
@@ -930,6 +936,21 @@ function EditMetadataForm({
/>
)}
+
+ {hasCustomTags && (
+
+ {(id) => (
+ setField("custom_tags", v)}
+ />
+ )}
+
+ )}
)}
@@ -1050,12 +1071,39 @@ function EditMetadataForm({
// The row gives its control an id, so the label names the control and
// clicking the label focuses it.
+/** The custom tags field, offering the tags already in use; it asks for them only when shown. */
+function CustomTagsInput({
+ id,
+ value,
+ onChange,
+}: {
+ id: string;
+ value: string[];
+ onChange: (tags: string[]) => void;
+}) {
+ const t = useT();
+ const inUse = useCatalogCustomTags();
+ const suggestions = useMemo(() => (inUse.data ?? []).map((c) => c.tag), [inUse.data]);
+ return (
+
+ );
+}
+
function FieldRow({
label,
+ hint,
lockIcon,
children,
}: {
label: string;
+ hint?: string;
lockIcon?: (label: string) => React.ReactNode;
children: (id: string) => React.ReactNode;
}) {
@@ -1069,6 +1117,7 @@ function FieldRow({
{lockIcon?.(label)}
{children(id)}
+ {hint &&
{hint}
}
);
}
diff --git a/web/src/components/TagInput.tsx b/web/src/components/TagInput.tsx
index c7f1d9b43f3..68d0f3104a1 100644
--- a/web/src/components/TagInput.tsx
+++ b/web/src/components/TagInput.tsx
@@ -1,21 +1,214 @@
-import { useState, useRef, type KeyboardEvent } from "react";
+import {
+ useContext,
+ useEffect,
+ useId,
+ useState,
+ useRef,
+ type KeyboardEvent,
+ type ReactNode,
+ type RefObject,
+} from "react";
+import { Popover as PopoverPrimitive } from "radix-ui";
import { X } from "lucide-react";
+import { PortalContainerContext } from "@/components/ui/portal-container-context";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { isImeComposing } from "@/lib/imeComposition";
+/** The bordered field that holds tag chips and the text box. */
+export const TAG_FIELD_CLASS =
+ "border-input bg-background focus-within:border-ring focus-within:ring-ring/50 flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm shadow-xs transition-[color,box-shadow] focus-within:ring-[3px]";
+
+/** A tag shown as a chip with a remove button. */
+export function TagChip({ tag, onRemove }: { tag: string; onRemove: () => void }) {
+ const t = useT();
+ return (
+
+ {tag}
+
+
+ );
+}
+
+/**
+ * A tag field with a list of options under it. The field keeps focus while
+ * the list is open, and clicking inside the field does not close the list.
+ * The list renders next to the field rather than under document.body, so a
+ * dialog's scroll lock still lets it scroll; a PortalContainerContext moves it.
+ * Inside a dialog it stays within the dialog: it flips and shrinks to fit there.
+ */
+export function TagSuggestions({
+ open,
+ onOpenChange,
+ anchorRef,
+ listboxId,
+ activeId,
+ listLabel,
+ multiselectable,
+ contentClassName,
+ field,
+ children,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ anchorRef: RefObject;
+ listboxId: string;
+ /** The highlighted option's id, kept scrolled into view. */
+ activeId?: string;
+ listLabel: string;
+ multiselectable?: boolean;
+ contentClassName: string;
+ field: ReactNode;
+ children: ReactNode;
+}) {
+ const portalContainer = useContext(PortalContainerContext);
+ const [anchor, setAnchor] = useState(null);
+ const dialog = anchor?.closest('[role="dialog"]') ?? undefined;
+ // Scrolls the list alone: scrollIntoView would also scroll the dialog,
+ // and before the list is placed it sits above it.
+ useEffect(() => {
+ const list = open && activeId ? document.getElementById(listboxId) : null;
+ const option = activeId ? document.getElementById(activeId) : null;
+ if (!list || !option) return;
+ const listRect = list.getBoundingClientRect();
+ const optionRect = option.getBoundingClientRect();
+ if (optionRect.top < listRect.top) list.scrollTop -= listRect.top - optionRect.top;
+ else if (optionRect.bottom > listRect.bottom)
+ list.scrollTop += optionRect.bottom - listRect.bottom;
+ }, [open, activeId, listboxId]);
+ const content = (
+ e.preventDefault()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ onInteractOutside={(e) => {
+ if (e.target instanceof Node && anchorRef.current?.contains(e.target)) {
+ e.preventDefault();
+ }
+ }}
+ className={cn(
+ "border-border bg-popover text-popover-foreground z-50 rounded-md border shadow-md",
+ contentClassName,
+ )}
+ >
+
+ {
+ setRequestsTouched(true);
+ updateDraft("requestsAllowed", checked);
+ }}
+ />
) : null}
diff --git a/web/src/components/profiles/ProfileExcludedTags.tsx b/web/src/components/profiles/ProfileExcludedTags.tsx
new file mode 100644
index 00000000000..a9e4b22e40b
--- /dev/null
+++ b/web/src/components/profiles/ProfileExcludedTags.tsx
@@ -0,0 +1,208 @@
+import { useId, useRef, useState, type KeyboardEvent } from "react";
+import { Check } from "lucide-react";
+
+import { TAG_FIELD_CLASS, TagChip, TagOption, TagSuggestions } from "@/components/TagInput";
+import type { ProfileRequestContextSnapshot } from "@/api/client";
+import { useCatalogCustomTags, type CustomTagCount } from "@/hooks/queries/customTags";
+import { useT } from "@/i18n";
+import { formatLocale } from "@/lib/appLocale";
+import { isImeComposing } from "@/lib/imeComposition";
+import type { ProfileDraft } from "@/lib/profile-management";
+import { cn } from "@/lib/utils";
+import { ProfileSwitchCard } from "./ProfileSwitchCard";
+
+const tagKey = (tag: string) => tag.trim().toLowerCase();
+
+/**
+ * The profile editor's tag limit: a switch, and when it is on, the custom
+ * tags whose titles the profile can't see, picked from the tags titles carry.
+ * Turning the switch off keeps the picked tags in the draft, as the library
+ * card keeps its libraries. With no custom tags on any title and none picked,
+ * a note stands in for the card.
+ */
+type TagDraft = Pick;
+
+export function ProfileExcludedTags({
+ draft: { excludedTagsEnabled: enabled, excludedTags: tags },
+ error,
+ profileContext,
+ onChange,
+}: {
+ draft: TagDraft;
+ error?: string;
+ /** Lists the tags as this profile instead of the active one, as the editor saves. */
+ profileContext?: ProfileRequestContextSnapshot;
+ onChange: (change: Partial) => void;
+}) {
+ const t = useT();
+ const available = useCatalogCustomTags(profileContext);
+
+ if (available.isPending) return null;
+ // The switch stays while it is on, so it can be turned off again.
+ if ((available.data?.length ?? 0) === 0 && tags.length === 0 && !enabled) {
+ return (
+