Home Information - Your home, your data, organized.
Python
Aded beginnings of attribute editing: form and template.
Anthony Cassandra48b119e1ffc9
diff --git a/src/hi/apps/attribute/enums.py b/src/hi/apps/attribute/enums.pyindex bb5beaa9..cacbd01c 100644--- a/src/hi/apps/attribute/enums.py+++ b/src/hi/apps/attribute/enums.py@@ -9,12 +9,20 @@ class AttributeType(LabeledEnum):class AttributeValueType(LabeledEnum):- STRING = ('String', '' )- INTEGER = ('Integer', '' )- FLOAT = ('Float', '' )- TEXT = ('Text', '' ) # relative filename in MEDIA_ROOT- PDF = ('PDF', '' ) # relative filename in MEDIA_ROOT- IMAGE = ('Image', '' ) # relative filename in MEDIA_ROOT- VIDEO = ('Video', '' ) # relative filename in MEDIA_ROOT- AUDIO = ('Audio', '' ) # relative filename in MEDIA_ROOT- LINK = ('Link', '' )+ STRING = ('String', '' )+ INTEGER = ('Integer', '' )+ FLOAT = ('Float', '' )+ TEXT = ('Text', '' ) # relative filename in MEDIA_ROOT+ PDF = ('PDF', '' ) # relative filename in MEDIA_ROOT+ IMAGE = ('Image', '' ) # relative filename in MEDIA_ROOT+ VIDEO = ('Video', '' ) # relative filename in MEDIA_ROOT+ AUDIO = ('Audio', '' ) # relative filename in MEDIA_ROOT+ LINK = ('Link', '' )+ PASSWORD = ('Password', '' )+ EMAIL = ('Email', '' )+ PHONE = ('Phone', '' )+ BOOLEAN = ('Boolean', '' )+ DATETIME = ('DateTime', '' )+ DATE = ('Date', '' )+ TIME = ('Time', '' )+ JSON = ('JSON', '' )diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.pynew file mode 100644index 00000000..5dcc0a45--- /dev/null+++ b/src/hi/apps/attribute/forms.py@@ -0,0 +1,178 @@+import json++from django.core.validators import validate_email, URLValidator+from django.core.exceptions import ValidationError+from django.core.files.storage import default_storage+from django import forms+from django.utils.dateparse import parse_date, parse_datetime, parse_time++from .enums import AttributeValueType+++class AttributeForm(forms.ModelForm):++ class Meta:+ abstract = True+ fields = (+ 'name',+ 'value',+ )+ widgets = {+ 'name': forms.TextInput(+ attrs = {+ 'class': 'form-control',+ }+ ),+ 'value': forms.TextInput(+ attrs = {+ 'class': 'form-control',+ }+ ),+ }++ def __init__(self, *args, **kwargs):+ self._is_editable = kwargs.pop( 'is_editable', True )+ super().__init__(*args, **kwargs)++ # Access the instance's value_type field+ instance = kwargs.get('instance')++ # Always set the name field as a TextInput widget+ self.fields['name'].widget = forms.TextInput(attrs={'class': 'form-control'})++ # Customize the value field based on the value_type in the instance+ if instance and instance.value_type:+ value_type = instance.value_type++ if value_type == AttributeValueType.INTEGER:+ self.fields['value'].widget = forms.NumberInput(+ attrs={'class': 'form-control'},+ )+ elif value_type == AttributeValueType.FLOAT:+ self.fields['value'].widget = forms.NumberInput(+ attrs={'step': 'any', 'class': 'form-control'},+ )+ elif value_type == AttributeValueType.BOOLEAN:+ self.fields['value'].widget = forms.CheckboxInput()+ elif value_type == AttributeValueType.DATE:+ self.fields['value'].widget = forms.DateInput(+ attrs={'type': 'date', 'class': 'form-control'},+ )+ elif value_type == AttributeValueType.DATETIME:+ self.fields['value'].widget = forms.DateTimeInput(+ attrs={'type': 'datetime-local', 'class': 'form-control'},+ )+ elif value_type == AttributeValueType.TIME:+ self.fields['value'].widget = forms.TimeInput(+ attrs={'type': 'time', 'class': 'form-control'},+ )+ elif value_type == AttributeValueType.TEXT:+ self.fields['value'].widget = forms.Textarea(+ attrs={'class': 'form-control'},+ )+ elif value_type == AttributeValueType.EMAIL:+ self.fields['value'].widget = forms.EmailInput(+ attrs={'class': 'form-control'},+ )+ elif value_type == AttributeValueType.LINK:+ self.fields['value'].widget = forms.URLInput(+ attrs={'class': 'form-control'},+ )+ elif value_type == AttributeValueType.PASSWORD:+ self.fields['value'].widget = forms.PasswordInput(+ attrs={'class': 'form-control'},+ )+ elif value_type in { AttributeValueType.IMAGE,+ AttributeValueType.PDF,+ AttributeValueType.VIDEO, AttributeValueType.AUDIO }:+ # File input for media types+ self.fields['value'].widget = forms.FileInput(+ attrs={'class': 'form-control'},+ )+ else:+ # Fallback to a simple TextInput+ self.fields['value'].widget = forms.TextInput(+ attrs={'class': 'form-control'},+ )+ else:+ # If no instance or no value_type, use default TextInput widget+ self.fields['value'].widget = forms.TextInput(+ attrs={'class': 'form-control'},+ )++ def clean(self):+ cleaned_data = super().clean()+ value = cleaned_data.get('value')+ value_type = self.instance.value_type++ # Validate based on value_type+ if value_type == AttributeValueType.INTEGER:+ try:+ int(value)+ except ValueError:+ self.add_error('value', 'Value must be an integer.')++ elif value_type == AttributeValueType.FLOAT:+ try:+ float(value)+ except ValueError:+ self.add_error('value', 'Value must be numeric.')++ elif value_type in { AttributeValueType.STRING,+ AttributeValueType.TEXT }:+ if not isinstance(value, str):+ self.add_error('value', 'Value must be a string.')++ elif value_type == AttributeValueType.EMAIL:+ try:+ validate_email(value)+ except ValidationError:+ self.add_error('value', 'Not a valid email address.')++ elif value_type == AttributeValueType.LINK:+ validate_url = URLValidator()+ try:+ validate_url(value)+ except ValidationError:+ self.add_error('value', 'Not a valid URL.')++ elif value_type == AttributeValueType.PHONE:+ # Simple phone number validation (customize if needed)+ if not value.isdigit() or len(value) < 10:+ self.add_error('value', 'Not a valid phone number.')++ elif value_type == AttributeValueType.BOOLEAN:+ if value not in [True, False, 'True', 'False', 1, 0]:+ self.add_error('value', 'Value must be a boolean.')++ elif value_type == AttributeValueType.DATETIME:+ if not parse_datetime(value):+ self.add_error('value', 'Value must be a valid datetime.')++ elif value_type == AttributeValueType.DATE:+ if not parse_date(value):+ self.add_error('value', 'Value must be a valid date.')++ elif value_type == AttributeValueType.TIME:+ if not parse_time(value):+ self.add_error('value', 'Value must be a valid time.')++ elif value_type == AttributeValueType.JSON:+ try:+ json.loads(value)+ except ValueError:+ self.add_error('value', 'Value must be a valid JSON.')++ elif value_type in { AttributeValueType.PDF,+ AttributeValueType.IMAGE,+ AttributeValueType.VIDEO,+ AttributeValueType.AUDIO }:+ if not default_storage.exists( value ):+ self.add_error('value', f'{value_type} file does not exist.')++ return cleaned_data++ @property+ def is_editable(self):+ return self._is_editable+diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pyindex 3ac6c08c..24eddf29 100644--- a/src/hi/apps/attribute/models.py+++ b/src/hi/apps/attribute/models.py@@ -11,11 +11,6 @@ class AttributeModel(models.Model):class Meta:abstract = True- attribute_value_type_str = models.CharField(- 'Attribute Value Type',- max_length = 32,- null = False, blank = False,- )name = models.CharField('Name',max_length = 64,@@ -23,6 +18,11 @@ class AttributeModel(models.Model):value = models.TextField('Value',)+ value_type_str = models.CharField(+ 'Value Type',+ max_length = 32,+ null = False, blank = False,+ )attribute_type_str = models.CharField('Attribute Type',max_length = 32,@@ -47,22 +47,22 @@ class AttributeModel(models.Model):)def __str__(self):- return f'Attr[{self}] {self.name}={self.value} [{self.attribute_value_type_str}] [{self.attribute_type_str}]'+ return f'Attr: {self.name}={self.value} [{self.value_type_str}] [{self.attribute_type_str}]'def __repr__(self):return self.__str__()@property- def attribute_value_type(self):- return AttributeValueType.from_name_safe( self.attribute_value_type_str )+ def value_type(self) -> AttributeValueType:+ return AttributeValueType.from_name_safe( self.value_type_str )- @attribute_value_type.setter- def attribute_value_type( self, attribute_value_type : AttributeValueType ):- self.attribute_value_type_str = str(attribute_value_type)+ @value_type.setter+ def value_type( self, value_type : AttributeValueType ):+ self.value_type_str = str(value_type)return@property- def attribute_type(self):+ def attribute_type(self) -> AttributeType:return AttributeType.from_name_safe( self.attribute_type_str )@attribute_type.setterdiff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.htmlnew file mode 100644index 00000000..2fec8dfe--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html@@ -0,0 +1,27 @@+<div class="">+ {{ attribute_formset.management_form }}++ {% for attribute_form in attribute_formset %}+ {{ attribute_form.id }}++ {% if attribute_form.non_field_errors %}+ <div class="non-field-errors">+ {% for err in attribute_form.non_field_errors %}+ <p class="form-error">{{ err }}</p>+ {% endfor %}+ </div>+ {% endif %}++ <div class="row p-3">+ <div class="col-8">+ <div class="input-group" >+ <div class="input-group-prepend" >+ <span class="input-group-text" >{{ attribute_form.instance.name }}</span>+ </div>+ {{ attribute_form.value }}+ </div>+ <div class="form-error text-danger" >{{ attribute_form.value.errors }}</div>+ </div>+ </div>+ {% endfor %}+</div>diff --git a/src/hi/apps/entity/migrations/0002_rename_attribute_value_type_str_entityattribute_value_type_str.py b/src/hi/apps/entity/migrations/0002_rename_attribute_value_type_str_entityattribute_value_type_str.pynew file mode 100644index 00000000..fff0809d--- /dev/null+++ b/src/hi/apps/entity/migrations/0002_rename_attribute_value_type_str_entityattribute_value_type_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0001_initial"),+ ]++ operations = [+ migrations.RenameField(+ model_name="entityattribute",+ old_name="attribute_value_type_str",+ new_name="value_type_str",+ ),+ ]diff --git a/src/hi/apps/entity/migrations/0003_alter_entityattribute_value_type_str.py b/src/hi/apps/entity/migrations/0003_alter_entityattribute_value_type_str.pynew file mode 100644index 00000000..7b4c8cb0--- /dev/null+++ b/src/hi/apps/entity/migrations/0003_alter_entityattribute_value_type_str.py@@ -0,0 +1,21 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ (+ "entity",+ "0002_rename_attribute_value_type_str_entityattribute_value_type_str",+ ),+ ]++ operations = [+ migrations.AlterField(+ model_name="entityattribute",+ name="value_type_str",+ field=models.CharField(max_length=32, verbose_name="Value Type"),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0002_rename_attribute_value_type_str_locationattribute_value_type_str.py b/src/hi/apps/location/migrations/0002_rename_attribute_value_type_str_locationattribute_value_type_str.pynew file mode 100644index 00000000..8796870e--- /dev/null+++ b/src/hi/apps/location/migrations/0002_rename_attribute_value_type_str_locationattribute_value_type_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0001_initial"),+ ]++ operations = [+ migrations.RenameField(+ model_name="locationattribute",+ old_name="attribute_value_type_str",+ new_name="value_type_str",+ ),+ ]diff --git a/src/hi/apps/location/migrations/0003_alter_locationattribute_value_type_str.py b/src/hi/apps/location/migrations/0003_alter_locationattribute_value_type_str.pynew file mode 100644index 00000000..70c2567e--- /dev/null+++ b/src/hi/apps/location/migrations/0003_alter_locationattribute_value_type_str.py@@ -0,0 +1,21 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ (+ "location",+ "0002_rename_attribute_value_type_str_locationattribute_value_type_str",+ ),+ ]++ operations = [+ migrations.AlterField(+ model_name="locationattribute",+ name="value_type_str",+ field=models.CharField(max_length=32, verbose_name="Value Type"),+ ),+ ]diff --git a/src/hi/integrations/core/forms.py b/src/hi/integrations/core/forms.pynew file mode 100644index 00000000..cc3256af--- /dev/null+++ b/src/hi/integrations/core/forms.py@@ -0,0 +1,26 @@+from django import forms++from hi.apps.attribute.forms import AttributeForm++from .models import Integration, IntegrationAttribute+++class IntegrationAttributeForm( AttributeForm ):++ class Meta:+ model = IntegrationAttribute+ fields = (+ 'name',+ 'value',+ )+++IntegrationAttributeFormSet = forms.inlineformset_factory(+ Integration,+ IntegrationAttribute,+ form = IntegrationAttributeForm,+ extra = 0,+ max_num = 100,+ absolute_max = 100,+ can_delete = False,+)diff --git a/src/hi/integrations/core/integration_gateway.py b/src/hi/integrations/core/integration_gateway.pyindex 511c7027..0a382be4 100644--- a/src/hi/integrations/core/integration_gateway.py+++ b/src/hi/integrations/core/integration_gateway.py@@ -9,13 +9,16 @@ class IntegrationGateway:Each integration needs to provide an Integration Manager that implements these methods."""- def enable( self, request : HttpRequest ) -> HttpResponse:+ def enable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:+ # Should return a modal via antinode.modal_from_template() (called async)raise NotImplementedError('Subclasses must override this method')- def disable( self, request : HttpRequest ) -> HttpResponse:+ def disable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:+ # Should return a modal via antinode.modal_from_template() (called async)raise NotImplementedError('Subclasses must override this method')def manage( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:+ # Should return HTML fragment for the management pane of the integration.raise NotImplementedError('Subclasses must override this method')def get_integration( self, integration_type : IntegrationType ) -> Integration:diff --git a/src/hi/integrations/core/migrations/0003_rename_attribute_value_type_str_integrationattribute_value_type_str.py b/src/hi/integrations/core/migrations/0003_rename_attribute_value_type_str_integrationattribute_value_type_str.pynew file mode 100644index 00000000..1346facf--- /dev/null+++ b/src/hi/integrations/core/migrations/0003_rename_attribute_value_type_str_integrationattribute_value_type_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("core", "0002_integrationattribute_delete_integrationproperty"),+ ]++ operations = [+ migrations.RenameField(+ model_name="integrationattribute",+ old_name="attribute_value_type_str",+ new_name="value_type_str",+ ),+ ]diff --git a/src/hi/integrations/core/migrations/0004_alter_integrationattribute_value_type_str.py b/src/hi/integrations/core/migrations/0004_alter_integrationattribute_value_type_str.pynew file mode 100644index 00000000..87ca0e1e--- /dev/null+++ b/src/hi/integrations/core/migrations/0004_alter_integrationattribute_value_type_str.py@@ -0,0 +1,21 @@+# Generated by Django 4.2.15 on 2024-10-12 20:29++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ (+ "core",+ "0003_rename_attribute_value_type_str_integrationattribute_value_type_str",+ ),+ ]++ operations = [+ migrations.AlterField(+ model_name="integrationattribute",+ name="value_type_str",+ field=models.CharField(max_length=32, verbose_name="Value Type"),+ ),+ ]diff --git a/src/hi/integrations/core/templates/core/panes/config_tab.html b/src/hi/integrations/core/templates/core/panes/config_tab.htmlindex abf29763..72cf2add 100644--- a/src/hi/integrations/core/templates/core/panes/config_tab.html+++ b/src/hi/integrations/core/templates/core/panes/config_tab.html@@ -25,28 +25,18 @@</div><div class="col-2">{% if integration.is_enabled %}- <form action="{% url 'integration_config' name=integration.integration_type.name action='disable' %}"- method="POST" role="form" data-async="#{{ DIVID.INTEGRATION_TAB }}">- {% csrf_token %}- <button type="submit" class="btn btn-danger btn-control" role="button"">DISABLE</button>- </form>+ <a href="{% url 'integration_action' name=integration.integration_type.name action='disable' %}"+ role="button" class="btn btn-danger btn-control" data-async="modal">DISABLE</a>{% else %}- <form action="{% url 'integration_config' name=integration.integration_type.name action='enable' %}"- method="POST" role="form" data-async="#{{ DIVID.INTEGRATION_TAB }}">- {% csrf_token %}- <button type="submit" class="btn btn-success btn-control" role="button" >ENABLE</button>- </form>+ <a href="{% url 'integration_action' name=integration.integration_type.name action='enable' %}"+ class="btn btn-success btn-control" role="button" data-async="modal">ENABLE</a>{% endif %}</div><div class="col-2">{% if integration.is_enabled %}- <a href="{% url 'integration_manage' name=integration.integration_type.name %}"- class="btn btn-info btn-control" role="button"- data-async="#{{ DIVID.INTEGRATION_TAB }}" >- MANAGE- </a>- </form>+ <a href="{% url 'integration_action' name=integration.integration_type.name action='manage' %}"+ class="btn btn-info btn-control" role="button" data-async="modal">MANAGE</a>{% else %} {% endif %}diff --git a/src/hi/integrations/core/urls.py b/src/hi/integrations/core/urls.pyindex 13bd8f0a..afdd0e18 100644--- a/src/hi/integrations/core/urls.py+++ b/src/hi/integrations/core/urls.py@@ -1,16 +1,16 @@-from django.urls import re_path+from django.urls import include, re_pathfrom . import viewsurlpatterns = [- re_path( r'^config/(?P<name>\w+)/(?P<action>\w+)$',- views.IntegrationConfigTabView.as_view(),- name='integration_config' ),+ re_path( r'^action/(?P<name>[\w\-]+)/(?P<action>[\w\-]+)$',+ views.IntegrationActionView.as_view(),+ name='integration_action' ),- re_path( r'^manage/(?P<name>\w+)$',- views.IntegrationManageView.as_view(),- name='integration_manage' ),+ re_path( r'^zm/', include('hi.integrations.zoneminder.urls' )),++]diff --git a/src/hi/integrations/core/views.py b/src/hi/integrations/core/views.pyindex eecaf272..9a96b8f1 100644--- a/src/hi/integrations/core/views.py+++ b/src/hi/integrations/core/views.py@@ -3,6 +3,8 @@ import loggingfrom django.shortcuts import renderfrom django.views.generic import View+from hi.views import bad_request_response+from .enums import IntegrationTypefrom .integration_factory import IntegrationFactory@@ -17,13 +19,9 @@ class IntegrationViewMixin:}-class IntegrationConfigTabView( View, IntegrationViewMixin ):+class IntegrationActionView( View, IntegrationViewMixin ):def get(self, request, *args, **kwargs):- context = self.get_integration_config_tab_context()- return render( request, 'core/panes/config_tab.html', context )-- def post(self, request, *args, **kwargs):error_message = Nonetry:@@ -35,43 +33,14 @@ class IntegrationConfigTabView( View, IntegrationViewMixin ):)if action == 'enable':- return integration_gateway.enable( request = request )+ return integration_gateway.enable( request = request, *args, **kwargs )elif action == 'disable':- return integration_gateway.disable( request = request )+ return integration_gateway.disable( request = request, *args, **kwargs )+ elif action == 'manage':+ return integration_gateway.manage( request = request, *args, **kwargs )- error_message = f'Unknown integration config action "{action}".'+ error_message = f'Unknown integration action "{action}".'except Exception as e:error_message = str(e)-- context = {- 'error_message': error_message,- }- context.update( self.get_integration_config_tab_context() )- return render( request, 'core/panes/config_tab.html', context )---class IntegrationManageView( View, IntegrationViewMixin ):- def get(self, request, *args, **kwargs):-- error_message = None- try:- integration_type = IntegrationType.from_name( kwargs.get('name') )- integration_gateway = IntegrationFactory().get_integration_gateway(- integration_type = integration_type,- )- return integration_gateway.manage( request = request, *args, **kwargs )- except Exception as e:- logger.exception( e )- error_message = str(e)-- context = {- 'error_message': error_message,- }- context.update( self.get_integration_config_tab_context() )- return render( request, 'core/panes/config_tab.html', context )-- def post(self, request, *args, **kwargs):- return self.get( request, *args, **kwargs)--+ return bad_request_response( request, message = error_message )diff --git a/src/hi/integrations/hass/enums.py b/src/hi/integrations/hass/enums.pyindex 5027ac9c..cd92659c 100644--- a/src/hi/integrations/hass/enums.py+++ b/src/hi/integrations/hass/enums.py@@ -6,13 +6,13 @@ from hi.apps.attribute.enums import AttributeValueTypeclass HassAttributeName(LabeledEnum):def __init__( self,- label : str,- description : str,- attribute_value_type : AttributeValueType,- is_editable : bool,- is_required : bool ):+ label : str,+ description : str,+ value_type : AttributeValueType,+ is_editable : bool,+ is_required : bool ):super().__init__( label, description )- self.attribute_value_type = attribute_value_type,+ self.value_type = value_type,self.is_editable = is_editableself.is_required = is_requiredreturndiff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.pyindex 992f181c..90fab03f 100644--- a/src/hi/integrations/hass/hass_converter.py+++ b/src/hi/integrations/hass/hass_converter.py@@ -241,7 +241,7 @@ class HassConverter:entity = entity,name = AttributeName.INSTEON_ADDRESS,value = insteon_address,- attribute_value_type_str = str( AttributeValueType.STRING ),+ value_type_str = str( AttributeValueType.STRING ),attribute_type_str = str( AttributeType.PREDEFINED ),is_editable = False,is_required = False,diff --git a/src/hi/integrations/hass/hass_gateway.py b/src/hi/integrations/hass/hass_gateway.pyindex 1b2f2429..aa66c85d 100644--- a/src/hi/integrations/hass/hass_gateway.py+++ b/src/hi/integrations/hass/hass_gateway.py@@ -11,10 +11,10 @@ logger = logging.getLogger(__name__)class HassGateway( IntegrationGateway ):- def enable( self, request : HttpRequest ) -> HttpResponse:+ def enable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:return views.HassEnableView().post( request )- def disable( self, request : HttpRequest ) -> HttpResponse:+ def disable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:return views.HassDisableView().post( request )def manage( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.pyindex a95e0eb2..d85799d8 100644--- a/src/hi/integrations/zoneminder/enums.py+++ b/src/hi/integrations/zoneminder/enums.py@@ -6,13 +6,13 @@ from hi.apps.attribute.enums import AttributeValueTypeclass ZmAttributeName(LabeledEnum):def __init__( self,- label : str,- description : str,- attribute_value_type : AttributeValueType,- is_editable : bool,- is_required : bool ):+ label : str,+ description : str,+ value_type : AttributeValueType,+ is_editable : bool,+ is_required : bool ):super().__init__( label, description )- self.attribute_value_type = attribute_value_type,+ self.value_type = value_typeself.is_editable = is_editableself.is_required = is_requiredreturn@@ -20,14 +20,14 @@ class ZmAttributeName(LabeledEnum):API_URL = ('API URL','e.g., https://myserver:8443/zm/api',- AttributeValueType.STRING,+ AttributeValueType.LINK,True,True,)PORTAL_URL = ('Portal URL','e.g., https://myserver:8443/zm',- AttributeValueType.STRING,+ AttributeValueType.LINK,True,True,)@@ -41,7 +41,7 @@ class ZmAttributeName(LabeledEnum):API_PASSWORD = ('Password','',- AttributeValueType.STRING,+ AttributeValueType.PASSWORD,True,True,)diff --git a/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_enable.html b/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_enable.htmlnew file mode 100644index 00000000..e49a9d23--- /dev/null+++ b/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_enable.html@@ -0,0 +1,30 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'zm_enable' %}" method="post" enctype="multipart/form-data"+ class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+ ZoneMInder+{% endblock %}++{% block body %}+ <h4>Enable ZoneMinder Integration</h4>++ <div>+ {% include "attribute/panes/attribute_form.html" with attribute_formset=integration_attribute_formset %}+ </div>+ {% endblock %}++ {% block action_right %}+ <button id="hi-zm-enable" type="submit" class="btn btn-lg btn-success"+ name="action" value="enable">+ ENABLE+ </button>+ {% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/integrations/zoneminder/templates/zoneminder/panes/activate.html b/src/hi/integrations/zoneminder/templates/zoneminder/panes/activate.htmldeleted file mode 100644index 371cb61f..00000000--- a/src/hi/integrations/zoneminder/templates/zoneminder/panes/activate.html+++ /dev/null@@ -1,3 +0,0 @@-<h3>ZM Activate</h3>--TBDdiff --git a/src/hi/integrations/zoneminder/urls.py b/src/hi/integrations/zoneminder/urls.pynew file mode 100644index 00000000..05edee39--- /dev/null+++ b/src/hi/integrations/zoneminder/urls.py@@ -0,0 +1,25 @@++from django.urls import re_path++from . import views+++urlpatterns = [++ re_path( r'^enable$',+ views.ZmEnableView.as_view(),+ name='zm_enable' ),++ re_path( r'^disable$',+ views.ZmDisableView.as_view(),+ name='zm_disable' ),++ re_path( r'^manage$',+ views.ZmManageView.as_view(),+ name='zm_manage' ),++ re_path( r'^sync$',+ views.ZmSyncView.as_view(),+ name='zm_sync' ),++]diff --git a/src/hi/integrations/zoneminder/views.py b/src/hi/integrations/zoneminder/views.pyindex c875a4ee..bd990846 100644--- a/src/hi/integrations/zoneminder/views.py+++ b/src/hi/integrations/zoneminder/views.py@@ -1,24 +1,110 @@+from django.db import transaction+from django.http import HttpRequestfrom django.shortcuts import renderfrom django.views.generic import View+import hi.apps.common.antinode as antinode+from hi.apps.attribute.enums import AttributeType+from hi.integrations.core.enums import IntegrationType+from hi.integrations.core.forms import IntegrationAttributeFormSet+from hi.integrations.core.models import Integration, IntegrationAttribute++from hi.views import bad_request_response+from .enums import ZmAttributeNamefrom .zm_manager import ZoneMinderManagerclass ZmEnableView( View ):+ def get(self, request, *args, **kwargs):++ integration = self.get_or_create_integration()+ if integration.is_enabled:+ return bad_request_response( request, message = 'ZoneMinder is already enabled' )++ integration_attribute_formset = IntegrationAttributeFormSet(+ instance = integration,+ form_kwargs = { 'is_editable': True },+ )+ return self.get_modal_response(+ request = request,+ integration_attribute_formset = integration_attribute_formset,+ )+def post(self, request, *args, **kwargs):+ integration = self.get_or_create_integration()++ integration_attribute_formset = IntegrationAttributeFormSet(+ request.POST,+ instance = integration,+ )+ if not integration_attribute_formset.is_valid():+ return self.get_modal_response(+ request = request,+ integration_attribute_formset = integration_attribute_formset,+ status = 400,+ )# TODO:# Check if have all needed properties# If not, render form for entering with button to activate+++++ raise NotImplementedError('FORCED')+++ integration_attribute_formset.save()+context = {}return render( request, 'zoneminder/panes/activate.html', context )+ def get_or_create_integration( self ):+ try:+ return Integration.objects.get(+ integration_type_str = IntegrationType.ZONEMINDER,+ )+ except Integration.DoesNotExist:+ pass++ with transaction.atomic():+ integration = Integration.objects.create(+ integration_type_str = IntegrationType.ZONEMINDER,+ is_enabled = False,+ )+ for attribute in ZmAttributeName:+ IntegrationAttribute.objects.create(+ integration = integration,+ value_type_str = str(attribute.value_type),+ name = attribute.label,+ value = '',+ attribute_type_str = AttributeType.PREDEFINED,+ is_editable = attribute.is_editable,+ is_required = attribute.is_required,+ )+ continue+ return integration++ def get_modal_response( self,+ request : HttpRequest,+ integration_attribute_formset : IntegrationAttributeFormSet,+ status : int = 200 ):+ context = {+ 'integration_attribute_formset': integration_attribute_formset,+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'zoneminder/modals/zm_enable.html',+ context = context,+ status = status,+ )+class ZmDisableView( View ):diff --git a/src/hi/integrations/zoneminder/zm_gateway.py b/src/hi/integrations/zoneminder/zm_gateway.pyindex 5ae1bb3f..ff15457e 100644--- a/src/hi/integrations/zoneminder/zm_gateway.py+++ b/src/hi/integrations/zoneminder/zm_gateway.py@@ -11,11 +11,11 @@ logger = logging.getLogger(__name__)class ZoneMinderGateway( IntegrationGateway ):- def enable( self, request : HttpRequest ) -> HttpResponse:- return views.ZmEnableView().post( request )+ def enable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:+ return views.ZmEnableView().get( request )- def disable( self, request : HttpRequest ) -> HttpResponse:- return views.ZmDisableView().post( request )+ def disable( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:+ return views.ZmDisableView().get( request )def manage( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse: