diff --git a/admin/openapi/admin.json b/admin/openapi/admin.json index ada240f5..5fa0efc4 100644 --- a/admin/openapi/admin.json +++ b/admin/openapi/admin.json @@ -474,6 +474,12 @@ }, "url": { "type": "string" + }, + "variants": { + "items": { + "$ref": "#/components/schemas/cabana.AdminMediaVariant" + }, + "type": "array" } }, "required": [ @@ -597,6 +603,311 @@ ], "type": "object" }, + "cabana.AdminMediaBase64UploadRequest": { + "properties": { + "alt": { + "type": "string" + }, + "caption": { + "type": "string" + }, + "content_base64": { + "type": "string" + }, + "filename": { + "type": "string" + }, + "folder_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + }, + "required": [ + "content_base64", + "filename" + ], + "type": "object" + }, + "cabana.AdminMediaDeleteResult": { + "properties": { + "deleted": { + "type": "boolean" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "cabana.AdminMediaFolder": { + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "parent_id": { + "type": "integer" + }, + "slug": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + }, + "required": [ + "created_at", + "id", + "name", + "slug", + "updated_at" + ], + "type": "object" + }, + "cabana.AdminMediaFolderRequest": { + "properties": { + "clear_parent": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "parent_id": { + "type": "integer" + } + }, + "type": "object" + }, + "cabana.AdminMediaItem": { + "properties": { + "alt": { + "type": "string" + }, + "caption": { + "type": "string" + }, + "content_type": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "file_name": { + "type": "string" + }, + "file_size": { + "type": "integer" + }, + "folder_id": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "is_image": { + "type": "boolean" + }, + "sha256": { + "type": "string" + }, + "short_id": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "srcset": { + "type": "string" + }, + "thumb_url": { + "type": "string" + }, + "title": { + "type": "string" + }, + "updated_at": { + "type": "string" + }, + "uploaded_by": { + "type": "integer" + }, + "url": { + "type": "string" + }, + "variants": { + "items": { + "$ref": "#/components/schemas/cabana.AdminMediaVariant" + }, + "type": "array" + }, + "width": { + "type": "integer" + } + }, + "required": [ + "alt", + "caption", + "content_type", + "created_at", + "file_name", + "file_size", + "id", + "is_image", + "sha256", + "short_id", + "slug", + "title", + "updated_at", + "url", + "variants" + ], + "type": "object" + }, + "cabana.AdminMediaItemUpdateRequest": { + "properties": { + "alt": { + "type": "string" + }, + "caption": { + "type": "string" + }, + "clear_folder": { + "type": "boolean" + }, + "folder_id": { + "type": "integer" + }, + "title": { + "type": "string" + } + }, + "type": "object" + }, + "cabana.AdminMediaItemsMeta": { + "properties": { + "can_manage": { + "type": "boolean" + }, + "last_page": { + "type": "integer" + }, + "page": { + "type": "integer" + }, + "per_page": { + "type": "integer" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "can_manage", + "last_page", + "page", + "per_page", + "total" + ], + "type": "object" + }, + "cabana.AdminMediaItemsResponse": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/cabana.AdminMediaItem" + }, + "type": "array" + }, + "meta": { + "$ref": "#/components/schemas/cabana.AdminMediaItemsMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, + "cabana.AdminMediaPrepareUploadRequest": { + "properties": { + "content_type": { + "type": "string" + }, + "filename": { + "type": "string" + }, + "folder_id": { + "type": "integer" + }, + "max_bytes": { + "type": "integer" + } + }, + "required": [ + "filename" + ], + "type": "object" + }, + "cabana.AdminMediaPrepareUploadResult": { + "properties": { + "expires_at": { + "type": "string" + }, + "max_bytes": { + "type": "integer" + }, + "method": { + "type": "string" + }, + "upload_url": { + "type": "string" + } + }, + "required": [ + "expires_at", + "max_bytes", + "method", + "upload_url" + ], + "type": "object" + }, + "cabana.AdminMediaVariant": { + "properties": { + "content_type": { + "type": "string" + }, + "height": { + "type": "integer" + }, + "size": { + "type": "integer" + }, + "url": { + "type": "string" + }, + "width": { + "type": "integer" + } + }, + "required": [ + "content_type", + "height", + "size", + "url", + "width" + ], + "type": "object" + }, "cabana.AdminPreferences": { "properties": { "locale": { @@ -976,6 +1287,24 @@ ], "type": "object" }, + "cabana.Envelope-array_cabana_AdminMediaFolder": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/cabana.AdminMediaFolder" + }, + "type": "array" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, "cabana.Envelope-array_cabana_FileItem": { "properties": { "data": { @@ -1213,6 +1542,66 @@ ], "type": "object" }, + "cabana.Envelope-cabana_AdminMediaDeleteResult": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.AdminMediaDeleteResult" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, + "cabana.Envelope-cabana_AdminMediaFolder": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.AdminMediaFolder" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, + "cabana.Envelope-cabana_AdminMediaItem": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.AdminMediaItem" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, + "cabana.Envelope-cabana_AdminMediaPrepareUploadResult": { + "properties": { + "data": { + "$ref": "#/components/schemas/cabana.AdminMediaPrepareUploadResult" + }, + "meta": { + "$ref": "#/components/schemas/cabana.SuccessMeta" + } + }, + "required": [ + "data", + "meta" + ], + "type": "object" + }, "cabana.Envelope-cabana_AdminPreferences": { "properties": { "data": { @@ -1791,6 +2180,10 @@ "description": "FirstDay is the first day of the week, 0 (Sunday) to 6.", "type": "integer" }, + "folder": { + "description": "Folder is the optional default virtual folder slug for a `type: mediafinder` field.", + "type": "string" + }, "form": { "allOf": [ { @@ -1859,7 +2252,7 @@ "type": "integer" }, "mode": { - "description": "Mode is the fileupload mode (image or file, default file), the\ndatepicker mode (date, datetime or time, default datetime), the\npermissioneditor mode (radio or checkbox), the taglist mode (string,\nthe default, or array), or the mailpreview mode (template, layout,\npartial or branding).", + "description": "Mode is the fileupload mode (image or file, default file), the\nmediafinder mode (image or file, default image), the datepicker mode\n(date, datetime or time, default datetime), the permissioneditor mode\n(radio or checkbox), the taglist mode (string, the default, or array),\nor the mailpreview mode (template, layout, partial or branding).", "type": "string" }, "multiple": { @@ -5420,6 +5813,896 @@ ] } }, + "/media/folders": { + "get": { + "description": "Lists all virtual folders in the Media Library ordered by parent, name, and ID. Requires media.view_media or media.manage_media.", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-array_cabana_AdminMediaFolder" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "List media folders", + "tags": [ + "admin" + ] + }, + "post": { + "description": "Creates a new virtual folder in the Media Library. Requires media.manage_media.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaFolderRequest" + } + } + }, + "description": "Folder name and optional parent_id", + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaFolder" + } + } + }, + "description": "Created" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Create a media folder", + "tags": [ + "admin" + ] + } + }, + "/media/folders/{id}": { + "delete": { + "description": "Deletes a virtual folder. Refuses non-empty folders (items or child folders) with 409 conflict. Requires media.manage_media.", + "parameters": [ + { + "description": "Folder id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaDeleteResult" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Conflict" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Delete an empty media folder", + "tags": [ + "admin" + ] + }, + "put": { + "description": "Renames a virtual folder or moves it under a new parent (or to root with clear_parent: true). Never changes item blob keys or public URLs. Requires media.manage_media.", + "parameters": [ + { + "description": "Folder id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaFolderRequest" + } + } + }, + "description": "Updated name or parent", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaFolder" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Rename or move a media folder", + "tags": [ + "admin" + ] + } + }, + "/media/items": { + "get": { + "description": "Lists paginated Media Library items with optional folder, search query, type (image|file), and sha256 filters. Requires media.view_media or media.manage_media.", + "parameters": [ + { + "description": "Folder id, or 'root' for unfiled items", + "in": "query", + "name": "folder_id", + "schema": { + "type": "string" + } + }, + { + "description": "Set to '1' for unfiled items only", + "in": "query", + "name": "root_only", + "schema": { + "type": "string" + } + }, + { + "description": "Search filename, title, alt, or slug", + "in": "query", + "name": "q", + "schema": { + "type": "string" + } + }, + { + "description": "Filter by type: image or file", + "in": "query", + "name": "type", + "schema": { + "type": "string" + } + }, + { + "description": "Filter by exact lowercase 64-char SHA-256 hex", + "in": "query", + "name": "sha256", + "schema": { + "type": "string" + } + }, + { + "description": "Page number (1-based)", + "in": "query", + "name": "page", + "schema": { + "type": "integer" + } + }, + { + "description": "Items per page (1-100, default 24)", + "in": "query", + "name": "per_page", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaItemsResponse" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "List media items", + "tags": [ + "admin" + ] + }, + "post": { + "description": "Uploads a file via multipart/form-data ('file' plus optional folder_id, alt, title, caption). Raster images synchronously generate responsive WebP variants. Requires media.manage_media.", + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "properties": { + "alt": { + "description": "Optional alternative text", + "type": "string" + }, + "caption": { + "description": "Optional caption", + "type": "string" + }, + "file": { + "description": "File to upload", + "format": "binary", + "type": "string" + }, + "folder_id": { + "description": "Optional destination folder id", + "type": "string" + }, + "title": { + "description": "Optional display title", + "type": "string" + } + }, + "required": [ + "file" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaItem" + } + } + }, + "description": "Created" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Upload a media item (multipart)", + "tags": [ + "admin" + ] + } + }, + "/media/items/base64": { + "post": { + "description": "Uploads a file via JSON base64 payload (decoded size capped at media.base64_max_bytes, default 5 MB). Bound by the media_upload MCP tool. Requires media.manage_media.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaBase64UploadRequest" + } + } + }, + "description": "Filename, base64 bytes, and optional metadata", + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaItem" + } + } + }, + "description": "Created" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Upload a media item (base64 JSON)", + "tags": [ + "admin" + ] + } + }, + "/media/items/{id}": { + "delete": { + "description": "Permanently deletes a Media Library item inside a database transaction and removes its original and WebP variant blobs after commit. Requires media.manage_media.", + "parameters": [ + { + "description": "Media item id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaDeleteResult" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Delete a media item", + "tags": [ + "admin" + ] + }, + "get": { + "description": "Returns full metadata, public URL, WebP variants, and srcset for one Media Library item. Requires media.view_media or media.manage_media.", + "parameters": [ + { + "description": "Media item id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaItem" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Get a media item", + "tags": [ + "admin" + ] + }, + "put": { + "description": "Updates alt, title, caption, or virtual folder on a Media Library item without changing its immutable public URL. Requires media.manage_media.", + "parameters": [ + { + "description": "Media item id", + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaItemUpdateRequest" + } + } + }, + "description": "Fields to update", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaItem" + } + } + }, + "description": "OK" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Update media item metadata", + "tags": [ + "admin" + ] + } + }, + "/media/uploads/prepare": { + "post": { + "description": "Mints a 5-minute single-use upload token in summer_media_upload_tokens and returns an absolute PUT upload_url. Bound by the media_prepare_upload MCP tool. Requires media.manage_media.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.AdminMediaPrepareUploadRequest" + } + } + }, + "description": "Expected filename, optional content type, folder, and max bytes", + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.Envelope-cabana_AdminMediaPrepareUploadResult" + } + } + }, + "description": "Created" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Not Found" + }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/cabana.ErrorEnvelope" + } + } + }, + "description": "Unprocessable Entity" + } + }, + "security": [ + { + "BackendBearer": [] + } + ], + "summary": "Prepare a single-use signed media upload URL", + "tags": [ + "admin" + ] + } + }, "/navigation": { "get": { "responses": { diff --git a/admin/src/api/schema.d.ts b/admin/src/api/schema.d.ts index ac7f31b4..4877000f 100644 --- a/admin/src/api/schema.d.ts +++ b/admin/src/api/schema.d.ts @@ -1786,6 +1786,797 @@ export interface paths { patch?: never; trace?: never; }; + "/media/folders": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List media folders + * @description Lists all virtual folders in the Media Library ordered by parent, name, and ID. Requires media.view_media or media.manage_media. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-array_cabana_AdminMediaFolder"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + put?: never; + /** + * Create a media folder + * @description Creates a new virtual folder in the Media Library. Requires media.manage_media. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Folder name and optional parent_id */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.AdminMediaFolderRequest"]; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaFolder"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/media/folders/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Rename or move a media folder + * @description Renames a virtual folder or moves it under a new parent (or to root with clear_parent: true). Never changes item blob keys or public URLs. Requires media.manage_media. + */ + put: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Folder id */ + id: number; + }; + cookie?: never; + }; + /** @description Updated name or parent */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.AdminMediaFolderRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaFolder"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + post?: never; + /** + * Delete an empty media folder + * @description Deletes a virtual folder. Refuses non-empty folders (items or child folders) with 409 conflict. Requires media.manage_media. + */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Folder id */ + id: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaDeleteResult"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/media/items": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List media items + * @description Lists paginated Media Library items with optional folder, search query, type (image|file), and sha256 filters. Requires media.view_media or media.manage_media. + */ + get: { + parameters: { + query?: { + /** @description Folder id, or 'root' for unfiled items */ + folder_id?: string; + /** @description Set to '1' for unfiled items only */ + root_only?: string; + /** @description Search filename, title, alt, or slug */ + q?: string; + /** @description Filter by type: image or file */ + type?: string; + /** @description Filter by exact lowercase 64-char SHA-256 hex */ + sha256?: string; + /** @description Page number (1-based) */ + page?: number; + /** @description Items per page (1-100, default 24) */ + per_page?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.AdminMediaItemsResponse"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + put?: never; + /** + * Upload a media item (multipart) + * @description Uploads a file via multipart/form-data ('file' plus optional folder_id, alt, title, caption). Raster images synchronously generate responsive WebP variants. Requires media.manage_media. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "multipart/form-data": { + /** @description Optional alternative text */ + alt?: string; + /** @description Optional caption */ + caption?: string; + /** + * Format: binary + * @description File to upload + */ + file: string; + /** @description Optional destination folder id */ + folder_id?: string; + /** @description Optional display title */ + title?: string; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaItem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Request Entity Too Large */ + 413: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/media/items/base64": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Upload a media item (base64 JSON) + * @description Uploads a file via JSON base64 payload (decoded size capped at media.base64_max_bytes, default 5 MB). Bound by the media_upload MCP tool. Requires media.manage_media. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Filename, base64 bytes, and optional metadata */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.AdminMediaBase64UploadRequest"]; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaItem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Request Entity Too Large */ + 413: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/media/items/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get a media item + * @description Returns full metadata, public URL, WebP variants, and srcset for one Media Library item. Requires media.view_media or media.manage_media. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Media item id */ + id: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaItem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + /** + * Update media item metadata + * @description Updates alt, title, caption, or virtual folder on a Media Library item without changing its immutable public URL. Requires media.manage_media. + */ + put: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Media item id */ + id: number; + }; + cookie?: never; + }; + /** @description Fields to update */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.AdminMediaItemUpdateRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaItem"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + post?: never; + /** + * Delete a media item + * @description Permanently deletes a Media Library item inside a database transaction and removes its original and WebP variant blobs after commit. Requires media.manage_media. + */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Media item id */ + id: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaDeleteResult"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/media/uploads/prepare": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Prepare a single-use signed media upload URL + * @description Mints a 5-minute single-use upload token in summer_media_upload_tokens and returns an absolute PUT upload_url. Bound by the media_prepare_upload MCP tool. Requires media.manage_media. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Expected filename, optional content type, folder, and max bytes */ + requestBody: { + content: { + "application/json": components["schemas"]["cabana.AdminMediaPrepareUploadRequest"]; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.Envelope-cabana_AdminMediaPrepareUploadResult"]; + }; + }; + /** @description Unauthorized */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Forbidden */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Request Entity Too Large */ + 413: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["cabana.ErrorEnvelope"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/navigation": { parameters: { query?: never; @@ -6428,6 +7219,7 @@ export interface components { thumbUrl?: string; title: string; url: string; + variants?: components["schemas"]["cabana.AdminMediaVariant"][]; }; "cabana.AdminMailImagesMeta": { canUpload: boolean; @@ -6460,6 +7252,90 @@ export interface components { "cabana.AdminMarkdownPreviewResult": { html: string; }; + "cabana.AdminMediaBase64UploadRequest": { + alt?: string; + caption?: string; + content_base64: string; + filename: string; + folder_id?: number; + title?: string; + }; + "cabana.AdminMediaDeleteResult": { + deleted: boolean; + }; + "cabana.AdminMediaFolder": { + created_at: string; + id: number; + name: string; + parent_id?: number; + slug: string; + updated_at: string; + }; + "cabana.AdminMediaFolderRequest": { + clear_parent?: boolean; + name?: string; + parent_id?: number; + }; + "cabana.AdminMediaItem": { + alt: string; + caption: string; + content_type: string; + created_at: string; + file_name: string; + file_size: number; + folder_id?: number; + height?: number; + id: number; + is_image: boolean; + sha256: string; + short_id: string; + slug: string; + srcset?: string; + thumb_url?: string; + title: string; + updated_at: string; + uploaded_by?: number; + url: string; + variants: components["schemas"]["cabana.AdminMediaVariant"][]; + width?: number; + }; + "cabana.AdminMediaItemUpdateRequest": { + alt?: string; + caption?: string; + clear_folder?: boolean; + folder_id?: number; + title?: string; + }; + "cabana.AdminMediaItemsMeta": { + can_manage: boolean; + last_page: number; + page: number; + per_page: number; + total: number; + }; + "cabana.AdminMediaItemsResponse": { + data: components["schemas"]["cabana.AdminMediaItem"][]; + meta: components["schemas"]["cabana.AdminMediaItemsMeta"]; + }; + "cabana.AdminMediaPrepareUploadRequest": { + content_type?: string; + filename: string; + folder_id?: number; + max_bytes?: number; + }; + "cabana.AdminMediaPrepareUploadResult": { + expires_at: string; + max_bytes: number; + method: string; + upload_url: string; + }; + "cabana.AdminMediaVariant": { + content_type: string; + height: number; + size: number; + url: string; + width: number; + }; "cabana.AdminPreferences": { /** * @description Locale is an admin locale code from GET /lang meta.locales, or "" when @@ -6573,6 +7449,10 @@ export interface components { data: components["schemas"]["cabana.AdminAPITokenScope"][]; meta: components["schemas"]["cabana.SuccessMeta"]; }; + "cabana.Envelope-array_cabana_AdminMediaFolder": { + data: components["schemas"]["cabana.AdminMediaFolder"][]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; "cabana.Envelope-array_cabana_FileItem": { data: components["schemas"]["cabana.FileItem"][]; meta: components["schemas"]["cabana.SuccessMeta"]; @@ -6633,6 +7513,22 @@ export interface components { data: components["schemas"]["cabana.AdminMarkdownPreviewResult"]; meta: components["schemas"]["cabana.SuccessMeta"]; }; + "cabana.Envelope-cabana_AdminMediaDeleteResult": { + data: components["schemas"]["cabana.AdminMediaDeleteResult"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; + "cabana.Envelope-cabana_AdminMediaFolder": { + data: components["schemas"]["cabana.AdminMediaFolder"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; + "cabana.Envelope-cabana_AdminMediaItem": { + data: components["schemas"]["cabana.AdminMediaItem"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; + "cabana.Envelope-cabana_AdminMediaPrepareUploadResult": { + data: components["schemas"]["cabana.AdminMediaPrepareUploadResult"]; + meta: components["schemas"]["cabana.SuccessMeta"]; + }; "cabana.Envelope-cabana_AdminPreferences": { data: components["schemas"]["cabana.AdminPreferences"]; meta: components["schemas"]["cabana.SuccessMeta"]; @@ -6818,6 +7714,8 @@ export interface components { fill?: string[]; /** @description FirstDay is the first day of the week, 0 (Sunday) to 6. */ firstDay?: number; + /** @description Folder is the optional default virtual folder slug for a `type: mediafinder` field. */ + folder?: string; /** * @description Form holds the nested fields of a `type: repeater` field, one set per * row (D-07). @@ -6866,10 +7764,10 @@ export interface components { minItems?: number; /** * @description Mode is the fileupload mode (image or file, default file), the - * datepicker mode (date, datetime or time, default datetime), the - * permissioneditor mode (radio or checkbox), the taglist mode (string, - * the default, or array), or the mailpreview mode (template, layout, - * partial or branding). + * mediafinder mode (image or file, default image), the datepicker mode + * (date, datetime or time, default datetime), the permissioneditor mode + * (radio or checkbox), the taglist mode (string, the default, or array), + * or the mailpreview mode (template, layout, partial or branding). */ mode?: string; multiple?: boolean; diff --git a/admin/src/api/types.ts b/admin/src/api/types.ts index 97e0cbb2..c3f7da1e 100644 --- a/admin/src/api/types.ts +++ b/admin/src/api/types.ts @@ -141,6 +141,28 @@ export type AdminMailTestSendResult = Schemas['cabana.AdminMailTestSendResult'] export type AdminMailImage = Schemas['cabana.AdminMailImage'] /** Meta of GET /mail/images (canUpload, paging). */ export type AdminMailImagesMeta = Schemas['cabana.AdminMailImagesMeta'] +/** One virtual folder in the Media Library. */ +export type AdminMediaFolder = Schemas['cabana.AdminMediaFolder'] +/** Body of POST /media/folders and PUT /media/folders/{id}. */ +export type AdminMediaFolderRequest = Schemas['cabana.AdminMediaFolderRequest'] +/** One generated WebP variant on a Media Library item. */ +export type AdminMediaVariant = Schemas['cabana.AdminMediaVariant'] +/** One item in the Media Library. */ +export type AdminMediaItem = Schemas['cabana.AdminMediaItem'] +/** Pagination and capability meta of GET /media/items. */ +export type AdminMediaItemsMeta = Schemas['cabana.AdminMediaItemsMeta'] +/** Answer of GET /media/items. */ +export type AdminMediaItemsResponse = Schemas['cabana.AdminMediaItemsResponse'] +/** Body of POST /media/items/base64. */ +export type AdminMediaBase64UploadRequest = Schemas['cabana.AdminMediaBase64UploadRequest'] +/** Body of PUT /media/items/{id}. */ +export type AdminMediaItemUpdateRequest = Schemas['cabana.AdminMediaItemUpdateRequest'] +/** Body of POST /media/uploads/prepare. */ +export type AdminMediaPrepareUploadRequest = Schemas['cabana.AdminMediaPrepareUploadRequest'] +/** Answer of POST /media/uploads/prepare. */ +export type AdminMediaPrepareUploadResult = Schemas['cabana.AdminMediaPrepareUploadResult'] +/** Answer of DELETE /media/folders/{id} and DELETE /media/items/{id}. */ +export type AdminMediaDeleteResult = Schemas['cabana.AdminMediaDeleteResult'] /** Body of a relation link: the ids and, for one id, its pivot values. */ export type AdminRelationLinkRequest = Schemas['cabana.AdminRelationLinkRequest'] /** A fileupload field's preview thumbnail mode. */ diff --git a/docs/backend/forms.md b/docs/backend/forms.md index 038a11ba..276aba0e 100644 --- a/docs/backend/forms.md +++ b/docs/backend/forms.md @@ -98,6 +98,7 @@ for _, f := range form.Fields { | `widget` | A plugin custom element with a server action; see [Partials and widgets](partials-and-widgets.md). | | `partial` | A server-rendered template; see [Partials and widgets](partials-and-widgets.md). | | `fileupload` | Uploads for an attachOne or attachMany relation; see [File uploads](#file-uploads). | +| `mediafinder` | Picks one or more items from the shared [Media Library](../services/media-library.md) (`mode: image\|file`, `multiple: bool`, `folder: `). | | `datepicker` | A date, date and time, or time of day; see [Date pickers](#date-pickers). | | `permissioneditor` | A list of permissions to allow, deny or leave inherited; see [Permission editor](#permission-editor). | | `password` | A masked input with a show and hide button. It is a form-only field: the value is sent with a save and never returned; see [Form-only fields](#form-only-fields). | @@ -114,11 +115,11 @@ for _, f := range form.Fields { | `mailimage` | A single image chosen from the mail image library (stores a file id or null). Missing library images show `backend::lang.mailimage.missing` in the admin and are a 422 on save. | | `mailpreview` | A valueless live preview control (`mode` required: `template`, `layout`, `partial` or `branding`); never bound or accepted in a save body. Renders the server HTML in a sandboxed iframe and can send a test to the signed-in administrator. | -The WinterCMS widgets that are not in this list (the media finder and the others) are not provided. A field with one of those types stops the start-up, unless a plugin registers that alias as its own field type: plugins add field types with a custom element and Go code that decides what is stored; see [Plugin field types](field-types.md). +The WinterCMS widgets that are not in this list are not provided. A field with one of those types stops the start-up, unless a plugin registers that alias as its own field type: plugins add field types with a custom element and Go code that decides what is stored; see [Plugin field types](field-types.md). ### Field options -A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields, `preset` on text and mltext fields, `dependsOn` on dropdowns (see [Dependent dropdowns](#dependent-dropdowns)), `currency`, `currencyFrom`, `scale` and `max` on money fields (see [Money](#money)), `mode`, `separator` and `customTags` on taglist fields (see [Taglist](#taglist)), `language` and `mailImages` on `codeeditor` (and `mailImages` on `markdown`), `mode` on `mailpreview`, and `trigger` (see [Triggers](#triggers)). WinterCMS keys outside this set, such as `readOnly` or `disabled`, are refused. +A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields, `preset` on text and mltext fields, `dependsOn` on dropdowns (see [Dependent dropdowns](#dependent-dropdowns)), `currency`, `currencyFrom`, `scale` and `max` on money fields (see [Money](#money)), `mode`, `separator` and `customTags` on taglist fields (see [Taglist](#taglist)), `mode`, `multiple` and `folder` on `mediafinder` fields, `language` and `mailImages` on `codeeditor` (and `mailImages` on `markdown`), `mode` on `mailpreview`, and `trigger` (see [Triggers](#triggers)). WinterCMS keys outside this set, such as `readOnly` or `disabled`, are refused. `context: update` shows a field only on the update form, and `context: create` only on the create form; a list of contexts is also accepted, and `context: preview` shows a field only on the [preview screen](#preview-screen). The context is enforced on the server too: a field that is hidden on a form is never written by that form's save, whatever the request body holds. diff --git a/docs/services/mcp.md b/docs/services/mcp.md index 3eeb2733..fa35c730 100644 --- a/docs/services/mcp.md +++ b/docs/services/mcp.md @@ -125,6 +125,20 @@ What pier does with it at boot: - **Prompts.** A `pact.MCPPrompt` is prefixed and filtered like a tool, names its guard, declares its arguments, and renders its messages in `Render`; required arguments are checked first. A prompt never dispatches a route. An error `Render` returns is logged, and the agent gets only a fixed "the prompt could not be rendered" error. Set `Writes` on a prompt whose text directs tools that are not read-only (for example "draft a post, then create it"): it then sits under the same read/write ceiling as those tools, so a read-only grant is not offered a prompt it cannot follow. - **Descriptions.** `Title` and `Description` are static text, at most 1024 characters, passed through unchanged. Keep them factual one-liners and never build them from data: tool text is read by the model, so data-derived text would be a prompt-injection surface. +## Built-in Media Library tools + +When the admin backend is mounted, SummerCMS automatically registers the framework `summercms.media` MCP plugin (`cabana.MediaMCPPlugin`), exposing 7 tools under the `backend` guard covered by the `media:read` (`media.view_media`) and `media` (`media.view_media` + `media.manage_media`) token scopes: + +- `media_prepare_upload` (`POST /media/uploads/prepare`) — mints a 5-minute single-use signed `PUT` URL for binary uploads up to `media.max_bytes` (default 25 MiB) without base64 overhead. +- `media_upload` (`POST /media/items/base64`) — uploads a file via base64 JSON up to `media.base64_max_bytes` (default 5 MiB decoded; the MCP request body cap is 8 MiB). +- `media_list` (`GET /media/items`) — lists, searches, and filters items by folder, query, type (`image` or `file`), or `sha256`. +- `media_get` (`GET /media/items/{id}`) — fetches metadata, public URL, WebP variants, and `srcset` for one item. +- `media_update` (`PUT /media/items/{id}`) — updates `alt`, `title`, `caption`, or virtual folder without changing the immutable public URL. +- `media_delete` (`DELETE /media/items/{id}`, destructive) — permanently deletes the item and removes its original and WebP variant blobs after commit. +- `media_create_folder` (`POST /media/folders`) — creates a new virtual folder. + +See [Media Library](media-library.md) for details. + ## Identity and sessions Every request is authorized afresh from its bearer; a session never replaces the bearer. An OAuth access token of the application's authorization server (`oas_at_…`) is verified through the `pact.MCPTokenVerifier` the OAuth server plugin publishes: the grant's user is the frontend subject, the grant's scopes are the ceiling. With the `backend` scope and a link the published `pact.MCPLinkedBackendResolver` confirms, the linked administrator is the backend subject, resolved on every request (cached for at most five seconds on one instance and dropped at once by a link event), so unlinking takes effect on the next call with no token surgery. The verifier also reports which administrator the user consented to (`pact.MCPGrant.BackendUserID`); while the link names anyone else, or when the grant records none, the grant has no backend subject, so a link that changes after the consent never re-targets it. The backend principal keeps the administrator's real permissions, superuser included, under the grant's ceiling. diff --git a/modules/cabana/README.md b/modules/cabana/README.md index 43dd2a6b..7160e2c0 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -53,6 +53,7 @@ Use cases: - Money fields: a `type: money` field in `fields.yaml` edits an exact decimal amount that travels as a decimal string with a dot and at most `scale` (2 to 4, default 4) significant fraction digits (trailing zeros beyond the scale are accepted unchanged), or null; the server never parses it into a float, never rounds it and never truncates it, and fills the accepted string into a string column or a type with its own `sql.Scanner` and `driver.Valuer` unchanged. A field declares exactly one of `currency` (an ISO 4217 code) or `currencyFrom` (a sibling string column holding the code) and may declare `max` (the column ceiling); two sources, none, a scale outside 2..4, a max beyond the scale, a column of another type or a currencyFrom that is not a string column fails boot naming the field. A save answers 422 on the field with `backend::lang.money.invalid`, `money.too_precise` (`:scale`) or `money.too_large` (`:max`, compared as scaled digit strings), on controller forms, settings forms and relation forms alike. The schema serves `currency`, `currencyFrom`, `scale` and `max` on the field. A list column `type: money` takes the same `currency` or `currencyFrom` key, is never searchable and not sortable by default, and every list row carries the `currencyFrom` column's value under its own key even when it is not a declared column; the admin right-aligns the locale-formatted amount with its ISO code. - Tag lists: a `type: taglist` field in `fields.yaml` edits a list of tags (WinterCMS TagList). `mode: array` binds a JSON column (a type with `sql.Scanner` and `driver.Valuer`, such as `lagoon.Jsonable[[]string]`) and travels as a JSON array of strings; `mode: string`, the default, binds a string column. `options` is a YAML list of suggested tags; `separator` (`comma` or `space`, string mode only) and `customTags` are refused on other types, and an unknown mode or separator, options that are not a list, the money keys, `nameFrom`, `emptyOption`, `dependsOn`, `preset` or a column of the wrong Go type fails boot naming the field. A save trims every tag, drops empty ones and keeps a repeated tag once; in array mode null or an empty list stores `[]`, in string mode the tags are split on the separator and stored joined by `,` or a single space (null stores an empty string). A value of the wrong shape is a 422 on the field with `backend::lang.taglist.invalid`, and with `customTags: false` a tag outside `options` is a 422 with `backend::lang.taglist.not_allowed` (`:tag`), on controller forms, settings forms and relation forms alike; a taglist in a repeater row fails boot. The record GET serves the stored list (array mode) or string (string mode). The schema serves `mode`, `options`, `separator` and `customTags` on the field; the admin edits the tags as chips. - File uploads: a `type: fileupload` field in `fields.yaml` edits an attachOne or attachMany relation the record model declares through `attach.HasRelations` (its `AttachRelations` method) next to `attach.Owner`. The field accepts WinterCMS's `mode` (`image` or `file`), `fileTypes`, `mimeTypes`, `maxFilesize` (megabytes), `maxFiles` (attachMany only), `imageWidth`, `imageHeight`, `thumbOptions` (only `mode`: `auto`, `exact`, `crop` or `fit`), `useCaption` and `prompt`; any other key, an image-mode file type outside jpg, jpeg, png, gif and webp, a name that is not a declared relation or a `maxFilesize` whose file plus 64 KiB of multipart framing exceeds `http.body_limits.upload_bytes` fails boot. Uploads and removals are deferred, as in WinterCMS: the SPA sends a random form session key in the `X-Session-Key` header (`cabana.SessionKeyHeader`) with every file call and with the save, the server keeps the pending work in `deferred_bindings` against that key and the signed-in administrator, and the record's next create or update save applies it inside its transaction. A retry of the same upload may send `X-Upload-Id` so the server returns the already stored file. A save that fails with 422 keeps the pending uploads; another administrator's key matches nothing. The upload route caps the request body at the smaller of `http.body_limits.upload_bytes` and `maxFilesize` plus 64 KiB and answers 413 `payload_too_large` past it; the size, type and image checks run on the server (through `attach.Store`) and answer 422 on the field. A file list (`cabana.FileItem`) carries `url` and `thumb_url` only for a public relation. +- Media Library: built on [album](../album/README.md), registering `cabana.PermissionViewMedia` (`media.view_media`) and `cabana.PermissionManageMedia` (`media.manage_media`) with no default role grants, plus `media:read` and `media` token scopes grouped under Media in the token scope picker. Exposes `/media/folders`, `/media/folders/{id}`, `/media/items`, `/media/items/{id}`, `/media/items/base64`, and `/media/uploads/prepare` (with post-commit blob deletion via `lagoon.AfterCommit`), compiles `type: mediafinder` (`mode: image|file`, `multiple`, `folder`) form fields, unifies `/mail/images` uploads onto the `mail` virtual folder (running idempotent `album.BackfillMailImages` on first use while preserving `cabana.AdminMailImage`), and exports `cabana.MediaMCPPlugin` for the 7 built-in `media_*` MCP tools. - Refusals: a lifecycle hook, a relation hook, a bulk, record, toolbar or widget action, a `pact.ReorderAfterSave` hook or a `pact.AdminSingleton` `SingletonRecord` call that returns a `cabana.ForbiddenError` is answered 403 `forbidden` with the error's `Message` and `Details` (a field name to a list of messages), both translated in the request locale; an empty `Message` stays empty. A `cabana.ValidationError` returned from the same places is answered 422 `validation_failed` with its `Details`, each message that is a translation key (`vendor.plugin::group.key`) translated in the request locale and any other text passed through unchanged. The plugin's error value is never modified, so it may be a shared variable. The surrounding transaction is rolled back. Every other error stays the opaque 500, logged on the server. - Roles screen: Settings → System → Roles (controller `cabana.RolesControllerID`, permission `cabana.PermissionManageRoles`) lists, creates, edits and deletes backend roles with name, code (slugged from the name), description and a checkbox permission editor. System roles (`is_system`, or a code that code-declared `pact.Permission` grants attach to) keep their code and cannot be deleted, a role any administrator holds (deleted ones included) cannot be deleted, a code another role uses is refused, and a non-superuser editor cannot add or remove a permission they lack. The update form's Administrators tab lists the role's holders read-only (a form partial): superusers only for superuser editors, deleted and deactivated holders marked, the first 100 with a note naming the total, each login linked to the Administrators preview for an editor holding `cabana.PermissionManageUsers`; roles are assigned only on the Administrators form. - Record actions on another plugin's controller: a plugin implementing `pact.HasAdminActionExtensions` adds `pact.AdminRecordAction` entries to any admin controller by its ID (`pact.AdminActionExtension`), its own, another plugin's or the admin's own Administrators screen (`cabana.AdministratorsControllerID`). They are merged at boot after the target's own record actions, in plugin activation order, offered on the target's preview screen and run through the same row-locked record action route; the target's `RequiredPermissions` and the action's own `Permissions` both apply. Contributions targeting `cabana.AdministratorsControllerID` run `guardOutranked` before `Run` (403 `user.outranked`, `Run` not called). An unknown controller ID, a target without a preview block, a name the target already registers (the owner's or an earlier contribution), a reserved or non-identifier name, a missing `Run` or an empty label stops the boot. Extensions are compiled only when the admin is active. diff --git a/modules/cabana/admin_openapi.go b/modules/cabana/admin_openapi.go index 66472b6d..2da46f80 100644 --- a/modules/cabana/admin_openapi.go +++ b/modules/cabana/admin_openapi.go @@ -1815,3 +1815,193 @@ func AdminFileDownload() {} // @Failure 422 {object} ErrorEnvelope // @Router /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}/thumb [get] func AdminFileThumb() {} + +// AdminMediaFoldersList documents GET /media/folders. +// +// @Summary List media folders +// @Description Lists all virtual folders in the Media Library ordered by parent, name, and ID. Requires media.view_media or media.manage_media. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Success 200 {object} Envelope[[]AdminMediaFolder] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Router /media/folders [get] +func AdminMediaFoldersList() {} + +// AdminMediaFoldersCreate documents POST /media/folders. +// +// @Summary Create a media folder +// @Description Creates a new virtual folder in the Media Library. Requires media.manage_media. +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param body body AdminMediaFolderRequest true "Folder name and optional parent_id" +// @Success 201 {object} Envelope[AdminMediaFolder] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/folders [post] +func AdminMediaFoldersCreate() {} + +// AdminMediaFoldersUpdate documents PUT /media/folders/{id}. +// +// @Summary Rename or move a media folder +// @Description Renames a virtual folder or moves it under a new parent (or to root with clear_parent: true). Never changes item blob keys or public URLs. Requires media.manage_media. +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param id path integer true "Folder id" +// @Param body body AdminMediaFolderRequest true "Updated name or parent" +// @Success 200 {object} Envelope[AdminMediaFolder] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/folders/{id} [put] +func AdminMediaFoldersUpdate() {} + +// AdminMediaFoldersDelete documents DELETE /media/folders/{id}. +// +// @Summary Delete an empty media folder +// @Description Deletes a virtual folder. Refuses non-empty folders (items or child folders) with 409 conflict. Requires media.manage_media. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param id path integer true "Folder id" +// @Success 200 {object} Envelope[AdminMediaDeleteResult] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 409 {object} ErrorEnvelope +// @Router /media/folders/{id} [delete] +func AdminMediaFoldersDelete() {} + +// AdminMediaItemsList documents GET /media/items. +// +// @Summary List media items +// @Description Lists paginated Media Library items with optional folder, search query, type (image|file), and sha256 filters. Requires media.view_media or media.manage_media. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param folder_id query string false "Folder id, or 'root' for unfiled items" +// @Param root_only query string false "Set to '1' for unfiled items only" +// @Param q query string false "Search filename, title, alt, or slug" +// @Param type query string false "Filter by type: image or file" +// @Param sha256 query string false "Filter by exact lowercase 64-char SHA-256 hex" +// @Param page query integer false "Page number (1-based)" +// @Param per_page query integer false "Items per page (1-100, default 24)" +// @Success 200 {object} AdminMediaItemsResponse +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Router /media/items [get] +func AdminMediaItemsList() {} + +// AdminMediaItemsShow documents GET /media/items/{id}. +// +// @Summary Get a media item +// @Description Returns full metadata, public URL, WebP variants, and srcset for one Media Library item. Requires media.view_media or media.manage_media. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param id path integer true "Media item id" +// @Success 200 {object} Envelope[AdminMediaItem] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Router /media/items/{id} [get] +func AdminMediaItemsShow() {} + +// AdminMediaItemsUpload documents POST /media/items. +// +// @Summary Upload a media item (multipart) +// @Description Uploads a file via multipart/form-data ('file' plus optional folder_id, alt, title, caption). Raster images synchronously generate responsive WebP variants. Requires media.manage_media. +// @Tags admin +// @Accept multipart/form-data +// @Produce json +// @Security BackendBearer +// @Param file formData file true "File to upload" +// @Param folder_id formData string false "Optional destination folder id" +// @Param alt formData string false "Optional alternative text" +// @Param title formData string false "Optional display title" +// @Param caption formData string false "Optional caption" +// @Success 201 {object} Envelope[AdminMediaItem] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 413 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/items [post] +func AdminMediaItemsUpload() {} + +// AdminMediaItemsUploadBase64 documents POST /media/items/base64. +// +// @Summary Upload a media item (base64 JSON) +// @Description Uploads a file via JSON base64 payload (decoded size capped at media.base64_max_bytes, default 5 MB). Bound by the media_upload MCP tool. Requires media.manage_media. +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param body body AdminMediaBase64UploadRequest true "Filename, base64 bytes, and optional metadata" +// @Success 201 {object} Envelope[AdminMediaItem] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 413 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/items/base64 [post] +func AdminMediaItemsUploadBase64() {} + +// AdminMediaItemsUpdate documents PUT /media/items/{id}. +// +// @Summary Update media item metadata +// @Description Updates alt, title, caption, or virtual folder on a Media Library item without changing its immutable public URL. Requires media.manage_media. +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param id path integer true "Media item id" +// @Param body body AdminMediaItemUpdateRequest true "Fields to update" +// @Success 200 {object} Envelope[AdminMediaItem] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/items/{id} [put] +func AdminMediaItemsUpdate() {} + +// AdminMediaItemsDelete documents DELETE /media/items/{id}. +// +// @Summary Delete a media item +// @Description Permanently deletes a Media Library item inside a database transaction and removes its original and WebP variant blobs after commit. Requires media.manage_media. +// @Tags admin +// @Produce json +// @Security BackendBearer +// @Param id path integer true "Media item id" +// @Success 200 {object} Envelope[AdminMediaDeleteResult] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Router /media/items/{id} [delete] +func AdminMediaItemsDelete() {} + +// AdminMediaPrepareUpload documents POST /media/uploads/prepare. +// +// @Summary Prepare a single-use signed media upload URL +// @Description Mints a 5-minute single-use upload token in summer_media_upload_tokens and returns an absolute PUT upload_url. Bound by the media_prepare_upload MCP tool. Requires media.manage_media. +// @Tags admin +// @Accept json +// @Produce json +// @Security BackendBearer +// @Param body body AdminMediaPrepareUploadRequest true "Expected filename, optional content type, folder, and max bytes" +// @Success 201 {object} Envelope[AdminMediaPrepareUploadResult] +// @Failure 401 {object} ErrorEnvelope +// @Failure 403 {object} ErrorEnvelope +// @Failure 404 {object} ErrorEnvelope +// @Failure 413 {object} ErrorEnvelope +// @Failure 422 {object} ErrorEnvelope +// @Router /media/uploads/prepare [post] +func AdminMediaPrepareUpload() {} diff --git a/modules/cabana/backend_screens.go b/modules/cabana/backend_screens.go index 7abe5d76..b54bae07 100644 --- a/modules/cabana/backend_screens.go +++ b/modules/cabana/backend_screens.go @@ -26,6 +26,13 @@ const ( AdministratorsControllerID = "summercms.cabana.users" // RolesControllerID is the admin controller ID of the Roles screen. RolesControllerID = "summercms.cabana.roles" + // PermissionViewMedia opens the Media Library screen and read-only media + // browsing/picking routes. No role is granted it in code. + PermissionViewMedia = "media.view_media" + // PermissionManageMedia allows uploading, organizing folders, editing + // metadata, and deleting items in the Media Library. No role is granted it + // in code. + PermissionManageMedia = "media.manage_media" ) // The mail screens (Settings → Mail), registered by the same pseudo-plugin @@ -86,6 +93,7 @@ var ( _ pact.HasAdminControllers = (*backendScreens)(nil) _ pact.HasPermissions = (*backendScreens)(nil) _ pact.HasSettings = (*backendScreens)(nil) + _ pact.HasTokenScopes = (*backendScreens)(nil) ) func (*backendScreens) ID() string { return backendScreensPluginID } @@ -121,6 +129,8 @@ func (s *backendScreens) Permissions() []pact.Permission { {Code: PermissionManageUsers, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_users"}, {Code: PermissionManageRoles, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_roles"}, {Code: PermissionViewPlugins, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.view_plugins"}, + {Code: PermissionViewMedia, Tab: "backend::lang.permissions.tab_media", Label: "backend::lang.permissions.view_media"}, + {Code: PermissionManageMedia, Tab: "backend::lang.permissions.tab_media", Label: "backend::lang.permissions.manage_media"}, } if s.mail != nil { out = append(out, mailPermissions()...) @@ -128,6 +138,40 @@ func (s *backendScreens) Permissions() []pact.Permission { return out } +// TokenScopes declares the framework Media Library token scopes (media:read +// and media) grouped under Media in Phase 36's ScopePicker. +func (*backendScreens) TokenScopes() []pact.TokenScope { + return mediaTokenScopes() +} + +func mediaPermissions() []pact.Permission { + return []pact.Permission{ + {Code: PermissionViewMedia, Tab: "backend::lang.permissions.tab_media", Label: "backend::lang.permissions.view_media"}, + {Code: PermissionManageMedia, Tab: "backend::lang.permissions.tab_media", Label: "backend::lang.permissions.manage_media"}, + } +} + +func mediaTokenScopes() []pact.TokenScope { + return []pact.TokenScope{ + { + Name: "media:read", + Label: "backend::lang.api_tokens.scope_media_read", + Description: "backend::lang.api_tokens.scope_media_read_description", + Group: "backend::lang.api_tokens.group_media", + Permissions: []string{PermissionViewMedia}, + Methods: []string{"GET", "HEAD"}, + }, + { + Name: "media", + Label: "backend::lang.api_tokens.scope_media", + Description: "backend::lang.api_tokens.scope_media_description", + Group: "backend::lang.api_tokens.group_media", + Permissions: []string{PermissionViewMedia, PermissionManageMedia}, + Methods: []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}, + }, + } +} + // Settings links the screens from Settings → System, and the mail screens // from Settings → Mail; there is no navigation entry. func (s *backendScreens) Settings() []pact.SettingsItem { diff --git a/modules/cabana/datepicker_smoke_test.go b/modules/cabana/datepicker_smoke_test.go index b50950eb..5b3eea7f 100644 --- a/modules/cabana/datepicker_smoke_test.go +++ b/modules/cabana/datepicker_smoke_test.go @@ -93,7 +93,7 @@ func TestDatepickerSmokeCompile(t *testing.T) { "minDate on time": {" day:\n type: datepicker\n mode: time\n minDate: 2026-01-01\n", "minDate is not valid with mode: time"}, "min after max": {" starts_at:\n type: datepicker\n minDate: 2026-02-01\n maxDate: 2026-01-01\n", "is after maxDate"}, "key on another type": {" title:\n type: text\n firstDay: 1\n", "firstDay is only valid on type: datepicker"}, - "mode on another type": {" title:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview"}, + "mode on another type": {" title:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, mediafinder, datepicker, permissioneditor, taglist or mailpreview"}, } { t.Run(name, func(t *testing.T) { err := activateFields(t, datepickerFields(tc.field)) diff --git a/modules/cabana/datepicker_test.go b/modules/cabana/datepicker_test.go index 590b9e23..ac08ea74 100644 --- a/modules/cabana/datepicker_test.go +++ b/modules/cabana/datepicker_test.go @@ -65,7 +65,7 @@ func TestDatepickerCompile(t *testing.T) { "ignoreTimezone not bool": {field("starts_at", " ignoreTimezone: maybe\n"), "ignoreTimezone:"}, "ignoreTimezone on date": {field("released_on", " mode: date\n ignoreTimezone: true\n"), "ignoreTimezone is only valid with mode: datetime"}, "key on another type": {" name2:\n type: text\n firstDay: 1\n", "firstDay is only valid on type: datepicker"}, - "mode on another type": {" name2:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview"}, + "mode on another type": {" name2:\n type: text\n mode: date\n", "mode is only valid on type: fileupload, mediafinder, datepicker, permissioneditor, taglist or mailpreview"}, "date on a datetime": {field("starts_at", " mode: date\n"), "field starts_at: datepicker mode date needs a lagoon.Date or *lagoon.Date column, found *time.Time"}, "datetime on a date": {field("released_on", " mode: datetime\n"), "datepicker mode datetime needs a time.Time or *time.Time column, found lagoon.Date"}, "time on a date": {field("released_on", " mode: time\n"), "datepicker mode time needs a lagoon.TimeOfDay or *lagoon.TimeOfDay column, found lagoon.Date"}, diff --git a/modules/cabana/field_file.go b/modules/cabana/field_file.go index 5e2417f2..2e5c4b78 100644 --- a/modules/cabana/field_file.go +++ b/modules/cabana/field_file.go @@ -75,8 +75,8 @@ func compileFileuploadKeys(typ string, values map[string]ast.Node, field *FormFi return fmt.Errorf("%s is only valid on type: fileupload", key) } } - if _, ok := values["mode"]; ok && typ != "datepicker" && typ != permissionFieldType && typ != taglistType && typ != mailPreviewType { - return fmt.Errorf("mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview") + if _, ok := values["mode"]; ok && typ != "datepicker" && typ != permissionFieldType && typ != taglistType && typ != mailPreviewType && typ != mediaFinderType { + return fmt.Errorf("mode is only valid on type: fileupload, mediafinder, datepicker, permissioneditor, taglist or mailpreview") } return nil } diff --git a/modules/cabana/field_media.go b/modules/cabana/field_media.go new file mode 100644 index 00000000..c0e41d1e --- /dev/null +++ b/modules/cabana/field_media.go @@ -0,0 +1,56 @@ +package cabana + +import ( + "fmt" + "strings" + + "github.com/goccy/go-yaml/ast" +) + +const mediaFinderType = "mediafinder" + +var mediaFinderKeys = []string{"multiple", "folder"} + +// compileMediaFinderKeys decodes the YAML keys of a `type: mediafinder` field: +// mode ("image" default or "file"), multiple (bool), and folder (optional +// default virtual folder slug). They are refused on other field types. +func compileMediaFinderKeys(typ string, values map[string]ast.Node, field *FormField) error { + if typ != mediaFinderType { + for _, key := range mediaFinderKeys { + if _, ok := values[key]; ok { + return fmt.Errorf("%s is only valid on type: mediafinder", key) + } + } + return nil + } + + field.Mode = "image" + if node, ok := values["mode"]; ok { + mode, err := nodeString(node) + if err != nil || (mode != "image" && mode != "file") { + return fmt.Errorf("mode %q must be image or file on type: mediafinder", nodeText(node)) + } + field.Mode = mode + } + + if node, ok := values["multiple"]; ok { + mult, err := nodeBool(node) + if err != nil { + return fmt.Errorf("multiple: %w", err) + } + field.Multiple = mult + } + + if node, ok := values["folder"]; ok { + folder, err := nodeString(node) + if err != nil { + return fmt.Errorf("folder: %w", err) + } + folder = strings.TrimSpace(folder) + if strings.ContainsAny(folder, "/\\") || strings.Contains(folder, "..") { + return fmt.Errorf("folder %q must be a single folder slug", folder) + } + field.Folder = folder + } + return nil +} diff --git a/modules/cabana/form_schema.go b/modules/cabana/form_schema.go index dc01a9b5..c62069e1 100644 --- a/modules/cabana/form_schema.go +++ b/modules/cabana/form_schema.go @@ -29,6 +29,7 @@ var ( "markdown": {}, "mltext": {}, "mltextarea": {}, "mlmarkdown": {}, "richeditor": {}, "repeater": {}, "money": {}, "taglist": {}, "codeeditor": {}, "colorpicker": {}, "mailimage": {}, "mailpreview": {}, + "mediafinder": {}, } formSpans = map[string]struct{}{ "left": {}, "right": {}, "full": {}, "auto": {}, "row": {}, @@ -52,6 +53,7 @@ var ( "currency": {}, "currencyFrom": {}, "scale": {}, "max": {}, "separator": {}, "customTags": {}, "language": {}, "mailImages": {}, + "multiple": {}, "folder": {}, } // widgetKeys are valid only on `type: widget` (D-06). widgetKeys = []string{"widget", "action", "fill"} @@ -652,6 +654,9 @@ func compileFieldNode(name string, node ast.Node, types *fieldTypeRegistry) (For if err := compileMailFieldKeys(typ, values, &field); err != nil { return FormField{}, err } + if err := compileMediaFinderKeys(typ, values, &field); err != nil { + return FormField{}, err + } if err := compilePresetKey(typ, values, &field); err != nil { return FormField{}, err } diff --git a/modules/cabana/http.go b/modules/cabana/http.go index 6e5cab4a..909a66a1 100644 --- a/modules/cabana/http.go +++ b/modules/cabana/http.go @@ -12,6 +12,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" "git.golem15.com/golem15/summercms/modules/backpack" @@ -59,6 +60,14 @@ type service struct { // catalog is the Plugins screen's registry view with its cache, built // by Activate. catalog *pluginCatalog + // mailBackfill tracks whether idempotent BackfillMailImages has succeeded + // for this service instance (pointer so service stays value-copyable). + mailBackfill *mailBackfillState +} + +type mailBackfillState struct { + mu sync.Mutex + done bool } // adminPrefix returns the mount path; a zero service uses the default. @@ -256,6 +265,7 @@ func Activate(app *backpack.App, plugins []party.Plugin) (*Routes, error) { } svc.spa = spa svc.catalog = newPluginCatalog(app.Config) + svc.mailBackfill = &mailBackfillState{} return &Routes{Middleware: mw, Mount: svc.mount, Prefix: prefix}, nil } @@ -365,6 +375,18 @@ func (s *service) mount(r pact.Router) { g.Post("/mail/images", requireAjax(s.mailImagesUpload)) g.Post("/mail/preview", requireAjax(s.mailPreview)) g.Post("/mail/test-send", interactiveOnly(requireAjax(s.mailTestSend))) + // Media Library (modules/album). + g.Get("/media/folders", s.mediaFoldersList) + g.Post("/media/folders", requireAjax(s.mediaFoldersCreate)) + g.Put("/media/folders/{id}", requireAjax(s.mediaFoldersUpdate)) + g.Delete("/media/folders/{id}", requireAjax(s.mediaFoldersDelete)) + g.Get("/media/items", s.mediaItemsList) + g.Get("/media/items/{id}", s.mediaItemsShow) + g.Post("/media/items", requireAjax(s.mediaItemsUpload)) + g.Post("/media/items/base64", requireAjax(s.mediaItemsUploadBase64)) + g.Put("/media/items/{id}", requireAjax(s.mediaItemsUpdate)) + g.Delete("/media/items/{id}", requireAjax(s.mediaItemsDelete)) + g.Post("/media/uploads/prepare", requireAjax(s.mediaPrepareUpload)) g.Get("/settings", s.settingsList) // The read-only Plugins screen (backend.view_plugins). g.Get("/plugins", s.pluginsInstalled) diff --git a/modules/cabana/mail_admin.go b/modules/cabana/mail_admin.go index 31bc3546..a8ead353 100644 --- a/modules/cabana/mail_admin.go +++ b/modules/cabana/mail_admin.go @@ -13,6 +13,7 @@ import ( "sync/atomic" "time" + "git.golem15.com/golem15/summercms/modules/album" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/pact" @@ -1840,11 +1841,19 @@ func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error { if b.LogoFileID != nil { var n int64 if err := tx.Session(&gorm.Session{NewDB: true}). - Table("system_files"). - Where("id = ? AND attachment_type = ? AND field = ?", *b.LogoFileID, mailImageLibraryMorph, "images"). + Table(album.ItemsTable). + Where("id = ? OR legacy_file_id = ?", *b.LogoFileID, *b.LogoFileID). Count(&n).Error; err != nil { return err } + if n == 0 { + if err := tx.Session(&gorm.Session{NewDB: true}). + Table("system_files"). + Where("id = ? AND attachment_type = ? AND field = ?", *b.LogoFileID, mailImageLibraryMorph, "images"). + Count(&n).Error; err != nil { + return err + } + } if n == 0 { details["logo_file_id"] = []string{"backend::lang.mailimage.missing"} } diff --git a/modules/cabana/mail_routes.go b/modules/cabana/mail_routes.go index 5e5cc108..c21b69e6 100644 --- a/modules/cabana/mail_routes.go +++ b/modules/cabana/mail_routes.go @@ -6,11 +6,13 @@ import ( "fmt" "io" "net/http" + "sort" "strconv" "strings" "sync" "time" + "git.golem15.com/golem15/summercms/modules/album" "git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/cooler" "git.golem15.com/golem15/summercms/modules/lagoon" @@ -21,11 +23,12 @@ import ( // AdminMailImage is one library image with absolute public URLs. type AdminMailImage struct { - ID uint `json:"id"` - FileName string `json:"fileName"` - Title string `json:"title"` - URL string `json:"url"` - ThumbURL string `json:"thumbUrl,omitempty"` + ID uint `json:"id"` + FileName string `json:"fileName"` + Title string `json:"title"` + URL string `json:"url"` + ThumbURL string `json:"thumbUrl,omitempty"` + Variants []AdminMediaVariant `json:"variants,omitempty"` } // AdminMailImagesMeta is the meta of GET /mail/images. @@ -53,6 +56,35 @@ var mailImageLimits = attach.Limits{ Image: true, } +// ensureMailImagesBackfilled runs album.BackfillMailImages once per service +// instance, retrying on error so legacy system_files mail images appear in the +// unified Media Library without breaking existing /uploads/... URLs. +func (s *service) ensureMailImagesBackfilled(ctx context.Context, db *gorm.DB) { + if s == nil || db == nil { + return + } + state := s.mailBackfill + if state != nil { + state.mu.Lock() + if state.done { + state.mu.Unlock() + return + } + state.mu.Unlock() + } + + if _, err := album.BackfillMailImages(ctx, db, s.config()); err != nil { + moduleLog.WarnContext(ctx, "cabana: backfill mail images failed; will retry", "error", err) + return + } + + if state != nil { + state.mu.Lock() + state.done = true + state.mu.Unlock() + } +} + // mailImagesList serves GET /mail/images: library images with absolute URLs, // for holders of either mail permission. canUpload is true only for layouts. func (s *service) mailImagesList(w http.ResponseWriter, r *http.Request) { @@ -78,6 +110,8 @@ func (s *service) mailImagesList(w http.ResponseWriter, r *http.Request) { WriteError(w, http.StatusInternalServerError, "error", msgServerError) return } + s.ensureMailImagesBackfilled(r.Context(), db) + q := strings.TrimSpace(r.URL.Query().Get("q")) page := 1 if raw := r.URL.Query().Get("page"); raw != "" { @@ -85,25 +119,38 @@ func (s *service) mailImagesList(w http.ResponseWriter, r *http.Request) { page = n } } - query := db.WithContext(r.Context()).Model(&attach.File{}). - Where("attachment_type = ? AND field = ?", mailImageLibraryMorph, "images") - if q != "" { - like := "%" + q + "%" - query = query.Where("file_name ILIKE ? OR title ILIKE ?", like, like) + + var mailFolder album.Folder + folderErr := db.WithContext(r.Context()).Where("parent_id IS NULL AND slug = ?", "mail").First(&mailFolder).Error + if errors.Is(folderErr, gorm.ErrRecordNotFound) { + WriteData(w, http.StatusOK, []AdminMailImage{}, AdminMailImagesMeta{ + CanUpload: Allows(principal, []string{PermissionManageMailLayouts}), + Total: 0, + Page: page, + PerPage: mailImagesPerPage, + }) + return } - var total int64 - if err := query.Count(&total).Error; err != nil { + if folderErr != nil { WriteError(w, http.StatusInternalServerError, "error", msgServerError) return } - var files []attach.File - if err := query.Order("id DESC").Offset((page - 1) * mailImagesPerPage).Limit(mailImagesPerPage).Find(&files).Error; err != nil { + + fid := mailFolder.ID + albumItems, total, err := s.albumService().ListItems(r.Context(), db, album.ListFilter{ + FolderID: &fid, + Query: q, + Type: "image", + Page: page, + PerPage: mailImagesPerPage, + }) + if err != nil { WriteError(w, http.StatusInternalServerError, "error", msgServerError) return } - items := make([]AdminMailImage, 0, len(files)) - for i := range files { - item, err := s.mailImageItem(r.Context(), &files[i]) + items := make([]AdminMailImage, 0, len(albumItems)) + for i := range albumItems { + item, err := s.mailImageFromAlbumItem(&albumItems[i]) if err != nil { if errors.Is(err, attach.ErrNoAbsoluteURL) { WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) @@ -146,6 +193,31 @@ func (s *service) mailImagesShow(w http.ResponseWriter, r *http.Request) { WriteError(w, http.StatusInternalServerError, "error", msgServerError) return } + s.ensureMailImagesBackfilled(r.Context(), db) + + var aItem album.Item + err = db.WithContext(r.Context()). + Where("id = ? OR legacy_file_id = ?", id, id). + Order("CASE WHEN id = " + strconv.FormatUint(id, 10) + " THEN 0 ELSE 1 END"). + Take(&aItem).Error + if err == nil { + item, convErr := s.mailImageFromAlbumItem(&aItem) + if convErr != nil { + if errors.Is(convErr, attach.ErrNoAbsoluteURL) { + WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) + return + } + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + WriteData(w, http.StatusOK, item, nil) + return + } + if !errors.Is(err, gorm.ErrRecordNotFound) { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + var f attach.File err = db.WithContext(r.Context()). Where("id = ? AND attachment_type = ? AND field = ?", id, mailImageLibraryMorph, "images"). @@ -171,7 +243,8 @@ func (s *service) mailImagesShow(w http.ResponseWriter, r *http.Request) { } // mailImagesUpload serves POST /mail/images: layouts holders only, multipart -// "file", attached to the library host with an absolute public URL. +// "file", stored in modules/album under virtual folder "mail" with an absolute +// public URL. func (s *service) mailImagesUpload(w http.ResponseWriter, r *http.Request) { principal, ok := bouncer.User(r.Context()) if !ok || principal == nil || !principal.Backend { @@ -215,50 +288,47 @@ func (s *service) mailImagesUpload(w http.ResponseWriter, r *http.Request) { writeCRUDError(w, invalidBody()) return } - var stored *attach.File + var uploaded *album.Item var item AdminMailImage + albumSvc := s.albumService() + uid := principal.ID err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error { - host, err := mailImagesAdmin{}.SingletonRecord(ctx, tx) + mailFolder, err := albumSvc.EnsureFolder(ctx, tx, "mail", "Mail", nil) if err != nil { return err } - library, ok := host.(*MailImageLibrary) - if !ok || library == nil || library.ID == 0 { - return errors.New("cabana: mail image library host missing") - } - f, err := attach.Store(ctx, tx, bucket, attach.Upload{FileName: part.FileName(), Body: part, Public: true}, mailImageLimits) + fid := mailFolder.ID + aItem, err := albumSvc.Upload(ctx, tx, bucket, album.UploadInput{ + FileName: part.FileName(), + Body: part, + FolderID: &fid, + UploadedBy: &uid, + ImageOnly: true, + MaxBytes: mailImageMaxBytes, + }) if err != nil { return err } - stored = f + uploaded = aItem if _, err := mr.NextPart(); !errors.Is(err, io.EOF) { if err == nil { return invalidBody() } return err } - if err := tx.Session(&gorm.Session{NewDB: true, Context: ctx}).Model(&attach.File{}).Where("id = ?", f.ID).Updates(map[string]any{ - "attachment_id": uitoa(library.ID), - "attachment_type": mailImageLibraryMorph, - "field": "images", - }).Error; err != nil { - return err - } - f.AttachmentID = uitoa(library.ID) - f.AttachmentType = mailImageLibraryMorph - f.Field = "images" - item, err = s.mailImageItem(ctx, f) + item, err = s.mailImageFromAlbumItem(aItem) return err }) if err != nil { - if stored != nil { - _ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored)) + if uploaded != nil { + _ = album.DeleteBlobs(context.WithoutCancel(r.Context()), bucket, uploaded.AllBlobKeys()) } if errors.Is(err, attach.ErrNoAbsoluteURL) { WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url")) return } - if errors.Is(err, attach.ErrNotImage) || errors.Is(err, attach.ErrFileType) || errors.Is(err, attach.ErrMIMEType) || errors.Is(err, attach.ErrTooLarge) { + if errors.Is(err, album.ErrNotImage) || errors.Is(err, album.ErrFileType) || errors.Is(err, album.ErrTooLarge) || + errors.Is(err, attach.ErrNotImage) || errors.Is(err, attach.ErrFileType) || errors.Is(err, attach.ErrMIMEType) || errors.Is(err, attach.ErrTooLarge) { writeCRUDError(w, &ValidationError{Details: map[string]any{"file": []string{err.Error()}}}) return } @@ -268,6 +338,54 @@ func (s *service) mailImagesUpload(w http.ResponseWriter, r *http.Request) { WriteData(w, http.StatusCreated, item, nil) } +func (s *service) mailImageFromAlbumItem(a *album.Item) (AdminMailImage, error) { + cfg := s.config() + absURL, err := a.AbsolutePublicURL(cfg) + if err != nil { + return AdminMailImage{}, err + } + title := a.FileName + if strings.TrimSpace(a.Title) != "" { + title = a.Title + } + sorted := make([]album.Variant, len(a.Variants)) + copy(sorted, a.Variants) + sort.Slice(sorted, func(i, j int) bool { + return sorted[i].Width < sorted[j].Width + }) + variants := make([]AdminMediaVariant, 0, len(sorted)) + thumbURL := "" + for _, v := range sorted { + vAbs := v.URL + if v.Key != "" { + if abs, vErr := (album.Item{BlobKey: v.Key}).AbsolutePublicURL(cfg); vErr == nil { + vAbs = abs + } + } + if thumbURL == "" && vAbs != "" { + thumbURL = vAbs + } + variants = append(variants, AdminMediaVariant{ + Width: v.Width, + Height: v.Height, + URL: vAbs, + Size: v.Size, + ContentType: v.ContentType, + }) + } + if thumbURL == "" { + thumbURL = absURL + } + return AdminMailImage{ + ID: a.ID, + FileName: a.FileName, + Title: title, + URL: absURL, + ThumbURL: thumbURL, + Variants: variants, + }, nil +} + func (s *service) mailImageItem(ctx context.Context, f *attach.File) (AdminMailImage, error) { url, err := attach.AbsolutePublicURL(s.config(), attach.BlobKey(f.DiskName)) if err != nil { @@ -608,6 +726,17 @@ func (s *service) mailLogoAbsoluteURL(ctx context.Context, id uint) (string, err if err != nil { return "", err } + var aItem album.Item + err = db.WithContext(ctx). + Where("id = ? OR legacy_file_id = ?", id, id). + Order("CASE WHEN id = " + strconv.FormatUint(uint64(id), 10) + " THEN 0 ELSE 1 END"). + Take(&aItem).Error + if err == nil { + return aItem.AbsolutePublicURL(s.config()) + } + if !errors.Is(err, gorm.ErrRecordNotFound) { + return "", err + } var f attach.File err = db.WithContext(ctx). Where("id = ? AND attachment_type = ? AND field = ?", id, mailImageLibraryMorph, "images"). diff --git a/modules/cabana/media_mcp.go b/modules/cabana/media_mcp.go new file mode 100644 index 00000000..041f2344 --- /dev/null +++ b/modules/cabana/media_mcp.go @@ -0,0 +1,176 @@ +package cabana + +import ( + "net/http" + "strings" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/pact" + "git.golem15.com/golem15/summercms/modules/party" +) + +const mediaMCPPluginID = "summercms.media" + +// MediaMCPPlugin returns the framework MCP pseudo-plugin (ID "summercms.media") +// exposing the 7 built-in Media Library tools (media_prepare_upload, +// media_upload, media_list, media_get, media_update, media_delete, +// media_create_folder) bound to cabana's {adminPrefix}/api/v1/media/* routes +// under the "backend" guard. +func MediaMCPPlugin(adminPrefix string) party.Plugin { + prefix := strings.TrimRight(strings.TrimSpace(adminPrefix), "/") + if prefix == "" { + prefix = DefaultAdminPrefix + } + return mediaMCPPlugin{apiBase: prefix + adminAPIVersion} +} + +type mediaMCPPlugin struct { + apiBase string +} + +var ( + _ party.Plugin = mediaMCPPlugin{} + _ pact.HasMCP = mediaMCPPlugin{} + _ pact.HasPermissions = mediaMCPPlugin{} + _ pact.HasTokenScopes = mediaMCPPlugin{} +) + +func (mediaMCPPlugin) ID() string { return mediaMCPPluginID } +func (mediaMCPPlugin) Requires() []string { return nil } +func (mediaMCPPlugin) Register(*backpack.App) error { return nil } +func (mediaMCPPlugin) Boot(*backpack.App) error { return nil } + +func (mediaMCPPlugin) Permissions() []pact.Permission { + return mediaPermissions() +} + +func (mediaMCPPlugin) TokenScopes() []pact.TokenScope { + return mediaTokenScopes() +} + +type mediaPrepareUploadMCPInput struct { + Filename string `json:"filename" jsonschema:"Target filename including extension (for example hero.jpg or guide.pdf)"` + ContentType string `json:"content_type,omitempty" jsonschema:"Optional expected MIME type"` + FolderID *uint `json:"folder_id,omitempty" jsonschema:"Optional destination virtual folder ID"` + MaxBytes int64 `json:"max_bytes,omitempty" jsonschema:"Optional byte limit (capped by server media.max_bytes)"` +} + +type mediaUploadMCPInput struct { + Filename string `json:"filename" jsonschema:"Filename including extension (for example photo.png or report.pdf)"` + ContentBase64 string `json:"content_base64" jsonschema:"Base64-encoded file bytes (decoded size capped at media.base64_max_bytes, default 5 MB)"` + FolderID *uint `json:"folder_id,omitempty" jsonschema:"Optional destination virtual folder ID"` + Alt string `json:"alt,omitempty" jsonschema:"Optional alternative text for images"` + Title string `json:"title,omitempty" jsonschema:"Optional display title"` + Caption string `json:"caption,omitempty" jsonschema:"Optional caption"` +} + +type mediaListMCPInput struct { + FolderID string `json:"folder_id,omitempty" query:"folder_id" jsonschema:"Filter by folder ID, or 'root' for root-level items"` + RootOnly string `json:"root_only,omitempty" query:"root_only" jsonschema:"Set to '1' to list only items not in any folder"` + Query string `json:"q,omitempty" query:"q" jsonschema:"Search filename, title, alt, or slug"` + Type string `json:"type,omitempty" query:"type" jsonschema:"Filter by media type: 'image' or 'file'"` + SHA256 string `json:"sha256,omitempty" query:"sha256" jsonschema:"Filter by exact lowercase 64-char SHA-256 hex digest"` + Page int `json:"page,omitempty" query:"page" jsonschema:"Page number (1-based)"` + PerPage int `json:"per_page,omitempty" query:"per_page" jsonschema:"Items per page (1-100, default 24)"` +} + +type mediaGetMCPInput struct { + ID uint `json:"id" path:"id" jsonschema:"Media item ID"` +} + +type mediaUpdateMCPInput struct { + ID uint `json:"id" path:"id" jsonschema:"Media item ID"` + Alt *string `json:"alt,omitempty" jsonschema:"Updated alternative text"` + Title *string `json:"title,omitempty" jsonschema:"Updated display title"` + Caption *string `json:"caption,omitempty" jsonschema:"Updated caption"` + FolderID *uint `json:"folder_id,omitempty" jsonschema:"Move item to this virtual folder ID (never changes public URL)"` + ClearFolder bool `json:"clear_folder,omitempty" jsonschema:"Set true to move item to the root library (no folder)"` +} + +type mediaDeleteMCPInput struct { + ID uint `json:"id" path:"id" jsonschema:"Media item ID to permanently delete"` +} + +type mediaCreateFolderMCPInput struct { + Name string `json:"name" jsonschema:"Display name of the new virtual folder"` + ParentID *uint `json:"parent_id,omitempty" jsonschema:"Optional parent folder ID"` +} + +func (p mediaMCPPlugin) MCP() pact.MCP { + destructive := true + return pact.MCP{ + Tools: []pact.MCPTool{ + { + Name: "prepare_upload", + Title: "Prepare media upload URL", + Description: "Create a single-use signed upload URL (valid for 5 minutes) for uploading binary media up to media.max_bytes via HTTP PUT without base64 overhead.", + Method: http.MethodPost, + Path: p.apiBase + "/media/uploads/prepare", + Guard: "backend", + Permissions: []string{PermissionManageMedia}, + Input: mediaPrepareUploadMCPInput{}, + }, + { + Name: "upload", + Title: "Upload media (base64)", + Description: "Upload a file directly via base64 encoding (decoded size capped at media.base64_max_bytes, default 5 MB). Raster images automatically generate WebP srcset variants.", + Method: http.MethodPost, + Path: p.apiBase + "/media/items/base64", + Guard: "backend", + Permissions: []string{PermissionManageMedia}, + Input: mediaUploadMCPInput{}, + }, + { + Name: "list", + Title: "List media items", + Description: "List, search, and filter items in the Media Library by folder, query string, type (image/file), or SHA-256 hash.", + Method: http.MethodGet, + Path: p.apiBase + "/media/items", + Guard: "backend", + Permissions: []string{PermissionViewMedia}, + Input: mediaListMCPInput{}, + }, + { + Name: "get", + Title: "Get media item", + Description: "Fetch full metadata, public URL, WebP variants, and srcset for a single Media Library item by ID.", + Method: http.MethodGet, + Path: p.apiBase + "/media/items/{id}", + Guard: "backend", + Permissions: []string{PermissionViewMedia}, + Input: mediaGetMCPInput{}, + }, + { + Name: "update", + Title: "Update media metadata", + Description: "Update alt, title, caption, or virtual folder on a Media Library item without changing its immutable public URL.", + Method: http.MethodPut, + Path: p.apiBase + "/media/items/{id}", + Guard: "backend", + Permissions: []string{PermissionManageMedia}, + Input: mediaUpdateMCPInput{}, + }, + { + Name: "delete", + Title: "Delete media item", + Description: "Permanently delete a Media Library item and its stored original and WebP variant blobs. Published URLs referencing this item will stop working.", + Method: http.MethodDelete, + Path: p.apiBase + "/media/items/{id}", + Guard: "backend", + Permissions: []string{PermissionManageMedia}, + Destructive: &destructive, + Input: mediaDeleteMCPInput{}, + }, + { + Name: "create_folder", + Title: "Create media folder", + Description: "Create a new virtual folder in the Media Library.", + Method: http.MethodPost, + Path: p.apiBase + "/media/folders", + Guard: "backend", + Permissions: []string{PermissionManageMedia}, + Input: mediaCreateFolderMCPInput{}, + }, + }, + } +} diff --git a/modules/cabana/media_routes.go b/modules/cabana/media_routes.go new file mode 100644 index 00000000..0be17f4c --- /dev/null +++ b/modules/cabana/media_routes.go @@ -0,0 +1,690 @@ +package cabana + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "io" + "math" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "time" + + "git.golem15.com/golem15/summercms/modules/album" + "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/lagoon" + "gorm.io/gorm" +) + +// AdminMediaFolder is a virtual folder returned by the admin Media Library API. +type AdminMediaFolder struct { + ID uint `json:"id"` + ParentID *uint `json:"parent_id,omitempty"` + Name string `json:"name"` + Slug string `json:"slug"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +// AdminMediaFolderRequest is the body of POST /media/folders and PUT /media/folders/{id}. +type AdminMediaFolderRequest struct { + Name string `json:"name,omitempty"` + ParentID *uint `json:"parent_id,omitempty"` + ClearParent bool `json:"clear_parent,omitempty"` +} + +// AdminMediaVariant is one generated WebP responsive variant on an AdminMediaItem. +type AdminMediaVariant struct { + Width int `json:"width"` + Height int `json:"height"` + URL string `json:"url"` + Size int64 `json:"size"` + ContentType string `json:"content_type"` +} + +// AdminMediaItem is one Media Library item returned by /media/items endpoints. +type AdminMediaItem struct { + ID uint `json:"id"` + ShortID string `json:"short_id"` + FolderID *uint `json:"folder_id,omitempty"` + FileName string `json:"file_name"` + Slug string `json:"slug"` + ContentType string `json:"content_type"` + FileSize int64 `json:"file_size"` + Width *int `json:"width,omitempty"` + Height *int `json:"height,omitempty"` + SHA256 string `json:"sha256"` + Alt string `json:"alt"` + Title string `json:"title"` + Caption string `json:"caption"` + URL string `json:"url"` + ThumbURL string `json:"thumb_url,omitempty"` + Srcset string `json:"srcset,omitempty"` + IsImage bool `json:"is_image"` + Variants []AdminMediaVariant `json:"variants"` + UploadedBy *uint `json:"uploaded_by,omitempty"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +// AdminMediaItemsMeta is the pagination and capability meta of GET /media/items. +type AdminMediaItemsMeta struct { + Page int `json:"page"` + PerPage int `json:"per_page"` + Total int64 `json:"total"` + LastPage int `json:"last_page"` + CanManage bool `json:"can_manage"` +} + +// AdminMediaItemsResponse is the GET /media/items answer. +type AdminMediaItemsResponse struct { + Data []AdminMediaItem `json:"data"` + Meta AdminMediaItemsMeta `json:"meta"` +} + +// AdminMediaBase64UploadRequest is the body of POST /media/items/base64. +type AdminMediaBase64UploadRequest struct { + Filename string `json:"filename"` + ContentBase64 string `json:"content_base64"` + FolderID *uint `json:"folder_id,omitempty"` + Alt string `json:"alt,omitempty"` + Title string `json:"title,omitempty"` + Caption string `json:"caption,omitempty"` +} + +// AdminMediaItemUpdateRequest is the body of PUT /media/items/{id}. +type AdminMediaItemUpdateRequest struct { + Alt *string `json:"alt,omitempty"` + Title *string `json:"title,omitempty"` + Caption *string `json:"caption,omitempty"` + FolderID *uint `json:"folder_id,omitempty"` + ClearFolder bool `json:"clear_folder,omitempty"` +} + +// AdminMediaPrepareUploadRequest is the body of POST /media/uploads/prepare. +type AdminMediaPrepareUploadRequest struct { + Filename string `json:"filename"` + ContentType string `json:"content_type,omitempty"` + FolderID *uint `json:"folder_id,omitempty"` + MaxBytes int64 `json:"max_bytes,omitempty"` +} + +// AdminMediaPrepareUploadResult is the data of POST /media/uploads/prepare. +type AdminMediaPrepareUploadResult struct { + UploadURL string `json:"upload_url"` + Method string `json:"method"` + ExpiresAt string `json:"expires_at"` + MaxBytes int64 `json:"max_bytes"` +} + +// AdminMediaDeleteResult is the data of DELETE /media/folders/{id} and DELETE /media/items/{id}. +type AdminMediaDeleteResult struct { + Deleted bool `json:"deleted"` +} + +func (s *service) albumService() *album.Service { + if s != nil && s.app != nil { + if svc, ok := album.ServiceFrom(s.app); ok && svc != nil { + return svc + } + } + return album.NewService(s.config()) +} + +func mediaCanView(p *bouncer.Principal) bool { + return Allows(p, []string{PermissionViewMedia}) || Allows(p, []string{PermissionManageMedia}) +} + +func mediaCanManage(p *bouncer.Principal) bool { + return Allows(p, []string{PermissionManageMedia}) +} + +func (s *service) mediaAuth(w http.ResponseWriter, r *http.Request, manage bool) (*bouncer.Principal, bool) { + principal, ok := bouncer.User(r.Context()) + if !ok || principal == nil || !principal.Backend { + WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated) + return nil, false + } + if manage { + if !mediaCanManage(principal) { + WriteError(w, http.StatusForbidden, "forbidden", msgForbidden) + return nil, false + } + } else { + if !mediaCanView(principal) { + WriteError(w, http.StatusForbidden, "forbidden", msgForbidden) + return nil, false + } + } + return principal, true +} + +func (s *service) mediaFolderView(f album.Folder) AdminMediaFolder { + return AdminMediaFolder{ + ID: f.ID, + ParentID: f.ParentID, + Name: f.Name, + Slug: f.Slug, + CreatedAt: f.CreatedAt.UTC().Format(time.RFC3339), + UpdatedAt: f.UpdatedAt.UTC().Format(time.RFC3339), + } +} + +func (s *service) mediaItemView(item album.Item) AdminMediaItem { + cfg := s.config() + pubURL := item.PublicURL(cfg) + variants := make([]AdminMediaVariant, 0, len(item.Variants)) + sorted := make([]album.Variant, len(item.Variants)) + copy(sorted, item.Variants) + sort.Slice(sorted, func(i, j int) bool { + return sorted[i].Width < sorted[j].Width + }) + thumbURL := "" + for _, v := range sorted { + vURL := v.URL + if vURL == "" && v.Key != "" { + vURL = album.Item{BlobKey: v.Key}.PublicURL(cfg) + } + if thumbURL == "" && vURL != "" { + thumbURL = vURL + } + variants = append(variants, AdminMediaVariant{ + Width: v.Width, + Height: v.Height, + URL: vURL, + Size: v.Size, + ContentType: v.ContentType, + }) + } + if thumbURL == "" && item.IsImage() { + thumbURL = pubURL + } + return AdminMediaItem{ + ID: item.ID, + ShortID: item.ShortID, + FolderID: item.FolderID, + FileName: item.FileName, + Slug: item.Slug, + ContentType: item.ContentType, + FileSize: item.FileSize, + Width: item.Width, + Height: item.Height, + SHA256: item.SHA256, + Alt: item.Alt, + Title: item.Title, + Caption: item.Caption, + URL: pubURL, + ThumbURL: thumbURL, + Srcset: item.Srcset(cfg), + IsImage: item.IsImage(), + Variants: variants, + UploadedBy: item.UploadedBy, + CreatedAt: item.CreatedAt.UTC().Format(time.RFC3339), + UpdatedAt: item.UpdatedAt.UTC().Format(time.RFC3339), + } +} + +func writeMediaError(w http.ResponseWriter, err error) { + var tooBig *http.MaxBytesError + switch { + case errors.Is(err, album.ErrNotFound), errors.Is(err, album.ErrFolderNotFound): + WriteError(w, http.StatusNotFound, "not_found", msgNotFound) + case errors.Is(err, album.ErrFolderNotEmpty): + WriteError(w, http.StatusConflict, "conflict", err.Error()) + case errors.Is(err, album.ErrTooLarge), errors.As(err, &tooBig): + WriteError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "The uploaded file exceeds the maximum allowed size.") + case errors.Is(err, album.ErrFileType), errors.Is(err, album.ErrNotImage), errors.Is(err, album.ErrInvalidFolder): + WriteError(w, http.StatusUnprocessableEntity, "validation_failed", err.Error()) + default: + writeCRUDError(w, err) + } +} + +func (s *service) mediaFoldersList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, false); !ok { + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + folders, err := s.albumService().ListFolders(r.Context(), db) + if err != nil { + writeMediaError(w, err) + return + } + out := make([]AdminMediaFolder, 0, len(folders)) + for _, f := range folders { + out = append(out, s.mediaFolderView(f)) + } + WriteData(w, http.StatusOK, out, nil) +} + +func (s *service) mediaFoldersCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, true); !ok { + return + } + var req AdminMediaFolderRequest + if err := s.decodeStrictBody(w, r, &req); err != nil { + writeCRUDError(w, err) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + folder, err := s.albumService().CreateFolder(r.Context(), db, req.Name, req.ParentID) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusCreated, s.mediaFolderView(*folder), nil) +} + +func (s *service) mediaFoldersUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, true); !ok { + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + var req AdminMediaFolderRequest + if err := s.decodeStrictBody(w, r, &req); err != nil { + writeCRUDError(w, err) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + setParent := req.ClearParent || req.ParentID != nil + parentID := req.ParentID + if req.ClearParent { + parentID = nil + } + folder, err := s.albumService().UpdateFolder(r.Context(), db, uint(id), req.Name, parentID, setParent) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusOK, s.mediaFolderView(*folder), nil) +} + +func (s *service) mediaFoldersDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, true); !ok { + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + if err := s.albumService().DeleteFolder(r.Context(), db, uint(id)); err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusOK, AdminMediaDeleteResult{Deleted: true}, nil) +} + +func (s *service) mediaItemsList(w http.ResponseWriter, r *http.Request) { + principal, ok := s.mediaAuth(w, r, false) + if !ok { + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + q := r.URL.Query() + filter := album.ListFilter{ + Query: strings.TrimSpace(q.Get("q")), + Type: strings.TrimSpace(q.Get("type")), + SHA256: strings.TrimSpace(q.Get("sha256")), + Page: 1, + } + if raw := strings.TrimSpace(q.Get("folder_id")); raw != "" { + if raw == "root" || raw == "0" { + filter.RootOnly = true + } else if parsed, err := strconv.ParseUint(raw, 10, 64); err == nil && parsed > 0 { + fid := uint(parsed) + filter.FolderID = &fid + } + } + if raw := strings.TrimSpace(q.Get("root_only")); raw == "1" || strings.EqualFold(raw, "true") { + filter.RootOnly = true + } + if raw := strings.TrimSpace(q.Get("page")); raw != "" { + if n, err := strconv.Atoi(raw); err == nil && n > 0 { + filter.Page = n + } + } + perPage := 24 + if raw := strings.TrimSpace(q.Get("per_page")); raw != "" { + if n, err := strconv.Atoi(raw); err == nil && n > 0 { + if n > 100 { + n = 100 + } + perPage = n + } + } + filter.PerPage = perPage + + items, total, err := s.albumService().ListItems(r.Context(), db, filter) + if err != nil { + writeMediaError(w, err) + return + } + out := make([]AdminMediaItem, 0, len(items)) + for _, it := range items { + out = append(out, s.mediaItemView(it)) + } + lastPage := 1 + if total > 0 { + lastPage = int(math.Ceil(float64(total) / float64(perPage))) + } + WriteData(w, http.StatusOK, out, AdminMediaItemsMeta{ + Page: filter.Page, + PerPage: perPage, + Total: total, + LastPage: lastPage, + CanManage: mediaCanManage(principal), + }) +} + +func (s *service) mediaItemsShow(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, false); !ok { + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + item, err := s.albumService().GetItem(r.Context(), db, uint(id)) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusOK, s.mediaItemView(*item), nil) +} + +func (s *service) mediaItemsUpload(w http.ResponseWriter, r *http.Request) { + principal, ok := s.mediaAuth(w, r, true) + if !ok { + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + bucket := s.bucket() + if bucket == nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + + maxBytes := album.MaxBytes(s.config()) + capBytes := maxBytes + multipartOverhead + if s.uploadBytes > 0 && s.uploadBytes < capBytes { + capBytes = s.uploadBytes + } + r.Body = http.MaxBytesReader(w, r.Body, capBytes) + if err := r.ParseMultipartForm(4 << 20); err != nil { + writeMediaError(w, err) + return + } + if r.MultipartForm != nil { + defer func() { _ = r.MultipartForm.RemoveAll() }() + } + + file, header, err := r.FormFile("file") + if err != nil || header == nil || strings.TrimSpace(header.Filename) == "" { + writeCRUDError(w, invalidBody()) + return + } + defer func() { _ = file.Close() }() + + var folderID *uint + if raw := strings.TrimSpace(r.FormValue("folder_id")); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 64) + if err != nil || parsed == 0 { + WriteError(w, http.StatusUnprocessableEntity, "validation_failed", "folder_id must be a positive integer.") + return + } + fid := uint(parsed) + folderID = &fid + } + uid := principal.ID + item, err := s.albumService().Upload(r.Context(), db, bucket, album.UploadInput{ + FileName: header.Filename, + Body: file, + FolderID: folderID, + Alt: r.FormValue("alt"), + Title: r.FormValue("title"), + Caption: r.FormValue("caption"), + UploadedBy: &uid, + MaxBytes: maxBytes, + }) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusCreated, s.mediaItemView(*item), nil) +} + +func (s *service) mediaItemsUploadBase64(w http.ResponseWriter, r *http.Request) { + principal, ok := s.mediaAuth(w, r, true) + if !ok { + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + bucket := s.bucket() + if bucket == nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + + maxBytes := album.Base64MaxBytes(s.config()) + // Base64 expands bytes by 4/3; add JSON envelope headroom. + jsonCap := (maxBytes*4)/3 + (128 << 10) + r.Body = http.MaxBytesReader(w, r.Body, jsonCap) + + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + var req AdminMediaBase64UploadRequest + if err := dec.Decode(&req); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + writeMediaError(w, album.ErrTooLarge) + return + } + writeCRUDError(w, invalidBody()) + return + } + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + writeCRUDError(w, invalidBody()) + return + } + if strings.TrimSpace(req.Filename) == "" || strings.TrimSpace(req.ContentBase64) == "" { + WriteError(w, http.StatusUnprocessableEntity, "validation_failed", "filename and content_base64 are required.") + return + } + + rawB64 := strings.TrimSpace(req.ContentBase64) + if idx := strings.Index(rawB64, ","); idx >= 0 && strings.HasPrefix(strings.ToLower(rawB64[:idx]), "data:") { + rawB64 = strings.TrimSpace(rawB64[idx+1:]) + } + decoded, err := base64.StdEncoding.DecodeString(rawB64) + if err != nil { + decoded, err = base64.RawStdEncoding.DecodeString(rawB64) + } + if err != nil { + WriteError(w, http.StatusUnprocessableEntity, "validation_failed", "content_base64 is not valid base64.") + return + } + if int64(len(decoded)) > maxBytes { + writeMediaError(w, album.ErrTooLarge) + return + } + + uid := principal.ID + item, err := s.albumService().Upload(r.Context(), db, bucket, album.UploadInput{ + FileName: req.Filename, + Body: bytes.NewReader(decoded), + FolderID: req.FolderID, + Alt: req.Alt, + Title: req.Title, + Caption: req.Caption, + UploadedBy: &uid, + MaxBytes: maxBytes, + }) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusCreated, s.mediaItemView(*item), nil) +} + +func (s *service) mediaItemsUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, true); !ok { + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + var req AdminMediaItemUpdateRequest + if err := s.decodeStrictBody(w, r, &req); err != nil { + writeCRUDError(w, err) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + item, err := s.albumService().UpdateItem(r.Context(), db, uint(id), album.UpdatePatch{ + Alt: req.Alt, + Title: req.Title, + Caption: req.Caption, + FolderID: req.FolderID, + ClearFolder: req.ClearFolder, + }) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusOK, s.mediaItemView(*item), nil) +} + +// mediaItemsDelete removes the item row inside lagoon.Transaction and deletes +// its original and WebP variant blobs strictly via lagoon.AfterCommit (D-12). +func (s *service) mediaItemsDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.mediaAuth(w, r, true); !ok { + return + } + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeNotFound(w, r) + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + bucket := s.bucket() + albumSvc := s.albumService() + err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error { + keys, txErr := albumSvc.DeleteItemInTx(ctx, tx, uint(id)) + if txErr != nil { + return txErr + } + if bucket != nil && len(keys) > 0 { + lagoon.AfterCommit(ctx, tx, func(acCtx context.Context, _ *gorm.DB) { + _ = album.DeleteBlobs(context.WithoutCancel(acCtx), bucket, keys) + }) + } + return nil + }) + if err != nil { + writeMediaError(w, err) + return + } + WriteData(w, http.StatusOK, AdminMediaDeleteResult{Deleted: true}, nil) +} + +func (s *service) mediaPrepareUpload(w http.ResponseWriter, r *http.Request) { + principal, ok := s.mediaAuth(w, r, true) + if !ok { + return + } + var req AdminMediaPrepareUploadRequest + if err := s.decodeStrictBody(w, r, &req); err != nil { + writeCRUDError(w, err) + return + } + if strings.TrimSpace(req.Filename) == "" { + WriteError(w, http.StatusUnprocessableEntity, "validation_failed", "filename is required.") + return + } + db, err := s.db() + if err != nil { + WriteError(w, http.StatusInternalServerError, "error", msgServerError) + return + } + prepared, err := s.albumService().PrepareUpload(r.Context(), db, album.PrepareUploadInput{ + CreatedBy: principal.ID, + FolderID: req.FolderID, + ExpectedFilename: req.Filename, + ExpectedContentType: req.ContentType, + MaxBytes: req.MaxBytes, + }) + if err != nil { + writeMediaError(w, err) + return + } + uploadPath := album.PublicPathPrefix(s.config()) + "/upload/" + prepared.Token + uploadURL := uploadPath + if cfg := s.config(); cfg != nil { + if raw := strings.TrimSpace(cfg.String("app.url")); raw != "" { + if u, parseErr := url.Parse(raw); parseErr == nil && u.Host != "" && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) { + base := u.Scheme + "://" + u.Host + strings.TrimRight(u.Path, "/") + uploadURL = base + "/" + strings.TrimLeft(uploadPath, "/") + } + } + } + WriteData(w, http.StatusCreated, AdminMediaPrepareUploadResult{ + UploadURL: uploadURL, + Method: http.MethodPut, + ExpiresAt: prepared.ExpiresAt.UTC().Format(time.RFC3339), + MaxBytes: prepared.MaxBytes, + }, nil) +} diff --git a/modules/cabana/openapi_conformance_test.go b/modules/cabana/openapi_conformance_test.go index 6dab3640..3659d841 100644 --- a/modules/cabana/openapi_conformance_test.go +++ b/modules/cabana/openapi_conformance_test.go @@ -491,6 +491,71 @@ func conformCases() []conformCase { }, }, true) }, into[cabana.Envelope[cabana.AdminMailTestSendResult]](), nil}, + {"POST /media/folders", 201, "cabana.Envelope-cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + rec := e.send(t, http.MethodPost, "/media/folders", map[string]any{"name": "Conform " + e.stamp}, true) + var body cabana.Envelope[cabana.AdminMediaFolder] + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("media folder create: %v body=%s", err, rec.Body.String()) + } + e.mediaFolderID = body.Data.ID + return rec + }, into[cabana.Envelope[cabana.AdminMediaFolder]](), nil}, + {"GET /media/folders", 200, "cabana.Envelope-array_cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodGet, "/media/folders", nil, true) + }, into[cabana.Envelope[[]cabana.AdminMediaFolder]](), nil}, + {"PUT /media/folders/{id}", 200, "cabana.Envelope-cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodPut, fmt.Sprintf("/media/folders/%d", e.mediaFolderID), map[string]any{"name": "Conform Renamed " + e.stamp}, true) + }, into[cabana.Envelope[cabana.AdminMediaFolder]](), nil}, + {"POST /media/items", 201, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + part, err := mw.CreateFormFile("file", "media-conform.png") + if err != nil { + t.Fatal(err) + } + if _, err := part.Write(conformPNG(t)); err != nil { + t.Fatal(err) + } + if err := mw.WriteField("folder_id", fmt.Sprintf("%d", e.mediaFolderID)); err != nil { + t.Fatal(err) + } + if err := mw.Close(); err != nil { + t.Fatal(err) + } + rec := e.sendWith(t, http.MethodPost, "/media/items", buf.Bytes(), mw.FormDataContentType(), map[string]string{"X-Requested-With": "XMLHttpRequest"}) + var body cabana.Envelope[cabana.AdminMediaItem] + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("media item upload: %v body=%s", err, rec.Body.String()) + } + e.mediaItemID = body.Data.ID + return rec + }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, + {"POST /media/items/base64", 201, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + rec := e.send(t, http.MethodPost, "/media/items/base64", map[string]any{ + "filename": "media-b64.png", + "content_base64": base64.StdEncoding.EncodeToString(conformPNG(t)), + "alt": "Conform b64", + }, true) + return rec + }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, + {"GET /media/items", 200, "cabana.AdminMediaItemsResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodGet, "/media/items", nil, true) + }, into[cabana.AdminMediaItemsResponse](), nil}, + {"GET /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodGet, fmt.Sprintf("/media/items/%d", e.mediaItemID), nil, true) + }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, + {"PUT /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodPut, fmt.Sprintf("/media/items/%d", e.mediaItemID), map[string]any{"alt": "Updated alt", "title": "Updated title"}, true) + }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, + {"POST /media/uploads/prepare", 201, "cabana.Envelope-cabana_AdminMediaPrepareUploadResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodPost, "/media/uploads/prepare", map[string]any{"filename": "prepared.png", "content_type": "image/png"}, true) + }, into[cabana.Envelope[cabana.AdminMediaPrepareUploadResult]](), nil}, + {"DELETE /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaDeleteResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodDelete, fmt.Sprintf("/media/items/%d", e.mediaItemID), nil, true) + }, into[cabana.Envelope[cabana.AdminMediaDeleteResult]](), nil}, + {"DELETE /media/folders/{id}", 200, "cabana.Envelope-cabana_AdminMediaDeleteResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { + return e.send(t, http.MethodDelete, fmt.Sprintf("/media/folders/%d", e.mediaFolderID), nil, true) + }, into[cabana.Envelope[cabana.AdminMediaDeleteResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/schema/list", 200, "cabana.Envelope-cabana_ListSchema", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/list", nil, true) var body cabana.Envelope[cabana.ListSchema] @@ -908,8 +973,10 @@ type conformEnv struct { partID uint partFileID uint childKey string - tokenID uint - mailImageID uint + tokenID uint + mailImageID uint + mediaFolderID uint + mediaItemID uint } // sendWith sends a raw body with extra headers through the assembled router. diff --git a/modules/cabana/phase10_coverage_test.go b/modules/cabana/phase10_coverage_test.go index 389a3b34..0112f817 100644 --- a/modules/cabana/phase10_coverage_test.go +++ b/modules/cabana/phase10_coverage_test.go @@ -90,6 +90,8 @@ func TestPhase10Coverage(t *testing.T) { want := []string{ "DELETE /account/avatar", "DELETE /account/tokens/{id}", + "DELETE /media/folders/{id}", + "DELETE /media/items/{id}", "DELETE /{vendor}/{plugin}/{controller}/{id}", "DELETE /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}", "DELETE /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}", @@ -105,6 +107,10 @@ func TestPhase10Coverage(t *testing.T) { "POST /mail/test-send", "POST /markdown/preview", "POST /mcp/consent/{request}", + "POST /media/folders", + "POST /media/items", + "POST /media/items/base64", + "POST /media/uploads/prepare", "POST /{vendor}/{plugin}/{controller}", "POST /{vendor}/{plugin}/{controller}/bulk-delete", "POST /{vendor}/{plugin}/{controller}/bulk/{action}", @@ -123,6 +129,8 @@ func TestPhase10Coverage(t *testing.T) { "POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/unlink", "PUT /account", "PUT /account/preferences", + "PUT /media/folders/{id}", + "PUT /media/items/{id}", "PUT /settings/{code}", "PUT /{vendor}/{plugin}/{controller}/{id}", "PUT /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}", diff --git a/modules/cabana/phase10_csrf_test.go b/modules/cabana/phase10_csrf_test.go index c3849d16..74cca30d 100644 --- a/modules/cabana/phase10_csrf_test.go +++ b/modules/cabana/phase10_csrf_test.go @@ -74,9 +74,9 @@ func TestPhase10CSRF(t *testing.T) { // update, child file upload, reorder, caption and remove, plugin field // type upload, tree reorder save, account contribution action, // mail image upload, mail preview, mail test-send, MCP consent decision, - // account contribution item action - if unsafe != 40 { - t.Fatalf("walked %d state-changing routes, want 40: %v", unsafe, router.order) + // account contribution item action, and 8 media library write routes. + if unsafe != 48 { + t.Fatalf("walked %d state-changing routes, want 48: %v", unsafe, router.order) } loginHandler := router.handlers[login] diff --git a/modules/cabana/phase121_schema_boot_test.go b/modules/cabana/phase121_schema_boot_test.go index 30b75285..107e9eef 100644 --- a/modules/cabana/phase121_schema_boot_test.go +++ b/modules/cabana/phase121_schema_boot_test.go @@ -169,7 +169,7 @@ func TestPhase121BootErrors(t *testing.T) { {name: "permissioneditor with a default", files: map[string]string{rosterFieldsFile: rosterFields(t, " mode: radio\n", " mode: radio\n default: 1\n")}, want: "default is not valid on type: permissioneditor", file: rosterFieldsFile}, {name: "mode on another type", files: map[string]string{rosterFieldsFile: rosterFields(t, " type: checkbox\n default: true\n", " type: checkbox\n default: true\n mode: radio\n")}, - want: "mode is only valid on type: fileupload, datepicker, permissioneditor, taglist or mailpreview", file: rosterFieldsFile}, + want: "mode is only valid on type: fileupload, mediafinder, datepicker, permissioneditor, taglist or mailpreview", file: rosterFieldsFile}, // Relation fields (D-27 G3) and controller filter choices. {name: "WritableForeignKey on belongsToMany", plugin: relations(func(in []cabana.FieldRelationContract) { in[1].WritableForeignKey = true }), want: "field tags: WritableForeignKey is only valid on belongsTo"}, diff --git a/modules/cabana/schema_types.go b/modules/cabana/schema_types.go index 3f46f9f4..2537aed6 100644 --- a/modules/cabana/schema_types.go +++ b/modules/cabana/schema_types.go @@ -318,11 +318,13 @@ type FormField struct { // template {ConfigDir}/_{path}.htm (D-09). Path string `json:"path,omitempty"` // Mode is the fileupload mode (image or file, default file), the - // datepicker mode (date, datetime or time, default datetime), the - // permissioneditor mode (radio or checkbox), the taglist mode (string, - // the default, or array), or the mailpreview mode (template, layout, - // partial or branding). + // mediafinder mode (image or file, default image), the datepicker mode + // (date, datetime or time, default datetime), the permissioneditor mode + // (radio or checkbox), the taglist mode (string, the default, or array), + // or the mailpreview mode (template, layout, partial or branding). Mode string `json:"mode,omitempty"` + // Folder is the optional default virtual folder slug for a `type: mediafinder` field. + Folder string `json:"folder,omitempty"` // Language is the codeeditor language: html, css or text. Language string `json:"language,omitempty"` // MailImages, when true, shows the mail image insert control on a diff --git a/modules/cabana/security_coverage_test.go b/modules/cabana/security_coverage_test.go index d6101d28..8e08bc3b 100644 --- a/modules/cabana/security_coverage_test.go +++ b/modules/cabana/security_coverage_test.go @@ -67,6 +67,17 @@ var phase09Routes = []adminRoute{ {key: "POST /mail/images"}, {key: "POST /mail/preview"}, {key: "POST /mail/test-send"}, + {key: "GET /media/folders"}, + {key: "POST /media/folders"}, + {key: "PUT /media/folders/{id}"}, + {key: "DELETE /media/folders/{id}"}, + {key: "GET /media/items"}, + {key: "GET /media/items/{id}"}, + {key: "POST /media/items"}, + {key: "POST /media/items/base64"}, + {key: "PUT /media/items/{id}"}, + {key: "DELETE /media/items/{id}"}, + {key: "POST /media/uploads/prepare"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/list"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/form"}, {key: "GET /{vendor}/{plugin}/{controller}/schema/relation/{name}"}, @@ -371,6 +382,17 @@ func phase09ProtectedCalls() []phase09Call { {"mail-images-list", (*service).mailImagesList}, {"mail-images-show", (*service).mailImagesShow}, {"mail-images-upload", (*service).mailImagesUpload}, + {"media-folders-list", (*service).mediaFoldersList}, + {"media-folders-create", (*service).mediaFoldersCreate}, + {"media-folders-update", (*service).mediaFoldersUpdate}, + {"media-folders-delete", (*service).mediaFoldersDelete}, + {"media-items-list", (*service).mediaItemsList}, + {"media-items-show", (*service).mediaItemsShow}, + {"media-items-upload", (*service).mediaItemsUpload}, + {"media-items-upload-base64", (*service).mediaItemsUploadBase64}, + {"media-items-update", (*service).mediaItemsUpdate}, + {"media-items-delete", (*service).mediaItemsDelete}, + {"media-prepare-upload", (*service).mediaPrepareUpload}, } } diff --git a/modules/cabana/token_commands.go b/modules/cabana/token_commands.go index 2097aa62..90dba777 100644 --- a/modules/cabana/token_commands.go +++ b/modules/cabana/token_commands.go @@ -11,6 +11,7 @@ import ( "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/bonfire" + "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/party" "git.golem15.com/golem15/summercms/modules/phrasebook" "gorm.io/gorm" @@ -99,15 +100,33 @@ permissions it needs. --json prints them as a JSON array.`, } func tokenCatalogForApp(app *backpack.App) (*Registry, error) { + if guard := publishedResolverGuard(app); guard != nil && guard.reg != nil && guard.reg.tokenScopes != nil { + return guard.reg, nil + } plugins := []party.Plugin{} if app != nil { if activated, ok := app.Lookup[party.Activated](); ok && activated != nil { plugins = []party.Plugin(activated) } } + if hasAdminControllers(plugins) { + plugins, _ = withBackendScreens(app, plugins) + } return compileTokenCatalog(plugins) } +func hasAdminControllers(plugins []party.Plugin) bool { + for _, p := range plugins { + if p == nil { + continue + } + if src, ok := p.(pact.HasAdminControllers); ok && src != nil && len(src.AdminControllers()) > 0 { + return true + } + } + return false +} + func adminTokenCreate(ctx context.Context, app *backpack.App, in bonfire.Input, out bonfire.Output) error { identifier := argValue(in, "identifier") if identifier == "" { diff --git a/modules/cabana/token_routes_test.go b/modules/cabana/token_routes_test.go index 122debf3..9e81ab90 100644 --- a/modules/cabana/token_routes_test.go +++ b/modules/cabana/token_routes_test.go @@ -63,6 +63,17 @@ var tokenRouteClasses = map[string]tokenRouteClass{ "POST /mail/images": classExplicitGate, "POST /mail/preview": classExplicitGate, "POST /mail/test-send": classInteractive, + "GET /media/folders": classAllowsProtect, + "POST /media/folders": classAllowsProtect, + "PUT /media/folders/{id}": classAllowsProtect, + "DELETE /media/folders/{id}": classAllowsProtect, + "GET /media/items": classAllowsProtect, + "GET /media/items/{id}": classAllowsProtect, + "POST /media/items": classAllowsProtect, + "POST /media/items/base64": classAllowsProtect, + "PUT /media/items/{id}": classAllowsProtect, + "DELETE /media/items/{id}": classAllowsProtect, + "POST /media/uploads/prepare": classAllowsProtect, "GET /{vendor}/{plugin}/{controller}/schema/list": classAllowsProtect, "GET /{vendor}/{plugin}/{controller}/schema/form": classAllowsProtect, diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml index 72acac5e..abe51c32 100644 --- a/modules/phrasebook/backend/lang/en/lang.yaml +++ b/modules/phrasebook/backend/lang/en/lang.yaml @@ -11,6 +11,7 @@ auth: session_expired: Your session has expired. Please sign in again. nav: plugins: Plugins + media: Media sections: Sections breadcrumbs: Breadcrumbs empty: No sections are available. @@ -325,6 +326,11 @@ api_tokens: scope_all_description: Everything you can do in the admin. Your account settings and tokens still need a signed-in session. scope_admin_read: Read-only, whole admin scope_admin_read_description: View everything you can see in the admin, without making changes. + group_media: Media Library + scope_media: Media Library (full) + scope_media_description: Browse, upload, organize folders, edit metadata, and delete items in the Media Library. + scope_media_read: Media Library (read-only) + scope_media_read_description: Browse, search, and inspect items in the Media Library without making changes. scope_unavailable: The scope :name is not available to you. read_only: Read-only scope_all_includes: Full access already includes every other scope. @@ -672,6 +678,9 @@ permissions: manage_mail_templates_comment: "Edit mail templates, preview them and send test messages to yourself." manage_mail_layouts: "Manage mail layouts and branding" manage_mail_layouts_comment: "Edit mail layouts, partials, branding and the mail image library. These change every message the application sends." + tab_media: "Media" + view_media: "View media library" + manage_media: "Manage media library" version: available: "A new version of the admin is available." reload: "Reload" @@ -856,3 +865,62 @@ mailimage: change: "Change image" remove: "Remove image" missing: "This image is no longer in the library. Choose another one." +media: + title: "Media" + all_files: "All files" + root_folder: "Unfiled" + folders: "Folders" + new_folder: "New folder" + folder_name: "Folder name" + folder_name_placeholder: "e.g. Blog photos" + rename_folder: "Rename folder" + delete_folder: "Delete folder" + folder_delete_confirm: "Delete folder “:name”? Only empty folders can be deleted." + folder_not_empty: "This folder is not empty. Move or delete its items and subfolders first." + folder_created: "Folder created" + folder_updated: "Folder updated" + folder_deleted: "Folder deleted" + upload: "Upload" + uploading: "Uploading…" + drop_hint: "Drop files here to upload" + upload_done: "File uploaded" + upload_failed: "The file could not be uploaded. Try again." + search_placeholder: "Search by filename, title, or alt…" + filter_all: "All types" + filter_images: "Images" + filter_files: "Files" + view_grid: "Grid view" + view_list: "List view" + empty_title: "No media items yet" + empty_body: "Upload images or files to build your shared media library." + empty_search: "No media items match your search." + load_failed: "The media library could not be loaded. Refresh the page to try again." + inspector_title: "Details" + alt: "Alternative text" + alt_placeholder: "Describe the image for screen readers" + item_title: "Title" + caption: "Caption" + folder: "Folder" + no_folder: "None (root)" + url: "Public URL" + copy_url: "Copy URL" + url_copied: "URL copied" + dimensions: "Dimensions" + size: "Size" + content_type: "Type" + sha256: "SHA-256" + variants: "WebP variants" + save: "Save details" + saved: "Media details saved" + delete: "Delete item" + delete_confirm_title: "Delete this media item?" + delete_confirm_body: "Deleting “:name” permanently removes the file and its WebP variants. Any published posts, pages, or emails referencing its URL will stop displaying it." + deleted: "Media item deleted" + picker_title: "Choose from Media Library" + picker_select: "Select" + picker_select_count: "Select (:count)" + finder_empty: "No media selected" + finder_choose: "Choose media" + finder_add: "Add media" + finder_change: "Change" + finder_remove: "Remove" diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml index 3b3bcecc..eddcbf86 100644 --- a/modules/phrasebook/backend/lang/pl/lang.yaml +++ b/modules/phrasebook/backend/lang/pl/lang.yaml @@ -13,6 +13,7 @@ auth: session_expired: Sesja wygasła. Zaloguj się ponownie. nav: plugins: Wtyczki + media: Media sections: Sekcje breadcrumbs: Ścieżka nawigacji empty: Brak dostępnych sekcji. @@ -347,6 +348,11 @@ api_tokens: scope_all_description: Wszystko, co możesz zrobić w panelu. Ustawienia konta i tokeny nadal wymagają zalogowania. scope_admin_read: Tylko odczyt, cały panel scope_admin_read_description: Podgląd wszystkiego, co widzisz w panelu, bez wprowadzania zmian. + group_media: Biblioteka mediów + scope_media: Biblioteka mediów (pełny) + scope_media_description: Przeglądanie, przesyłanie, organizacja folderów, edycja metadanych i usuwanie plików w Bibliotece mediów. + scope_media_read: Biblioteka mediów (tylko odczyt) + scope_media_read_description: Przeglądanie, wyszukiwanie i podgląd plików w Bibliotece mediów bez wprowadzania zmian. scope_unavailable: Zakres :name nie jest dla Ciebie dostępny. read_only: Tylko odczyt scope_all_includes: Pełny dostęp obejmuje wszystkie pozostałe zakresy. @@ -714,6 +720,9 @@ permissions: manage_mail_templates_comment: "Edycja szablonów wiadomości, ich podgląd i wysyłanie wiadomości testowych do siebie." manage_mail_layouts: "Zarządzanie układami i wyglądem wiadomości" manage_mail_layouts_comment: "Edycja układów, fragmentów i wyglądu wiadomości oraz biblioteki obrazów. Zmiany dotyczą każdej wiadomości wysyłanej przez aplikację." + tab_media: "Media" + view_media: "Przeglądanie biblioteki mediów" + manage_media: "Zarządzanie biblioteką mediów" version: available: "Dostępna jest nowa wersja panelu." reload: "Odśwież" @@ -900,3 +909,62 @@ mailimage: change: "Zmień obraz" remove: "Usuń obraz" missing: "Tego obrazu nie ma już w bibliotece. Wybierz inny." +media: + title: "Media" + all_files: "Wszystkie pliki" + root_folder: "Bez folderu" + folders: "Foldery" + new_folder: "Nowy folder" + folder_name: "Nazwa folderu" + folder_name_placeholder: "np. Zdjęcia blogowe" + rename_folder: "Zmień nazwę folderu" + delete_folder: "Usuń folder" + folder_delete_confirm: "Usunąć folder „:name”? Można usuwać tylko puste foldery." + folder_not_empty: "Ten folder nie jest pusty. Najpierw przenieś lub usuń jego pliki i podfoldery." + folder_created: "Utworzono folder" + folder_updated: "Zaktualizowano folder" + folder_deleted: "Usunięto folder" + upload: "Prześlij" + uploading: "Przesyłanie…" + drop_hint: "Upuść pliki tutaj, aby je przesłać" + upload_done: "Przesłano plik" + upload_failed: "Nie udało się przesłać pliku. Spróbuj ponownie." + search_placeholder: "Szukaj po nazwie pliku, tytule lub tekście alt…" + filter_all: "Wszystkie typy" + filter_images: "Obrazy" + filter_files: "Pliki" + view_grid: "Widok siatki" + view_list: "Widok listy" + empty_title: "Brak plików w bibliotece" + empty_body: "Prześlij obrazy lub pliki, aby zbudować wspólną bibliotekę mediów." + empty_search: "Brak plików pasujących do wyszukiwania." + load_failed: "Nie udało się wczytać biblioteki mediów. Odśwież stronę, aby spróbować ponownie." + inspector_title: "Szczegóły" + alt: "Tekst alternatywny" + alt_placeholder: "Opisz obraz dla czytników ekranu" + item_title: "Tytuł" + caption: "Podpis" + folder: "Folder" + no_folder: "Brak (katalog główny)" + url: "Publiczny adres URL" + copy_url: "Kopiuj URL" + url_copied: "Skopiowano URL" + dimensions: "Wymiary" + size: "Rozmiar" + content_type: "Typ" + sha256: "SHA-256" + variants: "Warianty WebP" + save: "Zapisz szczegóły" + saved: "Zapisano szczegóły pliku" + delete: "Usuń plik" + delete_confirm_title: "Usunąć ten plik z biblioteki?" + delete_confirm_body: "Usunięcie pliku „:name” trwale kasuje oryginał oraz jego warianty WebP. Opublikowane wpisy, strony i wiadomości korzystające z tego adresu URL przestaną go wyświetlać." + deleted: "Usunięto plik" + picker_title: "Wybierz z Biblioteki mediów" + picker_select: "Wybierz" + picker_select_count: "Wybierz (:count)" + finder_empty: "Nie wybrano mediów" + finder_choose: "Wybierz media" + finder_add: "Dodaj media" + finder_change: "Zmień" + finder_remove: "Usuń" diff --git a/modules/pier/README.md b/modules/pier/README.md index 15d0b0ea..77faea62 100644 --- a/modules/pier/README.md +++ b/modules/pier/README.md @@ -33,7 +33,7 @@ Use cases: - Annotations from the method (D-14): `GET` read-only and idempotent, `PUT` idempotent, `DELETE` destructive; `ReadOnly`, `Destructive`, `Idempotent` and `OpenWorld` override; the destructive and open-world hints are always explicit. - In-process dispatch through `pier.Host.Handler`, the route's compiled chain, with `pact.WithMCPCall` immediately before `bouncer.WithDispatch` carrying the guard provider's `MCPDispatch` principal and credential, path values set as the mux would, `RemoteAddr`, the `Host`, `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Real-IP` and `Accept-Language` copied from the MCP request (never `Authorization` or `Cookie`), `mcp.call_timeout` on the context and the answer captured up to `mcp.max_result_bytes` (D-17). A failed guard dispatch answers the fixed tool error `pier: the tool could not be run for this caller` and logs the cause server-side, so no provider or database error reaches the agent (an invalid token, a deactivated account and an admin personal token whose stored scopes no longer resolve keep their own fixed texts); a dispatch whose guard list names `backend` for a frontend tool, or whose principal kind contradicts the tool's guard, is refused the same way. - Results (D-13): 2xx is text plus structured content (an object as is, any other JSON wrapped as `{"data": …}`); a 4xx or 5xx is a tool error whose text is the route's body; a too-large answer is a tool error with a fixed text. -- Built-in `backend` guard provider (`pier.BackendGuard`): routes behind cabana's `backend` middleware, listing through `cabana.Allows` on the administrator's principal from `cabana.BackendPrincipal`, an admin personal token's (or a `pact.MCPSubject.ScopeLimited` subject's) scope limit computed per dispatched route method with `cabana.ScopeLimitFor`; a plugin that registers its own `backend` provider wins. +- Built-in `backend` guard provider (`pier.BackendGuard`): routes behind cabana's `backend` middleware, listing through `cabana.Allows` on the administrator's principal from `cabana.BackendPrincipal`, an admin personal token's (or a `pact.MCPSubject.ScopeLimited` subject's) scope limit computed per dispatched route method with `cabana.ScopeLimitFor`; a plugin that registers its own `backend` provider wins. When the admin is mounted, `surf` also passes `cabana.MediaMCPPlugin` so the 7 built-in Media Library tools (`media_prepare_upload`, `media_upload`, `media_list`, `media_get`, `media_update`, `media_delete`, `media_create_folder`) are exposed under `backend` with zero uncovered-scope warnings, and the MCP request body limit is 8 MiB so 5 MiB decoded base64 `media_upload` calls succeed. - Identity per request (`pier.Identity`): `oas_at_` tokens through the published verifier, personal tokens only with `mcp.allow_personal_tokens`, the backend subject through the published link resolver with an in-process cache of at most `pier.LinkCacheTTL`; the binding key `oauth::`, `oauth:backend::` (an administrator-only grant), `pat:user:` or `pat:backend:` survives access-token rotation. One `pact.MCPPersonalTokenResolver` serves the application; a subject it answers without a `TokenID` is refused, so personal-token users never share a binding. - Per-identity SDK server plus a receiving middleware that re-filters `tools/list` and `prompts/list` and refuses `tools/call` and `prompts/get` for the identity of the current request, so a permission change takes effect on the next request (D-08, D-25). - Stateful sessions (D-25, D-27): `initialize` opens a session (429 above `mcp.sessions.max_per_binding`), a request with an unknown id answers 404 (the client re-initialises), another identity presenting the id answers 403 `session_binding`, DELETE ends the session everywhere, the record's TTL slides on every request, a session initialised on one instance is rehydrated on another from the stored `ServerSessionState`. A standalone GET stream re-verifies its bearer every minute and ends when it no longer resolves to the session's binding or the session's record is gone. diff --git a/modules/pier/endpoint_guards_test.go b/modules/pier/endpoint_guards_test.go index 81504976..5c5345b5 100644 --- a/modules/pier/endpoint_guards_test.go +++ b/modules/pier/endpoint_guards_test.go @@ -63,10 +63,10 @@ func TestEndpointGuards(t *testing.T) { }) t.Run("body cap", func(t *testing.T) { - big := bytes.Repeat([]byte(" "), 5<<20) + big := bytes.Repeat([]byte(" "), 9<<20) body := append([]byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`), big...) if res := post("oas_at_test", "", bytes.NewReader(body)); res.StatusCode != http.StatusRequestEntityTooLarge { - t.Fatalf("5 MiB body = %d, want 413", res.StatusCode) + t.Fatalf("9 MiB body = %d, want 413", res.StatusCode) } }) diff --git a/modules/pier/pier.go b/modules/pier/pier.go index c21ec91b..793b478f 100644 --- a/modules/pier/pier.go +++ b/modules/pier/pier.go @@ -34,8 +34,9 @@ const streamRecheckInterval = time.Minute // frameworkModule is the module path whose version names the server. const frameworkModule = "git.golem15.com/golem15/summercms" -// maxRequestBody bounds one MCP request body, as the SDK's default does. -const maxRequestBody = 4 << 20 +// maxRequestBody bounds one MCP request body. Raised to 8 MiB so a 5 MiB +// decoded base64 media_upload JSON-RPC call (~6.7 MiB encoded) fits cleanly. +const maxRequestBody = 8 << 20 // wellKnownPRM is the RFC 9728 well-known path. const wellKnownPRM = "/.well-known/oauth-protected-resource" diff --git a/modules/surf/pier_on.go b/modules/surf/pier_on.go index e3d25366..ca7e0d28 100644 --- a/modules/surf/pier_on.go +++ b/modules/surf/pier_on.go @@ -9,6 +9,7 @@ import ( "strings" "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/party" "git.golem15.com/golem15/summercms/modules/pier" @@ -20,7 +21,13 @@ import ( // handler lookup and the two mount kinds without pier importing surf. func init() { mountPier = func(r *Router, app *backpack.App, plugins []party.Plugin) error { - if err := pier.Mount(pierHost{r: r, trusted: TrustedProxies(app.Config)}, app, plugins); err != nil { + mcpPlugins := plugins + if r != nil && r.adminMounted { + mcpPlugins = make([]party.Plugin, 0, len(plugins)+1) + mcpPlugins = append(mcpPlugins, plugins...) + mcpPlugins = append(mcpPlugins, cabana.MediaMCPPlugin(r.adminPrefix)) + } + if err := pier.Mount(pierHost{r: r, trusted: TrustedProxies(app.Config)}, app, mcpPlugins); err != nil { return err } // The router mounted the endpoint, so its Close stops the