refactor: iq_utils module with send_iq_sms function

refactor: settings.IQ_PUBLISH_MESSAGE_URL
This commit is contained in:
groovecoder 2023-04-05 16:32:04 -05:00 коммит произвёл luke crouch
Родитель 8a67c74770
Коммит 00e21397d5
7 изменённых файлов: 41 добавлений и 41 удалений

Просмотреть файл

@ -53,7 +53,7 @@ def mocked_twilio_client():
def _make_real_phone_with_mock_iq(phone_user, **kwargs):
responses.add(responses.POST, settings.IQ_MESSAGE_PATH, status=200)
responses.add(responses.POST, settings.IQ_PUBLISH_MESSAGE_URL, status=200)
real_phone = _make_real_phone(phone_user, **kwargs)
responses.reset()
return real_phone
@ -183,7 +183,7 @@ def test_iq_endpoint_success(phone_user):
}
# add response for forwarded text
rsp = responses.add(responses.POST, settings.IQ_MESSAGE_PATH, status=200)
rsp = responses.add(responses.POST, settings.IQ_PUBLISH_MESSAGE_URL, status=200)
resp = client.post(INBOUND_SMS_PATH, json=data)
assert resp.status_code == 200
@ -201,7 +201,7 @@ def test_reply_with_no_remaining_texts(phone_user):
relay_number.remaining_texts = 0
relay_number.save()
# add a response for error message sent to user
rsp = responses.add(responses.POST, settings.IQ_MESSAGE_PATH, status=200)
rsp = responses.add(responses.POST, settings.IQ_PUBLISH_MESSAGE_URL, status=200)
client = _prepare_valid_iq_request_client()
formatted_to = iq_fmt(relay_number.number)
@ -232,7 +232,7 @@ def test_reply_with_no_phone_capability(phone_user):
sa.extra_data = {"avatar": "avatar.png", "subscriptions": []}
sa.save()
# add response that should NOT be called
rsp = responses.add(responses.POST, settings.IQ_MESSAGE_PATH, status=200)
rsp = responses.add(responses.POST, settings.IQ_PUBLISH_MESSAGE_URL, status=200)
client = _prepare_valid_iq_request_client()
formatted_to = iq_fmt(relay_number.number)
@ -265,7 +265,7 @@ def test_reply_without_previous_sender_error(phone_user):
error_msg = "You can only reply to phone numbers that have sent you a text message."
rsp = responses.add(
responses.POST,
settings.IQ_MESSAGE_PATH,
settings.IQ_PUBLISH_MESSAGE_URL,
status=200,
match=[
responses.matchers.json_params_matcher(
@ -309,7 +309,7 @@ def test_reply_with_previous_sender_works(phone_user):
# add a response for sending error back to user
rsp = responses.add(
responses.POST,
settings.IQ_MESSAGE_PATH,
settings.IQ_PUBLISH_MESSAGE_URL,
status=200,
match=[
responses.matchers.json_params_matcher(

Просмотреть файл

@ -1,11 +1,9 @@
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
import hashlib
import json
import logging
import phonenumbers
import re
import requests
from rest_framework.request import Request
import string
from typing import Any, Literal, Optional
@ -32,6 +30,7 @@ from twilio.base.exceptions import TwilioRestException
from api.views import SaveToRequestUser
from emails.utils import incr_if_enabled
from phones.iq_utils import send_iq_sms
from phones.models import (
InboundContact,
@ -42,7 +41,6 @@ from phones.models import (
get_valid_realphone_verification_record,
get_verified_realphone_record,
get_verified_realphone_records,
phones_config,
send_welcome_message,
suggested_numbers,
location_numbers,
@ -583,7 +581,6 @@ def inbound_sms(request):
def inbound_sms_iq(request: Request) -> response.Response:
incr_if_enabled("phones_inbound_sms_iq")
_validate_iq_request(request)
config = phones_config()
inbound_body = request.data.get("text", None)
inbound_from = request.data.get("from", None)
@ -608,16 +605,14 @@ def inbound_sms_iq(request: Request) -> response.Response:
relay_number, destination_number, body = _prepare_sms_reply(
relay_number, inbound_body
)
config.send_iq_sms(destination_number, relay_number.number, body)
send_iq_sms(destination_number, relay_number.number, body)
relay_number.remaining_texts -= 1
relay_number.texts_forwarded += 1
relay_number.save()
incr_if_enabled("phones_send_sms_reply_iq")
except RelaySMSException as sms_exception:
user_error_message = _get_user_error_message(real_phone, sms_exception)
config.send_iq_sms(
real_phone.number, relay_number.number, user_error_message
)
send_iq_sms(real_phone.number, relay_number.number, user_error_message)
# Return 400 on critical exceptions
if sms_exception.critical:
@ -638,7 +633,7 @@ def inbound_sms_iq(request: Request) -> response.Response:
_check_and_update_contact(inbound_contact, "texts", relay_number)
text = message_body(inbound_from, inbound_body)
config.send_iq_sms(real_phone.number, relay_number.number, text)
send_iq_sms(real_phone.number, relay_number.number, text)
relay_number.remaining_texts -= 1
relay_number.texts_forwarded += 1

Просмотреть файл

@ -1,7 +1,5 @@
import json
import logging
import requests
from twilio.base.instance_resource import InstanceResource
from twilio.request_validator import RequestValidator
from twilio.rest import Client
@ -10,8 +8,6 @@ from django.apps import AppConfig
from django.conf import settings
from django.utils.functional import cached_property
from rest_framework import exceptions
logger = logging.getLogger("events")
@ -48,19 +44,3 @@ class PhonesConfig(AppConfig):
if not settings.TWILIO_AUTH_TOKEN:
raise Exception("Must define TWILIO_AUTH_TOKEN")
return RequestValidator(settings.TWILIO_AUTH_TOKEN)
def send_iq_sms(self, to_num: str, from_num: str, text: str) -> None:
iq_formatted_to_num = to_num.replace("+", "")
iq_formatted_from_num = from_num.replace("+", "")
json_body = {
"from": iq_formatted_from_num,
"to": [iq_formatted_to_num],
"text": text,
}
resp = requests.post(
"https://messagebroker.inteliquent.com/msgbroker/rest/publishMessages",
headers={"Authorization": f"Bearer {settings.IQ_OUTBOUND_API_KEY}"},
json=json_body,
)
if resp.status_code < 200 or resp.status_code > 299:
raise exceptions.ValidationError(json.loads(resp.content.decode()))

24
phones/iq_utils.py Normal file
Просмотреть файл

@ -0,0 +1,24 @@
import json
import requests
from django.conf import settings
from rest_framework import exceptions
def send_iq_sms(to_num: str, from_num: str, text: str) -> None:
iq_formatted_to_num = to_num.replace("+", "")
iq_formatted_from_num = from_num.replace("+", "")
json_body = {
"from": iq_formatted_from_num,
"to": [iq_formatted_to_num],
"text": text,
}
resp = requests.post(
settings.IQ_PUBLISH_MESSAGE_URL,
headers={"Authorization": f"Bearer {settings.IQ_OUTBOUND_API_KEY}"},
json=json_body,
)
if resp.status_code < 200 or resp.status_code > 299:
raise exceptions.ValidationError(json.loads(resp.content.decode()))

Просмотреть файл

@ -21,6 +21,7 @@ from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
from emails.utils import incr_if_enabled
from phones.iq_utils import send_iq_sms
logger = logging.getLogger("eventsinfo")
@ -208,8 +209,7 @@ def realphone_post_save(sender, instance, created, **kwargs):
f"Your Firefox Relay verification code is {instance.verification_code}"
)
if settings.IQ_FOR_VERIFICATION:
config = phones_config()
config.send_iq_sms(instance.number, settings.IQ_MAIN_NUMBER, text_body)
send_iq_sms(instance.number, settings.IQ_MAIN_NUMBER, text_body)
return
client = twilio_client()
client.messages.create(

Просмотреть файл

@ -159,7 +159,7 @@ def test_create_realphone_creates_iq_message(phone_user):
iq_number = iq_fmt(number)
resp = responses.add(
responses.POST,
settings.IQ_MESSAGE_PATH,
settings.IQ_PUBLISH_MESSAGE_URL,
status=200,
match=[
responses.matchers.json_params_matcher(

Просмотреть файл

@ -206,10 +206,11 @@ IQ_FOR_NEW_NUMBERS = config("IQ_FOR_NEW_NUMBERS", False, cast=bool)
IQ_MAIN_NUMBER = config("IQ_MAIN_NUMBER", "")
IQ_OUTBOUND_API_KEY = config("IQ_OUTBOUND_API_KEY", None)
IQ_INBOUND_API_KEY = config("IQ_INBOUND_API_KEY", "")
IQ_MESSAGE_PATH = config(
"IQ_MESSAGE_PATH",
"https://messagebroker.inteliquent.com/msgbroker/rest/publishMessages",
IQ_MESSAGE_API_ORIGIN = config(
"IQ_MESSAGE_API_ROOT", "https://messagebroker.inteliquent.com"
)
IQ_MESSAGE_PATH = "/msgbroker/rest/publishMessages"
IQ_PUBLISH_MESSAGE_URL = f"{IQ_MESSAGE_API_ORIGIN}{IQ_MESSAGE_PATH}"
DJANGO_STATSD_ENABLED = config("DJANGO_STATSD_ENABLED", False, cast=bool)
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)