function download_document_from_filecloud
Downloads a document version from FileCloud storage, with optional availability checking and audit logging for user-initiated downloads.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
467 - 531
moderate
Purpose
This function serves as the primary interface for retrieving document files from FileCloud storage. It supports downloading specific versions or the current version, can perform availability checks without downloading, and logs audit trails for user actions. It's designed to work both with authenticated user requests and system-level operations (when user is None). The function is protected by permission decorators that enforce access control and log controller actions.
Source Code
def download_document_from_filecloud(
document_uid: str,
user: Optional[DocUser] = None, # Make user optional
version: Optional[str] = None,
check_only: bool = False
) -> Union[Dict[str, Any], bytes]:
"""
Download a document version from FileCloud.
Args:
document_uid: UID of the document to download
user: Optional user performing the download (can be None for system operations)
version: Optional specific version to download (if None, downloads current version)
check_only: If True, only checks if the file is available without downloading
Returns:
If check_only is True, returns a dictionary with availability status
Otherwise, returns the file content as bytes
Raises:
ResourceNotFoundError: If document or version not found
FileCloudError: If download 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)
try:
client = get_filecloud_client()
# Check if file exists
if check_only:
result = client.check_file_exists(file_path)
if not result:
return {"success": False, "message": "File not found or not accessible"}
return {"success": True, "message": "File is available for download"}
# Download the file
result = client.download_file(file_path)
if isinstance(result, dict) and not result.get('success', False):
logger.error(f"Failed to download file from FileCloud: {result.get('message', 'Unknown error')}")
raise FileCloudError(f"Failed to download file: {result.get('message', 'Unknown error')}")
# Log audit event only if user is provided
target_version = doc.get_version_by_number(version) if version else doc.current_version
if target_version and user:
audit_trail.log_version_event(
event_type="VERSION_DOWNLOADED",
user=user,
version_uid=target_version.uid,
details={"file_path": file_path}
)
return result # This should be the file content as bytes
except Exception as e:
logger.error(f"Error downloading document from FileCloud: {e}")
raise FileCloudError(f"Error downloading document: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
document_uid |
str | - | positional_or_keyword |
user |
Optional[DocUser] | None | positional_or_keyword |
version |
Optional[str] | None | positional_or_keyword |
check_only |
bool | False | positional_or_keyword |
Parameter Details
document_uid: Unique identifier (UID) string for the document to download. Must correspond to an existing ControlledDocument in the system. Used to locate and retrieve the document instance.
user: Optional DocUser object representing the user performing the download. Can be None for system-level operations. When provided, the download action is logged in the audit trail. The require_permission decorator uses this for access control (with skip_if_no_user=True allowing None values).
version: Optional string specifying a particular document version number to download. If None or not provided, the function downloads the current/latest version of the document. Must match an existing version number for the document.
check_only: Boolean flag that when True, only verifies file availability in FileCloud without actually downloading the content. Returns a status dictionary instead of file bytes. Defaults to False for normal download operations.
Return Value
Type: Union[Dict[str, Any], bytes]
Returns Union[Dict[str, Any], bytes]. When check_only=True, returns a dictionary with keys 'success' (bool) and 'message' (str) indicating file availability status. When check_only=False (normal download), returns the file content as raw bytes. On failure with check_only=True, returns {'success': False, 'message': 'File not found or not accessible'}. On success with check_only=True, returns {'success': True, 'message': 'File is available for download'}.
Dependencies
CDocstypinglogging
Required Imports
from typing import Dict, Any, Optional, Union
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.controllers import require_permission, log_controller_action, ResourceNotFoundError
from CDocs.utils import audit_trail
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.utils.FC_api import FileCloudAPI
Condition: Required for get_filecloud_client() function call to interact with FileCloud storage
Required (conditional)from CDocs.controllers import FileCloudError
Condition: Required for raising FileCloud-specific exceptions when download operations fail
Required (conditional)Usage Example
# Example 1: Download current version with user audit logging
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import download_document_from_filecloud
user = DocUser.query.get(user_id)
document_uid = 'doc-12345-abcde'
try:
file_content = download_document_from_filecloud(
document_uid=document_uid,
user=user
)
# file_content is bytes, can be saved or sent to client
with open('downloaded_file.pdf', 'wb') as f:
f.write(file_content)
except ResourceNotFoundError:
print('Document not found')
except FileCloudError as e:
print(f'Download failed: {e}')
# Example 2: Check file availability without downloading
status = download_document_from_filecloud(
document_uid=document_uid,
user=user,
check_only=True
)
if status['success']:
print('File is available')
# Example 3: Download specific version (system operation, no user)
file_content = download_document_from_filecloud(
document_uid=document_uid,
user=None,
version='2.1'
)
Best Practices
- Always wrap calls in try-except blocks to handle ResourceNotFoundError and FileCloudError exceptions
- Use check_only=True before downloading large files to verify availability and avoid unnecessary bandwidth usage
- Provide the user parameter when downloading on behalf of a user to ensure proper audit trail logging
- The function can be called with user=None for system-level operations, but audit events will not be logged in this case
- Ensure the document_uid exists before calling to avoid ResourceNotFoundError
- When specifying a version parameter, verify the version exists for the document
- The function is protected by decorators: ensure the calling context has proper permissions and the user has 'DOWNLOAD_DOCUMENT' permission
- Handle the Union return type appropriately: check if check_only was True to determine if result is Dict or bytes
- The returned bytes should be handled as binary data (use 'wb' mode when writing to files)
- FileCloud client errors are wrapped in FileCloudError for consistent error handling
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function download_document_version 85.4% similar
-
function download_document_version_v1 83.9% similar
-
function get_document_download_url 78.5% similar
-
function get_document_metadata_from_filecloud 75.2% similar
-
function get_document_edit_url_v1 73.2% similar