function download_document_version_v1
Downloads a specific version of a controlled document, with optional audit trail and watermark inclusion, returning file content and metadata.
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
942 - 1041
moderate
Purpose
This function retrieves a document version from FileCloud storage, processes it according to specified options (audit trail, watermark), logs the download event, and returns the file content along with comprehensive metadata. It handles both specific version downloads and current version downloads when no version is specified. The function enforces permission checks and maintains audit trails for compliance purposes.
Source Code
def download_document_version(
user: DocUser,
document_uid: str,
version_uid: Optional[str] = None,
include_audit_trail: bool = False,
include_watermark: bool = False
) -> Dict[str, Any]:
"""
Download a document version.
Args:
user: User downloading the document
document_uid: UID of document
version_uid: Optional specific version to download (if None, downloads current version)
include_audit_trail: Whether to include audit trail in the document
include_watermark: Whether to include watermark
Returns:
Dictionary with download details and file content
"""
try:
# Get document instance
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get version to download
version = None
if version_uid:
version = DocumentVersion(uid=version_uid)
if not version or version.document_uid != document_uid:
raise ResourceNotFoundError(f"Version not found for document: {version_uid}")
else:
# Get current version
version = document.current_version
if not version:
raise ResourceNotFoundError(f"No current version found for document {document_uid}")
# Use the filecloud_controller's function to download the file
# which will use get_filecloud_document_path internally
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
file_content = download_document_from_filecloud(
user=user,
document_uid=document_uid,
version=version.version_number if version else None
)
# If not bytes, something went wrong
if not isinstance(file_content, bytes):
raise BusinessRuleError("Failed to download file content")
# Handle special processing if needed
processed_content = file_content
# Include audit trail if requested
if include_audit_trail:
# Implementation for audit trail...
pass
# Add watermark if requested
if include_watermark:
# Implementation for watermark...
pass
# Log download event - CHANGED: Use DOCUMENT_DOWNLOADED instead of VERSION_DOWNLOADED
audit_trail.log_document_lifecycle_event(
event_type="DOCUMENT_DOWNLOADED",
user=user,
document_uid=document_uid,
details={
"version_uid": version.uid,
"version_number": version.version_number,
"include_audit_trail": include_audit_trail,
"include_watermark": include_watermark
}
)
# Build result
return {
"success": True,
"document_uid": document_uid,
"document_number": document.doc_number,
"title": document.title,
"version_uid": version.uid,
"version_number": version.version_number,
"file_name": version.file_name,
"file_extension": '.'+version.file_type,
"file_size": len(processed_content),
"content": processed_content,
"audit_trail_included": include_audit_trail,
"watermark_included": include_watermark
}
except (ResourceNotFoundError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error downloading document version: {e}")
raise BusinessRuleError(f"Failed to download document version: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
version_uid |
Optional[str] | None | positional_or_keyword |
include_audit_trail |
bool | False | positional_or_keyword |
include_watermark |
bool | False | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user performing the download. Used for permission checks and audit logging.
document_uid: String unique identifier (UID) of the controlled document to download. Must correspond to an existing document in the system.
version_uid: Optional string UID of a specific document version to download. If None or not provided, the current/latest version of the document will be downloaded. If provided, must belong to the specified document.
include_audit_trail: Boolean flag indicating whether to include the document's audit trail in the downloaded file. Defaults to False. When True, audit history is embedded in the document.
include_watermark: Boolean flag indicating whether to apply a watermark to the downloaded document. Defaults to False. When True, a watermark is added to the file content.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (bool, always True on successful execution), 'document_uid' (str), 'document_number' (str, the document's number), 'title' (str, document title), 'version_uid' (str, UID of downloaded version), 'version_number' (int/str, version number), 'file_name' (str, original filename), 'file_extension' (str, file extension with leading dot), 'file_size' (int, size in bytes of processed content), 'content' (bytes, the actual file content), 'audit_trail_included' (bool), 'watermark_included' (bool). Raises ResourceNotFoundError if document/version not found, PermissionError if user lacks access, or BusinessRuleError for other failures.
Dependencies
logginguuidostempfiletypingdatetimeiopanelshutiltracebackjsonrerandomCDocs.dbCDocs.config.settingsCDocs.config.permissionsCDocs.models.documentCDocs.models.user_extensionsCDocs.utils.document_processorCDocs.utils.notificationsCDocs.utils.audit_trailCDocs.db.schema_managerCDocs.controllersCDocs.models.approvalCDocs.controllers.filecloud_controllerCDocs.controllers.share_controllerCDocs.db.db_operationsCDocs.utils.document_converterCDocs.models.document_statusCDocs.utils.filecloud_integrationCDocs.utils.notificationsCDocs.models.reviewdocument_auditor.src.document_processorCDocs.document_auditor.src.document_processorCDocs.controllers.training_controllerCDocs.utils.metadata_catalog
Required Imports
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.controllers import ResourceNotFoundError, PermissionError, BusinessRuleError
from CDocs.utils import audit_trail
from typing import Dict, Any, Optional
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
Condition: always required - used to retrieve file content from FileCloud storage
Required (conditional)Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import download_document_version
# Initialize user object
user = DocUser(uid='user123')
# Download current version without extras
result = download_document_version(
user=user,
document_uid='doc-abc-123'
)
# Access the file content
file_content = result['content']
file_name = result['file_name']
with open(file_name, 'wb') as f:
f.write(file_content)
# Download specific version with audit trail and watermark
result_with_extras = download_document_version(
user=user,
document_uid='doc-abc-123',
version_uid='ver-xyz-456',
include_audit_trail=True,
include_watermark=True
)
print(f"Downloaded {result_with_extras['file_name']} (v{result_with_extras['version_number']})")
print(f"File size: {result_with_extras['file_size']} bytes")
Best Practices
- Always handle the returned 'content' as bytes data - do not attempt to decode unless you know the file type
- Check the 'success' key in the returned dictionary before processing the content
- Wrap calls in try-except blocks to handle ResourceNotFoundError, PermissionError, and BusinessRuleError exceptions
- The function automatically logs download events to the audit trail - no additional logging needed
- When version_uid is None, the current version is downloaded - ensure the document has a current version
- The file_size in the response reflects the processed content size, which may differ from original if audit trail or watermark is added
- Ensure the user object has proper authentication and permissions before calling this function
- The function uses decorators for permission checking - ensure decorators are properly configured
- Note that audit trail and watermark implementations are currently placeholders (pass statements) - verify implementation status before relying on these features
- The function re-raises known exceptions but wraps unknown exceptions in BusinessRuleError - check logs for detailed error information
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function download_document_version 98.1% similar
-
function download_document_from_filecloud 83.9% similar
-
function get_document_download_url 79.8% similar
-
function get_document_edit_url_v1 76.0% similar
-
function create_document_v2 75.1% similar