示例#1
0
    def test_create_user_from_managed_identity(self, connection_string):
        endpoint, access_key = parse_connection_str(connection_string)
        from devtools_testutils import is_live
        if not is_live():
            credential = FakeTokenCredential()
        else:
            credential = DefaultAzureCredential()
        identity_client = CommunicationIdentityClient(endpoint, credential)
        user = identity_client.create_user()

        assert user.identifier is not None
    def create_user(self):
        from azure.communication.administration import CommunicationIdentityClient

        if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None:
            from azure.identity import DefaultAzureCredential
            identity_client = CommunicationIdentityClient(
                self.endpoint, DefaultAzureCredential())
        else:
            identity_client = CommunicationIdentityClient.from_connection_string(
                self.connection_string)
        user = identity_client.create_user()
        print(user.identifier)
    def issue_token(self):
        from azure.communication.administration import CommunicationIdentityClient

        if self.client_id is not None and self.client_secret is not None and self.tenant_id is not None:
            from azure.identity import DefaultAzureCredential
            identity_client = CommunicationIdentityClient(
                self.endpoint, DefaultAzureCredential())
        else:
            identity_client = CommunicationIdentityClient.from_connection_string(
                self.connection_string)
        user = identity_client.create_user()
        tokenresponse = identity_client.issue_token(user, scopes=["chat"])
        print(tokenresponse)
示例#4
0
    def test_issue_token_from_managed_identity(self, connection_string):
        endpoint, access_key = parse_connection_str(connection_string)
        from devtools_testutils import is_live
        if not is_live():
            credential = FakeTokenCredential()
        else:
            credential = DefaultAzureCredential()
        identity_client = CommunicationIdentityClient(endpoint, credential)
        user = identity_client.create_user()

        token_response = identity_client.issue_token(user, scopes=["chat"])

        assert user.identifier is not None
        assert token_response.token is not None
    def setUp(self):
        super(ChatThreadClientTestAsync, self).setUp()

        self.recording_processors.extend([
            BodyReplacerProcessor(keys=[
                "id", "token", "senderId", "chatMessageId", "nextLink",
                "members", "multipleStatus", "value"
            ]),
            URIIdentityReplacer(),
            ResponseReplacerProcessor(keys=[self._resource_name]),
            ChatURIReplacer()
        ])

        endpoint, _ = parse_connection_str(self.connection_str)
        self.endpoint = endpoint

        self.identity_client = CommunicationIdentityClient.from_connection_string(
            self.connection_str)

        # create user
        self.user = self.identity_client.create_user()
        token_response = self.identity_client.issue_token(self.user,
                                                          scopes=["chat"])
        self.token = token_response.token

        # create another user
        self.new_user = self.identity_client.create_user()

        # create ChatClient
        self.chat_client = ChatClient(self.endpoint,
                                      CommunicationUserCredential(self.token))
def create_user_grant_access(scope):
    # Create a new user
    try:
        connection_string = os.environ[
            'COMMUNICATION_SERVICES_CONNECTION_STRING']
        client = CommunicationIdentityClient.from_connection_string(
            connection_string)
        user = client.create_user()
        print("\nCreated a user with ID: " + user.identifier + ":")

        # Issue an access token with the "voip" scope for a new user
        token_result = client.issue_token(user, [scope])
        expires_on = token_result.expires_on.strftime('%d/%m/%y %I:%M %S %p')
        print("\nIssued a token with '" + scope + "' scope that expires at " +
              expires_on + ":")
        print("\n" + token_result.token)

        # Revoke user access tokens
        # client.revoke_tokens(user)
        # print("\nSuccessfully revoked all tokens for user with ID: " + user.identifier)

        # Delete user
        # client.delete_user(user)
        # print("\nDeleted the user with ID: " + user.identifier)

    except Exception as ex:
        print('Exception:')
        print(ex)
    def create_user(self):
        from azure.communication.administration import CommunicationIdentityClient
        identity_client = CommunicationIdentityClient.from_connection_string(
            self.connection_string)
        user = identity_client.create_user()

        print(user.identifier)
