Skip to content

Commit

Permalink
Fix typing
Browse files Browse the repository at this point in the history
  • Loading branch information
jace committed Nov 15, 2023
1 parent 632c8b2 commit 098e16b
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 32 deletions.
4 changes: 3 additions & 1 deletion funnel/models/phone_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,9 @@ class PhoneNumber(BaseMixin, Model):

#: The phone number, centrepiece of this model. Stored normalized in E164 format.
#: Validated by the :func:`_validate_phone` event handler
number = sa.orm.mapped_column(sa.Unicode, nullable=True, unique=True)
number: Mapped[str | None] = sa.orm.mapped_column(
sa.Unicode, nullable=True, unique=True
)

#: BLAKE2b 160-bit hash of :attr:`phone`. Kept permanently even if phone is
#: removed. SQLAlchemy type LargeBinary maps to PostgreSQL BYTEA. Despite the name,
Expand Down
2 changes: 1 addition & 1 deletion funnel/transports/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
}


def init():
def init() -> None:
if app.config.get('MAIL_SERVER'):
platform_transports['email'] = True
if sms_init():
Expand Down
3 changes: 0 additions & 3 deletions funnel/transports/exc.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
"""Transport exceptions."""


from __future__ import annotations


class TransportError(Exception):
"""Base class for transport exceptions."""

Expand Down
41 changes: 18 additions & 23 deletions funnel/transports/whatsapp/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
TransportRecipientError,
TransportTransactionError,
)
from .template import WhatsappTemplate


@dataclass
class WhatsappSender:
"""A WhatsApp sender."""

requires_config: set
func: Callable
requires_config: set[str]
func: Callable[[str, WhatsappTemplate], str]
init: Callable | None = None


Expand All @@ -42,16 +43,14 @@ def get_phone_number(
phone_number = PhoneNumber.add(phone)
except PhoneNumberBlockedError as exc:
raise TransportRecipientError(_("This phone number has been blocked")) from exc
# TODO: Confirm this phone number is available on WhatsApp (replacing `allow_wa`)
if not phone_number.has_wa:
raise TransportRecipientError(_("WhatsApp is disabled for this phone number"))
if not phone_number.number:
# This should never happen as :meth:`PhoneNumber.add` will restore the number
raise TransportRecipientError(_("This phone number is not available"))
# TODO: Confirm this phone number is available on WhatsApp
return phone_number


def send_via_meta(phone: str, message, callback: bool = True) -> str:
def send_via_meta(phone: str, message: WhatsappTemplate) -> str:
"""
Send the WhatsApp message using Meta Cloud API.
Expand All @@ -63,14 +62,11 @@ def send_via_meta(phone: str, message, callback: bool = True) -> str:
phone_number = get_phone_number(phone)
sid = app.config['WHATSAPP_PHONE_ID']
token = app.config['WHATSAPP_TOKEN']
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json", # Adjust the content type based on your API requirements
}
headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
payload = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
'to': phone_number.number,
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': phone_number.number, # FIXME: Should the leading + be stripped? Confirm
'type': 'template',
'template': json.dumps(message.template),
}
Expand All @@ -91,7 +87,7 @@ def send_via_meta(phone: str, message, callback: bool = True) -> str:
raise TransportConnectionError(_("WhatsApp not reachable")) from exc


def send_via_hosted(phone: str, message, callback: bool = True) -> str:
def send_via_hosted(phone: str, message: WhatsappTemplate) -> str:
"""
Send the Whatsapp message using On-Premise API.
Expand All @@ -104,17 +100,17 @@ def send_via_hosted(phone: str, message, callback: bool = True) -> str:
sid = app.config['WHATSAPP_PHONE_ID']
token = app.config['WHATSAPP_TOKEN']
payload = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
'to': phone_number.number,
"type": "template",
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': phone_number.number, # FIXME: Should the leading + be stripped? Confirm
'type': 'template',
'body': str(message),
}
try:
r = requests.post(
f'https://graph.facebook.com/v18.0/{sid}/messages',
timeout=30,
auth=(token),
auth=(token), # FIXME: This is not a valid auth parameter
data=payload,
)
if r.status_code == 200:
Expand All @@ -136,7 +132,7 @@ def send_via_hosted(phone: str, message, callback: bool = True) -> str:
WhatsappSender({'WHATSAPP_PHONE_ID_META', 'WHATSAPP_TOKEN_META'}, send_via_meta),
]

senders = []
senders: list[Callable[[str, WhatsappTemplate], str]] = []


def init() -> bool:
Expand All @@ -151,8 +147,7 @@ def init() -> bool:

def send(
phone: str | phonenumbers.PhoneNumber | PhoneNumber,
message,
callback: bool = True,
message: WhatsappTemplate,
) -> str:
"""
Send a WhatsApp message to a given phone number and return a transaction id.
Expand All @@ -165,5 +160,5 @@ def send(
phone_number = get_phone_number(phone)
phone = cast(str, phone_number.number)
for sender in senders:
return sender()
return sender(phone, message)
raise TransportRecipientError(_("No service provider available for this recipient"))
8 changes: 4 additions & 4 deletions funnel/transports/whatsapp/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
class WhatsappTemplate:
"""Whatsapp template formatter."""

registered_template_name = None
registered_template_language_code = None
registered_template = None
template = None
registered_template_name: str
registered_template_language_code: str
registered_template: str
template: str


class OTPTemplate(WhatsappTemplate):
Expand Down

0 comments on commit 098e16b

Please sign in to comment.