function _download_current_version
Downloads the current version of a document from either FileCloud storage or standard storage, handling different storage types and triggering a browser download.
/tf/active/vicechatdev/document_controller_backup.py
2427 - 2481
moderate
Purpose
This method is part of a document management system that handles downloading document versions. It checks the storage type of the current document version (FileCloud or standard), retrieves the document content from the appropriate storage backend, and triggers a browser download using Panel's download API. It provides user feedback through a notification area and handles various error conditions including missing versions, download failures, and storage-specific errors.
Source Code
def _download_current_version(self, event=None):
"""Download the current document version"""
if not self.current_version:
self.notification_area.object = "**Error:** No document version available"
return
try:
# Get version UID
version_uid = self.current_version.get('UID')
# Check if this is a FileCloud stored document
storage_type = self.current_version.get('storage_type', '')
if storage_type == 'FILECLOUD':
# Get the file from FileCloud
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
# Show downloading message
self.notification_area.object = "Downloading document from FileCloud..."
doc_content = download_document_from_filecloud(
user=self.user,
document_uid=self.document_uid
)
# Handle response correctly based on what download_document_from_filecloud returns
if isinstance(doc_content, bytes):
# Direct bytes content
file_data = io.BytesIO(doc_content)
file_name = self.current_version.get('file_name', 'document.pdf')
pn.state.execute_download(file_data, filename=file_name)
self.notification_area.object = "Document downloaded successfully"
elif isinstance(doc_content, dict) and doc_content.get('success') == False:
self.notification_area.object = f"**Error:** {doc_content.get('message', 'Could not download document')}"
else:
self.notification_area.object = "**Error:** Could not download document from FileCloud"
else:
# Try to use the standard document controller method
from CDocs.controllers.document_controller import download_document_version
doc_content = download_document_version(version_uid)
if doc_content and 'content' in doc_content:
# Create BytesIO object for download
file_data = io.BytesIO(doc_content['content'])
file_name = self.current_version.get('file_name', 'document.pdf')
# Use Panel's API to trigger download
pn.state.execute_download(file_data, filename=file_name)
self.notification_area.object = "Document downloaded successfully"
else:
self.notification_area.object = "**Error:** Could not download document"
except Exception as e:
logger.error(f"Error downloading document: {e}")
self.notification_area.object = f"**Error:** {str(e)}"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
self |
- | - | positional_or_keyword |
event |
- | None | positional_or_keyword |
Parameter Details
self: Instance reference to the containing class. Expected to have attributes: current_version (dict with document version metadata including UID, storage_type, file_name), user (DocUser object for authentication), document_uid (string identifier for the document), and notification_area (Panel object for displaying status messages).
event: Optional event parameter, typically passed by Panel UI event handlers when the method is bound to a button or widget. Defaults to None and is not used in the function body.
Return Value
Returns None. The function performs side effects: triggers a browser download via pn.state.execute_download() on success, or updates self.notification_area.object with error/success messages. No explicit return value is provided.
Dependencies
paneliologgingCDocs
Required Imports
import io
import panel as pn
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.controllers.filecloud_controller import download_document_from_filecloud
Condition: only when storage_type is 'FILECLOUD'
Required (conditional)from CDocs.controllers.document_controller import download_document_version
Condition: only when storage_type is not 'FILECLOUD' (standard storage)
Required (conditional)Usage Example
# Assuming this is a method in a Panel-based document viewer class
# Example class context:
class DocumentViewer:
def __init__(self, user, document_uid):
self.user = user
self.document_uid = document_uid
self.notification_area = pn.pane.Markdown('')
self.current_version = {
'UID': 'version-123',
'storage_type': 'FILECLOUD',
'file_name': 'report.pdf'
}
self.download_button = pn.widgets.Button(name='Download', button_type='primary')
self.download_button.on_click(self._download_current_version)
def _download_current_version(self, event=None):
# ... (the function code) ...
pass
# Usage:
from CDocs.models.user_extensions import DocUser
user = DocUser.get_by_username('john.doe')
viewer = DocumentViewer(user=user, document_uid='doc-456')
# When user clicks download button, _download_current_version is called
# Or call directly:
viewer._download_current_version()
Best Practices
- Ensure self.current_version is populated before calling this method to avoid 'No document version available' error
- The method expects a logger object to be available in the module scope for error logging
- Handle Panel state availability - pn.state.execute_download requires an active Panel server session
- The method modifies self.notification_area.object for user feedback - ensure this attribute exists and is a Panel component that accepts markdown strings
- FileCloud and standard storage backends must be properly configured before use
- The method handles two different response formats from download functions (bytes or dict), ensure backend controllers follow these conventions
- Consider wrapping calls in a try-except block at the caller level for additional error handling
- The method uses lazy imports which may cause import errors if CDocs modules are not available - ensure CDocs package is installed
- For FileCloud storage, the user object must have appropriate permissions to download documents
- Default filename 'document.pdf' is used if file_name is not in current_version metadata
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function _view_document 86.1% similar
-
function download_document_version 69.0% similar
-
function download_document_version_v1 67.8% similar
-
function download_document_from_filecloud 67.1% similar
-
function get_document_download_url 64.8% similar