示例#8
0
    def setUp(self):
        super(ChatClientTest, self).setUp()

        self.recording_processors.extend([
            BodyReplacerProcessor(keys=[
                "id", "token", "createdBy", "members", "multipleStatus",
                "value"
            ]),
            URIIdentityReplacer(),
            ChatURIReplacer()
        ])

        self.identity_client = CommunicationIdentityClient.from_connection_string(
            self.connection_str)

        endpoint, _ = parse_connection_str(self.connection_str)
        self.endpoint = endpoint

        # create user and issue token
        self.user = self.identity_client.create_user()
        tokenresponse = self.identity_client.issue_token(self.user,
                                                         scopes=["chat"])
        self.token = tokenresponse.token

        # create ChatClient
        self.chat_client = ChatClient(self.endpoint,
                                      CommunicationTokenCredential(self.token))
    def test_delete_user(self, connection_string):
        identity_client = CommunicationIdentityClient.from_connection_string(
            connection_string)
        user = identity_client.create_user()

        identity_client.delete_user(user)

        assert user.identifier is not None
 def setUp(self):
     super(CommunicationIdentityClientTest, self).setUp()
     self.recording_processors.extend([
         BodyReplacerProcessor(keys=["id", "token"]),
         URIIdentityReplacer()
     ])
     self.identity_client = CommunicationIdentityClient.from_connection_string(
         self.connection_str)
    def issue_token(self):
        from azure.communication.administration import CommunicationIdentityClient

        identity_client = CommunicationIdentityClient.from_connection_string(
            self.connection_string)
        user = identity_client.create_user()
        tokenresponse = identity_client.issue_token(user, scopes=["chat"])
        print(tokenresponse)
    def test_issue_token(self, connection_string):
        identity_client = CommunicationIdentityClient.from_connection_string(
            connection_string)
        user = identity_client.create_user()

        token_response = identity_client.issue_token(user, scopes=["chat"])

        assert user.identifier is not None
        assert token_response.token is not None
