Home Information - Your home, your data, organized.
Python
Added email sending test and fixed mail bugs and config.
Anthony Cassandra1a85ab2e9b30
diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex a73ce76f..b8412abd 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -68,8 +68,11 @@ class Alert:@propertydef title(self) -> str:- return self._first_alarm.title-+ title_text = f'{self.alarm_level.label}: {self._first_alarm.title}'+ if self.alarm_count > 1:+ title_text += f' ({self.alarm_count})'+ return title_text+@propertydef first_alarm(self) -> Alarm:return self._first_alarm@@ -116,4 +119,5 @@ class Alert:return NotificationItem(signature = self.signature,title = self.title,+ source_obj = self,)diff --git a/src/hi/apps/alert/templates/alert/panes/alert_banner_content.html b/src/hi/apps/alert/templates/alert/panes/alert_banner_content.htmlindex 650d858f..411702d1 100644--- a/src/hi/apps/alert/templates/alert/panes/alert_banner_content.html+++ b/src/hi/apps/alert/templates/alert/panes/alert_banner_content.html@@ -7,12 +7,9 @@class="btn btn-info" data-async="modal">DETAILS</a></div><div class="col-1">{{ alert.alarm_level.label }}</div>- <div class="col-6">{{ alert.alarm_type }}: {{ alert.title }}</div>+ <div class="col-6">{{ alert.title }}</div><div class="col-3">Since {{ alert.start_datetime|naturaltime }}- {% if alert.alarm_count > 1 %}- ({{ alert.alarm_count }} Alarms)- {% endif %}</div><div class="col-1"><form action="{% url 'alert_acknowledge' alert_id=alert.id %}" method="post"diff --git a/src/hi/apps/common/email_utils.py b/src/hi/apps/common/email_utils.pyindex aac1bce1..df02ad31 100644--- a/src/hi/apps/common/email_utils.py+++ b/src/hi/apps/common/email_utils.py@@ -46,7 +46,6 @@ def send_html_email( request,files = None,non_blocking = False,from_email_name = None ):-if not from_email_address:from_email_address = settings.DEFAULT_FROM_EMAILif not from_email_name:@@ -83,7 +82,7 @@ def send_html_email( request,for file in files:message.attach_file(file)- if non_blocking and not settings.UNIT_TESTING: # Unit tests will fail if async emails+ if False and non_blocking and not settings.UNIT_TESTING: # Unit tests will fail if async emailsEmailThread( message = message ).start()else:message.send()diff --git a/src/hi/apps/notify/email_sender.py b/src/hi/apps/notify/email_sender.pyindex 3c560e59..e631860d 100644--- a/src/hi/apps/notify/email_sender.py+++ b/src/hi/apps/notify/email_sender.py@@ -49,7 +49,7 @@ class EmailSender:effective_to_email_address = self._data.override_to_email_addresselse:effective_to_email_address = self._data.to_email_address-+send_html_email(request = self._data.request,subject_template_name = self._data.subject_template_name,diff --git a/src/hi/apps/notify/notification_manager.py b/src/hi/apps/notify/notification_manager.pyindex fb7553eb..3ae2d5d7 100644--- a/src/hi/apps/notify/notification_manager.py+++ b/src/hi/apps/notify/notification_manager.py@@ -35,19 +35,18 @@ class NotificationManager(Singleton):logger.exception( "Problem sending notifications", e )return- async def send_notifications( self, notification : Notification ):+ async def send_notifications( self, notification : Notification ) -> bool:notifications_enabled_str = self._settings_manager.get_setting_value(SubsystemAttributeType.NOTIFICATIONS_ENABLED,)notifications_enabled = str_to_bool( notifications_enabled_str )if not notifications_enabled:logger.debug( f'Notifications not enabled. Ignoring: {notification}.' )- return+ return False- await self.send_email_notification_if_needed( notification = notification )- return+ return await self.send_email_notification_if_needed_async( notification = notification )- async def send_email_notification_if_needed( self, notification : Notification ):+ async def send_email_notification_if_needed_async( self, notification : Notification ) -> bool:email_addresses_str = self._settings_manager.get_setting_value(SubsystemAttributeType.NOTIFICATIONS_EMAIL_ADDRESSES,@@ -55,10 +54,10 @@ class NotificationManager(Singleton):email_address_list = parse_emails_from_text( text = email_addresses_str )if not email_address_list:logger.debug( f'No valid notification emails defined. Ignoring: {notification}.' )- return+ return Falselogger.debug( f'Sending notification email to "{email_address_list}": {notification}.' )-+email_data = EmailData(request = None,to_email_address = email_address_list,@@ -69,6 +68,4 @@ class NotificationManager(Singleton):)email_sender = EmailSender( data = email_data )await email_sender.send_async()- return--+ return Truediff --git a/src/hi/apps/notify/notification_queue.py b/src/hi/apps/notify/notification_queue.pyindex cb3fa88c..a5895266 100644--- a/src/hi/apps/notify/notification_queue.py+++ b/src/hi/apps/notify/notification_queue.py@@ -61,5 +61,5 @@ class NotificationQueue:finally:self._queues_lock.release()- return list( notifications_map.items() )+ return list( notifications_map.values() )diff --git a/src/hi/apps/notify/templates/notify/tests/ui/home.html b/src/hi/apps/notify/templates/notify/tests/ui/home.htmlindex 4fc019ad..478c4031 100644--- a/src/hi/apps/notify/templates/notify/tests/ui/home.html+++ b/src/hi/apps/notify/templates/notify/tests/ui/home.html@@ -15,11 +15,11 @@<div class="panel-body"><ul><li>- <a href="{% url 'notify_tests_ui_view_email' name='notification' %}" data-async="modal">View Notification Email+ <a href="{% url 'notify_tests_ui_view_email' email_type='notification' %}" data-async="modal">View Notification Email</a></li><li>- <a href="{% url 'notify_tests_ui_send_email' name='notification' %}" data-async="modal">Send Notification Email+ <a href="{% url 'notify_tests_ui_send_email' email_type='notification' %}" data-async="modal">Send Notification Email</a></li></ul>diff --git a/src/hi/apps/notify/templates/notify/tests/ui/send_email_success.html b/src/hi/apps/notify/templates/notify/tests/ui/send_email_success.htmlnew file mode 100644index 00000000..5f2f5b74--- /dev/null+++ b/src/hi/apps/notify/templates/notify/tests/ui/send_email_success.html@@ -0,0 +1,11 @@+{% extends "modals/action_ok.html" %}++{% block title_text %}+Email Sent+{% endblock %}++{% block body %}+<div class="container">+ No errors or issues sending email.+</div>+{% endblock %}diff --git a/src/hi/apps/notify/tests/ui/urls.py b/src/hi/apps/notify/tests/ui/urls.pyindex 2bf35f3f..843de374 100644--- a/src/hi/apps/notify/tests/ui/urls.py+++ b/src/hi/apps/notify/tests/ui/urls.py@@ -9,11 +9,11 @@ urlpatterns = [views.TestUiNotifyHomeView.as_view(),name='notify_tests_ui'),- re_path( r'^email/view/(?P<name>\w+)$',+ re_path( r'^email/view/(?P<email_type>\w+)$',views.TestUiViewEmailView.as_view(),name='notify_tests_ui_view_email'),- re_path( r'^email/send/(?P<name>\w+)$',+ re_path( r'^email/send/(?P<email_type>\w+)$',views.TestUiSendEmailView.as_view(),name='notify_tests_ui_send_email'),]diff --git a/src/hi/apps/notify/tests/ui/views.py b/src/hi/apps/notify/tests/ui/views.pyindex 1f099767..425df3e1 100644--- a/src/hi/apps/notify/tests/ui/views.py+++ b/src/hi/apps/notify/tests/ui/views.py@@ -1,10 +1,13 @@+import asyncioimport html+from typing import Dict+from django.core.exceptions import BadRequestfrom django.shortcuts import renderfrom django.template.loader import render_to_string-from django.views.generic import View+from hi.apps.notify.notification_manager import NotificationManagerfrom hi.apps.notify.tests.synthetic_data import NotifySyntheticData@@ -19,18 +22,24 @@ class TestUiNotifyHomeView( View ):class TestUiViewEmailView( View ):def get( self, request, *args, **kwargs ):- view_name = kwargs.get('name')- notification = NotifySyntheticData().create_random_notification()- context = {- 'notification': notification,- }+ context = self.get_context_for_email_message( request, *args, **kwargs )return self.email_preview_response(request = request,app_name = 'notify',- view_name = view_name,+ view_name = context.get('email_type', 'Not specifified'),context = context,)+ def get_context_for_email_message( self, request, *args, **kwargs ) -> Dict[ str, object ]:+ email_type = kwargs.get('email_type')+ if email_type == 'notification':+ notification = NotifySyntheticData().create_random_notification()+ return {+ 'email_type': email_type,+ 'notification': notification,+ }+ return dict()+def email_preview_response( self, request, app_name : str, view_name : str, context : dict ):context.update({@@ -58,4 +67,20 @@ class TestUiViewEmailView( View ):class TestUiSendEmailView( View ):- pass++ def get( self, request, *args, **kwargs ):+ email_type = kwargs.get('email_type')+ if email_type == 'notification':+ notification = NotifySyntheticData().create_random_notification()+ send_email_coroutine = NotificationManager().send_email_notification_if_needed_async(+ notification = notification,+ )+ result = asyncio.run( send_email_coroutine )+ if not result:+ raise Exception( 'No able to send. Check email address configuration.' )++ else:+ raise BadRequest( f'Sending email type "{email_type}" not implemented.' )++ return render( request, 'notify/tests/ui/send_email_success.html' )+diff --git a/src/hi/apps/notify/transient_models.py b/src/hi/apps/notify/transient_models.pyindex ed8e7ee8..5cfefc66 100644--- a/src/hi/apps/notify/transient_models.py+++ b/src/hi/apps/notify/transient_models.py@@ -2,6 +2,19 @@ from dataclasses import dataclass, fieldfrom typing import Dict, List, Unionfrom django.http.request import HttpRequest+++@dataclass+class NotificationItem:+ signature : str+ title : str+ source_obj : object = None+++@dataclass+class Notification:+ title : str+ item_list : List[ NotificationItem ]@dataclass@@ -40,15 +53,3 @@ class EmailData:# For testing (can use the unsubscribe link to test for the original intended "to" email)override_to_email_address : str = None---@dataclass-class NotificationItem:- signature : str- title : str---@dataclass-class Notification:- title : str- item_list : List[ NotificationItem ]diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 87880387..8b74fde3 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -332,7 +332,7 @@ CACHES = {#====================# Transactional Emails-SITE_DOMAIN = 'pomdp.com'+SITE_DOMAIN = 'cassandra.org'EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'@@ -346,6 +346,7 @@ EMAIL_HOST = get_env_variable('HI_EMAIL_HOST')EMAIL_PORT = int(get_env_variable('HI_EMAIL_PORT'))EMAIL_HOST_USER = get_env_variable('HI_EMAIL_HOST_USER')EMAIL_HOST_PASSWORD = get_env_variable('HI_EMAIL_HOST_PASSWORD')+EMAIL_TIMEOUT = 10 # In secondsif get_env_variable('HI_EMAIL_USE_TLS').lower() == 'true':EMAIL_USE_TLS = Truediff --git a/src/hi/settings/development.py b/src/hi/settings/development.pyindex 167d959d..c118ccfa 100644--- a/src/hi/settings/development.py+++ b/src/hi/settings/development.py@@ -114,6 +114,10 @@ LOGGING = {'handlers': ['console'],'level': 'INFO',},+ "django.core.mail": {+ "handlers": ["console"],+ "level": "DEBUG",+ },'hi': {'handlers': ['console' ],'level': 'DEBUG',@@ -121,4 +125,8 @@ LOGGING = {},}-BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'+BASE_URL_FOR_EMAIL_LINKS = 'http:/127.0.0.1:8000/'++# Uncomment to suppress email sending and write to console.+#+# EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"