🔍 Code Extractor

class ObjectSharingInformation

Maturity: 48

A class that provides comprehensive information about the sharing state of SharePoint securable objects (documents, list items, sites), including permissions, sharing links, and user access details.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/object_sharing_information.py
Lines:
20 - 273
Complexity:
complex

Purpose

This class serves as a data container and query interface for retrieving and managing sharing information for SharePoint objects. It provides static methods to query sharing capabilities and states for documents, list items, and sites, as well as instance methods to retrieve users with whom objects are shared. The class inherits from Entity and integrates with SharePoint's client context to execute service operations for sharing-related queries.

Source Code

class ObjectSharingInformation(Entity):
    """Provides information about the sharing state of a securable object."""

    @staticmethod
    def can_current_user_share(context, doc_id):
        """Indicates whether the current user can share the document identified by docId.

        :param office365.sharepoint.client_context.ClientContext context: SharePoint client context
        :param str doc_id: Identifies the document that will be analyzed from a sharing perspective.
        """
        binding_type = ObjectSharingInformation(context)
        payload = {"docId": doc_id}
        return_type = ClientResult(context, int())
        qry = ServiceOperationQuery(
            binding_type, "CanCurrentUserShare", None, payload, None, return_type, True
        )
        context.add_query(qry)
        return return_type

    @staticmethod
    def can_current_user_share_remote(context, doc_id):
        """Indicates whether the current user can share the document identified by docId, from a remote context.

        :param office365.sharepoint.client_context.ClientContext context: SharePoint client context
        :param str doc_id: Identifies the document that will be analyzed from a sharing perspective.
        """
        binding_type = ObjectSharingInformation(context)
        payload = {"docId": doc_id}
        return_type = ClientResult(context)
        qry = ServiceOperationQuery(
            binding_type,
            "CanCurrentUserShareRemote",
            None,
            payload,
            None,
            return_type,
            True,
        )
        context.add_query(qry)
        return return_type

    @staticmethod
    def get_web_sharing_information(
        context,
        exclude_current_user=None,
        exclude_site_admin=None,
        exclude_security_groups=None,
        retrieve_anonymous_links=None,
        retrieve_user_info_details=None,
        check_for_access_requests=None,
    ):
        """
        Retrieves information about the sharing state for the current site. The current site is the site
        in the context of which this method is invoked.

        :param office365.sharepoint.client_context.ClientContext context: SharePoint client context
        :param bool exclude_current_user: Specifies whether the returned sharing state information will exclude
            information about the user making the request.
        :param bool exclude_site_admin: Specifies whether the returned sharing state information will exclude
            information about users who are site collection administrators of the site collection which contains
            the current site
        :param bool exclude_security_groups: Specifies whether the returned sharing state information will exclude
            information about security groups which have permissions to the current site
        :param bool retrieve_anonymous_links:  This parameter is ignored by the method.
        :param bool retrieve_user_info_details: Specifies whether the returned sharing state information will contain
             basic or detailed information about the users with permissions to the current site
        :param bool check_for_access_requests: Specifies whether the returned sharing state information will contain a
             URL to a location which describes any access requests present in the current site,
             if such a URL is available
        """
        return_type = ObjectSharingInformation(context)
        payload = {
            "excludeCurrentUser": exclude_current_user,
            "excludeSiteAdmin": exclude_site_admin,
            "excludeSecurityGroups": exclude_security_groups,
            "retrieveAnonymousLinks": retrieve_anonymous_links,
            "retrieveUserInfoDetails": retrieve_user_info_details,
            "checkForAccessRequests": check_for_access_requests,
        }
        qry = ServiceOperationQuery(
            return_type,
            "GetWebSharingInformation",
            None,
            payload,
            None,
            return_type,
            True,
        )
        context.add_query(qry)
        return return_type

    def get_shared_with_users(self):
        """Returns an array that contains the users with whom a securable object is shared."""
        return_type = EntityCollection(self.context, ObjectSharingInformationUser)
        qry = ServiceOperationQuery(
            self, "GetSharedWithUsers", None, None, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    @staticmethod
    def get_list_item_sharing_information(
        context,
        list_id,
        item_id,
        exclude_current_user=True,
        exclude_site_admin=True,
        exclude_security_groups=True,
        retrieve_anonymous_links=False,
        retrieve_user_info_details=False,
        check_for_access_requests=False,
        return_type=None,
    ):
        # type: (ClientContext, str, int, Optional[bool], Optional[bool], Optional[bool], Optional[bool], Optional[bool], Optional[bool], Optional[ObjectSharingInformation]) -> ObjectSharingInformation
        """
        Retrieves information about the sharing state for a given list.

        :param check_for_access_requests: Specifies whether the returned sharing state information will contain a URL
        to a location which describes any access requests present in the site (2), if such a URL is available.
        :param retrieve_user_info_details: Specifies whether the returned sharing state information will contain
        basic or detailed information about the users with permissions to the list item.
        :param retrieve_anonymous_links: Specifies whether the returned sharing state information will contain
        information about a URL that allows an anonymous user to access the list item.
        :param exclude_security_groups: Specifies whether the returned sharing state information will exclude
        information about security groups which have permissions to the list item.
        :param exclude_site_admin:  Specifies whether the returned sharing state information will exclude
        information about users who are site collection administrators of the site collection which contains the list.
        :param exclude_current_user: Specifies whether the returned sharing state information will exclude
        information about the user making the request.
        :param item_id: The list item identifier for the list item for which the sharing state is requested.
        :param list_id: The list identifier for the list which contains the list item for which
        the sharing state is requested.
        :param context: SharePoint client context
        :param return_type: Return type
        """
        binding_type = ObjectSharingInformation(context)
        payload = {
            "listID": list_id,
            "itemID": item_id,
            "excludeCurrentUser": exclude_current_user,
            "excludeSiteAdmin": exclude_site_admin,
            "excludeSecurityGroups": exclude_security_groups,
            "retrieveAnonymousLinks": retrieve_anonymous_links,
            "retrieveUserInfoDetails": retrieve_user_info_details,
            "checkForAccessRequests": check_for_access_requests,
        }
        if not return_type:
            return_type = binding_type
        qry = ServiceOperationQuery(
            binding_type,
            "GetListItemSharingInformation",
            None,
            payload,
            None,
            return_type,
        )
        qry.static = True
        context.add_query(qry)
        return return_type

    @property
    def anonymous_edit_link(self):
        # type: () -> Optional[str]
        """
        Provides the URL that allows an anonymous user to edit the securable object.
        If such a URL is not available, this property will provide an empty string.
        """
        return self.properties.get("AnonymousEditLink", None)

    @property
    def anonymous_view_link(self):
        # type: () -> Optional[str]
        """
        Provides the URL that allows an anonymous user to view the securable object.
        If such a URL is not available, this property will provide an empty string.
        """
        return self.properties.get("AnonymousViewLink", None)

    @property
    def can_be_shared(self):
        # type: () -> Optional[bool]
        """
        Indicates whether the current securable object can be shared.
        """
        return self.properties.get("CanBeShared", None)

    @property
    def can_be_unshared(self):
        # type: () -> Optional[bool]
        """
        Indicates whether the current securable object can be unshared.
        """
        return self.properties.get("CanBeUnshared", None)

    @property
    def can_manage_permissions(self):
        # type: () -> Optional[bool]
        """
        Specifies whether the current user is allowed to change the permissions of the securable object.
        """
        return self.properties.get("CanManagePermissions", None)

    @property
    def has_pending_access_requests(self):
        # type: () -> Optional[bool]
        """
        Provides information about whether there are any pending access requests for the securable object.

        This information is only provided if the current user has sufficient permissions to view any pending
        access requests. If the current user does not have such permissions, this property will return false.
        """
        return self.properties.get("HasPendingAccessRequests", None)

    @property
    def has_permission_levels(self):
        # type: () -> Optional[bool]
        """
        Indicates whether the object sharing information contains permissions information in addition to the identities
        of the users who have access to the securable object.
        """
        return self.properties.get("HasPermissionLevels", None)

    @property
    def sharing_links(self):
        """Indicates the collection of all available sharing links for the securable object."""
        return self.properties.get(
            "SharingLinks", ClientValueCollection(SharingLinkInfo)
        )

    @property
    def shared_with_users_collection(self):
        """A collection of shared with users."""
        return self.properties.get(
            "SharedWithUsersCollection",
            EntityCollection(
                self.context,
                ObjectSharingInformationUser,
                ResourcePath("SharedWithUsersCollection", self.resource_path),
            ),
        )

    def get_property(self, name, default_value=None):
        if name == "SharedWithUsersCollection":
            default_value = self.shared_with_users_collection
        elif name == "SharingLinks":
            default_value = self.sharing_links
        return super(ObjectSharingInformation, self).get_property(name, default_value)

    def set_property(self, name, value, persist_changes=True):
        super(ObjectSharingInformation, self).set_property(name, value, persist_changes)
        # fallback: create a new resource path
        if name == "AnonymousEditLink" and self._resource_path is None:
            self._resource_path = None
        return self

Parameters

Name Type Default Kind
bases Entity -

Parameter Details

context: A ClientContext instance representing the SharePoint client context. This is required for all operations and provides the connection to the SharePoint service. Passed to the parent Entity class constructor.

doc_id: String identifier for a document to be analyzed from a sharing perspective. Used in can_current_user_share and can_current_user_share_remote methods.

list_id: String identifier for a SharePoint list containing the item for which sharing state is requested.

item_id: Integer identifier for a specific list item within a list for which sharing state is requested.

exclude_current_user: Boolean flag to exclude information about the user making the request from the returned sharing state information. Defaults vary by method.

exclude_site_admin: Boolean flag to exclude information about site collection administrators from the returned sharing state information.

exclude_security_groups: Boolean flag to exclude information about security groups with permissions from the returned sharing state information.

retrieve_anonymous_links: Boolean flag to include information about anonymous access URLs in the returned sharing state information.

retrieve_user_info_details: Boolean flag to specify whether to return detailed (True) or basic (False) information about users with permissions.

check_for_access_requests: Boolean flag to include a URL to access requests location in the returned sharing state information if available.

return_type: Optional ObjectSharingInformation instance to use as the return type for get_list_item_sharing_information method.

Return Value

The class itself returns an ObjectSharingInformation instance when instantiated. Static methods return either ClientResult objects containing query results (can_current_user_share returns ClientResult with int, can_current_user_share_remote returns generic ClientResult) or ObjectSharingInformation instances (get_web_sharing_information, get_list_item_sharing_information). The get_shared_with_users instance method returns an EntityCollection of ObjectSharingInformationUser objects. Properties return various types: strings for links (anonymous_edit_link, anonymous_view_link), booleans for capabilities (can_be_shared, can_be_unshared, can_manage_permissions, has_pending_access_requests, has_permission_levels), ClientValueCollection for sharing_links, and EntityCollection for shared_with_users_collection.

Class Interface

Methods

can_current_user_share(context: ClientContext, doc_id: str) -> ClientResult static

Purpose: Determines whether the current user has permission to share a specific document

Parameters:

  • context: SharePoint client context for executing the query
  • doc_id: Document identifier to check sharing permissions for

Returns: ClientResult containing an integer indicating whether the user can share (requires execute_query() to populate)

can_current_user_share_remote(context: ClientContext, doc_id: str) -> ClientResult static

Purpose: Determines whether the current user can share a document from a remote context (cross-site scenario)

Parameters:

  • context: SharePoint client context for executing the query
  • doc_id: Document identifier to check sharing permissions for

Returns: ClientResult containing sharing capability information (requires execute_query() to populate)

get_web_sharing_information(context: ClientContext, exclude_current_user: bool = None, exclude_site_admin: bool = None, exclude_security_groups: bool = None, retrieve_anonymous_links: bool = None, retrieve_user_info_details: bool = None, check_for_access_requests: bool = None) -> ObjectSharingInformation static

Purpose: Retrieves comprehensive sharing state information for the current SharePoint site

Parameters:

  • context: SharePoint client context
  • exclude_current_user: Whether to exclude the requesting user from results
  • exclude_site_admin: Whether to exclude site collection administrators from results
  • exclude_security_groups: Whether to exclude security groups from results
  • retrieve_anonymous_links: Whether to include anonymous access links (parameter is ignored)
  • retrieve_user_info_details: Whether to return detailed user information
  • check_for_access_requests: Whether to include access request URL if available

Returns: ObjectSharingInformation instance with site-level sharing details (requires execute_query() to populate)

get_shared_with_users(self) -> EntityCollection

Purpose: Retrieves the collection of users with whom the securable object is shared

Returns: EntityCollection of ObjectSharingInformationUser objects (requires execute_query() to populate)

get_list_item_sharing_information(context: ClientContext, list_id: str, item_id: int, exclude_current_user: bool = True, exclude_site_admin: bool = True, exclude_security_groups: bool = True, retrieve_anonymous_links: bool = False, retrieve_user_info_details: bool = False, check_for_access_requests: bool = False, return_type: Optional[ObjectSharingInformation] = None) -> ObjectSharingInformation static

Purpose: Retrieves detailed sharing state information for a specific list item

Parameters:

  • context: SharePoint client context
  • list_id: GUID identifier of the list containing the item
  • item_id: Integer ID of the list item
  • exclude_current_user: Whether to exclude the requesting user from results
  • exclude_site_admin: Whether to exclude site administrators from results
  • exclude_security_groups: Whether to exclude security groups from results
  • retrieve_anonymous_links: Whether to include anonymous access URLs
  • retrieve_user_info_details: Whether to return detailed user information
  • check_for_access_requests: Whether to include access request URL
  • return_type: Optional custom return type instance

Returns: ObjectSharingInformation instance with list item sharing details (requires execute_query() to populate)

get_property(self, name: str, default_value=None) -> Any

Purpose: Retrieves a property value with special handling for collection properties

Parameters:

  • name: Property name to retrieve
  • default_value: Default value if property not found

Returns: Property value or default_value if not found, with special initialization for SharedWithUsersCollection and SharingLinks

set_property(self, name: str, value: Any, persist_changes: bool = True) -> ObjectSharingInformation

Purpose: Sets a property value with special handling for AnonymousEditLink that resets resource path

Parameters:

  • name: Property name to set
  • value: Value to assign to the property
  • persist_changes: Whether to persist the change

Returns: Self reference for method chaining

@property anonymous_edit_link(self) -> Optional[str] property

Purpose: Gets the URL that allows anonymous users to edit the securable object

Returns: URL string or empty string if not available, None if not yet loaded

@property anonymous_view_link(self) -> Optional[str] property

Purpose: Gets the URL that allows anonymous users to view the securable object

Returns: URL string or empty string if not available, None if not yet loaded

@property can_be_shared(self) -> Optional[bool] property

Purpose: Indicates whether the current securable object can be shared

Returns: Boolean indicating sharing capability, None if not yet loaded

@property can_be_unshared(self) -> Optional[bool] property

Purpose: Indicates whether the current securable object can be unshared

Returns: Boolean indicating unsharing capability, None if not yet loaded

@property can_manage_permissions(self) -> Optional[bool] property

Purpose: Indicates whether the current user can change permissions on the securable object

Returns: Boolean indicating permission management capability, None if not yet loaded

@property has_pending_access_requests(self) -> Optional[bool] property

Purpose: Indicates whether there are pending access requests for the securable object (only if user has permissions to view them)

Returns: Boolean indicating presence of access requests, False if user lacks permissions, None if not yet loaded

@property has_permission_levels(self) -> Optional[bool] property

Purpose: Indicates whether the sharing information includes permission level details in addition to user identities

Returns: Boolean indicating presence of permission level information, None if not yet loaded

@property sharing_links(self) -> ClientValueCollection property

Purpose: Gets the collection of all available sharing links for the securable object

Returns: ClientValueCollection of SharingLinkInfo objects

@property shared_with_users_collection(self) -> EntityCollection property

Purpose: Gets the collection of users with whom the object is shared

Returns: EntityCollection of ObjectSharingInformationUser objects

Attributes

Name Type Description Scope
context ClientContext SharePoint client context inherited from Entity base class, used for executing queries instance
properties dict Dictionary storing property values loaded from SharePoint service, inherited from Entity base class instance
_resource_path Optional[ResourcePath] Resource path for the entity, inherited from Entity base class, can be reset by set_property for AnonymousEditLink instance

Dependencies

  • office365-runtime
  • office365-sharepoint

Required Imports

from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.sharepoint.entity import Entity
from office365.sharepoint.entity_collection import EntityCollection
from office365.sharepoint.sharing.links.info import SharingLinkInfo
from office365.sharepoint.sharing.object_sharing_information_user import ObjectSharingInformationUser
from office365.sharepoint.client_context import ClientContext

Usage Example

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.sharing.object_sharing_information import ObjectSharingInformation

# Setup SharePoint context with authentication
ctx = ClientContext('https://yourtenant.sharepoint.com/sites/yoursite').with_credentials(user_credentials)

# Check if current user can share a document
can_share_result = ObjectSharingInformation.can_current_user_share(ctx, 'document_id_123')
ctx.execute_query()
print(f"Can share: {can_share_result.value}")

# Get sharing information for a list item
sharing_info = ObjectSharingInformation.get_list_item_sharing_information(
    ctx,
    list_id='list-guid-here',
    item_id=1,
    exclude_current_user=False,
    retrieve_user_info_details=True
)
ctx.execute_query()
print(f"Can be shared: {sharing_info.can_be_shared}")
print(f"Anonymous view link: {sharing_info.anonymous_view_link}")

# Get users with whom the object is shared
shared_users = sharing_info.get_shared_with_users()
ctx.execute_query()
for user in shared_users:
    print(f"Shared with: {user.properties}")

# Get web-level sharing information
web_sharing = ObjectSharingInformation.get_web_sharing_information(
    ctx,
    exclude_current_user=True,
    retrieve_user_info_details=True
)
ctx.execute_query()
print(f"Web can manage permissions: {web_sharing.can_manage_permissions}")

Best Practices

  • Always call ctx.execute_query() after invoking static methods or instance methods to execute the queued service operations and populate results.
  • Use static methods for initial queries to retrieve sharing information; use instance methods on returned objects for follow-up queries.
  • Check property values for None before using them, as they may not be populated until after execute_query() is called.
  • Set appropriate boolean flags (exclude_current_user, retrieve_user_info_details, etc.) based on your needs to optimize query performance and reduce data transfer.
  • Ensure the ClientContext has appropriate authentication and permissions before querying sharing information.
  • The class follows a lazy-loading pattern - properties are populated from the 'properties' dictionary after server queries execute.
  • When using get_list_item_sharing_information, you can optionally provide a return_type parameter for custom return type handling.
  • The set_property method includes special handling for AnonymousEditLink that resets the resource path - be aware of this side effect.
  • Use get_shared_with_users() to retrieve detailed user information rather than accessing shared_with_users_collection directly for better query control.
  • The sharing_links property returns a ClientValueCollection of SharingLinkInfo objects containing all available sharing links.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class SharingInformation 82.0% similar

    Represents sharing information for a SharePoint securable object, providing access to sharing settings, picker configurations, sharing abilities, and link templates.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/information.py
  • class SharingPermissionInformation 81.5% similar

    A class representing sharing permission information for SharePoint entities such as groups or roles, providing access to permission metadata and default permission status.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/permission_information.py
  • class ObjectSharingInformationUser 80.4% similar

    A class representing information about a principal (user or group) with whom a SharePoint securable object is shared, providing access to their email, SIP address, login name, and related principal/user objects.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/object_sharing_information_user.py
  • class ObjectSharingSettings 76.1% similar

    This class contains the information necessary to read and change the sharing status of a SharePoint object. It also contains a reference to SharePoint specific settings denoted by "SharePointSettings".

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/object_sharing_settings.py
  • class SharedDocumentInfo 74.9% similar

    A SharePoint entity class representing metadata and information about a shared document, including its activity and author details.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/sharing/shared_document_info.py
← Back to Browse