class ChatThreadClientSamples(object):
    from azure.communication.administration import CommunicationIdentityClient
    connection_string = os.environ.get(
        "AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING", None)
    if not connection_string:
        raise ValueError(
            "Set AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING env before run this sample."
        )

    identity_client = CommunicationIdentityClient.from_connection_string(
        connection_string)
    user = identity_client.create_user()
    tokenresponse = identity_client.issue_token(user, scopes=["chat"])
    token = tokenresponse.token

    endpoint = os.environ.get("AZURE_COMMUNICATION_SERVICE_ENDPOINT", None)
    if not endpoint:
        raise ValueError(
            "Set AZURE_COMMUNICATION_SERVICE_ENDPOINT env before run this sample."
        )

    _thread_id = None
    _message_id = None
    new_user = identity_client.create_user()

    def create_chat_thread_client(self):
        # [START create_chat_thread_client]
        from datetime import datetime
        from azure.communication.chat import (ChatClient, ChatThreadMember,
                                              CommunicationUserIdentifier,
                                              CommunicationTokenCredential,
                                              CommunicationTokenRefreshOptions)
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(refresh_options))
        topic = "test topic"
        members = [
            ChatThreadMember(user=self.user,
                             display_name='name',
                             share_history_time=datetime.utcnow())
        ]
        chat_thread_client = chat_client.create_chat_thread(topic, members)
        # [END create_chat_thread_client]
        self._thread_id = chat_thread_client.thread_id
        print("chat_thread_client created")

    def update_thread(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START update_thread]
        topic = "updated thread topic"
        chat_thread_client.update_thread(topic=topic)
        # [END update_thread]

        print("update_chat_thread succeeded")

    def send_message(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START send_message]
        from azure.communication.chat import ChatMessagePriority

        priority = ChatMessagePriority.NORMAL
        content = 'hello world'
        sender_display_name = 'sender name'

        send_message_result = chat_thread_client.send_message(
            content,
            priority=priority,
            sender_display_name=sender_display_name)
        # [END send_message]

        self._message_id = send_message_result.id
        print("send_chat_message succeeded, message id:", self._message_id)

    def get_message(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START get_message]
        chat_message = chat_thread_client.get_message(self._message_id)
        # [END get_message]

        print("get_chat_message succeeded, message id:", chat_message.id, \
            "content: ", chat_message.content)

    def list_messages(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START list_messages]
        from datetime import datetime, timedelta
        start_time = datetime.utcnow() - timedelta(days=1)
        chat_messages = chat_thread_client.list_messages(results_per_page=1,
                                                         start_time=start_time)

        print(
            "list_messages succeeded with results_per_page is 1, and start time is yesterday UTC"
        )
        for chat_message_page in chat_messages.by_page():
            l = list(chat_message_page)
            print("page size: ", len(l))
        # [END list_messages]

    def update_message(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START update_message]
        content = "updated content"
        chat_thread_client.update_message(self._message_id, content=content)
        # [END update_message]

        print("update_chat_message succeeded")

    def send_read_receipt(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START send_read_receipt]
        chat_thread_client.send_read_receipt(self._message_id)
        # [END send_read_receipt]

        print("send_read_receipt succeeded")

    def list_read_receipts(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START list_read_receipts]
        read_receipts = chat_thread_client.list_read_receipts()
        print("list_read_receipts succeeded, receipts:")
        for read_receipt in read_receipts:
            print(read_receipt)
        # [END list_read_receipts]

    def delete_message(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START delete_message]
        chat_thread_client.delete_message(self._message_id)
        # [END delete_message]
        print("delete_chat_message succeeded")

    def list_members(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START list_members]
        chat_thread_members = chat_thread_client.list_members()
        print("list_chat_members succeeded, members: ")
        for chat_thread_member in chat_thread_members:
            print(chat_thread_member)
        # [END list_members]

    def add_members(self):
        from azure.communication.chat import ChatThreadClient, CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)

        # [START add_members]
        from azure.communication.chat import ChatThreadMember
        from datetime import datetime
        new_member = ChatThreadMember(user=self.new_user,
                                      display_name='name',
                                      share_history_time=datetime.utcnow())
        thread_members = [new_member]
        chat_thread_client.add_members(thread_members)
        # [END add_members]
        print("add_chat_members succeeded")

    def remove_member(self):
        from azure.communication.chat import ChatThreadClient
        from azure.communication.chat import CommunicationTokenCredential, CommunicationUser, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)

        # [START remove_member]
        chat_thread_client.remove_member(self.new_user)
        # [END remove_member]

        print("remove_chat_member succeeded")

    def send_typing_notification(self):
        from azure.communication.chat import ChatThreadClient, CommunicationTokenCredential, CommunicationTokenRefreshOptions
        refresh_options = CommunicationTokenRefreshOptions(self.token)
        chat_thread_client = ChatThreadClient(
            self.endpoint, CommunicationTokenCredential(refresh_options),
            self._thread_id)
        # [START send_typing_notification]
        chat_thread_client.send_typing_notification()
        # [END send_typing_notification]

        print("send_typing_notification succeeded")

    def clean_up(self):
        print("cleaning up: deleting created users.")
        self.identity_client.delete_user(self.user)
        self.identity_client.delete_user(self.new_user)
