function create_document_share_link
Creates a shareable link for a document in FileCloud with optional password protection, expiry, and email notifications.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
726 - 816
moderate
Purpose
This function integrates with FileCloud to generate shareable links for controlled documents. It supports both system-level and user-level operations, allows sharing specific document versions, and provides audit logging. The function handles document retrieval by UID or direct object passing, creates the share in FileCloud, and logs the sharing event for compliance tracking.
Source Code
def create_document_share_link(
user: Optional[DocUser], # Make user parameter optional
document_uid: str = None,
document: Optional[ControlledDocument] = None, # Allow passing document directly
share_type: str = "view",
password: Optional[str] = None,
expiry_days: Optional[int] = None,
notify_emails: Optional[List[str]] = None,
version: Optional[str] = None
) -> Dict[str, Any]:
"""
Create a shareable link for a document in FileCloud.
Args:
user: User creating the share (optional for system operations)
document_uid: UID of the document
document: Document object (alternative to document_uid)
share_type: Type of share (view, download, etc.)
password: Optional password protection
expiry_days: Optional expiry period in days
notify_emails: Optional list of emails to notify
version: Optional specific version to share
Returns:
Dictionary with share information
"""
# Get document instance
if document:
doc = document
elif document_uid:
doc = ControlledDocument(uid=document_uid)
if not doc:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
else:
raise ValidationError("Either document or document_uid must be provided")
# Get file path
file_path = get_filecloud_document_path(doc, version)
try:
client = get_filecloud_client()
# Create share
# FIXED: Include file extension in share_name by using the full filename
file_name = os.path.basename(file_path)
share_name = file_name # Use the complete filename with extension
result = client.add_share(
share_location=file_path,
share_name=share_name
)
if not result.get('success', False):
logger.error(f"Failed to create share in FileCloud: {result.get('message', 'Unknown error')}")
raise FileCloudError(f"Failed to create share: {result.get('message', 'Unknown error')}")
share_url = result.get('share_url')
share_id = result.get('share_id')
# Log audit event only if user is provided
target_version = doc.get_version_by_number(version) if version else doc.current_version
if target_version and user:
audit_trail.log_version_event(
event_type="VERSION_SHARED",
user=user,
version_uid=target_version.uid,
details={
"file_path": file_path,
"share_type": share_type,
"share_url": share_url,
"share_id": share_id,
"has_password": password is not None,
"expiry_days": expiry_days,
"notify_emails": notify_emails
}
)
return {
"success": True,
"document_uid": doc.uid,
"file_path": file_path,
"share_url": share_url,
"share_id": share_id,
"share_type": share_type,
"has_password": password is not None,
"expiry_days": expiry_days
}
except Exception as e:
logger.error(f"Error creating document share in FileCloud: {e}")
raise FileCloudError(f"Error creating document share: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
Optional[DocUser] | - | positional_or_keyword |
document_uid |
str | None | positional_or_keyword |
document |
Optional[ControlledDocument] | None | positional_or_keyword |
share_type |
str | 'view' | positional_or_keyword |
password |
Optional[str] | None | positional_or_keyword |
expiry_days |
Optional[int] | None | positional_or_keyword |
notify_emails |
Optional[List[str]] | None | positional_or_keyword |
version |
Optional[str] | None | positional_or_keyword |
Parameter Details
user: Optional DocUser object representing the user creating the share. Can be None for system operations. When provided, enables audit logging of the share event.
document_uid: String UID (unique identifier) of the document to share. Alternative to passing the document object directly. Must be provided if document parameter is None.
document: Optional ControlledDocument object to share. Alternative to document_uid. Allows passing an already-loaded document instance to avoid redundant database queries.
share_type: String specifying the type of share access. Default is 'view'. Expected values include 'view', 'download', etc. Determines what recipients can do with the shared document.
password: Optional string password to protect the share link. When provided, recipients must enter this password to access the shared document.
expiry_days: Optional integer specifying how many days until the share link expires. When None, the link does not expire automatically.
notify_emails: Optional list of email addresses (strings) to notify about the share. These recipients will receive notification emails about the shared document.
version: Optional string specifying a specific document version number to share. When None, shares the current version. Allows sharing historical versions of the document.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (bool, always True on successful execution), 'document_uid' (str, UID of the shared document), 'file_path' (str, FileCloud path to the document), 'share_url' (str, the generated shareable URL), 'share_id' (str/int, FileCloud's internal share identifier), 'share_type' (str, echoes the share_type parameter), 'has_password' (bool, indicates if password protection is enabled), 'expiry_days' (int or None, echoes the expiry_days parameter). On error, raises FileCloudError, ResourceNotFoundError, or ValidationError.
Dependencies
loggingosjsonuuidtempfiletypingtimeCDocs.dbCDocs.config.settingsCDocs.config.permissionsCDocs.models.documentCDocs.models.user_extensionsCDocs.utils.document_processorCDocs.utils.audit_trailCDocs.utils.notificationsCDocs.controllersCDocs.utils.metadata_catalogCDocs.utils.FC_api
Required Imports
import os
from typing import Dict, List, Any, Optional
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import ResourceNotFoundError, ValidationError
from CDocs.utils.FC_api import FileCloudAPI
Conditional/Optional Imports
These imports are only needed under specific conditions:
import logging
Condition: Required for error logging throughout the function
Required (conditional)from CDocs.controllers import log_controller_action, require_permission
Condition: Required for the decorators applied to this function
Required (conditional)Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.models.document import ControlledDocument
from CDocs.controllers.document_controller import create_document_share_link
# Example 1: Share with user context and password protection
user = DocUser.query.get(user_id)
result = create_document_share_link(
user=user,
document_uid='doc-12345',
share_type='view',
password='SecurePass123',
expiry_days=7,
notify_emails=['recipient@example.com']
)
print(f"Share URL: {result['share_url']}")
# Example 2: System-level share of specific version
result = create_document_share_link(
user=None,
document_uid='doc-12345',
version='2.1',
share_type='download'
)
# Example 3: Share using document object
doc = ControlledDocument.query.filter_by(uid='doc-12345').first()
result = create_document_share_link(
user=user,
document=doc,
share_type='view',
expiry_days=30
)
Best Practices
- Always provide either document_uid or document parameter, but not necessarily both
- Use the user parameter when sharing on behalf of a specific user to enable proper audit logging
- Set user=None only for system-level operations where no user context exists
- Consider setting expiry_days for sensitive documents to limit exposure window
- Use password protection for documents containing confidential information
- Handle FileCloudError, ResourceNotFoundError, and ValidationError exceptions appropriately
- The function requires SHARE_DOCUMENT permission when user is provided
- Ensure FileCloud client is properly configured before calling this function
- When sharing specific versions, verify the version exists before calling
- The function preserves file extensions in share names for proper file type recognition
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function manage_user_share_access_v1 73.7% similar
-
function manage_user_share_access_v2 72.3% similar
-
function manage_user_share_access 71.8% similar
-
function get_document_share_url 71.4% similar
-
function get_user_access_url 63.1% similar