Skip to content

Commit

Permalink
Handle things like URLs in Package ID when exporting ezEML data package.
Browse files Browse the repository at this point in the history
  • Loading branch information
jon-ide committed Nov 20, 2024
1 parent 95e8c7d commit 767cc6d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
30 changes: 30 additions & 0 deletions webapp/home/utils/file_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import re
import unicodedata

def sanitize_filename(value):
"""
Sanitize a string to make it safe for use as a filename.
Parameters:
value (str): The original string.
Returns:
str: A sanitized string safe for filenames.
"""
# Normalize the string to remove accents and special characters
value = unicodedata.normalize('NFKD', value)
value = value.encode('ascii', 'ignore').decode('ascii')

# Replace invalid characters with an underscore
value = re.sub(r'[<>:"/\\|?*]', '_', value)

# Remove any remaining non-word characters (except spaces and hyphens)
value = re.sub(r'[^\w\s-]', '', value)

# Replace spaces and hyphens with a single underscore
value = re.sub(r'[\s-]+', '_', value)

# Trim leading and trailing underscores
value = value.strip('_')

return value
3 changes: 2 additions & 1 deletion webapp/home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

from markupsafe import Markup

from webapp.home.utils.file_utils import sanitize_filename
import webapp.home.utils.node_utils
import webapp.mimemail as mimemail

Expand Down Expand Up @@ -2732,7 +2733,7 @@ def create_ezeml_package_manifest(user_folder, manifest_files):
package_id = eml_node.attribute_value("packageId")
if package_id and package_id != current_document:
# copy the EML file using the package_id as name
arcname = f'{package_id}.xml'
arcname = f'{sanitize_filename(package_id)}.xml'
copyfile(f'{user_folder}/{current_document}.xml', f'{user_folder}/{arcname}')
else:
arcname = f'{current_document}.xml'
Expand Down

0 comments on commit 767cc6d

Please sign in to comment.