示例#14
0
class ChatClientSamples(object):
    from azure.communication.administration import CommunicationIdentityClient
    connection_string = os.environ.get(
        "AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING", None)
    if not connection_string:
        raise ValueError(
            "Set AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING env before run this sample."
        )

    identity_client = CommunicationIdentityClient.from_connection_string(
        connection_string)
    user = identity_client.create_user()
    tokenresponse = identity_client.issue_token(user, scopes=["chat"])
    token = tokenresponse.token

    endpoint = os.environ.get("AZURE_COMMUNICATION_SERVICE_ENDPOINT", None)
    if not endpoint:
        raise ValueError(
            "Set AZURE_COMMUNICATION_SERVICE_ENDPOINT env before run this sample."
        )

    _thread_id = None

    def create_chat_client(self):
        # [START create_chat_client]
        from azure.communication.chat import ChatClient, CommunicationTokenCredential
        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))
        # [END create_chat_client]

    def create_thread(self):
        # [START create_thread]
        from datetime import datetime
        from azure.communication.chat import (ChatClient, ChatThreadMember,
                                              CommunicationUserIdentifier,
                                              CommunicationTokenCredential)

        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))

        topic = "test topic"
        members = [
            ChatThreadMember(user=self.user,
                             display_name='name',
                             share_history_time=datetime.utcnow())
        ]
        chat_thread_client = chat_client.create_chat_thread(topic, members)
        # [END create_thread]

        self._thread_id = chat_thread_client.thread_id
        print("thread created, id: " + self._thread_id)

    def get_chat_thread_client(self):
        # [START get_chat_thread_client]
        from azure.communication.chat import ChatClient, CommunicationTokenCredential

        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))
        chat_thread_client = chat_client.get_chat_thread_client(
            self._thread_id)
        # [END get_chat_thread_client]

        print("chat_thread_client created with thread id: ",
              chat_thread_client.thread_id)

    def get_thread(self):
        # [START get_thread]
        from azure.communication.chat import ChatClient, CommunicationTokenCredential

        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))
        chat_thread = chat_client.get_chat_thread(self._thread_id)
        # [END get_thread]

        print("get_thread succeeded, thread id: " + chat_thread.id +
              ", thread topic: " + chat_thread.topic)

    def list_threads(self):
        # [START list_threads]
        from azure.communication.chat import ChatClient, CommunicationTokenCredential
        from datetime import datetime, timedelta
        import pytz

        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))
        start_time = datetime.utcnow() - timedelta(days=2)
        start_time = start_time.replace(tzinfo=pytz.utc)
        chat_thread_infos = chat_client.list_chat_threads(
            results_per_page=5, start_time=start_time)

        print(
            "list_threads succeeded with results_per_page is 5, and were created since 2 days ago."
        )
        for info in chat_thread_infos:
            print("thread id:", info.id)
        # [END list_threads]

    def delete_thread(self):
        # [START delete_thread]
        from azure.communication.chat import ChatClient, CommunicationTokenCredential

        chat_client = ChatClient(self.endpoint,
                                 CommunicationTokenCredential(self.token))
        chat_client.delete_chat_thread(self._thread_id)
        # [END delete_thread]

        print("delete_thread succeeded")

    def clean_up(self):
        print("cleaning up: deleting created user.")
        self.identity_client.delete_user(self.user)
1) Run `pip install azure.communication.administration` prior to running.

2) Set the `AZURE_COMMUNICATION_CS` environment variable

3) Run the script.

4) Copy the values to the AzureCommunicationChat scheme's testing environment variables and set `TEST_MODE` to
   "record".
"""

import os
from azure.communication.administration import CommunicationIdentityClient

connection_string = os.environ['AZURE_COMMUNICATION_CS']
identity_client = CommunicationIdentityClient.from_connection_string(
    connection_string)

items = {
    key: val
    for (key, val) in (x.split('=', 1) for x in connection_string.split(';'))
}
endpoint = items['endpoint']

user1 = identity_client.create_user()
user2 = identity_client.create_user()

token = identity_client.issue_token(user1, scopes=["chat"]).token

print('\n== AZURE_COMMUNICATION_ENDPOINT ==')
print(endpoint)