function get_document_download_url
Retrieves a download URL for a controlled document, automatically selecting between editable (Word) and PDF formats based on document status or explicit request.
/tf/active/vicechatdev/document_controller_backup.py
1176 - 1275
moderate
Purpose
This function provides a flexible way to obtain download URLs for controlled documents stored in FileCloud. It intelligently selects the appropriate file format (editable Word or PDF) 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 path resolution, and integration 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 (UID) string for the controlled document. This is required and must correspond to an existing document in the system.
version_uid: Optional unique identifier for a specific document version. If not provided, the function uses the document's current version. Use this to retrieve historical versions of a 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 return PDF, non-published return editable format).
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (bool indicating operation success), 'message' (error description if success is False), 'document_uid' (document identifier), 'document_number' (document number), 'version_uid' (version identifier), 'version_number' (version number), 'file_path' (FileCloud path to the file), 'is_pdf' (bool indicating if returned file is PDF), 'file_type' (string 'PDF' or 'Editable'), and 'download_url' (the actual download URL string). On failure, only 'success' and 'message' keys are present.
Dependencies
loggingtypingCDocs.models.documentCDocs.utils.filecloud_integrationCDocs.controllers
Required Imports
from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.utils.filecloud_integration import FileCloudIntegration
from CDocs.controllers import log_controller_action
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.utils.filecloud_integration import FileCloudIntegration
Condition: Required for FileCloud integration to generate download URLs
Required (conditional)Usage Example
# Get download URL for current version (auto-selects format based on status)
result = get_document_download_url(document_uid='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 PDF version explicitly
result = get_document_download_url(
document_uid='doc-12345',
file_type='pdf'
)
# Get specific version in editable format
result = get_document_download_url(
document_uid='doc-12345',
version_uid='ver-67890',
file_type='editable'
)
Best Practices
- Always check the 'success' key in the returned dictionary before accessing other fields
- Use explicit file_type parameter when you need a specific format regardless of document status
- Handle cases where the requested file format may not be available (function returns error message)
- The function is decorated with @log_controller_action, so all calls are automatically logged
- For published documents, PDF is preferred; for draft/review documents, editable format is preferred
- The function gracefully falls back to available format if the preferred format is missing
- Ensure proper error handling as the function catches all exceptions and returns them in the response dictionary
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function download_document_version 82.6% similar
-
function get_document_edit_url 76.3% similar
-
function convert_document_to_pdf 73.8% similar
-
function get_document 72.5% similar
-
function get_document_versions_v1 70.8% similar