Home Information - Your home, your data, organized.
Python
Aded system settings. Added ENUM attribute value type.
Anthony Cassandra20e6eb01e731
diff --git a/src/hi/apps/attribute/attribute_enums.py b/src/hi/apps/attribute/attribute_enums.pynew file mode 100644index 00000000..3843ea3d--- /dev/null+++ b/src/hi/apps/attribute/attribute_enums.py@@ -0,0 +1,55 @@+from typing import List, Tuple++from hi.apps.common.singleton import Singleton+from hi.apps.config.enums import Theme+++class AttributeEnums( Singleton ):+ """+ For attributes of type AttributeValueType.ENUM. There are some+ predefined common defaults, or can add others when modules are+ added.. This is needed so that the general attribute rendering+ templates can have access to them.++ TODO: Add some form of dynamic registration process to decouple+ this module from all the individual modules that need an enum type.+ """++ TIMEZONE_NAME_LIST = [+ 'UTC',+ 'America/New_York',+ 'America/Chicago',+ 'America/Denver',+ 'America/Los_Angeles',+ 'America/Toronto',+ 'America/Mexico_City',+ 'America/Sao_Paulo',+ 'Europe/London',+ 'Europe/Berlin',+ 'Europe/Paris',+ 'Europe/Moscow',+ 'Asia/Dubai',+ 'Asia/Tokyo',+ 'Asia/Seoul',+ 'Asia/Shanghai',+ 'Asia/Hong_Kong',+ 'Asia/Singapore',+ 'Asia/Kolkata',+ 'Asia/Jakarta',+ 'Australia/Sydney',+ 'Australia/Melbourne',+ 'Africa/Johannesburg',+ 'Africa/Lagos',+ 'Africa/Cairo',+ 'America/Argentina/Buenos_Aires',+ ]++ def __init_singleton__( self ):+ self._enum_name_to_choices = dict()+ self._enum_name_to_choices['Timezone'] = [ ( x, x ) for x in self.TIMEZONE_NAME_LIST ]+ self._enum_name_to_choices['Theme'] = Theme.choices()+ return++ @property+ def attribute_enums_map(self) -> List[ Tuple[ str, str ] ]:+ return self._enum_name_to_choicesdiff --git a/src/hi/apps/attribute/enums.py b/src/hi/apps/attribute/enums.pyindex 70d625e5..8159abb2 100644--- a/src/hi/apps/attribute/enums.py+++ b/src/hi/apps/attribute/enums.py@@ -16,7 +16,7 @@ class AttributeValueType(LabeledEnum):TEXT = ('Text' , '' )FILE = ('File' , '' ) # relative filename of MEDIA_ROOTSECRET = ('Secret' , '' )- TIMEZONE = ('Timezone' , '' , 'America/Chicago' )+ ENUM = ('Enum' , '' )@classmethoddef default(cls):@@ -35,13 +35,5 @@ class AttributeValueType(LabeledEnum):return bool( self == AttributeValueType.SECRET )@property- def is_timezone(self):- return bool( self == AttributeValueType.TIMEZONE )-- def __init__( self,- label : str,- description : str,- initial_value : str = '' ):- super().__init__( label, description )- self.initial_value = initial_value- return+ def is_enum(self):+ return bool( self == AttributeValueType.ENUM )diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.htmlindex abd282f2..e8ecbffb 100644--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html@@ -17,8 +17,8 @@{% if attribute_form.instance.value_type.is_file %}{% include "attribute/panes/attribute_form_file.html" %}- {% elif attribute_form.instance.value_type.is_timezone %}- {% include "attribute/panes/attribute_form_timezone.html" %}+ {% elif attribute_form.instance.value_type.is_enum %}+ {% include "attribute/panes/attribute_form_enum.html" %}{% else %}{% include "attribute/panes/attribute_form_text.html" %}{% endif %}diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_timezone.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.htmlsimilarity index 69%rename from src/hi/apps/attribute/templates/attribute/panes/attribute_form_timezone.htmlrename to src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.htmlindex 8a80d84d..42222ddf 100644--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_timezone.html+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.html@@ -1,3 +1,4 @@+{% load common_template_helpers %}<input type="hidden" id="{{ attribute_form.name.id_for_label }}"name="{{ attribute_form.name.html_name }}"value="{{ attribute_form.instance.name }}" />@@ -5,13 +6,15 @@<div class="input-group-prepend" ><span class="input-group-text" >{{ attribute_form.instance.name }}</span></div>+ {% with ATTRIBUTE_ENUMS|get_item:attribute_form.instance.name as choices_list %}<select name="{{ attribute_form.value.html_name }}" id="{{ attribute_form.value.id_for_label }}">- {% for tzname in TIMEZONE_NAME_LIST %}- <option value="{{ tzname }}" {% if attribute_form.value.value == tzname %}selected="true"{% endif %}>- {{ tzname }}+ {% for value, label in choices_list %}+ <option value="{{ value }}" {% if attribute_form.value.value == value %}selected="true"{% endif %}>+ {{ label }}</option>{% endfor %}</select>+ {% endwith %}</div>{% if attribute_form.show_as_editable and attribute_form.instance.is_editable and attribute_form.instance.attribute_type.can_delete %}diff --git a/src/hi/apps/common/templatetags/common_template_helpers.py b/src/hi/apps/common/templatetags/common_template_helpers.pyindex eb6ea8b4..258d96fd 100644--- a/src/hi/apps/common/templatetags/common_template_helpers.py+++ b/src/hi/apps/common/templatetags/common_template_helpers.py@@ -9,6 +9,11 @@ from django.urls import reverseregister = template.Library()+def get_item(dictionary, key):+ return dictionary.get(key)++@register.simple_tagdef pagination_url( page_number, existing_urlencoded_params = None ):diff --git a/src/hi/apps/config/admin.py b/src/hi/apps/config/admin.pyindex 8c38f3f3..f6886c6e 100644--- a/src/hi/apps/config/admin.py+++ b/src/hi/apps/config/admin.py@@ -1,3 +1,23 @@from django.contrib import admin-# Register your models here.+from . import models+++class SubsystemAttributeInLine(admin.TabularInline):+ model = models.SubsystemAttribute+ extra = 0+ show_change_link = True++[email protected](models.Subsystem)+class SubsystemAdmin(admin.ModelAdmin):+ show_full_result_count = False++ list_display = (+ 'name',+ 'subsystem_type_str',+ 'created_datetime',+ )++ inlines = [ SubsystemAttributeInLine, ]+diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.pyindex ef1e2528..7daaef16 100644--- a/src/hi/apps/config/enums.py+++ b/src/hi/apps/config/enums.py@@ -1,3 +1,4 @@+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum@@ -21,4 +22,52 @@ class ConfigPageType(LabeledEnum):def default(self):return ConfigPageType.SETTINGS+++class SubsystemType(LabeledEnum):++ LOCALE = ('Locale' , '' )+ DISPLAY = ('Display' , '' )+++class Theme(LabeledEnum):++ DEFAULT = ( 'Default', '' )++class SubsystemAttributeType(LabeledEnum):++ TIMEZONE = (+ 'Timezone',+ 'Timezone to use for display',+ SubsystemType.LOCALE,+ AttributeValueType.ENUM,+ True,+ True,+ 'America/Chicago',+ )+ THEME = (+ 'Theme',+ 'Overall look and feel of interfaces',+ SubsystemType.DISPLAY,+ AttributeValueType.ENUM,+ True,+ True,+ str( Theme.default() ),+ )++ def __init__( self,+ label : str,+ description : str,+ subsystem_type : SubsystemType,+ value_type : AttributeValueType,+ is_editable : bool,+ is_required : bool,+ initial_value : str ):+ super().__init__( label, description )+ self.subsystem_type = subsystem_type+ self.value_type = value_type+ self.is_editable = is_editable+ self.is_required = is_required+ self.initial_value = initial_value+ returndiff --git a/src/hi/apps/config/forms.py b/src/hi/apps/config/forms.pynew file mode 100644index 00000000..9c0bbfb9--- /dev/null+++ b/src/hi/apps/config/forms.py@@ -0,0 +1,21 @@+from django import forms++from hi.apps.attribute.forms import AttributeForm++from .models import Subsystem, SubsystemAttribute+++class SubsystemAttributeForm( AttributeForm ):+ class Meta( AttributeForm.Meta ):+ model = SubsystemAttribute+++SubsystemAttributeFormSet = forms.inlineformset_factory(+ Subsystem,+ SubsystemAttribute,+ form = SubsystemAttributeForm,+ extra = 0,+ max_num = 100,+ absolute_max = 100,+ can_delete = False,+)diff --git a/src/hi/apps/config/migrations/0001_initial.py b/src/hi/apps/config/migrations/0001_initial.pynew file mode 100644index 00000000..dd46ce92--- /dev/null+++ b/src/hi/apps/config/migrations/0001_initial.py@@ -0,0 +1,119 @@+# Generated by Django 4.2.15 on 2024-11-27 21:24++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ initial = True++ dependencies = []++ operations = [+ migrations.CreateModel(+ name="Subsystem",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "name",+ models.CharField(max_length=128, unique=True, verbose_name="Name"),+ ),+ (+ "subsystem_type_str",+ models.CharField(max_length=32, verbose_name="Subsystem Type"),+ ),+ (+ "created_datetime",+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),+ ),+ ],+ options={+ "verbose_name": "Integration",+ "verbose_name_plural": "Integrations",+ },+ ),+ migrations.CreateModel(+ name="SubsystemAttribute",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(max_length=64, verbose_name="Name")),+ (+ "value",+ models.TextField(blank=True, null=True, verbose_name="Value"),+ ),+ (+ "file_value",+ models.FileField(blank=True, null=True, upload_to="attributes/"),+ ),+ (+ "file_mime_type",+ models.CharField(+ blank=True, max_length=128, null=True, verbose_name="Mime Type"+ ),+ ),+ (+ "value_type_str",+ models.CharField(max_length=32, verbose_name="Value Type"),+ ),+ (+ "integration_key_str",+ models.CharField(+ blank=True,+ max_length=128,+ null=True,+ verbose_name="Integration Key",+ ),+ ),+ (+ "attribute_type_str",+ models.CharField(max_length=32, verbose_name="Attribute Type"),+ ),+ (+ "is_editable",+ models.BooleanField(default=True, verbose_name="Editable?"),+ ),+ (+ "is_required",+ models.BooleanField(default=False, verbose_name="Required?"),+ ),+ (+ "created_datetime",+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),+ ),+ (+ "updated_datetime",+ models.DateTimeField(auto_now=True, verbose_name="Updated"),+ ),+ (+ "subsystem",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributes",+ to="config.subsystem",+ verbose_name="Subsystem",+ ),+ ),+ ],+ options={+ "verbose_name": "Subsystem Attribute",+ "verbose_name_plural": "Subsystem Attributes",+ },+ ),+ ]diff --git a/src/hi/apps/config/migrations/0002_alter_subsystem_options.py b/src/hi/apps/config/migrations/0002_alter_subsystem_options.pynew file mode 100644index 00000000..c6300d3f--- /dev/null+++ b/src/hi/apps/config/migrations/0002_alter_subsystem_options.py@@ -0,0 +1,17 @@+# Generated by Django 4.2.15 on 2024-11-27 21:26++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("config", "0001_initial"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="subsystem",+ options={"verbose_name": "Subsystem", "verbose_name_plural": "Subsystems"},+ ),+ ]diff --git a/src/hi/apps/config/models.py b/src/hi/apps/config/models.pyindex 71a83623..083d0e53 100644--- a/src/hi/apps/config/models.py+++ b/src/hi/apps/config/models.py@@ -1,3 +1,59 @@from django.db import models-# Create your models here.+from hi.apps.attribute.models import AttributeModel++from .enums import SubsystemType+++class Subsystem( models.Model ):++ name = models.CharField(+ 'Name',+ max_length = 128,+ null = False, blank = False,+ unique = True,+ )+ subsystem_type_str = models.CharField(+ 'Subsystem Type',+ max_length = 32,+ null = False, blank = False,+ )+ created_datetime = models.DateTimeField(+ 'Created',+ auto_now_add = True,+ blank = True,+ )++ class Meta:+ verbose_name = 'Subsystem'+ verbose_name_plural = 'Subsystems'++ def __str__(self):+ return self.subsystem_type_str++ @property+ def subsystem_type(self) -> SubsystemType:+ return SubsystemType.from_name_safe( self.subsystem_type_str )++ @subsystem_type.setter+ def subsystem_type( self, subsystem_type : SubsystemType ):+ self.subsystem_type_str = str(subsystem_type)+ return+++class SubsystemAttribute( AttributeModel ):++ subsystem = models.ForeignKey(+ Subsystem,+ related_name = 'attributes',+ verbose_name = 'Subsystem',+ on_delete = models.CASCADE,+ )++ class Meta:+ verbose_name = 'Subsystem Attribute'+ verbose_name_plural = 'Subsystem Attributes'++ def get_upload_to(self):+ return 'subsystem/attributes/'+diff --git a/src/hi/apps/config/system_settings.py b/src/hi/apps/config/system_settings.pynew file mode 100644index 00000000..30250588--- /dev/null+++ b/src/hi/apps/config/system_settings.py@@ -0,0 +1,52 @@+from typing import List++from django.db import transaction++from hi.apps.attribute.enums import AttributeType+from hi.apps.common.singleton import Singleton++from .enums import SubsystemType, SubsystemAttributeType+from .models import Subsystem, SubsystemAttribute+++class SystemSettings( Singleton ):++ def __init_singleton__( self ):+ return++ def get_subsystems(self) -> List[ Subsystem ]:++ existing_subsystem_map = { x.subsystem_type: x for x in Subsystem.objects.all() }++ subsystem_list = list()+ with transaction.atomic():+ for subsystem_type in SubsystemType:+ if subsystem_type in existing_subsystem_map:+ subsystem = existing_subsystem_map[subsystem_type]+ else:+ subsystem = self._create_subsystem( subsystem_type )+ subsystem_list.append( subsystem )+ continue++ return subsystem_list++ def _create_subsystem( self, subsystem_type : SubsystemType ):+ subsystem = Subsystem.objects.create(+ name = subsystem_type.label,+ subsystem_type_str = str(subsystem_type),+ )+ for subsystem_attribute_type in SubsystemAttributeType:+ if subsystem_type != subsystem_attribute_type.subsystem_type:+ continue+ SubsystemAttribute.objects.create(+ subsystem = subsystem,+ name = subsystem_attribute_type.label,+ value = subsystem_attribute_type.initial_value,+ value_type_str = str(subsystem_attribute_type.value_type),+ attribute_type_str = AttributeType.PREDEFINED,+ is_editable = subsystem_attribute_type.is_editable,+ is_required = subsystem_attribute_type.is_required,+ )+ continue+ return subsystem+diff --git a/src/hi/apps/config/templates/config/panes/settings.html b/src/hi/apps/config/templates/config/panes/settings.htmlindex 308a9e64..5ee4c957 100644--- a/src/hi/apps/config/templates/config/panes/settings.html+++ b/src/hi/apps/config/templates/config/panes/settings.html@@ -1,9 +1,6 @@{% extends "config/pages/config_base.html" %}{% block config_content %}-<div class="h3">Settings</div>--<div>- TBD-</div>+<div class="h3">System Settings</div>+{% include "config/panes/settings_form.html" %}{% endblock %}diff --git a/src/hi/apps/config/templates/config/panes/settings_form.html b/src/hi/apps/config/templates/config/panes/settings_form.htmlnew file mode 100644index 00000000..933ef8ab--- /dev/null+++ b/src/hi/apps/config/templates/config/panes/settings_form.html@@ -0,0 +1,18 @@+<div id="hi-config-settings-form">+ <div>+ <form action="{% url 'config_settings' %}" method="post"+ class="form" data-async="#hi-config-settings-form" data-mode="replace">+ {% csrf_token %}++ {% for subsystem_attribute_formset in subsystem_attribute_formset_list %}+ <h5>{{ subsystem_attribute_formset.instance.name }}</h5>+ {% include "attribute/panes/attribute_form.html" with attribute_formset=subsystem_attribute_formset %}+ {% endfor %}++ <button id="hi-config-setting-button" type="submit" class="btn btn-info"+ name="action" value="update">+ UPDATE+ </button>+ </form>+ </div>+</div>diff --git a/src/hi/apps/config/views.py b/src/hi/apps/config/views.pyindex cd934627..b172ad73 100644--- a/src/hi/apps/config/views.py+++ b/src/hi/apps/config/views.py@@ -1,9 +1,15 @@+from django.db import transaction+from django.shortcuts import render+from django.views.generic import View+import hi.apps.common.antinode as antinodefrom hi.enums import ViewMode, ViewTypefrom hi.hi_grid_view import HiGridViewfrom .enums import ConfigPageType+from .forms import SubsystemAttributeFormSet+from .system_settings import SystemSettingsclass ConfigPageView( HiGridView ):@@ -69,5 +75,50 @@ class ConfigSettingsView( ConfigPageView ):def get_template_context( self, request, *args, **kwargs ):+ subsystem_list = SystemSettings().get_subsystems()++ subsystem_attribute_formset_list = list()+ for subsystem in subsystem_list:+ subsystem_attribute_formset = SubsystemAttributeFormSet(+ instance = subsystem,+ prefix = f'subsystem-{subsystem.id}',+ form_kwargs = {+ 'show_as_editable': True,+ },+ )+ subsystem_attribute_formset_list.append( subsystem_attribute_formset )+ continue+return {+ 'subsystem_attribute_formset_list': subsystem_attribute_formset_list,+ }++ def post( self, request, *args, **kwargs ):++ subsystem_list = SystemSettings().get_subsystems()++ all_valid = True+ subsystem_attribute_formset_list = list()+ for subsystem in subsystem_list:+ subsystem_attribute_formset = SubsystemAttributeFormSet(+ request.POST,+ request.FILES,+ instance = subsystem,+ prefix = f'subsystem-{subsystem.id}',+ )+ if not subsystem_attribute_formset.is_valid():+ all_valid = False+ subsystem_attribute_formset_list.append( subsystem_attribute_formset )+ continue++ if all_valid:+ with transaction.atomic():+ for subsystem_attribute_formset in subsystem_attribute_formset_list:+ subsystem_attribute_formset.save()+ continue++ context = {+ 'subsystem_attribute_formset_list': subsystem_attribute_formset_list,}+ return render( request, 'config/panes/settings_form.html', context )+diff --git a/src/hi/context_processors.py b/src/hi/context_processors.pyindex cd48b3ef..df17526e 100644--- a/src/hi/context_processors.py+++ b/src/hi/context_processors.py@@ -1,35 +1,10 @@+from hi.apps.attribute.attribute_enums import AttributeEnums+from .constants import DIVIDdef constants_context(request):return {'DIVID': DIVID,- 'TIMEZONE_NAME_LIST': [- 'UTC',- 'America/New_York',- 'America/Chicago',- 'America/Denver',- 'America/Los_Angeles',- 'America/Toronto',- 'America/Mexico_City',- 'America/Sao_Paulo',- 'Europe/London',- 'Europe/Berlin',- 'Europe/Paris',- 'Europe/Moscow',- 'Asia/Dubai',- 'Asia/Tokyo',- 'Asia/Seoul',- 'Asia/Shanghai',- 'Asia/Hong_Kong',- 'Asia/Singapore',- 'Asia/Kolkata',- 'Asia/Jakarta',- 'Australia/Sydney',- 'Australia/Melbourne',- 'Africa/Johannesburg',- 'Africa/Lagos',- 'Africa/Cairo',- 'America/Argentina/Buenos_Aires',- ],+ 'ATTRIBUTE_ENUMS': AttributeEnums().attribute_enums_map,}diff --git a/src/hi/integrations/core/enums.py b/src/hi/integrations/core/enums.pyindex 66351158..f58eb204 100644--- a/src/hi/integrations/core/enums.py+++ b/src/hi/integrations/core/enums.py@@ -6,14 +6,16 @@ class IntegrationAttributeType(LabeledEnum):""" Abstract base class for integrations ot define the required attributes they need. """def __init__( self,- label : str,- description : str,- value_type : AttributeValueType,- is_editable : bool,- is_required : bool ):+ label : str,+ description : str,+ value_type : AttributeValueType,+ is_editable : bool,+ is_required : bool,+ initial_value : str = '' ):super().__init__( label, description )self.value_type = value_typeself.is_editable = is_editableself.is_required = is_required+ self.initial_value = initial_valuereturndiff --git a/src/hi/integrations/core/helpers.py b/src/hi/integrations/core/helpers.pyindex 9c4bd5c8..79a593fb 100644--- a/src/hi/integrations/core/helpers.py+++ b/src/hi/integrations/core/helpers.py@@ -80,7 +80,7 @@ class IntegrationHelperMixin:IntegrationAttribute.objects.create(integration = integration,name = attribute_type.label,- value = attribute_type.value_type.initial_value,+ value = attribute_type.initial_value,value_type_str = str(attribute_type.value_type),integration_key_str = str(integration_key),attribute_type_str = AttributeType.PREDEFINED,diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.pyindex 4852a251..7f13042b 100644--- a/src/hi/integrations/zoneminder/enums.py+++ b/src/hi/integrations/zoneminder/enums.py@@ -37,9 +37,10 @@ class ZmAttributeType( IntegrationAttributeType ):TIMEZONE = ('Timezone','',- AttributeValueType.TIMEZONE,+ AttributeValueType.ENUM,True,True,+ 'America/Chicago',)diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex d5697d87..99922bfa 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -111,7 +111,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):for zm_event in closed_zm_event_list:if zm_event.event_id not in self._start_processed_event_ids:active_sensor_response = self._create_movement_active_sensor_response( zm_event )- sensor_response_map[active_sensor_response] = active_sensor_response+ sensor_response_map[active_sensor_response.integration_key] = active_sensor_responseidle_sensor_response = self._create_movement_idle_sensor_response( zm_event )sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_response