🔍 Code Extractor

function _view_document

Maturity: 50

Views and downloads the current version of a document, with special handling for FileCloud-stored documents versus locally stored documents.

File:
/tf/active/vicechatdev/document_controller_backup.py
Lines:
2389 - 2425
Complexity:
moderate

Purpose

This method is part of a document management system that handles viewing/downloading document versions. It checks if the current document version is stored in FileCloud (external storage) or locally, then retrieves and initiates a download of the document file. It provides error handling and user notifications through a notification area UI component.

Source Code

def _view_document(self, event=None):
    """View the current document version"""
    if not self.current_version:
        self.notification_area.object = "**Error:** No document version available"
        return
        
    # Get version UID
    version_uid = self.current_version.get('UID')
    
    # For FileCloud stored documents, we retrieve from there
    try:
        # Is this stored in FileCloud?
        storage_type = self.current_version.get('storage_type', '')
        
        if (storage_type == 'FILECLOUD' and self.current_version.get('filecloud_link')):
            # Get the file from FileCloud using the link
            from CDocs.controllers.filecloud_controller import download_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)
            else:
                # Handle dictionary response if that's what the function returns
                self.notification_area.object = "**Error:** Could not download document from FileCloud"
        else:
            # Fall back to default document retrieval
            self._download_current_version(event)
    except Exception as e:
        logger.error(f"Error viewing 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 metadata), notification_area (UI component for displaying messages), user (user object), and document_uid (unique identifier for the document).

event: Optional event parameter, typically passed by UI event handlers (e.g., button clicks). Defaults to None. Not directly used in the function body but may be passed to _download_current_version.

Return Value

Returns None implicitly. The function performs side effects: either initiates a file download via pn.state.execute_download(), displays error messages in the notification_area, or calls _download_current_version() as a fallback.

Dependencies

  • panel
  • io
  • logging
  • CDocs.controllers.filecloud_controller
  • CDocs

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: Required when storage_type is 'FILECLOUD' and filecloud_link exists in current_version

Required (conditional)

Usage Example

# Assuming this is a method in a DocumentViewer class
# Example usage within a Panel application:

import panel as pn
import io
from CDocs.controllers.filecloud_controller import download_document_from_filecloud

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': 'doc-123-v1',
            'storage_type': 'FILECLOUD',
            'filecloud_link': 'https://filecloud.example.com/doc-123',
            'file_name': 'report.pdf'
        }
    
    def _download_current_version(self, event=None):
        # Fallback method for local storage
        pass
    
    def _view_document(self, event=None):
        # Method implementation as provided
        if not self.current_version:
            self.notification_area.object = '**Error:** No document version available'
            return
        version_uid = self.current_version.get('UID')
        try:
            storage_type = self.current_version.get('storage_type', '')
            if storage_type == 'FILECLOUD' and self.current_version.get('filecloud_link'):
                doc_content = download_document_from_filecloud(
                    user=self.user,
                    document_uid=self.document_uid
                )
                if isinstance(doc_content, bytes):
                    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)
                else:
                    self.notification_area.object = '**Error:** Could not download document from FileCloud'
            else:
                self._download_current_version(event)
        except Exception as e:
            self.notification_area.object = f'**Error:** {str(e)}'

# Usage in a Panel app
viewer = DocumentViewer(user=current_user, document_uid='doc-123')
view_button = pn.widgets.Button(name='View Document')
view_button.on_click(viewer._view_document)

app = pn.Column(view_button, viewer.notification_area)
app.show()

Best Practices

  • Ensure self.current_version is validated and populated before calling this method
  • The method assumes a logger object exists in module scope; ensure logging is properly configured
  • This method should only be called within a Panel application context where pn.state is available
  • The _download_current_version fallback method must be implemented in the containing class
  • Consider adding type hints to improve code maintainability
  • The function handles FileCloud-specific logic; ensure FileCloud integration is properly configured before using storage_type='FILECLOUD'
  • Error messages are displayed in markdown format; ensure notification_area supports markdown rendering
  • The method performs I/O operations and should not be called in performance-critical loops
  • Consider adding permission checks before allowing document downloads
  • The isinstance check for bytes may need expansion if download_document_from_filecloud can return other types

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function _download_current_version 85.7% similar

    Downloads the current version of a document from either FileCloud storage or standard storage, handling different storage types and triggering a browser download.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function download_document_version 68.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 get_document_download_url 65.1% 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 create_document_v1 57.9% similar

    Creates a new version of an existing document in a document management system, storing the file in FileCloud and tracking version metadata in Neo4j graph database.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_versions_v1 56.3% similar

    Retrieves all versions of a document from the database given its unique identifier (UID).

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