🔍 Code Extractor

function get_document_download_url

Maturity: 65

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

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
1176 - 1275
Complexity:
moderate

Purpose

This function provides a flexible way to obtain download URLs for controlled documents stored in FileCloud. It intelligently determines which file format to serve based on the document's publication status: published documents default to PDF while draft/in-review documents default to editable format. Users can also explicitly request a specific format. The function handles version management, file availability checks, and integrates with FileCloud to generate secure download URLs.

Source Code

def get_document_download_url(
    document_uid: str, 
    version_uid: Optional[str] = None,
    file_type: Optional[str] = None  # 'editable' or 'pdf' or None for default based on status
) -> Dict[str, Any]:
    """
    Get the download URL for a document, respecting the dual format storage
    
    Parameters
    ----------
    document_uid : str
        ID of the document
    version_uid : str, optional
        ID of a specific version (default is current version)
    file_type : str, optional
        Type of file to download ('editable' or 'pdf'). If None, uses the primary file based on status.
        
    Returns
    -------
    Dict[str, Any]
        Dictionary with download URL and file information
    """
    try:
        # Get document
        document = ControlledDocument(uid=document_uid)
        if not document.uid:
            return {'success': False, 'message': f'Document not found: {document_uid}'}
            
        # Get version
        version = None
        if version_uid:
            version = DocumentVersion(uid=version_uid)
            if not version:
                return {'success': False, 'message': f'Version not found: {version_uid}'}
        else:
            version = document.current_version
            if not version:
                return {'success': False, 'message': f'No versions found for document: {document_uid}'}
                
        # Determine file path based on status and requested type
        file_path = None
        is_pdf = False
        
        if file_type == 'editable':
            # Explicitly request editable version
            file_path = version.word_file_path
            if not file_path:
                return {'success': False, 'message': 'No editable version available'}
                
        elif file_type == 'pdf':
            # Explicitly request PDF version
            file_path = version.pdf_file_path
            is_pdf = True
            if not file_path:
                return {'success': False, 'message': 'No PDF version available'}
                
        else:
            # Use default logic based on document status
            if document.is_published():
                # For published documents, prefer PDF
                file_path = version.pdf_file_path
                is_pdf = True
                if not file_path:
                    # Fall back to editable if no PDF (should be rare)
                    file_path = version.word_file_path
                    is_pdf = False
            else:
                # For non-published documents, prefer editable
                file_path = version.word_file_path
                if not file_path:
                    # Fall back to PDF if no editable
                    file_path = version.pdf_file_path
                    is_pdf = True
        
        if not file_path:
            return {'success': False, 'message': 'No file available for download'}
            
        # Get FileCloud integration and generate download URL
        fc_integration = _get_filecloud_integration()
        download_url_result = fc_integration.get_view_url(file_path)
        
        if not download_url_result.get('success'):
            return {'success': False, 'message': f'Failed to generate download URL: {download_url_result.get("message", "Unknown error")}'}
            
        # Return the download URL and file information
        return {
            'success': True,
            'document_uid': document_uid,
            'document_number': document.doc_number,
            'version_uid': version.uid,
            'version_number': version.version_number,
            'file_path': file_path,
            'is_pdf': is_pdf,
            'file_type': 'PDF' if is_pdf else 'Editable',
            'download_url': download_url_result.get('view_url')
        }
            
    except Exception as e:
        logger.error(f"Error getting document download URL: {str(e)}")
        return {'success': False, 'message': f'Error: {str(e)}'}

Parameters

Name Type Default Kind
document_uid str - positional_or_keyword
version_uid Optional[str] None positional_or_keyword
file_type Optional[str] None positional_or_keyword

Parameter Details

document_uid: Unique identifier (string) for the controlled document. This is required and must correspond to an existing document in the system.

version_uid: Optional unique identifier (string) for a specific document version. If not provided, the function uses the document's current version. Use this to retrieve historical versions of the document.

file_type: Optional string specifying the desired file format. Accepts 'editable' for Word documents, 'pdf' for PDF files, or None to use automatic selection based on document status. Published documents default to PDF, while non-published documents default to editable format.

Return Value

Type: Dict[str, Any]

Returns a dictionary with type Dict[str, Any]. On success, contains: 'success' (True), 'document_uid', 'document_number', 'version_uid', 'version_number', 'file_path' (FileCloud path), 'is_pdf' (boolean), 'file_type' (string: 'PDF' or 'Editable'), and 'download_url' (the actual URL). On failure, contains: 'success' (False) and 'message' (error description).

Dependencies

  • logging
  • typing
  • CDocs.models.document
  • CDocs.utils.filecloud_integration
  • CDocs.controllers

Required Imports

from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.utils.filecloud_integration import FileCloudIntegration
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.controllers import log_controller_action

Condition: Required for the decorator that wraps this function

Required (conditional)

Usage Example

# Get download URL for current version (auto-selects format based on status)
result = get_document_download_url('doc-12345')
if result['success']:
    print(f"Download URL: {result['download_url']}")
    print(f"File type: {result['file_type']}")
else:
    print(f"Error: {result['message']}")

# Get specific version as PDF
result = get_document_download_url(
    document_uid='doc-12345',
    version_uid='ver-67890',
    file_type='pdf'
)

# Get editable version explicitly
result = get_document_download_url(
    document_uid='doc-12345',
    file_type='editable'
)

Best Practices

  • Always check the 'success' field in the returned dictionary before accessing other fields
  • Handle both PDF and editable format availability - not all documents may have both formats
  • Use version_uid when you need to access historical versions rather than the current version
  • For published documents, PDF format is preferred and should be the default choice
  • The function includes fallback logic: if the preferred format is unavailable, it attempts to use the alternative format
  • Ensure proper error handling as the function can fail due to missing documents, versions, files, or FileCloud integration issues
  • The download URL returned is typically time-limited or session-specific depending on FileCloud configuration
  • This function requires the log_controller_action decorator to be properly configured for audit logging

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_edit_url_v1 84.3% 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 download_document_version 82.2% similar

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

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function download_document_version_v1 79.8% 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 78.5% 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_edit_url 75.2% similar

    Generates an online editing URL for a document stored in FileCloud, allowing users to edit documents that are in editable states.

    From: /tf/active/vicechatdev/document_controller_backup.py
← Back to Browse