oncall-engine/engine/apps/public_api/views/phone_notifications.py
Innokentii Konstantinov 1f786e8d2a
Phone provider refactoring (#1713)
# What this PR does
This PR moves phone notification logic into separate object PhoneBackend
and introduces PhoneProvider interface to hide actual implementation of
external phone services provider. It should allow add new phone
providers just by implementing one class (See SimplePhoneProvider for
example).
# Why 
[Asterisk PR](https://github.com/grafana/oncall/pull/1282) showed that
our phone notification system is not flexible. However this is one of
the most frequent community questions - how to add "X" phone provider.
Also, this refactoring move us one step closer to unifying all
notification backends, since with PhoneBackend all phone notification
logic is collected in one place and independent from concrete
realisation.
# Highligts
1. PhoneBackend object - contains all phone notifications business
logic.
2. PhoneProvider - interface to  external phone services provider.
3. TwilioPhoneProvider and SimplePhoneProvider - two examples of
PhoneProvider implementation.
4. PhoneCallRecord and SMSRecord models. I introduced these models to
keep phone notification limits logic decoupled from external providers.
Existing TwilioPhoneCall and TwilioSMS objects will be migrated to the
new table to not to reset limits counter. To be able to receive status
callbacks and gather from Twilio TwilioPhoneCall and TwilioSMS still
exists, but they are linked to PhoneCallRecord and SMSRecord via fk, to
not to leat twilio logic into core code.

---------

Co-authored-by: Yulia Shanyrova <yulia.shanyrova@grafana.com>
2023-05-24 06:27:48 +00:00

92 lines
3.5 KiB
Python

import logging
from rest_framework import serializers, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.auth_token.auth import ApiTokenAuthentication
from apps.phone_notifications.exceptions import (
CallsLimitExceeded,
FailedToMakeCall,
FailedToSendSMS,
NumberNotVerified,
SMSLimitExceeded,
)
from apps.phone_notifications.phone_backend import PhoneBackend
from apps.public_api.throttlers.phone_notification_throttler import PhoneNotificationThrottler
logger = logging.getLogger(__name__)
class PhoneNotificationDataSerializer(serializers.Serializer):
email = serializers.EmailField()
message = serializers.CharField(max_length=1024)
class MakeCallView(APIView):
authentication_classes = (ApiTokenAuthentication,)
permission_classes = (IsAuthenticated,)
throttle_classes = [
PhoneNotificationThrottler,
]
def post(self, request):
serializer = PhoneNotificationDataSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
response_data = {}
organization = self.request.auth.organization
logger.info(f"Making cloud call. Email {serializer.validated_data['email']}")
user = organization.users.filter(email=serializer.validated_data["email"]).first()
if user is None:
response_data = {"error": "user-not-found"}
return Response(status=status.HTTP_404_NOT_FOUND, data=response_data)
phone_backend = PhoneBackend()
try:
phone_backend.relay_oss_call(user, serializer.validated_data["message"])
except FailedToMakeCall:
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE, data={"error": "failed"})
except CallsLimitExceeded:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"error": "limit-exceeded"})
except NumberNotVerified:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"error": "number-not-verified"})
return Response(status=status.HTTP_200_OK, data=response_data)
class SendSMSView(APIView):
authentication_classes = (ApiTokenAuthentication,)
permission_classes = (IsAuthenticated,)
throttle_classes = [
PhoneNotificationThrottler,
]
def post(self, request):
serializer = PhoneNotificationDataSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
response_data = {}
organization = self.request.auth.organization
logger.info(f"Sending cloud sms. Email {serializer.validated_data['email']}")
user = organization.users.filter(
email=serializer.validated_data["email"], _verified_phone_number__isnull=False
).first()
if user is None:
response_data = {"error": "user-not-found"}
return Response(status=status.HTTP_404_NOT_FOUND, data=response_data)
phone_backend = PhoneBackend()
try:
phone_backend.relay_oss_sms(user, serializer.validated_data["message"])
except FailedToSendSMS:
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE, data={"error": "failed"})
except SMSLimitExceeded:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"error": "limit-exceeded"})
except NumberNotVerified:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"error": "number-not-verified"})
return Response(status=status.HTTP_200_OK, data=response_data)