Home Information - Your home, your data, organized.
Python
Added notification module and email sending capabilities, but WIP.
Anthony Cassandrab88a4a70ac83
diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex 9941c52e..a73ce76f 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -115,4 +115,5 @@ class Alert:def to_notification_item(self):return NotificationItem(signature = self.signature,+ title = self.title,)diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex efd71061..bd13d6f6 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -3,7 +3,7 @@ import loggingfrom hi.apps.common.singleton import Singletonfrom hi.apps.security.security_manager import SecurityManager-from hi.apps.notify.notification_queue import NotificationQueue+from hi.apps.notify.notification_manager import NotificationManagerfrom .alert import Alertfrom .alert_queue import AlertQueue@@ -17,7 +17,7 @@ class AlertManager(Singleton):def __init_singleton__(self):self._alert_queue = AlertQueue()- self._notification_queue = NotificationQueue()+ self._notification_manager = NotificationManager()return@property@@ -81,7 +81,9 @@ class AlertManager(Singleton):try:alert = self._alert_queue.add_alarm( alarm = alarm )if security_state.uses_notifications and alert.has_single_alarm:- self._notification_queue.add_item( notification = alert.to_notification_item() )+ self._notification_manager.add_notification_item(+ notification_item = alert.to_notification_item(),+ )except ValueError as ve:logging.info( str(ve) )except Exception as e:@@ -91,7 +93,6 @@ class AlertManager(Singleton):def do_periodic_maintenance(self):try:self._alert_queue.remove_expired_or_acknowledged_alerts()- self._notification_queue.check_for_notifications()except Exception as e:logger.exception( 'Problem doing periodic alert maintenance.', e )returndiff --git a/src/hi/apps/alert/apps.py b/src/hi/apps/alert/apps.pyindex cad085a2..e68d0057 100644--- a/src/hi/apps/alert/apps.py+++ b/src/hi/apps/alert/apps.py@@ -1,4 +1,5 @@import os+from django.apps import AppConfigdiff --git a/src/hi/apps/common/email_utils.py b/src/hi/apps/common/email_utils.pyindex 97062e9f..aac1bce1 100644--- a/src/hi/apps/common/email_utils.py+++ b/src/hi/apps/common/email_utils.py@@ -7,21 +7,19 @@ from django.conf import settingsfrom django.core.mail import EmailMultiAlternativesfrom django.template.loader import render_to_string-import waa.apps.common.metrics as metrics-logger = logging.getLogger(__name__)ALLOW_NON_BLOCKING_EMAILS = bool( not settings.DEBUG )-def parse_emails_from_text( text ):+def parse_emails_from_text( text : str ) -> List[ str ]:result_list = list()if not text:return result_listfor line in text.split( '\n' ):- for element in re.split( r'[\,\;]+', line ):+ for element in re.split( r'[\,\;\s]+', line ):if element.strip():result_list.append( element.strip() )continue@@ -104,6 +102,5 @@ class EmailThread( threading.Thread ):try:self.message.send()except Exception as e:- logger.exception( 'Problem in email thread.' )- metrics.exception( e )+ logger.exception( 'Problem in email thread.', e )returndiff --git a/src/hi/apps/common/queues.py b/src/hi/apps/common/queues.pyindex f028a436..4ad8d036 100644--- a/src/hi/apps/common/queues.py+++ b/src/hi/apps/common/queues.py@@ -23,7 +23,7 @@ class RateLimitedQueue:"""def __init__( self,label : str,- emit_interval_secs : int = 60,+ emit_interval_secs : int = 30,max_queue_size : int = 30,unique_items_only : bool = True ):self._label = labeldiff --git a/src/hi/apps/config/audio_signal.py b/src/hi/apps/config/audio_signal.pyindex 1ee27219..4a476086 100644--- a/src/hi/apps/config/audio_signal.py+++ b/src/hi/apps/config/audio_signal.py@@ -5,9 +5,9 @@ from hi.apps.config.enums import SubsystemAttributeTypeclass AudioSignal(LabeledEnum):- INFO = ( 'Info' , '', SubsystemAttributeType.INFO_AUDIO_FILE )- WARNING = ( 'Warning' , '', SubsystemAttributeType.WARNING_AUDIO_FILE)- CRITICAL = ( 'Critical' , '', SubsystemAttributeType.CRITICAL_AUDIO_FILE )+ INFO = ( 'Info' , '', SubsystemAttributeType.CONSOLE_INFO_AUDIO_FILE )+ WARNING = ( 'Warning' , '', SubsystemAttributeType.CONSOLE_WARNING_AUDIO_FILE)+ CRITICAL = ( 'Critical' , '', SubsystemAttributeType.CONSOLE_CRITICAL_AUDIO_FILE )def __init__( self,label : str,diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.pyindex 08f614fe..2dc165ea 100644--- a/src/hi/apps/config/enums.py+++ b/src/hi/apps/config/enums.py@@ -31,9 +31,11 @@ class ConfigPageType(LabeledEnum):class SubsystemType(LabeledEnum):- LOCALE = ('Locale' , '' )- DISPLAY = ('Display' , '' )- ALERTS = ('Alerts' , '' )+ LOCALE = ('Locale' , '' )+ DISPLAY = ('Display' , '' )+ NOTIFICATIONS = ('Notifications' , '' )+ SECURITY = ('Security' , '' )+ CONSOLE = ('Console' , '' )class Theme(LabeledEnum):@@ -63,96 +65,96 @@ class SubsystemAttributeType(LabeledEnum):True,str( Theme.default() ),)- AWAY_ALERT_EMAILS_ENABLED = (- 'Send Email When Away',- 'Whether to send emails for critical alerts to when away.',- SubsystemType.ALERTS,+ SECURITY_DAY_START = (+ 'Security Day Start',+ 'Determines what time of day to switch to the "Day" security posture.',+ SubsystemType.SECURITY,+ AttributeValueType.ENUM,+ 'hi.datetime.time-of-day',+ True,+ True,+ '08:00',+ )+ SECURITY_NIGHT_START = (+ 'Security Night Start',+ 'Determines what time of day to switch to the "Night" security posture.',+ SubsystemType.SECURITY,+ AttributeValueType.ENUM,+ 'hi.datetime.time-of-day',+ True,+ True,+ '23:00',+ )+ SECURITY_AWAY_DELAY_MINS = (+ 'Away Delay Time (mins)',+ 'Amount of time to ignore alarms when switching to "Away" security posture.',+ SubsystemType.SECURITY,+ AttributeValueType.INTEGER,+ '',+ True,+ True,+ '5',+ )+ SECURITY_SNOOZE_DELAY_MINS = (+ 'Snooze Delay Time (mins)',+ 'Amount of time to ignore alarms when "Snooze" option is chosen.',+ SubsystemType.SECURITY,+ AttributeValueType.INTEGER,+ '',+ True,+ True,+ '5',+ )+ NOTIFICATIONS_ENABLED = (+ 'Enable Notifications',+ 'Whether to send notifications (e.g., emails).',+ SubsystemType.NOTIFICATIONS,AttributeValueType.BOOLEAN,'',True,- False,- False,+ True,+ True,)- AWAY_ALERT_EMAILS = (- 'Away Alert Addresses',- 'Email addresses to send critical alerts to when away.',- SubsystemType.ALERTS,+ NOTIFICATIONS_EMAIL_ADDRESSES = (+ 'Notification Email Addresses',+ 'Email addresses to send notifications to (if enabled).',+ SubsystemType.NOTIFICATIONS,AttributeValueType.TEXT,'',True,False,'',)- INFO_AUDIO_FILE = (+ CONSOLE_INFO_AUDIO_FILE = ('Info Alert Sound','The sound to play when an INFO level alert arrives.',- SubsystemType.ALERTS,+ SubsystemType.CONSOLE,AttributeValueType.ENUM,'hi.audio.file',True,False,AudioFile.INFO,)- WARNING_AUDIO_FILE = (+ CONSOLE_WARNING_AUDIO_FILE = ('Warning Alert Sound','The sound to play when an WARNING level alert arrives.',- SubsystemType.ALERTS,+ SubsystemType.CONSOLE,AttributeValueType.ENUM,'hi.audio.file',True,False,AudioFile.WARNING,)- CRITICAL_AUDIO_FILE = (+ CONSOLE_CRITICAL_AUDIO_FILE = ('Critical Alert Sound','The sound to play when an CRITICAL level alert arrives.',- SubsystemType.ALERTS,+ SubsystemType.CONSOLE,AttributeValueType.ENUM,'hi.audio.file',True,False,AudioFile.CRITICAL,)- ALERTS_DAY_START = (- 'Security Day Start',- 'Determines what time of day to switch to the "Day" security posture.',- SubsystemType.ALERTS,- AttributeValueType.ENUM,- 'hi.datetime.time-of-day',- True,- True,- '08:00',- )- ALERTS_NIGHT_START = (- 'Security Night Start',- 'Determines what time of day to switch to the "Night" security posture.',- SubsystemType.ALERTS,- AttributeValueType.ENUM,- 'hi.datetime.time-of-day',- True,- True,- '23:00',- )- ALERTS_AWAY_DELAY_MINS = (- 'Away Delay Time (mins)',- 'Amount of time to ignore alerts when switching to "Away" security posture.',- SubsystemType.ALERTS,- AttributeValueType.INTEGER,- '',- True,- True,- '5',- )- ALERTS_SNOOZE_DELAY_MINS = (- 'Snooze Delay Time (mins)',- 'Amount of time to ignore alerts when "Snooze" option is chosen.',- SubsystemType.ALERTS,- AttributeValueType.INTEGER,- '',- True,- True,- '5',- )def __init__( self,label : str,diff --git a/src/hi/apps/notify/apps.py b/src/hi/apps/notify/apps.pyindex 6bee3274..b2cb92e3 100644--- a/src/hi/apps/notify/apps.py+++ b/src/hi/apps/notify/apps.py@@ -1,6 +1,18 @@+import os+from django.apps import AppConfigclass NotifyConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "hi.apps.notify"++ def ready(self):+ if os.getenv( "RUN_MAIN", None ) != "true":+ # Avoid double initialization when using the reloader in development+ return+ from hi.apps.monitor.monitor_manager import MonitorManager+ from hi.apps.notify.notification_monitor import NotificationMonitor+ notification_monitor = NotificationMonitor()+ MonitorManager().register( notification_monitor )+ returndiff --git a/src/hi/apps/notify/email_sender.py b/src/hi/apps/notify/email_sender.pyindex fab7be70..3c560e59 100644--- a/src/hi/apps/notify/email_sender.py+++ b/src/hi/apps/notify/email_sender.py@@ -1,15 +1,15 @@-from dataclasses import dataclass, field+from asgiref.sync import sync_to_asyncimport logging-from typing import Dict, List+from typing import Dictfrom django.conf import settings-from django.http.request import HttpRequestfrom django.urls import reversefrom hi.apps.common.email_utils import send_html_emailfrom hi.apps.common.utils import hash_with_seedfrom .models import UnsubscribedEmail+from .transient_models import EmailDatalogger = logging.getLogger(__name__)@@ -18,48 +18,44 @@ class UnsubscribedEmailError(Exception):pass-@dataclass-class EmailSenderData:- request : HttpRequest- subject_template_name : str- message_text_template_name : str- message_html_template_name : str- to_email_address : str- from_email_address : str = None # Defaults to system-wide FROM- template_context : Dict[str, str] = field( default_factory = dict )- files : List = None # For attachments- non_blocking : bool = True-- # For testing (can use the unsubscribe link to test for the original intended "to" email)- override_to_email_address : str = None--class EmailSender:""" For sending a single email message. """++ HOME_URL_NAME = 'home'+ UNSUBSCRIBE_URL_NAME = 'notify_email_unsubscribe'- def __init__( self, data : EmailSenderData ):+ def __init__( self, data : EmailData ):self._data = datareturn- def send( self):- if UnsubscribedEmail.objects.exists_by_email( email = self._data.to_email_address ):- raise UnsubscribedEmailError( f'Email address is unsubscribed for {self._data.to_email_address}' )+ def send(self):+ self._assert_not_unsubscribed()+ self._send_helper()+ return++ async def send_async( self):+ await self._assert_not_unsubscribed_async()+ self._send_helper()+ return++ def _send_helper(self):context = self._data.template_contextself._add_base_url( context = context )- self._add_game_home_url( context = context )+ self._add_home_url( context = context )self._add_unsubscribe_url( context = context )- effective_to_email_address = self._data.to_email_addressif self._data.override_to_email_address:effective_to_email_address = self._data.override_to_email_address-+ else:+ effective_to_email_address = self._data.to_email_address+send_html_email(request = self._data.request,subject_template_name = self._data.subject_template_name,message_text_template_name = self._data.message_text_template_name,message_html_template_name = self._data.message_html_template_name,- to_email_addresses = [ effective_to_email_address ],+ to_email_addresses = effective_to_email_address,from_email_address = self._data.from_email_address,context = context,files = self._data.files,@@ -74,17 +70,17 @@ class EmailSender:context['BASE_URL'] = settings.BASE_URL_FOR_EMAIL_LINKSreturn- def _add_game_home_url( self, context : Dict ):- relative_url = reverse( 'game_home' )+ def _add_home_url( self, context : Dict ):+ relative_url = reverse( self.HOME_URL_NAME )if self._data.request:- context['USER_HOME_URL'] = self._data.request.build_absolute_uri( relative_url )+ context['HOME_URL'] = self._data.request.build_absolute_uri( relative_url )elif "BASE_URL" in context:- context['USER_HOME_URL'] = f'{context["BASE_URL"]}{relative_url}'+ context['HOME_URL'] = f'{context["BASE_URL"]}{relative_url}'returndef _add_unsubscribe_url( self, context : Dict ):token = hash_with_seed( self._data.to_email_address )- relative_url = reverse( 'user_unsubscribe_email',+ relative_url = reverse( self.UNSUBSCRIBE_URL_NAME,kwargs = {'email': self._data.to_email_address,'token': token,@@ -95,3 +91,13 @@ class EmailSender:context['UNSUBSCRIBE_URL'] = f'{context["BASE_URL"]}{relative_url}'return+ async def _assert_not_unsubscribed_async( self ):+ await sync_to_async( self._assert_not_unsubscribed )()+ return++ def _assert_not_unsubscribed( self ):+ email_address = self._data.to_email_address+ if UnsubscribedEmail.objects.exists_by_email( email = email_address ):+ raise UnsubscribedEmailError( f'Email address is unsubscribed for {email_address}' )+ return+diff --git a/src/hi/apps/notify/migrations/0001_initial.py b/src/hi/apps/notify/migrations/0001_initial.pynew file mode 100644index 00000000..a29f4984--- /dev/null+++ b/src/hi/apps/notify/migrations/0001_initial.py@@ -0,0 +1,39 @@+# Generated by Django 4.2.15 on 2024-12-10 14:31++from django.db import migrations, models+++class Migration(migrations.Migration):++ initial = True++ dependencies = []++ operations = [+ migrations.CreateModel(+ name="UnsubscribedEmail",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "email",+ models.EmailField(+ max_length=254, unique=True, verbose_name="Email"+ ),+ ),+ (+ "created_datetime",+ models.DateTimeField(+ auto_now_add=True, db_index=True, verbose_name="Created"+ ),+ ),+ ],+ ),+ ]diff --git a/src/hi/apps/notify/notification_manager.py b/src/hi/apps/notify/notification_manager.pynew file mode 100644index 00000000..fb7553eb--- /dev/null+++ b/src/hi/apps/notify/notification_manager.py@@ -0,0 +1,74 @@+import logging++from hi.apps.common.email_utils import parse_emails_from_text+from hi.apps.common.singleton import Singleton+from hi.apps.common.utils import str_to_bool+from hi.apps.config.enums import SubsystemAttributeType+from hi.apps.config.settings_manager import SettingsManager+from hi.apps.notify.notification_queue import NotificationQueue++from .email_sender import EmailSender+from .transient_models import EmailData, Notification, NotificationItem++logger = logging.getLogger(__name__)+++class NotificationManager(Singleton):++ def __init_singleton__(self):+ self._notification_queue = NotificationQueue()+ self._settings_manager = SettingsManager()+ return++ def add_notification_item( self, notification_item : NotificationItem ):+ self._notification_queue.add_item( notification_item = notification_item )+ return++ async def do_periodic_maintenance(self):+ try:+ notification_list = self._notification_queue.check_for_notifications()+ logger.debug( f'Notifications found: {len(notification_list)}.' )+ for notification in notification_list:+ await self.send_notifications( notification )+ continue+ except Exception as e:+ logger.exception( "Problem sending notifications", e )+ return++ async def send_notifications( self, notification : Notification ):+ 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++ await self.send_email_notification_if_needed( notification = notification )+ return++ async def send_email_notification_if_needed( self, notification : Notification ):++ email_addresses_str = self._settings_manager.get_setting_value(+ SubsystemAttributeType.NOTIFICATIONS_EMAIL_ADDRESSES,+ )+ 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++ logger.debug( f'Sending notification email to "{email_address_list}": {notification}.' )++ email_data = EmailData(+ request = None,+ to_email_address = email_address_list,+ subject_template_name = 'notify/emails/notification_subject.txt',+ message_text_template_name = 'notify/emails/notification_message.txt',+ message_html_template_name = 'notify/emails/notification_message.html',+ template_context = { 'notification': notification },+ )+ email_sender = EmailSender( data = email_data )+ await email_sender.send_async()+ return++diff --git a/src/hi/apps/notify/notification_monitor.py b/src/hi/apps/notify/notification_monitor.pynew file mode 100644index 00000000..eeb77a9a--- /dev/null+++ b/src/hi/apps/notify/notification_monitor.py@@ -0,0 +1,25 @@+import logging++from hi.apps.monitor.periodic_monitor import PeriodicMonitor++from .notification_manager import NotificationManager++logger = logging.getLogger(__name__)+++class NotificationMonitor( PeriodicMonitor ):++ NOTIFICATION_POLLING_INTERVAL_SECS = 10++ def __init__( self ):+ super().__init__(+ id = 'notification-monitor',+ interval_secs = self.NOTIFICATION_POLLING_INTERVAL_SECS,+ )+ self._notification_manager = NotificationManager()+ return++ async def do_work(self):+ logger.debug( 'Checking for notification maintenance work.' )+ await self._notification_manager.do_periodic_maintenance()+ returndiff --git a/src/hi/apps/notify/notification_queue.py b/src/hi/apps/notify/notification_queue.pyindex 2b8e4f82..234e8db6 100644--- a/src/hi/apps/notify/notification_queue.py+++ b/src/hi/apps/notify/notification_queue.py@@ -1,5 +1,6 @@import loggingimport threading+from typing import Listimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.queues import ExponentialBackoffRateLimitedQueue@@ -17,6 +18,7 @@ class NotificationQueue:returndef add_item( self, notification_item : NotificationItem ):+ logger.debug( f'Adding notification to queue: {notification_item}' )try:self._queues_lock.acquire()@@ -28,7 +30,6 @@ class NotificationQueue:)queue = self._queues_map[notification_item.signature]queue.add_to_queue( notification_item )- logger.debug( f'Added notification event to queue: {notification_item}' )except Exception as e:logger.exception( 'Problem adding notification to notification queue.', e )@@ -36,13 +37,14 @@ class NotificationQueue:self._queues_lock.release()return- def check_for_notifications( self ):+ def check_for_notifications( self ) -> List[ Notification ]:notifications_map = dict()try:self._queues_lock.acquire()now = datetimeproxy.now()for signature, queue in self._queues_map.items():+ logger.debug( f'Notify queue "{signature}" contains {len(queue)} items.' )notification_item_list = queue.get_queue_emissions( cur_datetime = now )if len(notification_item_list) < 1:continue@@ -54,19 +56,9 @@ class NotificationQueue:continueexcept Exception as e:- logger.exception( 'Problem with sending notifications.', e )+ logger.exception( 'Problem checking notification queues.', e )finally:self._queues_lock.release()- # We do not want to send notifications while we have the data lock- try:- for signature, notification in notifications_map.items():- self.send_notifications( notification )- continue- except Exception as e:- logger.exception( "Problem Sending notifications", e )- return-- def send_notifications( self, notification : Notification ):- pass-+ return list( notifications_map.items() )+diff --git a/src/hi/apps/notify/templates/notify/emails/base_email_message.html b/src/hi/apps/notify/templates/notify/emails/base_email_message.htmlnew file mode 100644index 00000000..3b1ccb68--- /dev/null+++ b/src/hi/apps/notify/templates/notify/emails/base_email_message.html@@ -0,0 +1,45 @@+{% load static %}+<html>+ <head>+ </head>+ <body>+ <div style="border: 4px solid #040408; padding: 0; margin: 0">+ <div style="border: 4px solid white; padding: 0; margin: 0;">+ <div style="border: 4px solid #721917; padding: 0;">+ {% block body %}+ <table style="width: 100%;" cellpadding="0" cellspacing="0">+ <tr style="background-color: #721917;">+ <td style="width: 128px; padding-left: 2px; padding-bottom: 4px;">+ {% block logo %}+ {% if BASE_URL %}+ <a href="{{ BASE_URL }}" alt="Home Information Home"><img src="{{ BASE_URL }}{% static 'img/hi-logo-128x64.png' %}" alt="Home Information Logo"/></a>+ {% endif %}+ {% endblock %}+ </td>+ <td>+ <p style="font-size: 18px; font-weight: 800; color: white; padding: 12px;" >+ {% block title %}+ {% endblock %}+ </p>+ </td>+ </tr>+ </table>++ {% endblock %}++ <div style="margin: 8px;">+ {% block content %}+ {% endblock %}+ </div>++ {% if UNSUBSCRIBE_URL %}+ <hr />+ <p style="margin: 8px;">+ <a style="color: #888888; font-size: 0.8rem;" href="{{ UNSUBSCRIBE_URL }}">Unsubscribe.</a>+ </p>+ {% endif %}+ </div>+ </div>+ </div>+ </body>+</html>diff --git a/src/hi/apps/notify/templates/notify/emails/base_email_message.txt b/src/hi/apps/notify/templates/notify/emails/base_email_message.txtnew file mode 100644index 00000000..1369ae86--- /dev/null+++ b/src/hi/apps/notify/templates/notify/emails/base_email_message.txt@@ -0,0 +1,5 @@+{% block content %}+{% endblock %}+++Unsubscribe: {{ UNSUBSCRIBE_URL }}diff --git a/src/hi/apps/notify/templates/notify/emails/notification_message.html b/src/hi/apps/notify/templates/notify/emails/notification_message.htmlnew file mode 100644index 00000000..bba57a0c--- /dev/null+++ b/src/hi/apps/notify/templates/notify/emails/notification_message.html@@ -0,0 +1,7 @@+{% extends "notify/emails/base_email_message.html" %}+{% block title %}Home Information Notification{% endblock %}+{% block content %}+<p>+ TBD : {{ notification }}+</p>+{% endblock %}diff --git a/src/hi/apps/notify/templates/notify/emails/notification_message.txt b/src/hi/apps/notify/templates/notify/emails/notification_message.txtnew file mode 100644index 00000000..74a54808--- /dev/null+++ b/src/hi/apps/notify/templates/notify/emails/notification_message.txt@@ -0,0 +1,6 @@+{% extends "notify/emails/base_email_message.txt" %}+{% block content %}Home Information Notification++{{ notification.title }}++{% endblock %}diff --git a/src/hi/apps/notify/templates/notify/emails/notification_subject.txt b/src/hi/apps/notify/templates/notify/emails/notification_subject.txtnew file mode 100644index 00000000..97903162--- /dev/null+++ b/src/hi/apps/notify/templates/notify/emails/notification_subject.txt@@ -0,0 +1 @@+HI Notification: {{ notification.title }}diff --git a/src/hi/apps/notify/templates/notify/pages/email_unsubscribe_success.html b/src/hi/apps/notify/templates/notify/pages/email_unsubscribe_success.htmlnew file mode 100644index 00000000..3ed46910--- /dev/null+++ b/src/hi/apps/notify/templates/notify/pages/email_unsubscribe_success.html@@ -0,0 +1,7 @@+{% extends "pages/base.html" %}++{% block content %}+<div class="container">+ <h1>You have been successfuly unsubscribed.</h1>+</div>+{% endblock %}diff --git a/src/hi/apps/notify/transient_models.py b/src/hi/apps/notify/transient_models.pyindex ec1eafd5..f7bc4704 100644--- a/src/hi/apps/notify/transient_models.py+++ b/src/hi/apps/notify/transient_models.py@@ -1,13 +1,53 @@-from dataclasses import dataclass-from typing import List+from dataclasses import dataclass, field+from typing import Dict, List, Union++from django.http.request import HttpRequest+@dataclass+class EmailData:+ """+ Input data format for sending emails with EmailSender. Caller defines+ the three required templates for formatting the email. The email sender+ will create a template context that includes the following variables+ that should be used in the email:++ BASE_URL - Use this to forms any needed site links.+ HOME_URL - Url to the site's main landing page page.+ UNSUBSCRIBE_URL - Include as best practice if you send email more broadly.++ The templates are best defined by extending some pre-defined base+ templates to make all emails have a consistent formatting. e.g.,+ Unsubscribe URL appearing in footer.+ """++ # Set the request to None for background tasks, but also make sure+ # settings.BASE_URL_FOR_EMAIL_LINKS is set.+ #+ request : HttpRequest++ subject_template_name : str+ message_text_template_name : str+ message_html_template_name : str+ to_email_address : Union[ str, List[ str ]]++ # Defaults to system-wide settings.DEFAULT_FROM_EMAIL+ from_email_address : str = None++ template_context : Dict[str, str] = field( default_factory = dict )+ files : List = None # For attachments+ non_blocking : bool = True++ # For testing (can use the unsubscribe link to test for the original intended "to" email)+ override_to_email_address : str = None++@dataclassclass NotificationItem:signature : str-+ title : str+@dataclassclass Notification:item_list : List[ NotificationItem ]-diff --git a/src/hi/apps/notify/urls.py b/src/hi/apps/notify/urls.pynew file mode 100644index 00000000..9806180e--- /dev/null+++ b/src/hi/apps/notify/urls.py@@ -0,0 +1,11 @@+from django.urls import re_path++from . import views+++urlpatterns = [++ re_path( r'^email/unsubscribe/(?P<token>[\w-]+)/(?P<email>.+)$',+ views.EmailUnsubscribeView.as_view(),+ name='notify_email_unsubscribe'),+]diff --git a/src/hi/apps/notify/views.py b/src/hi/apps/notify/views.pynew file mode 100644index 00000000..d8297dc8--- /dev/null+++ b/src/hi/apps/notify/views.py@@ -0,0 +1,47 @@+import logging++from django.core.exceptions import BadRequest+from django.shortcuts import render+from django.views.generic import View++from hi.apps.common.utils import hash_with_seed++from .models import UnsubscribedEmail++logger = logging.getLogger(__name__)+++class EmailUnsubscribeView( View ):++ SUCCESS_PAGE_TEMPLATE_NAME = 'notify/pages/email_unsubscribe_success.html'++ def get( self, request, *args, **kwargs ):+ email = kwargs.get('email')+ token = kwargs.get('token')+ if not email or not token:+ raise BadRequest( 'Improperly formed unsubscribe url.' )++ # A psuedo-secure hash to prevent malicious unsubscribes.+ # Attackers needs to know a "seed" to be able to hash the email+ # properly. Motivation is that we should not require a user to+ # login or do any other complicated flow to be able to unsubscribe.+ #+ expected_token = hash_with_seed( email )+ context = { 'email': email }++ if expected_token != token:+ raise BadRequest( 'Invalid unsubscribe url.' )++ # If already unsubscribed, just treat like success.+ try:+ UnsubscribedEmail.objects.get( email__iexact = email )+ return render( request, self.SUCCESS_PAGE_TEMPLATE_NAME, context )+ except UnsubscribedEmail.DoesNotExist:+ pass++ try:+ UnsubscribedEmail.objects.create( email = email )+ except Exception as e:+ logger.exception( f'Problem unsubscribing email {email}', e )++ return render( request, self.SUCCESS_PAGE_TEMPLATE_NAME, context )diff --git a/src/hi/apps/security/security_manager.py b/src/hi/apps/security/security_manager.pyindex 960dc044..03a4e8b7 100644--- a/src/hi/apps/security/security_manager.py+++ b/src/hi/apps/security/security_manager.py@@ -99,14 +99,14 @@ class SecurityManager(Singleton):immediate_security_state = SecurityState.DISABLEDfuture_security_state = SecurityState.AWAYdelay_mins_str = SettingsManager().get_setting_value(- SubsystemAttributeType.ALERTS_AWAY_DELAY_MINS,+ SubsystemAttributeType.SECURITY_AWAY_DELAY_MINS,)elif security_state_action == SecurityStateAction.SNOOZE:immediate_security_state = SecurityState.DISABLEDfuture_security_state = self._security_statedelay_mins_str = SettingsManager().get_setting_value(- SubsystemAttributeType.ALERTS_SNOOZE_DELAY_MINS,+ SubsystemAttributeType.SECURITY_SNOOZE_DELAY_MINS,)else:@@ -163,6 +163,13 @@ class SecurityManager(Singleton):self._delayed_security_state_timer.cancel()self._delayed_security_state_timer = Timer( delay_secs, self._apply_delayed_state )self._delayed_security_state_timer.start()++ # N.B. We want to set the cached security state to the desired+ # future state. Otherwise, if system restarts during the+ # SNOOZE or SET_AWAY transition period, it will come back up in+ # the (transitional) DISABLED state, which is undesirable.+ #+ self._redis_client.set( self.SECURITY_STATE_CACHE_KEY, str(self._delayed_security_state ))finally:if not lock_acquired:@@ -268,10 +275,10 @@ class SecurityManager(Singleton):SubsystemAttributeType.TIMEZONE,)day_start_time_of_day_str = settings_manager.get_setting_value(- SubsystemAttributeType.ALERTS_DAY_START,+ SubsystemAttributeType.SECURITY_DAY_START,)night_start_time_of_day_str = settings_manager.get_setting_value(- SubsystemAttributeType.ALERTS_NIGHT_START,+ SubsystemAttributeType.SECURITY_NIGHT_START,)current_datetime = datetimeproxy.now()diff --git a/src/hi/apps/security/security_monitor.py b/src/hi/apps/security/security_monitor.pyindex e2a59f93..b7ab7aa3 100644--- a/src/hi/apps/security/security_monitor.py+++ b/src/hi/apps/security/security_monitor.py@@ -41,7 +41,7 @@ class SecurityMonitor( PeriodicMonitor ):returnday_start_time_of_day = settings_manager.get_setting_value(- SubsystemAttributeType.ALERTS_DAY_START,+ SubsystemAttributeType.SECURITY_DAY_START,)if datetimeproxy.is_time_of_day_in_interval(time_of_day_str = day_start_time_of_day,@@ -55,7 +55,7 @@ class SecurityMonitor( PeriodicMonitor ):returnnight_start_time_of_day = settings_manager.get_setting_value(- SubsystemAttributeType.ALERTS_NIGHT_START,+ SubsystemAttributeType.SECURITY_NIGHT_START,)if datetimeproxy.is_time_of_day_in_interval(time_of_day_str = night_start_time_of_day,diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.pyindex 7eb8a164..781baaa4 100644--- a/src/hi/apps/sense/sensor_response_manager.py+++ b/src/hi/apps/sense/sensor_response_manager.py@@ -170,9 +170,9 @@ class SensorResponseManager( Singleton ):sensor_response.sensor = await sync_to_async( self._get_sensor )(integration_key = sensor_response.integration_key,)- if sensor_response.detail_attrs:+ if sensor_response.sensor and sensor_response.detail_attrs:sensor_response.detail_attrs['Sensor Name'] = sensor_response.sensor.name- else:+ elif sensor_response.sensor:sensor_response.detail_attrs = { 'Sensor Name': sensor_response.sensor.name }continuereturndiff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 1876cb9b..133df1ff 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -358,6 +358,10 @@ else:EMAIL_USE_TLS = FalseEMAIL_USE_SSL = False-# Override this for test sites+# Needed when sending emails in background tasks since HttpRequest not+# available. Override this for development/testing/staging.+#BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'+# When tests functionalityt requires knowing if in unit test context.+UNIT_TESTING = Falsediff --git a/src/hi/settings/development.py b/src/hi/settings/development.pyindex b7144c86..167d959d 100644--- a/src/hi/settings/development.py+++ b/src/hi/settings/development.py@@ -120,3 +120,5 @@ LOGGING = {},},}++BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'diff --git a/src/hi/urls.py b/src/hi/urls.pyindex 98ce6094..24fa847c 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -39,6 +39,7 @@ urlpatterns = [re_path( r'^event/', include('hi.apps.event.urls' )),re_path( r'^alert/', include('hi.apps.alert.urls' )),re_path( r'^security/', include('hi.apps.security.urls' )),+ re_path( r'^notify/', include('hi.apps.notify.urls' )),# Custom error pagesre_path( r'^400.html$', views.bad_request_response, name='bad_request' ),