Home Information - Your home, your data, organized.
Python
Refactoring and better user flow for dealing with SVG uploads.
Anthony Cassandra7a4bdc0f24e5
diff --git a/src/hi/apps/common/svg_file_form.py b/src/hi/apps/common/svg_file_form.pynew file mode 100644index 00000000..eb96ba2b--- /dev/null+++ b/src/hi/apps/common/svg_file_form.py@@ -0,0 +1,200 @@+import logging+import os+import time+import xml.etree.ElementTree as ET++from django import forms+from django.core.exceptions import ValidationError++from hi.apps.common.svg_models import SvgViewBox++logger = logging.getLogger(__name__)++# Need this to avoid library adding "ns0:" namespacing when writing content.+ET.register_namespace('', 'http://www.w3.org/2000/svg')+++class SvgFileForm(forms.Form):++ svg_file = forms.FileField(+ label = 'SVG file',+ required = False,+ )+ remove_dangerous_svg_items = forms.BooleanField(+ label = 'Remove dangerous SVG items?',+ widget = forms.CheckboxInput(+ attrs = {+ 'class': 'form-check-input',+ 'style': 'display: none;', # Conditionally shown only+ }+ ),+ required = False,+ )+ has_dangerous_svg_items = forms.CharField(+ widget = forms.HiddenInput(),+ initial = 'false',+ required = False,+ )++ def get_default_source_directory(self):+ # e.g., static image area+ raise NotImplementedError( 'Subclasses must override this method.' )++ def get_default_basename(self):+ # Base filename for the default source (and destination) files.+ raise NotImplementedError( 'Subclasses must override this method.' )++ def get_media_destination_directory(self):+ # Relative to MEDIA_ROOT.+ raise NotImplementedError( 'Subclasses must override this method.' )++ MAX_SVG_FILE_SIZE_MEGABYTES = 5+ MAX_SVG_FILE_SIZE_BYTES = MAX_SVG_FILE_SIZE_MEGABYTES * 1024 * 1024++ DANGEROUS_TAGS = {+ 'script', 'foreignObject', 'iframe', 'object',+ 'animation', 'audio', 'video', 'style',+ }+ DANGEROUS_ATTRS = {+ 'onload', 'onclick', 'onmouseover', 'xlink:href',+ 'href',+ }++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self._has_dangerous_svg_items = bool( self.data.get('has_dangerous_svg_items', 'false' ) == 'true' )+ if self._has_dangerous_svg_items:+ self.fields['remove_dangerous_svg_items'].widget.attrs.update( { 'style': '' } )+ return++ def clean(self):+ cleaned_data = super().clean()++ self._dangerous_tag_counts = dict()+ self._dangerous_attr_counts = dict()++ self._has_dangerous_svg_items = bool(+ cleaned_data.get( 'has_dangerous_svg_items', 'false' ) == 'true'+ )+ if self._has_dangerous_svg_items:+ require_svg_file = True++ remove_dangerous_svg_items = cleaned_data.get( 'remove_dangerous_svg_items' )++ svg_file_handle = cleaned_data.get('svg_file')+ if not svg_file_handle:+ if require_svg_file:+ raise ValidationError( 'You need to re-select the SVG file.' )++ default_svg_path = os.path.join(+ self.get_default_source_directory(),+ self.get_default_basename(),+ )+ with open( default_svg_path, 'r' ) as f:+ svg_content = f.read()+ svg_filename = self.get_default_basename()+ else:+ svg_file_handle.seek(0) # Guard against multiple calls to clean()+ svg_content = svg_file_handle.read().decode('utf-8')+ svg_filename = svg_file_handle.name++ try:+ if len(svg_content) > self.MAX_SVG_FILE_SIZE_BYTES:+ raise ValidationError( f'SVG file too large. Max {self.MAX_SVG_FILE_SIZE_MEGABYTES} MB.' )++ root = ET.fromstring( svg_content )+ if root.tag != '{http://www.w3.org/2000/svg}svg':+ raise ValidationError( 'The uploaded file is not a valid SVG file.' )++ view_box_str = root.attrib.get( 'viewBox' )+ if not view_box_str:+ raise ValidationError( 'The SVG must contain a viewBox attribute.' )++ svg_viewbox = SvgViewBox.from_attribute_value( view_box_str )+ cleaned_data['svg_viewbox'] = svg_viewbox++ # Remove the outer <svg> tag if necessary+ for element in list( root.iter() ):+ if element is root:+ continue++ # Remove the namespace from the child elements+ if element.tag.startswith('{http://www.w3.org/2000/svg}'):+ element.tag = element.tag.split('}', 1)[1] # Strip the namespace++ tag_name = element.tag.split('}')[-1] # Handle namespaces+ if tag_name in self.DANGEROUS_TAGS:+ logger.debug( f'Removing dangerous SVG tag "{tag_name}"' )+ root.remove(element)+ self._increment_dangerous_tag_count( tag_name )+ continue++ for attr_name in list(element.attrib):+ if attr_name in self.DANGEROUS_ATTRS:+ logger.debug(f'Removing dangerous SVG attribute "{attr_name}"')+ del element.attrib[attr_name]+ self._increment_dangerous_attr_count( attr_name )+ continue++ continue++ if ( not remove_dangerous_svg_items+ and (( len(self._dangerous_tag_counts) + len(self._dangerous_attr_counts) ) > 0 )):+ self._add_dangerous_messages()+ self.fields['remove_dangerous_svg_items'].widget.attrs.update( { 'style': '' } )+ self.data = self.data.copy() # Need a mutable copy to change this data+ self.data['has_dangerous_svg_items'] = 'true'+ self._has_dangerous_svg_items = True++ inner_content = ''.join( ET.tostring( element, encoding = 'unicode' ) for element in root )+ cleaned_data['svg_fragment_content'] = inner_content++ svg_fragment_filename = os.path.join(+ self.get_media_destination_directory(),+ self.generate_unique_filename( svg_filename ),+ )+ cleaned_data['svg_fragment_filename'] = svg_fragment_filename++ except ET.ParseError as pe:+ logger.exception( pe )+ raise ValidationError( 'The uploaded file is not a valid XML (SVG) file.' )+ except Exception as e:+ logger.exception( e )+ raise ValidationError(f'Error processing the SVG file: {str(e)}' )++ return cleaned_data++ def show_remove_dangerous_svg_items(self):+ return self._has_dangerous_svg_items++ def _increment_dangerous_tag_count( self, tag_name : str ):+ if tag_name in self._dangerous_tag_counts:+ self._dangerous_tag_counts[tag_name] += 1+ else:+ self._dangerous_tag_counts[tag_name] = 1+ return++ def _increment_dangerous_attr_count( self, attr_name : str ):+ if attr_name in self._dangerous_attr_counts:+ self._dangerous_attr_counts[attr_name] += 1+ else:+ self._dangerous_attr_counts[attr_name] = 1+ return++ def _add_dangerous_messages(self):+ self.add_error( 'svg_file', 'Dangerous SVG items found which are not allowed.' )+ self.add_error( 'svg_file', 'Confirm changes to have them removed duringn the upload.' )+ self.add_error( 'svg_file', 'The dangerous items (with counts) are:' )+ for tag_name, count in self._dangerous_tag_counts.items():+ self.add_error( 'svg_file', f'- Tag: <{tag_name}>, Count: {count:,} ' )+ continue+ for attr_name, count in self._dangerous_attr_counts.items():+ self.add_error( 'svg_file', f'- Attr: {attr_name}, Count: {count:,} ' )+ continue+ return++ def generate_unique_filename( self, filename : str ):+ original_name, extension = os.path.splitext( filename )+ timestamp = int( time.time() )+ unique_name = f'{original_name}-{timestamp}{extension}'+ return unique_namediff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.pyindex 2dafada0..4f3b8762 100644--- a/src/hi/apps/location/edit/forms.py+++ b/src/hi/apps/location/edit/forms.py@@ -1,122 +1,33 @@import loggingimport os-import time-import xml.etree.ElementTree as ETfrom django import formsfrom django.conf import settings-from django.core.exceptions import ValidationError-from hi.apps.common.svg_models import SvgViewBox+from hi.apps.common.svg_file_form import SvgFileFormlogger = logging.getLogger(__name__)-# Need this to avoid library adding "ns0:" namespacing when writing content.-ET.register_namespace('', 'http://www.w3.org/2000/svg')--class LocationForm(forms.Form):-- LOCATION_DEFAULT_FILENAME = 'location-default.svg'- MEDIA_DIRECTORY = 'location/svg'- MAX_SVG_FILE_SIZE_MEGABYTES = 5- MAX_SVG_FILE_SIZE_BYTES = MAX_SVG_FILE_SIZE_MEGABYTES * 1024 * 1024-- DANGEROUS_TAGS = {- 'script', 'foreignObject', 'iframe', 'object',- 'animation', 'audio', 'video', 'style',- }- DANGEROUS_ATTRS = {- 'onload', 'onclick', 'onmouseover', 'xlink:href',- 'href',- }+class LocationForm( SvgFileForm ):name = forms.CharField(label = 'Location Name',required = True,)- svg_file = forms.FileField(- label = 'SVG file',- required = False,- )-- def clean(self):- cleaned_data = super().clean()-- svg_file_handle = cleaned_data.get('svg_file')- if not svg_file_handle:- default_svg_path = os.path.join(- settings.BASE_DIR,- 'static',- 'img',- self.LOCATION_DEFAULT_FILENAME,- )- with open(default_svg_path, 'r') as f:- svg_content = f.read()- svg_filename = self.LOCATION_DEFAULT_FILENAME- else:- svg_content = svg_file_handle.read().decode('utf-8')- svg_filename = svg_file_handle.name-- try:- if len(svg_content) > self.MAX_SVG_FILE_SIZE_BYTES:- raise ValidationError( f'SVG file too large. Max {self.MAX_SVG_FILE_SIZE_MEGABYTES} MB.' )-- root = ET.fromstring( svg_content )- if root.tag != '{http://www.w3.org/2000/svg}svg':- raise ValidationError( 'The uploaded file is not a valid SVG file.' )-- view_box_str = root.attrib.get( 'viewBox' )- if not view_box_str:- raise ValidationError( 'The SVG must contain a viewBox attribute.' )-- svg_viewbox = SvgViewBox.from_attribute_value( view_box_str )- cleaned_data['svg_viewbox'] = svg_viewbox-- # Remove the outer <svg> tag if necessary- for element in list( root.iter() ):- if element is root:- continue-- # Remove the namespace from the child elements- if element.tag.startswith('{http://www.w3.org/2000/svg}'):- element.tag = element.tag.split('}', 1)[1] # Strip the namespace-- tag_name = element.tag.split('}')[-1] # Handle namespaces- if tag_name in self.DANGEROUS_TAGS:- logger.debug( f'Removing dangerous SVG tag "{tag_name}"' )- root.remove(element)- continue-- for attr in list(element.attrib):- if attr in self.DANGEROUS_ATTRS:- logger.debug(f'Removing dangerous SVG attribute "{attr}"')- del element.attrib[attr]- continue-- continue-- inner_content = ''.join( ET.tostring( element, encoding = 'unicode' ) for element in root )- cleaned_data['svg_fragment_content'] = inner_content- svg_fragment_filename = os.path.join(- self.MEDIA_DIRECTORY,- self.generate_unique_filename( svg_filename ),- )- cleaned_data['svg_fragment_filename'] = svg_fragment_filename-- except ET.ParseError:- raise ValidationError( 'The uploaded file is not a valid XML (SVG) file.' )- except Exception as e:- raise ValidationError(f'Error processing the SVG file: {str(e)}' )+ def get_default_source_directory(self):+ return os.path.join(+ settings.BASE_DIR,+ 'static',+ 'img',+ )- return cleaned_data+ def get_default_basename(self):+ return 'location-default.svg'- def generate_unique_filename( self, filename : str ):- original_name, extension = os.path.splitext( filename )- timestamp = int( time.time() )- unique_name = f'{original_name}-{timestamp}{extension}'- return unique_name+ def get_media_destination_directory(self):+ return 'location/svg'class LocationViewForm(forms.Form):diff --git a/src/hi/apps/location/edit/urls.py b/src/hi/apps/location/edit/urls.pyindex feef6042..f57fc6fa 100644--- a/src/hi/apps/location/edit/urls.py+++ b/src/hi/apps/location/edit/urls.py@@ -9,6 +9,10 @@ urlpatterns = [views.LocationAddView.as_view(),name='location_edit_location_add'),+ re_path( r'^location/edit/(?P<location_id>\d+)$',+ views.LocationEditView.as_view(),+ name='location_edit_location_edit'),+re_path( r'^location/delete/(?P<location_id>\d+)$',views.LocationDeleteView.as_view(),name='location_edit_location_delete' ),@@ -17,6 +21,10 @@ urlpatterns = [views.LocationViewAddView.as_view(),name='location_edit_location_view_add' ),+ re_path( r'^location-view/edit/(?P<location_view_id>\d+)$',+ views.LocationViewEditView.as_view(),+ name='location_edit_location_view_edit' ),+re_path( r'^location-view/geometry/(?P<location_view_id>\d+)$',views.LocationViewGeometryView.as_view(),name='location_edit_location_view_geometry' ),diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.pyindex b0966747..7bf88642 100644--- a/src/hi/apps/location/edit/views.py+++ b/src/hi/apps/location/edit/views.py@@ -45,6 +45,7 @@ class LocationAddView( View ):return self._show_modal( request, location_form = forms.LocationForm() )def post( self, request, *args, **kwargs ):+location_form = forms.LocationForm( request.POST, request.FILES )if not location_form.is_valid():return self._show_modal( request, location_form = location_form )@@ -81,6 +82,13 @@ class LocationAddView( View ):)+@method_decorator( edit_required, name='dispatch' )+class LocationEditView( View ):++ def get( self, request, *args, **kwargs ):+ raise NotImplementedError()++@method_decorator( edit_required, name='dispatch' )class LocationDeleteView( View ):@@ -176,6 +184,13 @@ class LocationViewAddView( View ):return antinode.redirect_response( redirect_url )+@method_decorator( edit_required, name='dispatch' )+class LocationViewEditView( View ):++ def get( self, request, *args, **kwargs ):+ raise NotImplementedError()++class LocationViewGeometryView( View ):def post(self, request, *args, **kwargs):diff --git a/src/hi/apps/location/forms.py b/src/hi/apps/location/forms.pyindex bd79f3cb..65c0ccc4 100644--- a/src/hi/apps/location/forms.py+++ b/src/hi/apps/location/forms.py@@ -1,9 +1,5 @@-from decimal import Decimal-from django import forms-from hi.enums import ItemType-from .models import LocationItemModelMixin, LocationItemPositionModeldiff --git a/src/hi/apps/location/templates/location/edit/modals/location_edit.html b/src/hi/apps/location/templates/location/edit/modals/location_edit.htmlnew file mode 100644index 00000000..603718ee--- /dev/null+++ b/src/hi/apps/location/templates/location/edit/modals/location_edit.html@@ -0,0 +1,38 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'location_edit_location_add' %}" method="post" enctype="multipart/form-data"+ class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+New Location+{% endblock %}++{% block body %}+<div>+{% include "location/edit/panes/location_form.html" %}+</div>++<div>+ <a href="{% url 'location_edit_location_delete' location_id=location_detail_data.location.id %}"+ id="hi-delete-location-link" class="btn btn-danger btn-control" role="button"+ data-async="true">+ DELETE LOCATION AND ALL VIEWS+ </a>+</div>+++{% endblock %}++{% block action_right %}+<button id="hi-add-location-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="add">+ ADD+</button>+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/modals/location_view_edit.html b/src/hi/apps/location/templates/location/edit/modals/location_view_edit.htmlnew file mode 100644index 00000000..742fad0d--- /dev/null+++ b/src/hi/apps/location/templates/location/edit/modals/location_view_edit.html@@ -0,0 +1,37 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'location_edit_location_view_add' %}" method="post"+ class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+New Location View+{% endblock %}++{% block body %}+<div>+{% include "location/edit/panes/location_view_form.html" %}+</div>++<div>+ <a href="{% url 'location_edit_location_view_delete' location_view_id=request.view_parameters.location_view_id %}"+ id="hi-delete-location-view-link" class="btn btn-danger btn-control" role="button"+ data-async="true">+ DELETE THIS VIEW+ </a>+</div>++{% endblock %}++{% block action_right %}+<button id="hi-add-location-view-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="add">+ ADD+</button>+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_form.html b/src/hi/apps/location/templates/location/edit/panes/location_form.htmlindex b61bb676..d94b6f82 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_form.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_form.html@@ -23,8 +23,14 @@<p><label for="id_svg_file">Select an SVG file:</label><input type="file" name="svg_file" id="id_svg_file">+ {{ location_form.svg_file.errors }}</p>+{% if location_form.show_remove_dangerous_svg_items %}<p>-+ <div class="form-check">+ {{ location_form.remove_dangerous_svg_items }}+ {{ location_form.remove_dangerous_svg_items.label }}+ </div></p>+{% endif %}diff --git a/src/hi/apps/location/templates/location/panes/location_details.html b/src/hi/apps/location/templates/location/panes/location_details.htmlindex eb814471..0d0f9766 100644--- a/src/hi/apps/location/templates/location/panes/location_details.html+++ b/src/hi/apps/location/templates/location/panes/location_details.html@@ -8,19 +8,18 @@ TBD<div>{{ location_detail_data.location.order_id }}</div><div>- <a href="{% url 'location_edit_location_view_delete' location_view_id=request.view_parameters.location_view_id %}"- id="hi-delete-location-view-link" class="btn btn-danger btn-control" role="button"+ <a href="{% url 'location_edit_location_edit' location_id=location_detail_data.location.id %}"+ id="hi-location-edit-link" class="btn btn-primary btn-control" role="button"data-async="true">- DELETE THIS VIEW+ EDIT LOCATION</a></div>-<div>- <a href="{% url 'location_edit_location_delete' location_id=location_detail_data.location.id %}"- id="hi-delete-location-link" class="btn btn-danger btn-control" role="button"+ <a href="{% url 'location_edit_location_view_edit' location_view_id=request.view_parameters.location_view_id %}"+ id="hi-location-view-edit-link" class="btn btn-info btn-control" role="button"data-async="true">- DELETE LOCATION AND ALL VIEWS+ EDIT VIEW</a></div>