function get_document_edit_url
Generates an online editing URL for a document stored in FileCloud, allowing users to edit documents that are in editable states.
/tf/active/vicechatdev/document_controller_backup.py
1547 - 1634
moderate
Purpose
This function retrieves a document and its version from the database, validates that the document is in an editable state, and constructs a FileCloud URL that allows the user to access and edit the document online. It handles both current versions and specific version requests, performs permission checks via decorators, and ensures the document has an editable file path before generating the URL.
Source Code
def get_document_edit_url(
user: DocUser,
document_uid: str,
version_uid: Optional[str] = None
) -> Dict[str, Any]:
"""
Get an online editing URL for a document in FileCloud.
Only allowed for documents in editable states.
Parameters
----------
user : DocUser
User requesting the edit URL
document_uid : str
ID of the document
version_uid : str, optional
ID of a specific version (default is current version)
Returns
-------
Dict[str, Any]
Dictionary with the edit URL
"""
try:
# Get document
document = ControlledDocument(uid=document_uid)
if not document:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Check if document is in an editable state
if not document.is_editable():
raise BusinessRuleError(f"Document with status {document.status} cannot be edited")
# Get version
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: {version_uid}")
else:
version = document.current_version
if not version:
raise ResourceNotFoundError(f"No versions found for document: {document_uid}")
# Check if the version has an editable file
editable_file_path = version.word_file_path
if not editable_file_path:
raise BusinessRuleError("Version has no editable document")
# Generate edit URL through FileCloud
try:
filename = os.path.basename(editable_file_path)
# Escape spaces in filename with + for the first part
encoded_filename = filename.replace(' ', '+')
# Encode path for the second part (after #expl-tabl.)
# Extract directory path without filename
directory_path = os.path.dirname(editable_file_path)
# Ensure path ends with '/'
if directory_path and not directory_path.endswith('/'):
directory_path += '/'
encoded_path = directory_path.replace(' ', '%20')
# Construct the full URL
file_url = f"https://filecloud.vicebio.com/ui/core/index.html?filter={encoded_filename}#expl-tabl.{encoded_path}"
return {
'success': True,
'document_uid': document_uid,
'document_number': document.doc_number,
'version_uid': version.uid,
'version_number': version.version_number,
'edit_url': file_url,
#'expires': edit_url_result.get('expires')
}
except Exception as e:
logger.error(f"Error generating edit URL: {str(e)}")
raise BusinessRuleError(f"Failed to generate edit URL: {str(e)}")
except (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) as e:
# Re-raise known errors
raise
except Exception as e:
logger.error(f"Error getting document edit URL: {str(e)}")
raise BusinessRuleError(f"Failed to get edit URL: {str(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 |
Parameter Details
user: DocUser object representing the authenticated user requesting the edit URL. Used for permission validation through the decorator.
document_uid: String identifier (UID) of the document for which to generate an edit URL. Must correspond to an existing ControlledDocument in the system.
version_uid: Optional string identifier (UID) of a specific document version. If not provided, the current version of the document will be used. If provided, must belong to the specified document.
Return Value
Type: Dict[str, Any]
Returns a dictionary containing: 'success' (bool, always True on success), 'document_uid' (str, the document's UID), 'document_number' (str, the document's number), 'version_uid' (str, the version's UID), 'version_number' (str/int, the version number), and 'edit_url' (str, the FileCloud URL for editing). On error, raises exceptions rather than returning error dictionaries.
Dependencies
loggingostypingCDocs.models.documentCDocs.models.user_extensionsCDocs.controllersCDocs.config.settings
Required Imports
import os
from typing import Dict, Any, Optional
from CDocs.models.document import ControlledDocument, DocumentVersion
from CDocs.models.user_extensions import DocUser
from CDocs.controllers import log_controller_action, require_permission, ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from your_module import get_document_edit_url
# Assuming user and document_uid are already available
user = DocUser(uid='user123')
document_uid = 'doc-456'
# Get edit URL for current version
result = get_document_edit_url(user, document_uid)
print(f"Edit URL: {result['edit_url']}")
print(f"Version: {result['version_number']}")
# Get edit URL for specific version
version_uid = 'ver-789'
result = get_document_edit_url(user, document_uid, version_uid)
print(f"Edit URL: {result['edit_url']}")
Best Practices
- Ensure the user has 'EDIT_DOCUMENT' permission before calling this function (enforced by decorator)
- Handle all custom exceptions (ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError) when calling this function
- The function only works with documents in editable states - check document status before attempting to get edit URL
- The generated URL is specific to FileCloud at 'filecloud.vicebio.com' - modify the hardcoded URL if using a different FileCloud instance
- The function expects documents to have a 'word_file_path' attribute on their versions - ensure this is populated
- URL encoding handles spaces in filenames and paths differently (+ for filename filter, %20 for path)
- Always check the 'success' field in the returned dictionary before using the edit_url
- The function logs errors using the logger - ensure logging is properly configured for debugging
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_document_edit_url_v1 91.9% similar
-
function get_document_download_url 75.2% similar
-
function download_document_from_filecloud 69.7% similar
-
function download_document_version 69.0% similar
-
function convert_document_to_pdf_v1 67.9% similar