-
Notifications
You must be signed in to change notification settings - Fork 3
feat: sms webhooks #103
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
feat: sms webhooks #103
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
asein-sinch marked this conversation as resolved.
Show resolved
Hide resolved
|
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,50 @@ | ||
| import json | ||
| import re | ||
| from datetime import datetime | ||
| from typing import Any, Dict | ||
|
|
||
|
|
||
| def parse_json(payload: str) -> Dict[str, Any]: | ||
| """ | ||
| Parse JSON string into a dictionary. | ||
|
|
||
| :param payload: JSON string to parse. | ||
| :type payload: str | ||
| :returns: Parsed dictionary. | ||
| :rtype: Dict[str, Any] | ||
| :raises ValueError: If JSON parsing fails. | ||
| """ | ||
| try: | ||
| return json.loads(payload) | ||
| except json.JSONDecodeError as e: | ||
| raise ValueError(f"Failed to decode JSON: {e}") | ||
|
|
||
|
|
||
| def normalize_iso_timestamp(timestamp: str) -> datetime: | ||
| """ | ||
| Normalize a timestamp string to ensure compatibility with Python's `datetime.fromisoformat()`. | ||
|
|
||
| - Ensures that the timestamp includes a UTC offset (e.g., "+00:00") if missing. | ||
| - Replaces trailing "Z" with "+00:00" to indicate UTC. | ||
| - Trims microseconds to 6 digits. | ||
|
|
||
| :param timestamp: Timestamp string to normalize. | ||
| :type timestamp: str | ||
| :returns: Timezone-aware datetime object. | ||
| :rtype: datetime | ||
| :raises ValueError: If timestamp format is invalid. | ||
| """ | ||
| if timestamp.endswith("Z"): | ||
| timestamp = timestamp.replace("Z", "+00:00") | ||
| elif not re.search(r"(Z|[+-]\d{2}:?\d{2})$", timestamp): | ||
| timestamp += "+00:00" | ||
| match_ms = re.search(r"\.(\d{7,})(?=[+-])", timestamp) | ||
| if match_ms: | ||
| micro_trimmed = match_ms.group(1)[:6] | ||
| timestamp = re.sub( | ||
| r"\.\d{7,}(?=[+-])", f".{micro_trimmed}", timestamp | ||
| ) | ||
| try: | ||
| return datetime.fromisoformat(timestamp) | ||
| except ValueError as e: | ||
| raise ValueError(f"Invalid timestamp format: {e}") |
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
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
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,17 @@ | ||
| from sinch.domains.sms.webhooks.v1.events.sms_webhooks_event import ( | ||
| IncomingSMSWebhookEvent, | ||
| MOTextWebhookEvent, | ||
| MOBinaryWebhookEvent, | ||
| MOMediaWebhookEvent, | ||
| MediaBody, | ||
| MediaItem, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "IncomingSMSWebhookEvent", | ||
| "MOTextWebhookEvent", | ||
| "MOBinaryWebhookEvent", | ||
| "MOMediaWebhookEvent", | ||
| "MediaBody", | ||
| "MediaItem", | ||
| ] |
97 changes: 97 additions & 0 deletions
97
sinch/domains/sms/webhooks/v1/events/sms_webhooks_event.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,97 @@ | ||
| from datetime import datetime | ||
| from typing import Optional, Union, Literal, Annotated | ||
| from pydantic import Field, StrictStr, StrictInt, conlist | ||
| from sinch.domains.sms.webhooks.v1.internal import WebhookEvent | ||
|
|
||
|
|
||
| class MediaItem(WebhookEvent): | ||
| url: StrictStr = Field(..., description="URL to the media file") | ||
| content_type: StrictStr = Field( | ||
| ..., description="Content type of the media file" | ||
| ) | ||
| status: Union[Literal["Uploaded", "Failed"], StrictStr] = Field( | ||
| ..., description="Status of the media upload" | ||
| ) | ||
| code: StrictInt = Field(..., description="Status code") | ||
|
|
||
|
|
||
| class MediaBody(WebhookEvent): | ||
| subject: Optional[StrictStr] = Field( | ||
| default=None, description="The subject text" | ||
| ) | ||
| message: Optional[StrictStr] = Field( | ||
| default=None, description="The message text" | ||
| ) | ||
| media: conlist(MediaItem) = Field(..., description="Array of media items") | ||
|
|
||
|
|
||
| class BaseIncomingSMSWebhookEvent(WebhookEvent): | ||
| from_: StrictStr = Field( | ||
| ..., | ||
| alias="from", | ||
| description="The phone number that sent the message.", | ||
| ) | ||
| id: StrictStr = Field(..., description="The ID of this inbound message.") | ||
| received_at: datetime = Field( | ||
| ..., | ||
| description="When the system received the message. Formatted as ISO-8601: YYYY-MM-DDThh:mm:ss.SSSZ.", | ||
| ) | ||
| to: StrictStr = Field( | ||
| ..., | ||
| description="The Sinch phone number or short code to which the message was sent.", | ||
| ) | ||
| client_reference: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="If this inbound message is in response to a previously sent message that contained a client reference, then this field contains that client reference. Utilizing this feature requires additional setup on your account.", | ||
| ) | ||
| operator_id: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="The MCC/MNC of the sender's operator if known.", | ||
| ) | ||
| sent_at: Optional[datetime] = Field( | ||
| default=None, | ||
| description="When the message left the originating device. Only available if provided by operator. Formatted as ISO-8601: YYYY-MM-DDThh:mm:ss.SSSZ.", | ||
| ) | ||
|
|
||
|
|
||
| class MOTextWebhookEvent(BaseIncomingSMSWebhookEvent): | ||
| body: StrictStr = Field( | ||
| ..., | ||
| description="The incoming message body. Maximum 2000 characters.", | ||
| ) | ||
| type: Literal["mo_text"] = Field( | ||
| ..., description="The type of incoming message. Regular SMS." | ||
| ) | ||
|
|
||
|
|
||
| class MOBinaryWebhookEvent(BaseIncomingSMSWebhookEvent): | ||
| body: StrictStr = Field( | ||
| ..., description="The incoming message body (Base64 encoded)." | ||
| ) | ||
| type: Literal["mo_binary"] = Field( | ||
| ..., description="The type of incoming message. Binary SMS." | ||
| ) | ||
| udh: StrictStr = Field( | ||
| ..., description="The UDH header of a binary message HEX encoded." | ||
| ) | ||
|
|
||
|
|
||
| class MOMediaWebhookEvent(BaseIncomingSMSWebhookEvent): | ||
| body: MediaBody = Field( | ||
| ..., | ||
| description="The media message body containing subject, message, and media items.", | ||
| ) | ||
| type: Literal["mo_media"] = Field( | ||
| ..., description="The type of incoming message. MMS." | ||
| ) | ||
|
|
||
|
|
||
| # Union type for isinstance checks | ||
| _IncomingSMSWebhookEventUnion = Union[ | ||
| MOTextWebhookEvent, MOBinaryWebhookEvent, MOMediaWebhookEvent | ||
| ] | ||
|
|
||
| # Discriminated union for validation | ||
| IncomingSMSWebhookEvent = Annotated[ | ||
| _IncomingSMSWebhookEventUnion, Field(discriminator="type") | ||
| ] |
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.sms.webhooks.v1.internal.webhook_event import ( | ||
| WebhookEvent, | ||
| ) | ||
|
|
||
| __all__ = ["WebhookEvent"] |
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.