class DocumentSharingManager
A SharePoint document sharing manager class that provides static methods for managing document permissions, sharing settings, and shared views in SharePoint.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/document_manager.py
13 - 135
moderate
Purpose
DocumentSharingManager is a utility class that encapsulates SharePoint document sharing operations. It provides static methods to retrieve role definitions, manage the 'Shared With Me' view, and update document sharing permissions for multiple users. This class acts as a service layer for SharePoint sharing functionality, handling permission management, email notifications, and access control list (ACL) propagation. It inherits from Entity to integrate with the SharePoint client context framework.
Source Code
class DocumentSharingManager(Entity):
"""Specifies document sharing related methods."""
@staticmethod
def get_role_definition(context, role):
"""This method returns a role definition in the current web that is associated with a given Role
(section 3.2.5.188) value.
:type context: office365.sharepoint.client_context.ClientContext
:param int role: A Role value for which to obtain the associated role definition object.
"""
return_type = RoleDefinition(context)
context.web.role_definitions.add_child(return_type)
binding_type = DocumentSharingManager(context)
qry = ServiceOperationQuery(
binding_type, "GetRoleDefinition", [role], None, None, return_type, True
)
context.add_query(qry)
return return_type
@staticmethod
def remove_items_from_shared_with_me_view(context, item_urls):
"""
Removes an item so that it no longer shows in the current user's 'Shared With Me' view. However, this
does not remove the user's actual permissions to the item. Up to 200 items can be provided in a single call.
Returns a list of results indicating whether the items were successfully removed. The length of this array
will match the length of the itemUrls array that was provided.
:type context: office365.sharepoint.client_context.ClientContext
:param list[str] item_urls: A list of absolute URLs of the items to be removed from the view.
These items might belong to any site or site collection in the tenant.
"""
return_type = ClientResult(
context, ClientValueCollection(SharedWithMeViewItemRemovalResult)
)
binding_type = DocumentSharingManager(context)
qry = ServiceOperationQuery(
binding_type,
"RemoveItemsFromSharedWithMeView",
[item_urls],
None,
None,
return_type,
True,
)
context.add_query(qry)
return return_type
@staticmethod
def update_document_sharing_info(
context,
resource_address,
user_role_assignments,
validate_existing_permissions=None,
additive_mode=None,
send_server_managed_notification=None,
custom_message=None,
include_anonymous_links_in_notification=None,
propagate_acl=None,
return_type=None,
):
"""
This method allows a caller with the 'ManagePermission' permission to update sharing information about a
document to enable document sharing with a set of users. It returns an array of
UserSharingResult (section 3.2.5.190) elements where each element contains the sharing status for each user.
:type context: office365.sharepoint.client_context.ClientContext
:param str resource_address: A URL that points to a securable object, which can be a document, folder or the
root folder of a document library.
:param list[UserRoleAssignment] user_role_assignments:An array of recipients and assigned roles on the securable
object pointed to by the resourceAddress parameter.
:param bool validate_existing_permissions: A Boolean flag indicating how to honor a requested permission
for a user. If this value is "true", the protocol server will not grant the requested permission if a user
already has sufficient permissions, and if this value is "false", the protocol server will grant the
requested permission whether or not a user already has the same or more permissions.
This parameter is applicable only when the parameter additiveMode is set to true.
:param bool additive_mode: A Boolean flag indicating whether the permission setting uses the additive or strict
mode. If this value is "true", the permission setting uses the additive mode, which means that the
specified permission will be added to the user's current list of permissions if it is not there already,
and if this value is "false", the permission setting uses the strict mode, which means that the specified
permission will replace the user's current permissions.
:param bool send_server_managed_notification: A Boolean flag to indicate whether or not to generate an email
notification to each recipient in the "userRoleAssignments" array after the document update is completed
successfully. If this value is "true", the protocol server will send an email notification if an email
server is configured, and if the value is "false", no email notification will be sent.
:param str custom_message: A custom message to be included in the email notification.
:param bool include_anonymous_links_in_notification: A Boolean flag that indicates whether or not to include
anonymous access links in the email notification to each recipient in the userRoleAssignments array after
the document update is completed successfully. If the value is "true", the protocol server will include
an anonymous access link in the email notification, and if the value is "false", no link will be included.
:param bool propagate_acl: A flag to determine if permissions SHOULD be pushed to items with unique permission.
:param ClientResult return_type:
"""
if return_type is None:
return_type = ClientResult(
context, ClientValueCollection(UserSharingResult)
)
payload = {
"resourceAddress": resource_address,
"userRoleAssignments": user_role_assignments,
"validateExistingPermissions": validate_existing_permissions,
"additiveMode": additive_mode,
"sendServerManagedNotification": send_server_managed_notification,
"customMessage": custom_message,
"includeAnonymousLinksInNotification": include_anonymous_links_in_notification,
"propagateAcl": propagate_acl,
}
binding_type = DocumentSharingManager(context)
qry = ServiceOperationQuery(
binding_type,
"UpdateDocumentSharingInfo",
None,
payload,
None,
return_type,
True,
)
context.add_query(qry)
return return_type
@property
def entity_type_name(self):
return "SP.Sharing.DocumentSharingManager"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
context: A ClientContext instance representing the SharePoint connection and execution context. Required for all operations to communicate with SharePoint services.
role: An integer representing a SharePoint Role value (from section 3.2.5.188 of SharePoint protocol) used to identify and retrieve the associated role definition.
item_urls: A list of absolute URL strings pointing to SharePoint items to be removed from the 'Shared With Me' view. Maximum of 200 items per call. Items can belong to any site or site collection in the tenant.
resource_address: A URL string pointing to a securable SharePoint object (document, folder, or document library root folder) where sharing permissions will be updated.
user_role_assignments: A list of UserRoleAssignment objects specifying recipients and their assigned roles on the target resource. Each assignment defines a user and their permission level.
validate_existing_permissions: Boolean flag controlling permission validation. If True, requested permissions are not granted if user already has sufficient permissions. If False, requested permissions are granted regardless of existing permissions. Only applicable when additiveMode is True.
additive_mode: Boolean flag controlling permission mode. If True, uses additive mode where new permissions are added to existing ones. If False, uses strict mode where new permissions replace existing ones.
send_server_managed_notification: Boolean flag to control email notifications. If True and email server is configured, sends notification to all recipients in user_role_assignments after successful update.
custom_message: Optional string containing a custom message to include in email notifications sent to recipients.
include_anonymous_links_in_notification: Boolean flag to include anonymous access links in email notifications. If True, anonymous links are included in notifications to recipients.
propagate_acl: Boolean flag determining whether permissions should be pushed to items with unique permissions in the hierarchy.
return_type: Optional ClientResult object to store the operation results. If not provided, a new ClientResult with ClientValueCollection of UserSharingResult is created.
Return Value
The class itself returns an Entity instance when instantiated. The static methods return different types: get_role_definition returns a RoleDefinition object representing the SharePoint role; remove_items_from_shared_with_me_view returns a ClientResult containing a ClientValueCollection of SharedWithMeViewItemRemovalResult objects indicating success/failure for each item; update_document_sharing_info returns a ClientResult containing a ClientValueCollection of UserSharingResult objects with sharing status for each user. The entity_type_name property returns the string 'SP.Sharing.DocumentSharingManager'.
Class Interface
Methods
get_role_definition(context: ClientContext, role: int) -> RoleDefinition
static
Purpose: Retrieves a SharePoint role definition object associated with a given Role value from the current web
Parameters:
context: ClientContext instance for SharePoint communicationrole: Integer Role value (section 3.2.5.188) to identify the role definition
Returns: RoleDefinition object representing the SharePoint role with its permissions and settings
remove_items_from_shared_with_me_view(context: ClientContext, item_urls: list[str]) -> ClientResult
static
Purpose: Removes items from the current user's 'Shared With Me' view without removing actual permissions. Supports up to 200 items per call
Parameters:
context: ClientContext instance for SharePoint communicationitem_urls: List of absolute URLs of items to remove from the view (max 200 items)
Returns: ClientResult containing ClientValueCollection of SharedWithMeViewItemRemovalResult objects indicating success/failure for each item
update_document_sharing_info(context: ClientContext, resource_address: str, user_role_assignments: list[UserRoleAssignment], validate_existing_permissions: bool = None, additive_mode: bool = None, send_server_managed_notification: bool = None, custom_message: str = None, include_anonymous_links_in_notification: bool = None, propagate_acl: bool = None, return_type: ClientResult = None) -> ClientResult
static
Purpose: Updates document sharing permissions for multiple users with configurable permission modes, validation, and notification options. Requires 'ManagePermission' permission
Parameters:
context: ClientContext instance for SharePoint communicationresource_address: URL pointing to the securable object (document, folder, or library root)user_role_assignments: List of UserRoleAssignment objects specifying users and their rolesvalidate_existing_permissions: If True, don't grant permission if user already has sufficient permissions (only with additive_mode=True)additive_mode: If True, add permissions to existing ones; if False, replace existing permissionssend_server_managed_notification: If True, send email notification to recipients (requires email server)custom_message: Custom message to include in email notificationsinclude_anonymous_links_in_notification: If True, include anonymous access links in notificationspropagate_acl: If True, push permissions to items with unique permissionsreturn_type: Optional ClientResult to store results; created if not provided
Returns: ClientResult containing ClientValueCollection of UserSharingResult objects with sharing status for each user
@property entity_type_name() -> str
property
Purpose: Returns the SharePoint entity type name for this manager class
Returns: String 'SP.Sharing.DocumentSharingManager' representing the SharePoint entity type
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
entity_type_name |
str | The SharePoint entity type identifier 'SP.Sharing.DocumentSharingManager' | instance |
Dependencies
office365
Required Imports
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.sharing.document_sharing_manager import DocumentSharingManager
from office365.sharepoint.sharing.user_role_assignment import UserRoleAssignment
Usage Example
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.sharing.document_sharing_manager import DocumentSharingManager
from office365.sharepoint.sharing.user_role_assignment import UserRoleAssignment
# Initialize SharePoint context
ctx = ClientContext('https://tenant.sharepoint.com/sites/site').with_credentials(credentials)
# Get a role definition
role_def = DocumentSharingManager.get_role_definition(ctx, role=1073741827)
ctx.execute_query()
print(f"Role: {role_def.name}")
# Remove items from Shared With Me view
item_urls = ['https://tenant.sharepoint.com/sites/site/Shared%20Documents/file.docx']
result = DocumentSharingManager.remove_items_from_shared_with_me_view(ctx, item_urls)
ctx.execute_query()
for removal_result in result.value:
print(f"Removed: {removal_result.itemRemoved}")
# Update document sharing permissions
user_assignments = [UserRoleAssignment(userId='user@domain.com', roleValue=1073741827)]
sharing_result = DocumentSharingManager.update_document_sharing_info(
ctx,
resource_address='https://tenant.sharepoint.com/sites/site/Shared%20Documents/file.docx',
user_role_assignments=user_assignments,
additive_mode=True,
send_server_managed_notification=True,
custom_message='Document shared with you'
)
ctx.execute_query()
for user_result in sharing_result.value:
print(f"User: {user_result.user}, Status: {user_result.status}")
Best Practices
- Always call ctx.execute_query() after invoking static methods to execute the queued operations against SharePoint
- Use additive_mode=True when you want to preserve existing permissions and only add new ones
- Set validate_existing_permissions=True to avoid redundant permission grants when using additive mode
- Limit item_urls to 200 items maximum per call to remove_items_from_shared_with_me_view
- Ensure the authenticated user has 'ManagePermission' permission before calling update_document_sharing_info
- Use custom_message parameter to provide context when sending notifications to users
- Set propagate_acl=True carefully as it affects items with unique permissions in the hierarchy
- All methods are static and do not require class instantiation - call them directly on the class
- The class inherits from Entity but is primarily used as a static utility class
- Return values are ClientResult objects that need to be accessed via the .value property after execute_query()
- Handle potential exceptions from execute_query() for network or permission errors
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class DocumentsSharedWithMe 75.8% similar
-
class WebSharingManager 74.5% similar
-
class ObjectSharingInformation 73.3% similar
-
class SharedWithMeDocument 72.5% similar
-
class DocumentsSharedWithGroup 69.8% similar