Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Communication chat preview4 #16905

Merged
merged 16 commits into from
Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
367 changes: 269 additions & 98 deletions sdk/communication/azure-communication-chat/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@
from ._generated.models import (
SendChatMessageResult,
ChatThreadInfo,
ChatMessageType
ChatMessageType,
AddChatParticipantsResult,
CommunicationError
)
from ._shared.user_credential import CommunicationTokenCredential
from ._shared.user_token_refresh_options import CommunicationTokenRefreshOptions

from ._models import (
ChatThreadParticipant,
ChatMessage,
ChatThread,
ChatMessageReadReceipt,
ChatMessageContent
ChatMessageContent,
CreateChatThreadResult
)
from ._shared.models import CommunicationUserIdentifier

__all__ = [
'ChatClient',
Expand All @@ -26,10 +27,10 @@
'SendChatMessageResult',
'ChatThread',
'ChatThreadInfo',
'CommunicationTokenCredential',
'CommunicationTokenRefreshOptions',
'CommunicationUserIdentifier',
'ChatThreadParticipant',
'ChatMessageType'
'ChatMessageType',
'CreateChatThreadResult',
'AddChatParticipantsResult',
'CommunicationError'
]
__version__ = VERSION
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@
from ._generated.models import CreateChatThreadRequest
from ._models import (
ChatThread,
ChatThreadParticipant
CreateChatThreadResult
)
from ._utils import ( # pylint: disable=unused-import
_to_utc_datetime,
return_response,
CommunicationErrorResponseConverter
)
from ._utils import _to_utc_datetime, return_response # pylint: disable=unused-import
from ._version import SDK_MONIKER

