-
Notifications
You must be signed in to change notification settings - Fork 3
DEVEXP-794: Conversation API - Messages (E2E - delete/get/update) #109
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2c6e5db
DEVEXP-794: Conversation API - Messages (E2E - delete/get/update)
matsk-sinch fca12e8
refactor(models): restructure model directories
matsk-sinch a7828c5
solve PR comments
matsk-sinch d05ed76
refine model names
matsk-sinch 58cb1a5
PR Comments
matsk-sinch 4ee6cfa
fix CI
matsk-sinch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from sinch.domains.conversation.api.v1.messages_apis import Messages | ||
|
|
||
| __all__ = [ | ||
| "Messages", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from sinch.domains.conversation.api.v1.base.base_conversation import ( | ||
| BaseConversation, | ||
| ) | ||
|
|
||
| __all__ = ["BaseConversation"] |
23 changes: 23 additions & 0 deletions
23
sinch/domains/conversation/api/v1/base/base_conversation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| class BaseConversation: | ||
| """Base class for handling Sinch Conversation operations.""" | ||
|
|
||
| def __init__(self, sinch): | ||
| self._sinch = sinch | ||
|
|
||
| def _request(self, endpoint_class, request_data): | ||
| """ | ||
| A helper method to make requests to endpoints. | ||
|
|
||
| Args: | ||
| endpoint_class: The endpoint class to call. | ||
| request_data: The request data to pass to the endpoint. | ||
|
|
||
| Returns: | ||
| The response from the Sinch transport request. | ||
| """ | ||
| return self._sinch.configuration.transport.request( | ||
| endpoint_class( | ||
| project_id=self._sinch.configuration.project_id, | ||
| request_data=request_data, | ||
| ) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from sinch.core.exceptions import SinchException | ||
|
|
||
|
|
||
| class ConversationException(SinchException): | ||
| pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| from sinch.domains.conversation.api.v1.internal.messages_endpoints import ( | ||
| DeleteMessageEndpoint, | ||
| GetMessageEndpoint, | ||
| UpdateMessageMetadataEndpoint, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "DeleteMessageEndpoint", | ||
| "GetMessageEndpoint", | ||
| "UpdateMessageMetadataEndpoint", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from sinch.domains.conversation.api.v1.internal.base.conversation_endpoint import ( | ||
| ConversationEndpoint, | ||
| ) | ||
|
|
||
| __all__ = ["ConversationEndpoint"] |
114 changes: 114 additions & 0 deletions
114
sinch/domains/conversation/api/v1/internal/base/conversation_endpoint.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import re | ||
| from abc import ABC | ||
| from typing import Type, Union, get_origin, get_args | ||
| from sinch.core.models.http_response import HTTPResponse | ||
| from sinch.core.endpoint import HTTPEndpoint | ||
| from sinch.core.types import BM | ||
| from sinch.domains.conversation.api.v1.exceptions import ConversationException | ||
|
|
||
|
|
||
| class ConversationEndpoint(HTTPEndpoint, ABC): | ||
| def __init__(self, project_id: str, request_data: BM): | ||
| super().__init__(project_id, request_data) | ||
|
|
||
| def build_url(self, sinch) -> str: | ||
| if not self.ENDPOINT_URL: | ||
| raise NotImplementedError( | ||
| f"ENDPOINT_URL must be defined in the Conversation endpoint subclass " | ||
| f"'{self.__class__.__name__}'." | ||
| ) | ||
|
|
||
| # TODO: Add support and validation for conversation_region in SinchClient initialization; | ||
|
|
||
| return self.ENDPOINT_URL.format( | ||
| origin=sinch.configuration.conversation_origin, | ||
| project_id=self.project_id, | ||
| **vars(self.request_data), | ||
| ) | ||
|
|
||
| def _get_path_params_from_url(self) -> set: | ||
| """ | ||
| Extracts path parameters from ENDPOINT_URL template. | ||
|
|
||
| Returns: | ||
| set: Set of path parameter names that should be excluded from request body and query params. | ||
| """ | ||
| if not self.ENDPOINT_URL: | ||
| return set() | ||
|
|
||
| # Extract all placeholders from the URL template (e.g., {message_id}, {project_id}) | ||
| path_params = set(re.findall(r"\{(\w+)\}", self.ENDPOINT_URL)) | ||
|
|
||
| # Exclude 'origin' and 'project_id' as they are always path params but not from request_data | ||
| path_params.discard("origin") | ||
| path_params.discard("project_id") | ||
|
|
||
| return path_params | ||
|
|
||
| def build_query_params(self) -> dict: | ||
| """ | ||
| Constructs the query parameters for the endpoint. | ||
|
|
||
| Returns: | ||
| dict: The query parameters to be sent with the API request. | ||
| """ | ||
| return {} | ||
|
|
||
| def request_body(self) -> str: | ||
| """ | ||
| Returns the request body as a JSON string. | ||
|
|
||
| Returns: | ||
| str: The request body as a JSON string. | ||
| """ | ||
| return "" | ||
|
|
||
| def process_response_model( | ||
| self, response_body: dict, response_model: Type[BM] | ||
| ) -> BM: | ||
| """ | ||
| Processes the response body and maps it to a response model. | ||
|
|
||
| Args: | ||
| response_body (dict): The raw response body. | ||
| response_model (type): The Pydantic model class or Union type to map the response. | ||
|
|
||
| Returns: | ||
| Parsed response object. | ||
| """ | ||
| try: | ||
| origin = get_origin(response_model) | ||
| # Check if response_model is a Union type | ||
| if origin is Union: | ||
| # For Union types, try to validate against each type in the Union sequentially | ||
| # This handles cases where TypeAdapter might not be fully defined | ||
| union_args = get_args(response_model) | ||
| last_error = None | ||
|
|
||
| # Try each type in the Union until one succeeds | ||
| for union_type in union_args: | ||
| try: | ||
| return union_type.model_validate(response_body) | ||
| except Exception as e: | ||
| last_error = e | ||
| continue | ||
|
|
||
| # If all Union types failed, raise an error with the last error details | ||
| if last_error is not None: | ||
| raise ValueError( | ||
| f"Invalid response structure: None of the Union types matched. " | ||
| f"Last error: {last_error}" | ||
| ) from last_error | ||
|
|
||
| # Use standard model_validate for regular Pydantic models | ||
| return response_model.model_validate(response_body) | ||
| except Exception as e: | ||
| raise ValueError(f"Invalid response structure: {e}") from e | ||
|
|
||
| def handle_response(self, response: HTTPResponse): | ||
| if response.status_code >= 400: | ||
| raise ConversationException( | ||
| message=f"{response.body['error'].get('message')} {response.body['error'].get('status')}", | ||
| response=response, | ||
| is_from_server=True, | ||
| ) | ||
126 changes: 126 additions & 0 deletions
126
sinch/domains/conversation/api/v1/internal/messages_endpoints.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import json | ||
| from sinch.core.enums import HTTPAuthentication, HTTPMethods | ||
| from sinch.core.models.http_response import HTTPResponse | ||
| from sinch.domains.conversation.models.v1.messages.internal.request import ( | ||
| MessageIdRequest, | ||
| UpdateMessageMetadataRequest, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.messages.response.types import ( | ||
| ConversationMessageResponse, | ||
| ) | ||
| from sinch.domains.conversation.api.v1.internal.base import ( | ||
| ConversationEndpoint, | ||
| ) | ||
| from sinch.domains.conversation.api.v1.exceptions import ConversationException | ||
|
|
||
|
|
||
| class MessageEndpoint(ConversationEndpoint): | ||
| """ | ||
| Base class for message-related endpoints that share common query parameter handling. | ||
| """ | ||
|
|
||
| QUERY_PARAM_FIELDS = {"messages_source"} | ||
| BODY_PARAM_FIELDS = set() | ||
|
|
||
| def build_query_params(self) -> dict: | ||
| path_params = self._get_path_params_from_url() | ||
| exclude_set = path_params.union(self.BODY_PARAM_FIELDS) | ||
| query_params = self.request_data.model_dump( | ||
| include=self.QUERY_PARAM_FIELDS, | ||
| exclude_none=True, | ||
| by_alias=True, | ||
| exclude=exclude_set, | ||
| ) | ||
| return query_params | ||
|
|
||
|
|
||
| class DeleteMessageEndpoint(MessageEndpoint): | ||
| ENDPOINT_URL = "{origin}/v1/projects/{project_id}/messages/{message_id}" | ||
| HTTP_METHOD = HTTPMethods.DELETE.value | ||
| HTTP_AUTHENTICATION = HTTPAuthentication.OAUTH.value | ||
|
|
||
| def __init__(self, project_id: str, request_data: MessageIdRequest): | ||
| super(DeleteMessageEndpoint, self).__init__(project_id, request_data) | ||
| self.project_id = project_id | ||
| self.request_data = request_data | ||
|
|
||
| def handle_response(self, response: HTTPResponse): | ||
| try: | ||
| super(DeleteMessageEndpoint, self).handle_response(response) | ||
| except ConversationException as e: | ||
| raise ConversationException( | ||
| message=e.args[0], | ||
| response=e.http_response, | ||
| is_from_server=e.is_from_server, | ||
| ) | ||
|
|
||
|
|
||
| class GetMessageEndpoint(MessageEndpoint): | ||
| ENDPOINT_URL = "{origin}/v1/projects/{project_id}/messages/{message_id}" | ||
| HTTP_METHOD = HTTPMethods.GET.value | ||
| HTTP_AUTHENTICATION = HTTPAuthentication.OAUTH.value | ||
|
|
||
| def __init__(self, project_id: str, request_data: MessageIdRequest): | ||
| super(GetMessageEndpoint, self).__init__(project_id, request_data) | ||
| self.project_id = project_id | ||
| self.request_data = request_data | ||
|
|
||
| def handle_response( | ||
| self, response: HTTPResponse | ||
| ) -> ConversationMessageResponse: | ||
| try: | ||
| super(GetMessageEndpoint, self).handle_response(response) | ||
| except ConversationException as e: | ||
| raise ConversationException( | ||
| message=e.args[0], | ||
| response=e.http_response, | ||
| is_from_server=e.is_from_server, | ||
| ) | ||
| return self.process_response_model( | ||
| response.body, ConversationMessageResponse | ||
| ) | ||
|
|
||
|
|
||
| class UpdateMessageMetadataEndpoint(MessageEndpoint): | ||
| ENDPOINT_URL = "{origin}/v1/projects/{project_id}/messages/{message_id}" | ||
| HTTP_METHOD = HTTPMethods.PATCH.value | ||
| HTTP_AUTHENTICATION = HTTPAuthentication.OAUTH.value | ||
|
|
||
| BODY_PARAM_FIELDS = {"metadata"} | ||
|
|
||
| def __init__( | ||
| self, project_id: str, request_data: UpdateMessageMetadataRequest | ||
| ): | ||
| super(UpdateMessageMetadataEndpoint, self).__init__( | ||
| project_id, request_data | ||
| ) | ||
| self.project_id = project_id | ||
| self.request_data = request_data | ||
|
|
||
| def request_body(self): | ||
| path_params = self._get_path_params_from_url() | ||
| exclude_set = path_params.union(self.QUERY_PARAM_FIELDS) | ||
| request_data = self.request_data.model_dump( | ||
| include=self.BODY_PARAM_FIELDS, | ||
| by_alias=True, | ||
| exclude_none=True, | ||
| exclude=exclude_set, | ||
| ) | ||
| return json.dumps(request_data) | ||
|
|
||
| def handle_response( | ||
| self, response: HTTPResponse | ||
| ) -> ConversationMessageResponse: | ||
| try: | ||
| super(UpdateMessageMetadataEndpoint, self).handle_response( | ||
| response | ||
| ) | ||
| except ConversationException as e: | ||
| raise ConversationException( | ||
| message=e.args[0], | ||
| response=e.http_response, | ||
| is_from_server=e.is_from_server, | ||
| ) | ||
| return self.process_response_model( | ||
| response.body, ConversationMessageResponse | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.