🔍 Code Extractor

function download_document_version

Maturity: 72

Downloads a specific version of a controlled document from FileCloud storage, with optional audit trail and watermark inclusion, and logs the download event.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
696 - 792
Complexity:
moderate

Purpose

This function retrieves a document version (either specified or current) from a document management system, processes it with optional features (audit trail, watermark), and returns the file content along with comprehensive metadata. It enforces permission checks, validates document and version existence, handles file retrieval from FileCloud storage, and maintains an audit trail of download activities. Used in document management workflows where controlled access to versioned documents is required.

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}")
                
        # Download file from FileCloud
        file_content = download_document_from_filecloud(
            user=user,
            document_uid=document_uid,
            version=version.version_number
        )
        
        # 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 validation and audit logging.

document_uid: String containing the unique identifier (UID) of the document to download. Must correspond to an existing ControlledDocument in the system.

version_uid: Optional string containing the UID of a specific document version to download. If None or not provided, the function downloads the current/latest version of the document.

include_audit_trail: Boolean flag (default False) indicating whether to embed the document's audit trail history into the downloaded file. Implementation is placeholder in provided code.

include_watermark: Boolean flag (default False) indicating whether to apply a watermark to the downloaded document. Implementation is placeholder in provided code.

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys: 'success' (bool, always True on successful execution), 'document_uid' (str), 'document_number' (str, document identifier), 'title' (str, document title), 'version_uid' (str, version identifier), '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), 'content' (bytes, actual file binary 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

  • logging
  • uuid
  • os
  • tempfile
  • typing
  • datetime
  • io
  • panel
  • shutil
  • traceback
  • CDocs

Required Imports

from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import require_permission, log_controller_action, ResourceNotFoundError, PermissionError, BusinessRuleError
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
import logging

Usage Example

from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import download_document_version

# Get authenticated user
user = DocUser(uid='user-123')

# Download current version of a document
result = download_document_version(
    user=user,
    document_uid='doc-456'
)

if result['success']:
    file_content = result['content']
    file_name = result['file_name']
    # Save to disk or send to client
    with open(file_name, 'wb') as f:
        f.write(file_content)

# Download specific version with watermark
result = download_document_version(
    user=user,
    document_uid='doc-456',
    version_uid='version-789',
    include_watermark=True
)

# Download with audit trail
result = download_document_version(
    user=user,
    document_uid='doc-456',
    include_audit_trail=True,
    include_watermark=True
)

Best Practices

  • Always handle the returned 'content' bytes object appropriately for the file type being downloaded
  • Wrap calls in try-except blocks to catch ResourceNotFoundError, PermissionError, and BusinessRuleError exceptions
  • Ensure the user object passed has been properly authenticated before calling this function
  • The function is decorated with @require_permission('DOWNLOAD_DOCUMENT', 'document_uid'), so permission checks happen automatically
  • The function is decorated with @log_controller_action('download_document_version') for automatic action logging
  • Note that include_audit_trail and include_watermark parameters have placeholder implementations (pass statements) in the provided code
  • The function logs a 'DOCUMENT_DOWNLOADED' event (not 'VERSION_DOWNLOADED') to the audit trail
  • File size is calculated from processed_content length, which may differ from original if processing is implemented
  • The function retrieves the current version if version_uid is None, ensure documents have a current_version set
  • Binary content is returned in memory; for large files, consider streaming implementations

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function download_document_version_v1 98.1% similar

    Downloads a specific version of a controlled document, with optional audit trail and watermark inclusion, returning file content and metadata.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function download_document_from_filecloud 85.4% similar

    Downloads a document version from FileCloud storage, with optional availability checking and audit logging for user-initiated downloads.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function get_document_download_url 82.2% similar

    Retrieves a download URL for a controlled document, automatically selecting between editable (Word) and PDF formats based on document status or explicit request.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_edit_url_v1 77.6% similar

    Generates a FileCloud URL to view or edit a controlled document, selecting the appropriate file format (PDF or Word) based on document status and version availability.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function upload_document_to_filecloud 75.8% similar

    Uploads a document version to FileCloud storage system with metadata, handling file creation, folder structure, and audit logging.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
← Back to Browse