if TYPE_CHECKING:
Expand Down Expand Up @@ -119,26 +123,24 @@ def get_chat_thread_client(
@distributed_trace
def create_chat_thread(
self, topic, # type: str
thread_participants, # type: list[ChatThreadParticipant]
repeatability_request_id=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> ChatThreadClient
# type: (...) -> CreateChatThreadResult
"""Creates a chat thread.

:param topic: Required. The thread topic.
:type topic: str
:param thread_participants: Required. Participants to be added to the thread.
:type thread_participants: list[~azure.communication.chat.ChatThreadParticipant]
:param repeatability_request_id: If specified, the client directs that the request is
:keyword thread_participants: Optional. Participants to be added to the thread.
:paramtype thread_participants: list[~azure.communication.chat.ChatThreadParticipant]
:keyword repeatability_request_id: Optional. If specified, the client directs that the request is
repeatable; that is, that the client can make the request multiple times with the same
Repeatability-Request-ID and get back an appropriate response without the server executing the
request multiple times. The value of the Repeatability-Request-ID is an opaque string
representing a client-generated, globally unique for all time, identifier for the request. If not
specified, a new unique id would be generated.
:type repeatability_request_id: str
:return: ChatThreadClient
:rtype: ~azure.communication.chat.ChatThreadClient
:paramtype repeatability_request_id: str
:return: CreateChatThreadResult
:rtype: ~azure.communication.chat.CreateChatThreadResult
:raises: ~azure.core.exceptions.HttpResponseError, ValueError

.. admonition:: Example:
Expand All @@ -148,40 +150,45 @@ def create_chat_thread(
:end-before: [END create_thread]
:language: python
:dedent: 8
:caption: Creating ChatThreadClient by creating a new chat thread.
:caption: Creating ChatThread by creating a new chat thread.
"""
if not topic:
raise ValueError("topic cannot be None.")
if not thread_participants:
raise ValueError("List of ChatThreadParticipant cannot be None.")

repeatability_request_id = kwargs.pop('repeatability_request_id', None)
if repeatability_request_id is None:
repeatability_request_id = str(uuid4())

participants = [m._to_generated() for m in thread_participants] # pylint:disable=protected-access
create_thread_request = \
CreateChatThreadRequest(topic=topic, participants=participants)
thread_participants = kwargs.pop('thread_participants', None)
participants = []
if thread_participants is not None:
participants = [m._to_generated() for m in thread_participants] # pylint:disable=protected-access

create_thread_request = CreateChatThreadRequest(topic=topic, participants=participants)

create_chat_thread_result = self._client.chat.create_chat_thread(
create_chat_thread_request=create_thread_request,
repeatability_request_id=repeatability_request_id,
**kwargs)

errors = None
if hasattr(create_chat_thread_result, 'errors') and \
create_chat_thread_result.errors is not None:
participants = \
create_chat_thread_result.errors.invalid_participants
errors = []
for participant in participants:
errors.append('participant ' + participant.target +
' failed to join thread due to: ' + participant.message)
raise RuntimeError(errors)
thread_id = create_chat_thread_result.chat_thread.id
return ChatThreadClient(
endpoint=self._endpoint,
credential=self._credential,
thread_id=thread_id,
**kwargs
errors = CommunicationErrorResponseConverter._convert( # pylint:disable=protected-access
participants=[thread_participants],
communication_errors=create_chat_thread_result.errors.invalid_participants
)

chat_thread = ChatThread._from_generated( # pylint:disable=protected-access
create_chat_thread_result.chat_thread)

create_chat_thread_result = CreateChatThreadResult(
chat_thread=chat_thread,
errors=errors
)

return create_chat_thread_result

@distributed_trace
def get_chat_thread(
self, thread_id, # type: str
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
ChatMessageReadReceipt
)

from ._utils import _to_utc_datetime # pylint: disable=unused-import
from ._utils import ( # pylint: disable=unused-import
_to_utc_datetime,
CommunicationUserIdentifierConverter,
CommunicationErrorResponseConverter
)
from ._version import SDK_MONIKER

if TYPE_CHECKING:
Expand Down Expand Up @@ -339,7 +343,8 @@ def list_messages(
"""Gets a list of messages from a thread.

:keyword int results_per_page: The maximum number of messages to be returned per page.
:keyword ~datetime.datetime start_time: The start time where the range query.
:keyword ~datetime.datetime start_time: The earliest point in time to get messages up to.
The timestamp should be in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of ChatMessage
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.chat.ChatMessage]
Expand Down Expand Up @@ -478,14 +483,16 @@ def add_participant(
thread_participant, # type: ChatThreadParticipant
**kwargs # type: Any
):
# type: (...) -> None
# type: (...) -> tuple(ChatThreadParticipant, CommunicationError)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case of the single add_participant, we shouldn't return the error object - we should just raise an error.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@annatisch add_participant raises error - change implemented

Copy link
Member

@juancamilor juancamilor Mar 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@annatisch are we ok with having this diverge in python ? I am ok if you are.
When we run this in that meeting, the answer was to leave it as is in case in the future any additional data is required back from that call. I don't see that coming but that was the decision.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@juancamilor - raising errors rather than returning them is Pythonic behaviour that I would expect to differ from .Net.
We can still return the ChatThreadParticipant object - when you say additional data, you mean other information outside of these two fields?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, something like extra headers is what Ted G mentioned, but I don't have any requirements yet to back it up.

tg-msft1
There aren't today, but maybe it'll come back with extra headers in the future?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@annatisch after today's review we will address all the changes on the next iteration (including the removal of this operation).

"""Adds single thread participant to a thread. If participant already exist, no change occurs.

If participant is added successfully, a tuple of (None, None) is expected.
Failure to add participant to thread returns tuple of (chat_thread_participant, communication_error).

:param thread_participant: Required. Single thread participant to be added to the thread.
:type thread_participant: ~azure.communication.chat.ChatThreadParticipant
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:return: Tuple(ChatThreadParticipant, CommunicationError)
:rtype: tuple(~azure.communication.chat.ChatThreadParticipant, ~azure.communication.chat.CommunicationError)
:raises: ~azure.core.exceptions.HttpResponseError, ValueError

.. admonition:: Example:
Expand All @@ -496,33 +503,59 @@ def add_participant(
:language: python
:dedent: 8
:caption: Adding single participant to chat thread.

.. literalinclude:: ../samples/chat_thread_client_sample.py
:start-after: [START add_participant_w_failed_participant]
:end-before: [END add_participant_w_failed_participant]
:language: python
:dedent: 8
:caption: Retry adding participant to chat thread after initial failure.
"""
if not thread_participant:
raise ValueError("thread_participant cannot be None.")

participants = [thread_participant._to_generated()] # pylint:disable=protected-access
add_thread_participants_request = AddChatParticipantsRequest(participants=participants)

return self._client.chat_thread.add_chat_participants(
add_chat_participants_result = self._client.chat_thread.add_chat_participants(
chat_thread_id=self._thread_id,
add_chat_participants_request=add_thread_participants_request,
**kwargs)

response = []
failed_participant = None
communication_error = None
if hasattr(add_chat_participants_result, 'errors') and \
add_chat_participants_result.errors is not None:
response = CommunicationErrorResponseConverter._convert( # pylint:disable=protected-access
participants=[thread_participant],
communication_errors=add_chat_participants_result.errors.invalid_participants
)

if len(response) != 0:
failed_participant = response[0][0]
communication_error = response[0][1]

return (failed_participant, communication_error)

@distributed_trace
def add_participants(
self,
thread_participants, # type: list[ChatThreadParticipant]
**kwargs # type: Any
):
# type: (...) -> None
# type: (...) -> list[(ChatThreadParticipant, CommunicationError)]
"""Adds thread participants to a thread. If participants already exist, no change occurs.

If all participants are added successfully, then an empty list is returned;
otherwise, a list of tuple(chat_thread_participant, communincation_error) is returned,
of failed participants and its respective error

:param thread_participants: Required. Thread participants to be added to the thread.
:type thread_participants: list[~azure.communication.chat.ChatThreadParticipant]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError, ValueError
:return: List[Tuple(ChatThreadParticipant, CommunicationError)]
:rtype: list[(~azure.communication.chat.ChatThreadParticipant, ~azure.communication.chat.CommunicationError)]
:raises: ~azure.core.exceptions.HttpResponseError, ValueError, RuntimeError

.. admonition:: Example:

Expand All @@ -532,18 +565,35 @@ def add_participants(
:language: python
:dedent: 8
:caption: Adding participants to chat thread.

.. literalinclude:: ../samples/chat_thread_client_sample.py
:start-after: [START add_participants_w_failed_participants]
:end-before: [END add_participants_w_failed_participants]
:language: python
:dedent: 8
:caption: Retry adding participants to chat thread after initial failure.
"""
if not thread_participants:
raise ValueError("thread_participants cannot be None.")

participants = [m._to_generated() for m in thread_participants] # pylint:disable=protected-access
add_thread_participants_request = AddChatParticipantsRequest(participants=participants)

return self._client.chat_thread.add_chat_participants(
add_chat_participants_result = self._client.chat_thread.add_chat_participants(
chat_thread_id=self._thread_id,
add_chat_participants_request=add_thread_participants_request,
**kwargs)

response = []
if hasattr(add_chat_participants_result, 'errors') and \
add_chat_participants_result.errors is not None:
response = CommunicationErrorResponseConverter._convert( # pylint:disable=protected-access
participants=thread_participants,
communication_errors=add_chat_participants_result.errors.invalid_participants
)

return response

@distributed_trace
def remove_participant(
self,
Expand Down Expand Up @@ -574,7 +624,7 @@ def remove_participant(

return self._client.chat_thread.remove_chat_participant(
chat_thread_id=self._thread_id,
chat_participant_id=user.identifier,
participant_communication_identifier=CommunicationUserIdentifierConverter.to_identifier_model(user),
**kwargs)

def close(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(
super(AzureCommunicationChatServiceConfiguration, self).__init__(**kwargs)

self.endpoint = endpoint
self.api_version = "2020-11-01-preview3"
self.api_version = "2021-01-27-preview4"
kwargs.setdefault('sdk_moniker', 'azurecommunicationchatservice/{}'.format(VERSION))
self._configure(**kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(
super(AzureCommunicationChatServiceConfiguration, self).__init__(**kwargs)

self.endpoint = endpoint
self.api_version = "2020-11-01-preview3"
self.api_version = "2021-01-27-preview4"
kwargs.setdefault('sdk_moniker', 'azurecommunicationchatservice/{}'.format(VERSION))
self._configure(**kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ async def create_chat_thread(
:type create_chat_thread_request: ~azure.communication.chat.models.CreateChatThreadRequest
:param repeatability_request_id: If specified, the client directs that the request is
repeatable; that is, that the client can make the request multiple times with the same
Repeatability-Request-ID and get back an appropriate response without the server executing the
request multiple times. The value of the Repeatability-Request-ID is an opaque string
Repeatability-Request-Id and get back an appropriate response without the server executing the
request multiple times. The value of the Repeatability-Request-Id is an opaque string
representing a client-generated, globally unique for all time, identifier for the request. It
is recommended to use version 4 (random) UUIDs.
:type repeatability_request_id: str
Expand All @@ -75,7 +75,7 @@ async def create_chat_thread(
503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.CommunicationErrorResponse, response)),
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01-preview3"
api_version = "2021-01-27-preview4"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"

Expand All @@ -93,7 +93,7 @@ async def create_chat_thread(
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if repeatability_request_id is not None:
header_parameters['repeatability-Request-ID'] = self._serialize.header("repeatability_request_id", repeatability_request_id, 'str')
header_parameters['repeatability-Request-Id'] = self._serialize.header("repeatability_request_id", repeatability_request_id, 'str')
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

Expand Down Expand Up @@ -146,7 +146,7 @@ def list_chat_threads(
503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.CommunicationErrorResponse, response)),
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01-preview3"
api_version = "2021-01-27-preview4"
accept = "application/json"

def prepare_request(next_link=None):
Expand Down Expand Up @@ -230,7 +230,7 @@ async def get_chat_thread(
503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.CommunicationErrorResponse, response)),
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01-preview3"
api_version = "2021-01-27-preview4"
accept = "application/json"

# Construct URL
Expand Down Expand Up @@ -291,7 +291,7 @@ async def delete_chat_thread(
503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.CommunicationErrorResponse, response)),
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01-preview3"
api_version = "2021-01-27-preview4"
accept = "application/json"

# Construct URL
Expand Down
Loading