-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
move common functionality to base class
- Loading branch information
Showing
4 changed files
with
213 additions
and
211 deletions.
There are no files selected for viewing
This file contains 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 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,145 @@ | ||
from __future__ import annotations | ||
|
||
import logging | ||
from typing import TYPE_CHECKING | ||
|
||
from django import forms | ||
from django.conf import settings | ||
from django.core.mail import send_mail | ||
from django.template.loader import render_to_string | ||
from rest_framework.exceptions import ValidationError | ||
|
||
from argus.incident.models import Event | ||
from .base import NotificationMedium | ||
from ..models import DestinationConfig | ||
from argus.util.datetime_utils import INFINITY, LOCAL_INFINITY | ||
|
||
if TYPE_CHECKING: | ||
import sys | ||
|
||
from collections.abc import Iterable | ||
|
||
from types import NoneType | ||
from typing import Union, Set | ||
|
||
from django.contrib.auth import get_user_model | ||
from django.db.models.query import QuerySet | ||
|
||
from ..serializers import RequestDestinationConfigSerializer | ||
|
||
User = get_user_model() | ||
|
||
LOG = logging.getLogger(__name__) | ||
|
||
__all__ = [ | ||
"modelinstance_to_dict", | ||
"send_email_safely", | ||
"EmailNotification", | ||
] | ||
|
||
|
||
def modelinstance_to_dict(obj): | ||
dict_ = vars(obj).copy() | ||
dict_.pop("_state") | ||
return dict_ | ||
|
||
|
||
def send_email_safely(function, additional_error=None, *args, **kwargs) -> int: | ||
try: | ||
result = function(*args, **kwargs) | ||
return result | ||
except ConnectionRefusedError as e: | ||
EMAIL_HOST = getattr(settings, "EMAIL_HOST", None) | ||
if not EMAIL_HOST: | ||
LOG.error("Notification: Email: EMAIL_HOST not set, cannot send") | ||
EMAIL_PORT = getattr(settings, "EMAIL_PORT", None) | ||
if not EMAIL_PORT: | ||
LOG.error("Notification: Email: EMAIL_PORT not set, cannot send") | ||
if EMAIL_HOST and EMAIL_PORT: | ||
LOG.error('Notification: Email: Connection refused to "%s", port "%s"', EMAIL_HOST, EMAIL_PORT) | ||
if additional_error: | ||
LOG.error(*additional_error) | ||
# TODO: Store error as incident | ||
|
||
|
||
class EmailNotification(NotificationMedium): | ||
MEDIA_SLUG = "email" | ||
MEDIA_NAME = "Email" | ||
MEDIA_SETTINGS_KEY = "email_address" | ||
MEDIA_JSON_SCHEMA = { | ||
"title": "Email Settings", | ||
"description": "Settings for a DestinationConfig using email.", | ||
"type": "object", | ||
"required": [MEDIA_SETTINGS_KEY], | ||
"properties": { | ||
MEDIA_SETTINGS_KEY: { | ||
"type": "string", | ||
"title": "Email address", | ||
}, | ||
}, | ||
} | ||
|
||
class Form(forms.Form): | ||
email_address = forms.EmailField() | ||
|
||
@staticmethod | ||
def create_message_context(event: Event): | ||
"""Creates the subject, message and html message for the email""" | ||
title = f"{event}" | ||
incident_dict = modelinstance_to_dict(event.incident) | ||
for field in ("id", "source_id"): | ||
incident_dict.pop(field) | ||
incident_dict["details_url"] = event.incident.pp_details_url() | ||
if event.incident.end_time in {INFINITY, LOCAL_INFINITY}: | ||
incident_dict["end_time"] = "Still open" | ||
|
||
template_context = { | ||
"title": title, | ||
"event": event, | ||
"incident_dict": incident_dict, | ||
} | ||
subject = f"{settings.NOTIFICATION_SUBJECT_PREFIX}{title}" | ||
message = render_to_string("notificationprofile/email.txt", template_context) | ||
html_message = render_to_string("notificationprofile/email.html", template_context) | ||
|
||
return subject, message, html_message | ||
|
||
@classmethod | ||
def send(cls, event: Event, destinations: Iterable[DestinationConfig], **_) -> bool: | ||
""" | ||
Sends email about a given event to the given email destinations | ||
Returns False if no email destinations were given and | ||
True if emails were sent | ||
""" | ||
email_addresses = cls.get_relevant_addresses(destinations=destinations) | ||
if not email_addresses: | ||
return False | ||
num_emails = len(email_addresses) | ||
|
||
subject, message, html_message = cls.create_message_context(event=event) | ||
|
||
failed = set() | ||
for email_address in email_addresses: | ||
sent = send_email_safely( | ||
send_mail, | ||
subject=subject, | ||
message=message, | ||
from_email=None, | ||
recipient_list=[email_address], | ||
html_message=html_message, | ||
) | ||
if not sent: # 0 for failure otherwise 1 | ||
failed.add(email_address) | ||
|
||
if failed: | ||
if num_emails == len(failed): | ||
LOG.error("Email: Failed to send to any addresses") | ||
return False | ||
LOG.warn( | ||
"Email: Failed to send to %i of %i addresses", | ||
len(failed), | ||
num_emails, | ||
) | ||
LOG.debug("Email: Failed to send to:", " ".join(failed)) | ||
return True |
Oops, something went wrong.