function update_document_metadata_in_filecloud
Updates metadata for a document stored in FileCloud, merging new metadata with existing values and logging the update in an audit trail.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
578 - 647
moderate
Purpose
This function provides a controlled way to update document metadata in FileCloud storage. It retrieves the current metadata, merges it with new values, updates FileCloud, and logs the action for audit purposes. It enforces permission checks and handles version-specific metadata updates. The function is designed for document management systems that need to maintain metadata synchronization between application state and cloud storage.
Source Code
def update_document_metadata_in_filecloud(
user: DocUser,
document_uid: str,
metadata: Dict[str, Any],
version: Optional[str] = None
) -> Dict[str, Any]:
"""
Update metadata for a document in FileCloud.
Args:
user: User performing the update
document_uid: UID of the document
metadata: Metadata values to update
version: Optional specific version to update metadata for
Returns:
Dictionary with update status
Raises:
ResourceNotFoundError: If document or version not found
PermissionError: If user doesn't have permission
FileCloudError: If metadata update fails
"""
# Get document instance
doc = ControlledDocument(uid=document_uid)
if not doc:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get file path
file_path = get_filecloud_document_path(doc, version)
# Get the current metadata first
current_metadata = get_document_metadata_from_filecloud(document_uid, version)
# Merge with new metadata (keeping existing values not in update)
updated_metadata = {**current_metadata, **metadata}
try:
client = get_filecloud_client()
# Update metadata
result = client.set_file_metadata(file_path, updated_metadata)
if not result.get('success', False):
logger.error(f"Failed to update metadata in FileCloud: {result.get('message', 'Unknown error')}")
raise FileCloudError(f"Failed to update metadata: {result.get('message', 'Unknown error')}")
# Log audit event
target_version = doc.get_version_by_number(version) if version else doc.current_version
if target_version:
audit_trail.log_version_event(
event_type="VERSION_METADATA_UPDATED",
user=user,
version_uid=target_version.uid,
details={
"file_path": file_path,
"metadata": metadata
}
)
return {
"success": True,
"document_uid": document_uid,
"file_path": file_path,
"metadata": updated_metadata
}
except Exception as e:
logger.error(f"Error updating document metadata in FileCloud: {e}")
raise FileCloudError(f"Error updating document metadata: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
metadata |
Dict[str, Any] | - | positional_or_keyword |
version |
Optional[str] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user performing the metadata update. Used for permission validation and audit logging.
document_uid: String containing the unique identifier (UID) of the document whose metadata should be updated. Must correspond to an existing ControlledDocument in the system.
metadata: Dictionary containing key-value pairs of metadata to update. Keys are metadata field names and values can be of any type. New values will be merged with existing metadata, overwriting matching keys while preserving others.
version: Optional string specifying a particular document version number to update metadata for. If None, metadata is updated for the current version. Must be a valid version number if provided.
Return Value
Type: Dict[str, Any]
Returns a dictionary with four keys: 'success' (boolean, always True if no exception raised), 'document_uid' (string, echoes the input document UID), 'file_path' (string, the FileCloud path where the document is stored), and 'metadata' (dictionary, the complete merged metadata after the update including both old and new values).
Dependencies
loggingosjsonuuidtempfiletypingtimeCDocs
Required Imports
from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import require_permission, log_controller_action, ResourceNotFoundError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import update_document_metadata_in_filecloud
# Assume user is authenticated and has proper permissions
user = DocUser.query.get(user_id)
document_uid = "doc-12345-abcde"
# Update metadata for current version
metadata_updates = {
"author": "John Doe",
"department": "Engineering",
"classification": "Internal"
}
try:
result = update_document_metadata_in_filecloud(
user=user,
document_uid=document_uid,
metadata=metadata_updates
)
print(f"Metadata updated successfully: {result['metadata']}")
except ResourceNotFoundError:
print("Document not found")
except PermissionError:
print("User lacks required permissions")
except FileCloudError as e:
print(f"FileCloud error: {e}")
# Update metadata for specific version
result = update_document_metadata_in_filecloud(
user=user,
document_uid=document_uid,
metadata={"reviewed_by": "Jane Smith"},
version="2.1"
)
Best Practices
- Always handle ResourceNotFoundError, PermissionError, and FileCloudError exceptions when calling this function
- Ensure the user object has been properly authenticated before passing to this function
- The function merges metadata rather than replacing it entirely, so existing metadata fields not in the update dictionary will be preserved
- Use the version parameter only when updating metadata for historical versions; omit it to update the current version
- The function requires both 'EDIT_DOCUMENT' and 'MANAGE_METADATA' permissions via the decorator
- All metadata updates are logged in the audit trail with VERSION_METADATA_UPDATED event type
- The metadata dictionary values can be of any JSON-serializable type supported by FileCloud
- Check the 'success' field in the returned dictionary even though exceptions are raised on failure, for defensive programming
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function upload_document_to_filecloud 81.1% similar
-
function get_document_metadata_from_filecloud 77.9% similar
-
function set_document_permissions_in_filecloud 74.2% similar
-
function update_document 72.1% similar
-
function update_document_v1 71.8% similar