diff --git a/front/php/templates/language/en_us.json b/front/php/templates/language/en_us.json
index 2faee1ae..27620372 100755
--- a/front/php/templates/language/en_us.json
+++ b/front/php/templates/language/en_us.json
@@ -536,17 +536,7 @@
"WEBHOOK_SIZE_name" : "Max payload size",
"WEBHOOK_SIZE_description" : "The maximum size of the webhook payload as number of characters in the passed string. If above limit, it will be truncated and a (text was truncated) message is appended.",
"WEBHOOK_SECRET_name": "HMAC Secret",
- "WEBHOOK_SECRET_description": "When set, use this secret to generate the SHA256-HMAC hex digest value of the request body, which will be passed as the X-Webhook-Signature header to the request. You can find more informations here.",
- "Apprise_display_name" : "Apprise",
- "Apprise_icon" : "",
- "REPORT_APPRISE_name" : "Enable Apprise",
- "REPORT_APPRISE_description" : "Enable sending notifications via Apprise.",
- "APPRISE_HOST_name" : "Apprise host URL",
- "APPRISE_HOST_description" : "Apprise host URL starting with http:// or https://. (do not forget to include /notify at the end)",
- "APPRISE_URL_name" : "Apprise notification URL",
- "APPRISE_URL_description" : "Apprise notification target URL. For example for Telegram it would be tgram://{bot_token}/{chat_id}.",
- "APPRISE_SIZE_name" : "Max payload size",
- "APPRISE_SIZE_description" : "The maximum size of the apprise payload as number of characters in the passed string. If above limit, it will be truncated and a (text was truncated) message is appended.",
+ "WEBHOOK_SECRET_description": "When set, use this secret to generate the SHA256-HMAC hex digest value of the request body, which will be passed as the X-Webhook-Signature header to the request. You can find more informations here.",
"NTFY_display_name" : "NTFY",
"NTFY_icon" : "",
"REPORT_NTFY_name" : "Enable NTFY",
@@ -564,9 +554,7 @@
"REPORT_PUSHSAFER_name" : "Enable Pushsafer",
"REPORT_PUSHSAFER_description" : "Enable sending notifications via Pushsafer.",
"PUSHSAFER_TOKEN_name" : "Pushsafer token",
- "PUSHSAFER_TOKEN_description" : "Your secret Pushsafer API key (token).",
- "APPRISE_PAYLOAD_name" : "Payload type",
- "APPRISE_PAYLOAD_description" : "Select the payoad type sent to Apprise. For example html works well with emails, text with chat apps, such as Telegram.",
+ "PUSHSAFER_TOKEN_description" : "Your secret Pushsafer API key (token).",
"MQTT_display_name" : "MQTT",
"MQTT_icon" : "",
"REPORT_TITLE" : "Report",
diff --git a/front/plugins/_publisher_apprise/apprise.py b/front/plugins/_publisher_apprise/apprise.py
index ac2fc7d0..c3ddb3c8 100755
--- a/front/plugins/_publisher_apprise/apprise.py
+++ b/front/plugins/_publisher_apprise/apprise.py
@@ -15,7 +15,9 @@ sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
import conf
from plugin_helper import Plugin_Objects
from logger import mylog, append_line_to_file
-from helper import timeNowTZ, noti_struc
+from helper import timeNowTZ, noti_obj
+from notification import Notification_obj
+from database import DB
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
@@ -24,41 +26,60 @@ RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
def main():
mylog('verbose', ['[APPRISE](publisher) In script'])
+
+ # Check if basic config settings supplied
+ if check_config() == False:
+ mylog('none', ['[Check Config] Error: Apprise service not set up correctly. Check your pialert.conf APPRISE_* variables.'])
+ return
- parser = argparse.ArgumentParser(description='APPRISE publisher Plugin')
- values = parser.parse_args()
+ # Create a database connection
+ db = DB() # instance of class DB
+ db.open()
+ # parser = argparse.ArgumentParser(description='APPRISE publisher Plugin')
+ # values = parser.parse_args()
+
+ # Initialize the Plugin obj output file
plugin_objects = Plugin_Objects(RESULT_FILE)
- speedtest_result = send()
+ # Create a Notification_obj instance
+ Notification_obj(db)
- plugin_objects.add_object(
- primaryId = 'APPRISE',
- secondaryId = timeNowTZ(),
- watched1 = speedtest_result['download_speed'],
- watched2 = speedtest_result['upload_speed'],
- watched3 = 'null',
- watched4 = 'null',
- extra = 'null',
- foreignKey = 'null'
- )
+ # Retrieve new notifications
+ new_notifications = notifications.getNew()
+
+ # Process the new notifications
+ for notification in new_notifications:
+
+ # Send notification
+ result = send(notification["HTML"], notification["Text"])
+
+ # Log result
+ plugin_objects.add_object(
+ primaryId = 'APPRISE',
+ secondaryId = timeNowTZ(),
+ watched1 = notification["GUID"],
+ watched2 = result,
+ watched3 = 'null',
+ watched4 = 'null',
+ extra = 'null',
+ foreignKey = 'null'
+ )
plugin_objects.write_result_file()
#-------------------------------------------------------------------------------
def check_config():
- if conf.APPRISE_URL == '' or conf.APPRISE_HOST == '':
- mylog('none', ['[Check Config] Error: Apprise service not set up correctly. Check your pialert.conf APPRISE_* variables.'])
+ if conf.APPRISE_URL == '' or conf.APPRISE_HOST == '':
return False
else:
return True
#-------------------------------------------------------------------------------
-def send(msg: noti_struc):
- html = msg.html
- text = msg.text
+def send(html, text):
payloadData = ''
+ result = ''
# limit = 1024 * 1024 # 1MB limit (1024 bytes * 1024 bytes = 1MB)
limit = conf.APPRISE_SIZE
@@ -66,7 +87,7 @@ def send(msg: noti_struc):
# truncate size
if conf.APPRISE_PAYLOAD == 'html':
if len(msg.html) > limit:
- payloadData = msg.html[:limit] + "
schedule the scheduling settings from below are applied. If you select once the scan is run only once on start of the application (container) for the time specified in INTRSPD_RUN_TIMEOUT setting."
- }]
+ "string" : "Enable sending notifications via Apprise."
+ },
+ {
+ "language_code": "es_es",
+ "string" : "Habilitar el envío de notificaciones a través de Apprise."
+ }
+ ]
},
{
"function": "CMD",
"type": "readonly",
- "default_value":"python3 /home/pi/pialert/front/plugins/internet_speedtest/script.py",
+ "default_value":"python3 /home/pi/pialert/front/plugins/_publisher_apprise/apprise.py",
"options": [],
"localized": ["name", "description"],
"name" : [{
@@ -321,33 +301,10 @@
"string" : "Comando a ejecutar"
}]
},
- {
- "function": "RUN_SCHD",
- "type": "text",
- "default_value":"*/30 * * * *",
- "options": [],
- "localized": ["name", "description"],
- "name" : [{
- "language_code": "en_us",
- "string" : "Schedule"
- },
- {
- "language_code": "es_es",
- "string" : "Schedule"
- }],
- "description": [{
- "language_code": "en_us",
- "string" : "Only enabled if you select schedule in the INTRSPD_RUN setting. Make sure you enter the schedule in the correct cron-like format (e.g. validate at crontab.guru). For example entering 0 4 * * * will run the scan after 4 am in the TIMEZONE you set above. Will be run NEXT time the time passes."
- },
- {
- "language_code": "es_es",
- "string": "Solo habilitado si selecciona schedule en la configuración INTRSPD_RUN. Asegúrese de ingresar el schedule en el formato similar a cron correcto (por ejemplo, valide en crontab.guru). Por ejemplo, ingrese 0 4 * * * ejecutará el escaneo después de las 4 am en el TIMEZONE que configuró arriba . Se ejecutará la PRÓXIMA vez que pase el tiempo."
- }]
- },
{
"function": "RUN_TIMEOUT",
"type": "integer",
- "default_value":60,
+ "default_value": 10,
"options": [],
"localized": ["name", "description"],
"name" : [{
@@ -372,46 +329,96 @@
}]
},
{
- "function": "WATCH",
- "type": "text.multiselect",
- "default_value":[],
- "options": ["Watched_Value1","Watched_Value2","Watched_Value3","Watched_Value4"],
+ "function": "HOST",
+ "type": "text",
+ "default_value": "",
+ "options": [],
"localized": ["name", "description"],
- "name" :[{
+ "name" : [{
"language_code": "en_us",
- "string" : "Watched"
+ "string" : "Apprise host URL"
},
{
"language_code": "es_es",
- "string" : "Visto"
- }],
- "description":[{
+ "string" : "URL del host de Apprise"
+ }],
+ "description": [{
"language_code": "en_us",
- "string" : "Send a notification if selected values change. Use CTRL + Click to select/deselect. Watched_Value1 is Download speed (not recommended)Watched_Value2 is Upload speed (not recommended)Watched_Value3 unused Watched_Value4 unused http:// or https://. (do not forget to include /notify at the end)"
+ },
+ {
+ "language_code": "es_es",
+ "string" : "URL del host de Apprise que comienza con http:// o https://. (no olvide incluir /notify al final)"
+ }]
},
{
- "function": "REPORT_ON",
- "type": "text.multiselect",
- "default_value":[],
- "options": ["new","watched-changed","watched-not-changed", "missing-in-last-scan"],
+ "function": "URL",
+ "type": "text",
+ "default_value": "",
+ "options": [],
"localized": ["name", "description"],
- "name" :[{
+ "name" : [{
"language_code": "en_us",
- "string" : "Report on"
+ "string" : "Apprise notification URL"
},
{
"language_code": "es_es",
- "string" : "Informar sobre"
- }] ,
- "description":[{
+ "string" : "URL de notificación de Apprise"
+ }],
+ "description": [{
"language_code": "en_us",
- "string" : "Send a notification only on these statuses. new means a new unique (unique combination of PrimaryId and SecondaryId) object was discovered. watched-changed means that selected Watched_ValueN columns changed."
+ "string" : "Apprise notification target URL. For example for Telegram it would be tgram://{bot_token}/{chat_id}."
},
{
"language_code": "es_es",
- "string" : "Envíe una notificación solo en estos estados. new significa que se descubrió un nuevo objeto único (combinación única de PrimaryId y SecondaryId). watched-changed significa que seleccionó Watched_ValueN Las columnas cambiaron."
- }]
- }
+ "string" : "Informar de la URL de destino de la notificación. Por ejemplo, para Telegram sería tgram://{bot_token}/{chat_id}."
+ }]
+ },
+ {
+ "function": "PAYLOAD",
+ "type": "text.select",
+ "default_value": "html",
+ "options": ["html", "text"],
+ "localized": ["name", "description"],
+ "name" : [{
+ "language_code": "en_us",
+ "string" : "Payload type"
+ },
+ {
+ "language_code": "es_es",
+ "string" : "Tipo de carga"
+ }],
+ "description": [{
+ "language_code": "en_us",
+ "string" : "Select the payoad type sent to Apprise. For example html works well with emails, text with chat apps, such as Telegram."
+ },
+ {
+ "language_code": "es_es",
+ "string" : "Seleccione el tipo de carga útil enviada a Apprise. Por ejemplo, html funciona bien con correos electrónicos, text con aplicaciones de chat, como Telegram."
+ }]
+ },
+ {
+ "function": "SIZE",
+ "type": "integer",
+ "default_value": 1024,
+ "options": [],
+ "localized": ["name", "description"],
+ "name" : [{
+ "language_code": "en_us",
+ "string" : "Max payload size"
+ },
+ {
+ "language_code": "es_es",
+ "string" : "Tamaño máximo de carga útil"
+ }],
+ "description": [{
+ "language_code": "en_us",
+ "string" : "The maximum size of the apprise payload as number of characters in the passed string. If above limit, it will be truncated and a (text was truncated) message is appended."
+ },
+ {
+ "language_code": "es_es",
+ "string" : "El tamaño máximo de la carga útil de información como número de caracteres en la cadena pasada. Si supera el límite, se truncará y se agregará un mensaje (text was truncated)."
+ }]
+ }
]
}
diff --git a/front/plugins/_publisher_apprise/ignore_plugin b/front/plugins/_publisher_apprise/ignore_plugin
deleted file mode 100755
index 77ffa1c1..00000000
--- a/front/plugins/_publisher_apprise/ignore_plugin
+++ /dev/null
@@ -1 +0,0 @@
-This plugin will not be loaded
\ No newline at end of file
diff --git a/front/settings.php b/front/settings.php
index d18cbcf1..d2d48b85 100755
--- a/front/settings.php
+++ b/front/settings.php
@@ -749,8 +749,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
- // Show last time settings have been imported
- // getParam("lastImportedTime", "Back_Settings_Imported", skipCache = true);
+ // Show last time settings have been imported
handleLoadingDialog()
diff --git a/pialert/__main__.py b/pialert/__main__.py
index fe7d5221..fd01c6b6 100755
--- a/pialert/__main__.py
+++ b/pialert/__main__.py
@@ -24,13 +24,13 @@ import multiprocessing
import conf
from const import *
from logger import mylog
-from helper import filePermissions, timeNowTZ, updateState, get_setting_value, noti_struc
+from helper import filePermissions, timeNowTZ, updateState, get_setting_value, noti_obj
from api import update_api
from networkscan import process_scan
from initialise import importConfigs
-from database import DB, get_all_devices
+from database import DB
from reporting import get_notifications
-from notifications import Notifications
+from notification import Notification_obj
from plugin import run_plugin_scripts, check_and_run_user_event
@@ -154,16 +154,13 @@ def main ():
notiStructure = get_notifications(db)
# Write the notifications into the DB
- notification = Notifications(db)
+ notification = Notification_obj(db)
+ hasNotification = notification.create(notiStructure.json, notiStructure.text, notiStructure.html, "")
- # mylog('debug', f"[MAIN] notiStructure.text: {notiStructure.text} ")
- # mylog('debug', f"[MAIN] notiStructure.json: {notiStructure.json} ")
- # mylog('debug', f"[MAIN] notiStructure.html: {notiStructure.html} ")
-
- hasNotifications = notification.create(notiStructure.json, notiStructure.text, notiStructure.html, "")
-
- if hasNotifications:
+ # run all enabled publisher gateways
+ if hasNotification:
pluginsState = run_plugin_scripts(db, 'on_notification', pluginsState)
+ notification.setAllProcessed()
# Commit SQL
diff --git a/pialert/appevent.py b/pialert/appevent.py
new file mode 100644
index 00000000..acbbe245
--- /dev/null
+++ b/pialert/appevent.py
@@ -0,0 +1,125 @@
+import datetime
+import json
+import uuid
+
+# PiAlert modules
+import conf
+import const
+from const import pialertPath, logPath, apiPath
+from logger import logResult, mylog, print_log
+from helper import timeNowTZ
+
+#-------------------------------------------------------------------------------
+# Execution object handling
+#-------------------------------------------------------------------------------
+class AppEvent_obj:
+ def __init__(self, db):
+ self.db = db
+
+ # Create AppEvent table if missing
+ self.db.sql.execute("""CREATE TABLE IF NOT EXISTS "AppEvents" (
+ "Index" INTEGER,
+ "GUID" TEXT UNIQUE,
+ "DateTimeCreated" TEXT,
+ "ObjectType" TEXT, -- ObjectType (Plugins, Notifications, Events)
+ "ObjectGUID" TEXT,
+ "ObjectPlugin" TEXT,
+ "ObjectMAC" TEXT,
+ "ObjectIP" TEXT,
+ "ObjectPrimaryID" TEXT,
+ "ObjectSecondaryID" TEXT,
+ "ObjectForeignKey" TEXT,
+ "ObjectIndex" TEXT,
+ "ObjectRowID" TEXT,
+ "ObjectStatusColumn" TEXT, -- Status (Notifications, Plugins), eve_EventType (Events)
+ "ObjectStatus" TEXT, -- new_devices, down_devices, events, new, watched-changed, watched-not-changed, missing-in-last-scan, Device down, New Device, IP Changed, Connected, Disconnected, VOIDED - Disconnected, VOIDED - Connected,