Skip to content

Commit

Permalink
refactor: adjust amazon forwarding validation function (#957)
Browse files Browse the repository at this point in the history
* refactor: adjust amazon forwarding validation function

* linting, update translations

* add additional test

* use regex when checking for domain

* formatting

* update test
  • Loading branch information
firstof9 authored Jul 23, 2024
1 parent 26f0ac1 commit 1e8c614
Show file tree
Hide file tree
Showing 23 changed files with 301 additions and 152 deletions.
41 changes: 30 additions & 11 deletions custom_components/mail_and_packages/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Adds config flow for Mail and Packages."""

import logging
import re
from os import path
from typing import Any

Expand Down Expand Up @@ -55,26 +56,44 @@
_LOGGER = logging.getLogger(__name__)


async def _check_amazon_forwards(forwards: str) -> tuple:
async def _check_amazon_forwards(forwards: str, domain: str) -> tuple:
"""Validate and format amazon forward emails for user input.
Returns tuple: dict of errors, list of email addresses
"""
amazon_forwards_list = forwards
emails = forwards.split(",")
errors = []

# Check for amazon domains
if "@amazon" in forwards:
errors.append("amazon_domain")
# Validate each email address
for email in emails:
email = email.strip()

# No forwards
elif forwards in ["", "(none)", '""']:
amazon_forwards_list = []
if "@" in email:
if not re.match(r"[a-zA-Z\.0-9\s]+@", email):
_LOGGER.error("Invalid email address: %s", email)
errors.append("invalid_email_format")

# Check for amazon domains
if f"@{domain}" in email:
_LOGGER.error("Invalid domain for email: %s", email)
errors.append("amazon_domain")

# No forwards
elif forwards in ["", "(none)", '""']:
forwards = []

else:
_LOGGER.error("Missing '@' in email address: %s", email)
errors.append("invalid_email_format")
# Add error message for Amazon emails
if re.match(rf"\b{domain}\b", email):
_LOGGER.error("Invalid domain for email: %s", email)
errors.append("amazon_domain")

if len(errors) == 0:
errors.append("ok")

return errors, amazon_forwards_list
return errors, forwards


async def _validate_user_input(user_input: dict) -> tuple:
Expand All @@ -88,7 +107,7 @@ async def _validate_user_input(user_input: dict) -> tuple:
if CONF_AMAZON_FWDS in user_input:
if isinstance(user_input[CONF_AMAZON_FWDS], str):
status, amazon_list = await _check_amazon_forwards(
user_input[CONF_AMAZON_FWDS]
user_input[CONF_AMAZON_FWDS], user_input[CONF_AMAZON_DOMAIN]
)
if status[0] == "ok":
user_input[CONF_AMAZON_FWDS] = amazon_list
Expand Down Expand Up @@ -252,7 +271,7 @@ def _get_default(key: str, fallback_default: Any = None) -> None:
CONF_AMAZON_DOMAIN, default=_get_default(CONF_AMAZON_DOMAIN)
): cv.string,
vol.Optional(
CONF_AMAZON_FWDS, default=_get_default(CONF_AMAZON_FWDS, "(none)")
CONF_AMAZON_FWDS, default=_get_default(CONF_AMAZON_FWDS)
): cv.string,
vol.Optional(CONF_AMAZON_DAYS, default=_get_default(CONF_AMAZON_DAYS)): int,
}
Expand Down
197 changes: 97 additions & 100 deletions custom_components/mail_and_packages/strings.json
Original file line number Diff line number Diff line change
@@ -1,109 +1,106 @@
{
"config": {
"abort": {
"single_instance_allowed": "Only a single configuration of Mail and Packages is allowed.",
"reconfigure_successful": "Reconfigure Successful"
},
"error": {
"communication": "Unable to connect or login to the mail server. Please check the log for details.",
"invalid_path": "Please store the images in another directory.",
"ffmpeg_not_found": "Generate MP4 requires ffmpeg",
"amazon_domain": "Invalid forwarding email address.",
"file_not_found": "Image file not found",
"scan_too_low": "Scan interval too low (minimum 5)",
"timeout_too_low": "IMAP timeout too low (minumim 10)"
},
"step": {
"user": {
"data": {
"host": "Host",
"password": "Password",
"port": "Port",
"username": "Username",
"imap_security": "IMAP Security",
"verify_ssl": "Verify SSL Cert"
},
"description": "Please enter the connection information of your mail server.",
"title": "Mail and Packages (Step 1 of 2)"
"abort": {
"single_instance_allowed": "Only a single configuration of Mail and Packages is allowed.",
"reconfigure_successful": "Reconfigure Successful"
},
"config_2": {
"data": {
"folder": "Mail Folder",
"resources": "Sensors List",
"scan_interval": "Scanning Interval (minutes, minimum 5)",
"image_path": "Image Path",
"gif_duration": "Image Duration (seconds)",
"image_security": "Random Image Filename",
"imap_timeout": "Time in seconds before connection timeout (seconds, minimum 10)",
"generate_mp4": "Create mp4 from images",
"allow_external": "Create image for notification apps",
"custom_img": "Use custom 'no image' image?"
},
"description": "Finish the configuration by customizing the following based on your email structure and Home Assistant installation.\n\nFor details on the [Mail and Packages integration](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) options review the [configuration, templates, and automations section](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) on GitHub.",
"title": "Mail and Packages (Step 2 of 2)"
"error": {
"communication": "Unable to connect or login to the mail server. Please check the log for details.",
"invalid_path": "Please store the images in another directory.",
"ffmpeg_not_found": "Generate MP4 requires ffmpeg",
"amazon_domain": "Invalid forwarding email address.",
"file_not_found": "Image file not found",
"invalid_email_format": "Invalid email address format."
},
"config_3": {
"data": {
"custom_img_file": "Path to custom image: (ie: images/my_custom_no_mail.jpg)"
},
"description": "Enter the path and file name to your custom no mail image below.\n\nExample: images/custom_nomail.gif",
"title": "Mail and Packages (Step 3 of 3)"
},
"config_amazon": {
"data": {
"amazon_domain": "Amazon domain",
"amazon_fwds": "Amazon forwarded email addresses",
"amazon_days": "Days back to check for Amazon emails"
},
"description": "Please enter the domain amazon sends email's from (ie: amazon.com or amazon.de)\n\nIf using Amazon forwarded emails please seperate each address with a comma or enter (none) to clear this setting.",
"title": "Amazon Settings"
},
"reconfigure": {
"data": {
"host": "Host",
"password": "Password",
"port": "Port",
"username": "Username",
"imap_security": "IMAP Security",
"verify_ssl": "Verify SSL Cert"
"step": {
"user": {
"description": "Please enter the connection information of your mail server.",
"data": {
"host": "Host",
"password": "Password",
"port": "Port",
"username": "Username",
"verify_ssl": "Verify SSL Cert",
"imap_security": "IMAP Security"
},
"title": "Mail and Packages (Step 1 of 2)"
},
"description": "Please enter the connection information of your mail server.",
"title": "Mail and Packages (Step 1 of 2)"
},
"reconfig_2": {
"data": {
"folder": "Mail Folder",
"scan_interval": "Scanning Interval (minutes)",
"image_path": "Image Path",
"gif_duration": "Image Duration (seconds)",
"image_security": "Random Image Filename",
"generate_mp4": "Create mp4 from images",
"resources": "Sensors List",
"imap_timeout": "Time in seconds before connection timeout (seconds, minimum 10)",
"amazon_fwds": "Amazon fowarded email addresses",
"allow_external": "Create image for notification apps",
"amazon_days": "Days back to check for Amazon emails",
"custom_img": "Use custom 'no image' image?"
"config_2": {
"data": {
"folder": "Mail Folder",
"resources": "Sensors List",
"scan_interval": "Scanning Interval (minutes, minimum 5)",
"image_path": "Image Path",
"gif_duration": "Image Duration (seconds)",
"image_security": "Random Image Filename",
"imap_timeout": "Time in seconds before connection timeout (seconds, minimum 10)",
"generate_mp4": "Create mp4 from images",
"allow_external": "Create image for notification apps",
"custom_img": "Use custom 'no image' image?"
},
"description": "Finish the configuration by customizing the following based on your email structure and Home Assistant installation.\n\nFor details on the [Mail and Packages integration](https:\/\/github.com\/moralmunky\/Home-Assistant-Mail-And-Packages\/wiki\/Configuration-and-Email-Settings#configuration) options review the [configuration, templates, and automations section](https:\/\/github.com\/moralmunky\/Home-Assistant-Mail-And-Packages\/wiki\/Configuration-and-Email-Settings#configuration) on GitHub.\n\nIf using Amazon forwarded emails please separate each address with a comma.",
"title": "Mail and Packages (Step 2 of 2)"
},
"description": "Finish the configuration by customizing the following based on your email structure and Home Assistant installation.\n\nFor details on the [Mail and Packages integration](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) options review the [configuration, templates, and automations section](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) on GitHub.\n\nIf using Amazon forwarded emails please seperate each address with a comma or enter (none) to clear this setting.",
"title": "Mail and Packages (Step 2 of 2)"
},
"reconfig_3": {
"data": {
"custom_img_file": "Path to custom image: (i.e.: images/my_custom_no_mail.jpg)"
"config_3": {
"data": {
"custom_img_file": "Path to custom image: (ie: images\/my_custom_no_mail.jpg)"
},
"description": "Enter the path and file name to your custom no mail image below.\n\nExample: images\/custom_nomail.gif",
"title": "Mail and Packages (Step 3 of 3)"
},
"description": "Enter the path and file name to your custom no mail image below.\n\nExample: images/custom_nomail.gif",
"title": "Mail and Packages (Step 3 of 3)"
},
"reconfig_amazon": {
"data": {
"amazon_domain": "Amazon domain",
"amazon_fwds": "Amazon forwarded email addresses",
"amazon_days": "Days back to check for Amazon emails"
},
"description": "Please enter the domain amazon sends email's from (ie: amazon.com or amazon.de)\n\nIf using Amazon forwarded emails please seperate each address with a comma or enter (none) to clear this setting.",
"title": "Amazon Settings"
}
}
"config_amazon": {
"data": {
"amazon_domain": "Amazon domain",
"amazon_fwds": "Amazon fowarded email addresses",
"amazon_days": "Days back to check for Amazon emails"
},
"description": "Please enter the domain Amazon sends email's from (ie: amazon.com or amazon.de)\n\nIf using Amazon forwarded emails please seperate each address with a comma or enter (none) to clear this setting.",
"title": "Amazon Settings"
},
"reconfigure": {
"data": {
"host": "Host",
"password": "Password",
"port": "Port",
"username": "Username",
"imap_security": "IMAP Security",
"verify_ssl": "Verify SSL Cert"
},
"description": "Please enter the connection information of your mail server.",
"title": "Mail and Packages (Step 1 of 2)"
},
"reconfig_2": {
"data": {
"folder": "Mail Folder",
"scan_interval": "Scanning Interval (minutes, minimum 5)",
"image_path": "Image Path",
"gif_duration": "Image Duration (seconds)",
"image_security": "Random Image Filename",
"generate_mp4": "Create mp4 from images",
"resources": "Sensors List",
"imap_timeout": "Time in seconds before connection timeout (seconds, minimum 10)",
"allow_external": "Create image for notification apps",
"custom_img": "Use custom 'no image' image?"
},
"description": "Finish the configuration by customizing the following based on your email structure and Home Assistant installation.\n\nFor details on the [Mail and Packages integration](https:\/\/github.com\/moralmunky\/Home-Assistant-Mail-And-Packages\/wiki\/Configuration-and-Email-Settings#configuration) options review the [configuration, templates, and automations section](https:\/\/github.com\/moralmunky\/Home-Assistant-Mail-And-Packages\/wiki\/Configuration-and-Email-Settings#configuration) on GitHub.\n\nIf using Amazon forwarded emails please separate each address with a comma or enter (none) to clear this setting.",
"title": "Mail and Packages (Step 2 of 2)"
},
"reconfig_3": {
"data": {
"custom_img_file": "Path to custom image: (i.e.: images\/my_custom_no_mail.jpg)"
},
"description": "Enter the path and file name to your custom no mail image below.\n\nExample: images\/custom_nomail.gif",
"title": "Mail and Packages (Step 3 of 3)"
},
"reconfig_amazon": {
"data": {
"amazon_domain": "Amazon domain",
"amazon_fwds": "Amazon fowarded email addresses",
"amazon_days": "Days back to check for Amazon emails"
},
"description": "Please enter the domain Amazon sends email's from (ie: amazon.com or amazon.de)\n\nIf using Amazon forwarded emails please seperate each address with a comma or enter (none) to clear this setting.",
"title": "Amazon Settings"
}
}
}
}
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/ca.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "No es pot connectar o iniciar la sessió al servidor de correu. Consulteu el registre per obtenir més detalls.",
"invalid_path": "Guardeu les imatges en un altre directori.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "Generar MP4 requereix ffmpeg",
"amazon_domain": "Adreça de correu electrònic de reenviament no vàlida.",
"file_not_found": "No s'ha trobat el fitxer d'imatge"
"file_not_found": "No s'ha trobat el fitxer d'imatge",
"invalid_email_format": "Format d'adreça de correu electrònic no vàlid."
},
"step": {
"user": {
Expand Down
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "Es kann keine Verbindung zum Mailserver hergestellt oder angemeldet werden. Bitte überprüfen Sie das Protokoll für Details.",
"invalid_path": "Bitte speichern Sie die Bilder in einem anderen Verzeichnis.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "MP4 erstellen erfordert ffmpeg",
"amazon_domain": "Ungültige Weiterleitungs-E-Mail-Adresse.",
"file_not_found": "Bilddatei nicht gefunden"
"file_not_found": "Bilddatei nicht gefunden",
"invalid_email_format": "Ungültiges E-Mail-Adressformat."
},
"step": {
"user": {
Expand Down
3 changes: 2 additions & 1 deletion custom_components/mail_and_packages/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"invalid_path": "Please store the images in another directory.",
"ffmpeg_not_found": "Generate MP4 requires ffmpeg",
"amazon_domain": "Invalid forwarding email address.",
"file_not_found": "Image file not found"
"file_not_found": "Image file not found",
"invalid_email_format": "Invalid email address format."
},
"step": {
"user": {
Expand Down
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "No se puede conectar o iniciar sesión en el servidor de correo. Por favor, consulte el registro para más detalles.",
"invalid_path": "Guarde las imágenes en otro directorio.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "Generar MP4 requiere ffmpeg",
"amazon_domain": "Dirección de correo electrónico de reenvío no válida.",
"file_not_found": "Archivo de imagen no encontrado"
"file_not_found": "Archivo de imagen no encontrado",
"invalid_email_format": "Formato de dirección de correo electrónico no válido."
},
"step": {
"user": {
Expand Down
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/es_419.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "No se puede conectar o iniciar sesión en el servidor de correo. Por favor, consulte el registro para más detalles.",
"invalid_path": "Guarde las imágenes en otro directorio.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "Generar MP4 requiere ffmpeg",
"amazon_domain": "Dirección de correo electrónico de reenvío no válida.",
"file_not_found": "Archivo de imagen no encontrado"
"file_not_found": "Archivo de imagen no encontrado",
"invalid_email_format": "Formato de dirección de correo electrónico inválido."
},
"step": {
"user": {
Expand Down
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "Ei voida muodostaa yhteyttä tai kirjautua sisään postipalvelimeen. Tarkista lokista yksityiskohdat.",
"invalid_path": "Tallenna kuvat toiseen hakemistoon.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "MP4:n luominen vaatii ffmpeg:n",
"amazon_domain": "Virheellinen edelleenlähetettävä sähköpostiosoite.",
"file_not_found": "Kuvatiedostoa ei löydy"
"file_not_found": "Kuvatiedostoa ei löydy",
"invalid_email_format": "Virheellinen sähköpostiosoitteen muoto."
},
"step": {
"user": {
Expand Down
5 changes: 3 additions & 2 deletions custom_components/mail_and_packages/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"error": {
"communication": "Impossible de se connecter ou de se connecter au serveur de messagerie. Veuillez consulter le journal pour plus de détails.",
"invalid_path": "Veuillez stocker les images dans un autre répertoire.",
"ffmpeg_not_found": "",
"ffmpeg_not_found": "Générer MP4 nécessite ffmpeg",
"amazon_domain": "Adresse e-mail de transfert invalide.",
"file_not_found": "Fichier image non trouvé"
"file_not_found": "Fichier image non trouvé",
"invalid_email_format": "Format d'adresse e-mail invalide."
},
"step": {
"user": {
Expand Down
Loading

0 comments on commit 1e8c614

Please sign in to comment.