Files
notifications-api/app/notifications/rest.py

239 lines
8.2 KiB
Python
Raw Normal View History

2021-03-10 13:55:06 +00:00
from flask import Blueprint, current_app, jsonify, request
from app import api_user, authenticated_service
2024-01-22 10:55:09 -08:00
from app.aws.s3 import get_personalisation_from_s3, get_phone_number_from_s3
from app.config import QueueNames
2021-03-10 13:55:06 +00:00
from app.dao import notifications_dao
from app.enums import KeyType, NotificationType, TemplateProcessType
2021-03-10 13:55:06 +00:00
from app.errors import InvalidRequest, register_errors
from app.notifications.process_notifications import (
persist_notification,
send_notification_to_queue,
2021-03-10 13:55:06 +00:00
simulated_recipient,
)
from app.notifications.validators import (
check_if_service_can_send_to_number,
2017-06-29 18:02:21 +01:00
check_rate_limiting,
service_has_permission,
validate_template,
)
from app.schemas import (
email_notification_schema,
notification_with_personalisation_schema,
2021-03-10 13:55:06 +00:00
notifications_filter_schema,
sms_template_notification_schema,
)
from app.service.utils import service_allowed_to_send_to
2021-03-10 13:55:06 +00:00
from app.utils import get_public_notify_type_text, pagination_links
from notifications_utils import SMS_CHAR_COUNT_LIMIT
2023-08-29 14:54:30 -07:00
notifications = Blueprint("notifications", __name__)
register_errors(notifications)
2023-08-29 14:54:30 -07:00
@notifications.route("/notifications/<uuid:notification_id>", methods=["GET"])
def get_notification_by_id(notification_id):
notification = notifications_dao.get_notification_with_personalisation(
2023-08-29 14:54:30 -07:00
str(authenticated_service.id), notification_id, key_type=None
)
2024-01-22 10:55:09 -08:00
if notification.job_id is not None:
notification.personalisation = get_personalisation_from_s3(
notification.service_id,
notification.job_id,
notification.job_row_number,
)
recipient = get_phone_number_from_s3(
notification.service_id,
notification.job_id,
notification.job_row_number,
)
notification.to = recipient
notification.normalised_to = recipient
2023-08-29 14:54:30 -07:00
return (
jsonify(
data={
"notification": notification_with_personalisation_schema.dump(
notification
)
}
),
200,
)
2023-08-29 14:54:30 -07:00
@notifications.route("/notifications", methods=["GET"])
def get_all_notifications():
2024-05-15 08:34:56 -07:00
current_app.logger.debug("enter get_all_notifications()")
data = notifications_filter_schema.load(request.args)
2024-05-15 08:34:56 -07:00
current_app.logger.debug(
f"get_all_notifications() data {data} request.args {request.args}"
)
2023-08-29 14:54:30 -07:00
include_jobs = data.get("include_jobs", False)
page = data.get("page", 1)
page_size = data.get("page_size", current_app.config.get("API_PAGE_SIZE"))
limit_days = data.get("limit_days")
2016-03-21 12:37:34 +00:00
pagination = notifications_dao.get_notifications_for_service(
str(authenticated_service.id),
personalisation=True,
2016-03-21 12:37:34 +00:00
filter_dict=data,
page=page,
page_size=page_size,
limit_days=limit_days,
key_type=api_user.key_type,
2023-08-29 14:54:30 -07:00
include_jobs=include_jobs,
)
2024-01-22 10:55:09 -08:00
for notification in pagination.items:
if notification.job_id is not None:
notification.personalisation = get_personalisation_from_s3(
notification.service_id,
notification.job_id,
notification.job_row_number,
)
recipient = get_phone_number_from_s3(
notification.service_id,
notification.job_id,
notification.job_row_number,
)
notification.to = recipient
notification.normalised_to = recipient
result = jsonify(
2024-05-15 08:34:56 -07:00
notifications=notification_with_personalisation_schema.dump(
pagination.items, many=True
),
page_size=page_size,
total=pagination.total,
links=pagination_links(
pagination, ".get_all_notifications", **request.args.to_dict()
2023-08-29 14:54:30 -07:00
),
)
current_app.logger.debug(f"result={result}")
2024-05-15 08:34:56 -07:00
return result, 200
2023-08-29 14:54:30 -07:00
@notifications.route("/notifications/<string:notification_type>", methods=["POST"])
def send_notification(notification_type):
if notification_type not in {NotificationType.SMS, NotificationType.EMAIL}:
msg = f"{notification_type} notification type is not supported"
raise InvalidRequest(msg, 400)
notification_form = (
2023-08-29 14:54:30 -07:00
sms_template_notification_schema
if notification_type == NotificationType.SMS
2023-08-29 14:54:30 -07:00
else email_notification_schema
).load(request.get_json())
check_rate_limiting(authenticated_service, api_user)
template, template_with_content = validate_template(
2023-08-29 14:54:30 -07:00
template_id=notification_form["template"],
personalisation=notification_form.get("personalisation", {}),
service=authenticated_service,
2023-08-29 14:54:30 -07:00
notification_type=notification_type,
)
_service_allowed_to_send_to(notification_form, authenticated_service)
2017-06-30 15:00:44 +01:00
if not service_has_permission(notification_type, authenticated_service.permissions):
raise InvalidRequest(
2023-08-29 14:54:30 -07:00
{
"service": [
"Cannot send {}".format(
get_public_notify_type_text(notification_type, plural=True)
)
]
},
status_code=400,
2017-06-30 15:00:44 +01:00
)
2017-06-29 18:02:21 +01:00
if notification_type == NotificationType.SMS:
2023-08-29 14:54:30 -07:00
check_if_service_can_send_to_number(
authenticated_service, notification_form["to"]
)
# Do not persist or send notification to the queue if it is a simulated recipient
2023-08-29 14:54:30 -07:00
simulated = simulated_recipient(notification_form["to"], notification_type)
notification_model = persist_notification(
template_id=template.id,
template_version=template.version,
recipient=request.get_json()["to"],
service=authenticated_service,
personalisation=notification_form.get("personalisation", None),
notification_type=notification_type,
api_key_id=api_user.id,
key_type=api_user.key_type,
simulated=simulated,
reply_to_text=template.reply_to_text,
)
if not simulated:
queue_name = (
QueueNames.PRIORITY
if template.process_type == TemplateProcessType.PRIORITY
else None
)
2023-08-29 14:54:30 -07:00
send_notification_to_queue(notification=notification_model, queue=queue_name)
2023-08-29 16:21:18 -07:00
else:
2023-08-29 14:54:30 -07:00
current_app.logger.debug(
"POST simulated notification for id: {}".format(notification_model.id)
)
notification_form.update({"template_version": template.version})
2023-08-29 14:54:30 -07:00
return (
jsonify(
data=get_notification_return_data(
notification_model.id, notification_form, template_with_content
)
),
201,
)
def get_notification_return_data(notification_id, notification, template):
output = {
2023-08-29 14:54:30 -07:00
"template_version": notification["template_version"],
"notification": {"id": notification_id},
"body": template.content_with_placeholders_filled_in,
}
2023-08-29 14:54:30 -07:00
if hasattr(template, "subject"):
output["subject"] = template.subject
return output
2016-05-19 16:42:21 +01:00
def _service_allowed_to_send_to(notification, service):
2023-08-29 14:54:30 -07:00
if not service_allowed_to_send_to(notification["to"], service, api_user.key_type):
if api_user.key_type == KeyType.TEAM:
2023-08-29 14:54:30 -07:00
message = "Cant send to this recipient using a team-only API key"
else:
message = (
2023-08-29 14:54:30 -07:00
"Cant send to this recipient when service is in trial mode "
" see https://www.notifications.service.gov.uk/trial-mode"
)
2023-08-29 14:54:30 -07:00
raise InvalidRequest({"to": [message]}, status_code=400)
def create_template_object_for_notification(template, personalisation):
template_object = template._as_utils_template_with_personalisation(personalisation)
if template_object.missing_data:
2023-08-29 14:54:30 -07:00
message = "Missing personalisation: {}".format(
", ".join(template_object.missing_data)
)
errors = {"template": [message]}
raise InvalidRequest(errors, status_code=400)
if (
template_object.template_type == NotificationType.SMS
2023-08-29 14:54:30 -07:00
and template_object.is_message_too_long()
):
2023-08-29 14:54:30 -07:00
message = "Content has a character count greater than the limit of {}".format(
SMS_CHAR_COUNT_LIMIT
)
errors = {"content": [message]}
raise InvalidRequest(errors, status_code=400)
return template_object