PUSHSAFER + cleanup work⤵

This commit is contained in:
Jokob-sk
2023-10-19 21:59:06 +11:00
parent 346a22f2f6
commit fdd199935a
15 changed files with 461 additions and 78 deletions

View File

@@ -533,15 +533,7 @@
"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 <code>(text was truncated)</code> message is appended.", "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 <code>(text was truncated)</code> message is appended.",
"WEBHOOK_SECRET_name": "HMAC Secret", "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 <code>X-Webhook-Signature</code> header to the request. You can find more informations <a target=\"_blank\" href=\"https://github.com/jokob-sk/Pi.Alert/blob/main/docs/WEBHOOK_SECRET.md\">here</a>.", "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 <code>X-Webhook-Signature</code> header to the request. You can find more informations <a target=\"_blank\" href=\"https://github.com/jokob-sk/Pi.Alert/blob/main/docs/WEBHOOK_SECRET.md\">here</a>.",
"PUSHSAFER_display_name" : "Pushsafer",
"PUSHSAFER_icon" : "<i class=\"fa fa-bell\"></i>",
"REPORT_PUSHSAFER_name" : "Enable Pushsafer",
"REPORT_PUSHSAFER_description" : "Enable sending notifications via <a target=\"_blank\" href=\"https://www.pushsafer.com/\">Pushsafer</a>.",
"PUSHSAFER_TOKEN_name" : "Pushsafer token",
"PUSHSAFER_TOKEN_description" : "Your secret Pushsafer API key (token).",
"MQTT_display_name" : "MQTT",
"MQTT_icon" : "<i class=\"fa fa-square-rss\"></i>",
"REPORT_TITLE" : "Report", "REPORT_TITLE" : "Report",
"REPORT_ERROR" : "The page you are looking for is temporarily unavailable, please try again after a few seconds", "REPORT_ERROR" : "The page you are looking for is temporarily unavailable, please try again after a few seconds",

View File

@@ -14,7 +14,7 @@ sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
import conf import conf
from plugin_helper import Plugin_Objects from plugin_helper import Plugin_Objects
from logger import mylog, append_line_to_file from logger import mylog, append_line_to_file
from helper import timeNowTZ, noti_obj, get_setting_value from helper import timeNowTZ, get_setting_value
from notification import Notification_obj from notification import Notification_obj
from database import DB from database import DB

View File

@@ -22,7 +22,7 @@ sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
import conf import conf
from plugin_helper import Plugin_Objects from plugin_helper import Plugin_Objects
from logger import mylog, append_line_to_file, print_log from logger import mylog, append_line_to_file, print_log
from helper import timeNowTZ, noti_obj, get_setting_value, hide_email from helper import timeNowTZ, get_setting_value, hide_email
from notification import Notification_obj from notification import Notification_obj
from database import DB from database import DB

View File

@@ -1,6 +1,6 @@
## Overview ## Overview
- TBC - Feed your data and device changes into [Home Assistant](https://github.com/jokob-sk/Pi.Alert/blob/main/docs/HOME_ASSISTANT.md) via the MQTT Mosquito broker.
### Usage ### Usage

View File

@@ -22,7 +22,7 @@ from const import apiPath
from plugin_utils import getPluginObject from plugin_utils import getPluginObject
from plugin_helper import Plugin_Objects from plugin_helper import Plugin_Objects
from logger import mylog, append_line_to_file from logger import mylog, append_line_to_file
from helper import timeNowTZ, noti_obj, get_setting_value, bytes_to_string, sanitize_string from helper import timeNowTZ, get_setting_value, bytes_to_string, sanitize_string
from notification import Notification_obj from notification import Notification_obj
from database import DB, get_all_devices, get_device_stats from database import DB, get_all_devices, get_device_stats

View File

@@ -1,6 +1,6 @@
## Overview ## Overview
- TBC A plugin to publish a notification via the NTFY gateway. Enable sending notifications via <a target="_blank" href="https://ntfy.sh/">NTFY</a>. Supports authentication.
### Usage ### Usage

View File

@@ -17,7 +17,7 @@ sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
import conf import conf
from plugin_helper import Plugin_Objects, handleEmpty from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, append_line_to_file from logger import mylog, append_line_to_file
from helper import timeNowTZ, noti_obj, get_setting_value from helper import timeNowTZ, get_setting_value
from notification import Notification_obj from notification import Notification_obj
from database import DB from database import DB

View File

@@ -0,0 +1,8 @@
## Overview
A plugin to publish a notification via the Pushsafer gateway. Enable sending notifications via <a target="_blank" href="https://www.pushsafer.com/">Pushsafer</a>.
### Usage
- Go to settings and fill in relevant details.

View File

@@ -0,0 +1,316 @@
{
"code_name": "_publisher_pushsafer",
"unique_prefix": "PUSHSAFER",
"plugin_type": "publisher",
"enabled": true,
"data_source": "script",
"show_ui": true,
"localized": ["display_name", "description", "icon"],
"display_name" : [
{
"language_code": "en_us",
"string" : "Pushsafer publisher"
},
{
"language_code": "es_es",
"string" : "Habilitar Pushsafer"
}
],
"icon":[{
"language_code": "en_us",
"string" : "<i class=\"fa-solid fa-bell\"></i>"
}],
"description": [
{
"language_code": "en_us",
"string" : "A plugin to publish a notification via the Pushsafer gateway."
}
],
"params" : [
],
"database_column_definitions":
[
{
"column": "Index",
"css_classes": "col-sm-2",
"show": false,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "N/A"
},
{
"language_code": "es_es",
"string" : "N/A"
}]
},
{
"column": "Plugin",
"css_classes": "col-sm-2",
"show": false,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "N/A"
},
{
"language_code": "es_es",
"string" : "N/A"
}]
},
{
"column": "Object_PrimaryID",
"css_classes": "col-sm-2",
"show": false,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "N/A"
}]
},
{
"column": "Object_SecondaryID",
"css_classes": "col-sm-2",
"show": true,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Sent when"
}]
},
{
"column": "Watched_Value1",
"css_classes": "col-sm-3",
"show": true,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Notification GUID"
}]
},
{
"column": "Watched_Value2",
"css_classes": "col-sm-2",
"show": true,
"type": "textarea_readonly",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Response"
}]
},
{
"column": "Watched_Value3",
"css_classes": "col-sm-2",
"show": true,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Response code"
}]
},
{
"column": "Watched_Value4",
"css_classes": "col-sm-2",
"show": false,
"type": "device_mac",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Device"
}
]
},
{
"column": "UserData",
"css_classes": "col-sm-2",
"show": false,
"type": "textbox_save",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Comments"
},
{
"language_code": "es_es",
"string" : "Comentarios"
}]
},
{
"column": "Status",
"css_classes": "col-sm-1",
"show": false,
"type": "replace",
"default_value":"",
"options": [
{
"equals": "watched-not-changed",
"replacement": "<div style='text-align:center'><i class='fa-solid fa-square-check'></i><div></div>"
},
{
"equals": "watched-changed",
"replacement": "<div style='text-align:center'><i class='fa-solid fa-triangle-exclamation'></i></div>"
},
{
"equals": "new",
"replacement": "<div style='text-align:center'><i class='fa-solid fa-circle-plus'></i></div>"
},
{
"equals": "missing-in-last-scan",
"replacement": "<div style='text-align:center'><i class='fa-solid fa-question'></i></div>"
}
],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Status"
},
{
"language_code": "es_es",
"string" : "Estado"
}]
},
{
"column": "Extra",
"css_classes": "col-sm-3",
"show": false,
"type": "label",
"default_value":"",
"options": [],
"localized": ["name"],
"name":[{
"language_code": "en_us",
"string" : "Extra"
},
{
"language_code": "es_es",
"string" : "Extra"
}]
}
],
"settings":[
{
"function": "RUN",
"events": ["test"],
"type": "text.select",
"default_value":"disabled",
"options": ["disabled", "on_notification" ],
"localized": ["name", "description"],
"name" :[{
"language_code": "en_us",
"string" : "When to run"
},
{
"language_code": "es_es",
"string" : "Cuando ejecuta"
}],
"description": [
{
"language_code": "en_us",
"string" : "Enable sending notifications via <a target=\"_blank\" href=\"https://www.pushsafer.com/\">Pushsafer</a>."
},
{
"language_code": "es_es",
"string" : "Habilitar el envío de notificaciones a través de <a target=\"_blank\" href=\"https://www.pushsafer.com/\">Pushsafer</a>."
}
]
},
{
"function": "CMD",
"type": "readonly",
"default_value":"python3 /home/pi/pialert/front/plugins/_publisher_pushsafer/pushsafer.py",
"options": [],
"localized": ["name", "description"],
"name" : [{
"language_code": "en_us",
"string" : "Command"
},
{
"language_code": "es_es",
"string" : "Comando"
}],
"description": [{
"language_code": "en_us",
"string" : "Command to run"
},
{
"language_code": "es_es",
"string" : "Comando a ejecutar"
}]
},
{
"function": "RUN_TIMEOUT",
"type": "integer",
"default_value": 10,
"options": [],
"localized": ["name", "description"],
"name" : [{
"language_code": "en_us",
"string" : "Run timeout"
},
{
"language_code": "es_es",
"string" : "Tiempo de espera de ejecución"
},
{
"language_code": "de_de",
"string" : "Wartezeit"
}],
"description": [{
"language_code": "en_us",
"string" : "Maximum time in seconds to wait for the script to finish. If this time is exceeded the script is aborted."
},
{
"language_code": "es_es",
"string" : "Tiempo máximo en segundos para esperar a que finalice el script. Si se supera este tiempo, el script se cancela."
}]
},
{
"function": "TOKEN",
"type": "text",
"default_value": "ApiKey",
"options": [],
"localized": ["name", "description"],
"name" : [{
"language_code": "en_us",
"string" : "Pushsafer token"
},
{
"language_code": "es_es",
"string" : "Token de Pushsafer"
}],
"description": [{
"language_code": "en_us",
"string" : "Your secret Pushsafer API key (token)."
},
{
"language_code": "es_es",
"string" : "Su clave secreta de la API de Pushsafer (token)."
}]
}
]
}

View File

@@ -1 +0,0 @@
This plugin will not be loaded

View File

@@ -0,0 +1,128 @@
#!/usr/bin/env python
import json
import subprocess
import argparse
import os
import pathlib
import sys
import requests
from datetime import datetime
from base64 import b64encode
# Replace these paths with the actual paths to your Pi.Alert directories
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
import conf
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, append_line_to_file
from helper import timeNowTZ, get_setting_value
from notification import Notification_obj
from database import DB
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
pluginName = 'PUSHSAFER'
def main():
mylog('verbose', [f'[{pluginName}](publisher) In script'])
# Check if basic config settings supplied
if check_config() == False:
mylog('none', [f'[{pluginName}] Error: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
return
# Create a database connection
db = DB() # instance of class DB
db.open()
# Initialize the Plugin obj output file
plugin_objects = Plugin_Objects(RESULT_FILE)
# Create a Notification_obj instance
notifications = Notification_obj(db)
# Retrieve new notifications
new_notifications = notifications.getNew()
# Process the new notifications
for notification in new_notifications:
# Send notification
response_text, response_status_code = send(notification["HTML"], notification["Text"])
# Log result
plugin_objects.add_object(
primaryId = pluginName,
secondaryId = timeNowTZ(),
watched1 = notification["GUID"],
watched2 = handleEmpty(response_text),
watched3 = response_status_code,
watched4 = 'null',
extra = 'null',
foreignKey = notification["GUID"]
)
plugin_objects.write_result_file()
#-------------------------------------------------------------------------------
def send(text):
response_text = ''
response_status_code = ''
try:
url = 'https://www.pushsafer.com/api'
post_fields = {
"t" : 'Pi.Alert Message',
"m" : text,
"s" : 11,
"v" : 3,
"i" : 148,
"c" : '#ef7f7f',
"d" : 'a',
"u" : get_setting_value('REPORT_DASHBOARD_URL'),
"ut" : 'Open Pi.Alert',
"k" : get_setting_value('PUSHSAFER_TOKEN'),
}
response = requests.post(url, data=post_fields)
response_status_code = response.status_code
# Check if the request was successful (status code 200)
if response_status_code == 200:
response_text = response.text # This captures the response body/message
else:
response_text = json.dumps(response.text)
except requests.exceptions.RequestException as e:
mylog('none', [f'[{pluginName}] Error: ', e])
response_text = e
return response_text, response_status_code
return response_text, response_status_code
#-------------------------------------------------------------------------------
def check_config():
if get_setting_value('PUSHSAFER_TOKEN') == 'ApiKey':
return False
else:
return True
# -------------------------------------------------------
if __name__ == '__main__':
sys.exit(main())

View File

@@ -24,7 +24,7 @@ import multiprocessing
import conf import conf
from const import * from const import *
from logger import mylog from logger import mylog
from helper import filePermissions, timeNowTZ, updateState, get_setting_value, noti_obj from helper import filePermissions, timeNowTZ, updateState, get_setting_value
from api import update_api from api import update_api
from networkscan import process_scan from networkscan import process_scan
from initialise import importConfigs from initialise import importConfigs

View File

@@ -128,10 +128,6 @@ def importConfigs (db):
conf.WEBHOOK_SIZE = ccd('WEBHOOK_SIZE', 1024 , c_d, 'Payload size', 'integer', '', 'Webhooks') conf.WEBHOOK_SIZE = ccd('WEBHOOK_SIZE', 1024 , c_d, 'Payload size', 'integer', '', 'Webhooks')
conf.WEBHOOK_SECRET = ccd('WEBHOOK_SECRET', '' , c_d, 'Secret', 'text', '', 'Webhooks') conf.WEBHOOK_SECRET = ccd('WEBHOOK_SECRET', '' , c_d, 'Secret', 'text', '', 'Webhooks')
# PUSHSAFER
conf.REPORT_PUSHSAFER = ccd('REPORT_PUSHSAFER', False , c_d, 'Enable PUSHSAFER', 'boolean', '', 'PUSHSAFER', ['test'])
conf.PUSHSAFER_TOKEN = ccd('PUSHSAFER_TOKEN', 'ApiKey' , c_d, 'PUSHSAFER token', 'text', '', 'PUSHSAFER')
# Init timezone in case it changed # Init timezone in case it changed
conf.tz = timezone(conf.TIMEZONE) conf.tz = timezone(conf.TIMEZONE)

View File

@@ -1,33 +0,0 @@
import requests
import conf
from helper import noti_obj
from logger import mylog
#-------------------------------------------------------------------------------
def check_config():
if conf.PUSHSAFER_TOKEN == 'ApiKey':
mylog('none', ['[Check Config] Error: Pushsafer service not set up correctly. Check your pialert.conf PUSHSAFER_TOKEN variable.'])
return False
else:
return True
#-------------------------------------------------------------------------------
def send ( msg:noti_obj ):
_Text = msg.text
url = 'https://www.pushsafer.com/api'
post_fields = {
"t" : 'Pi.Alert Message',
"m" : _Text,
"s" : 11,
"v" : 3,
"i" : 148,
"c" : '#ef7f7f',
"d" : 'a',
"u" : conf.REPORT_DASHBOARD_URL,
"ut" : 'Open Pi.Alert',
"k" : conf.PUSHSAFER_TOKEN,
}
requests.post(url, data=post_fields)

View File

@@ -258,15 +258,6 @@ def get_notifications (db):
return noti_obj(final_json, final_text, final_html) return noti_obj(final_json, final_text, final_html)
# if conf.REPORT_MAIL and check_config('email'):
# updateState("Send: Email")
# mylog('minimal', ['[Notification] Sending report by Email'])
# send_email (msg )
# else :
# mylog('verbose', ['[Notification] Skip email'])
#
# if conf.REPORT_WEBHOOK and check_config('webhook'): # if conf.REPORT_WEBHOOK and check_config('webhook'):
# updateState("Send: Webhook") # updateState("Send: Webhook")
@@ -274,27 +265,13 @@ def get_notifications (db):
# send_webhook (msg) # send_webhook (msg)
# else : # else :
# mylog('verbose', ['[Notification] Skip webhook']) # mylog('verbose', ['[Notification] Skip webhook'])
# if conf.REPORT_NTFY and check_config('ntfy'):
# updateState("Send: NTFY")
# mylog('minimal', ['[Notification] Sending report by NTFY'])
# send_ntfy (msg)
# else :
# mylog('verbose', ['[Notification] Skip NTFY'])
# if conf.REPORT_PUSHSAFER and check_config('pushsafer'): # if conf.REPORT_PUSHSAFER and check_config('pushsafer'):
# updateState("Send: PUSHSAFER") # updateState("Send: PUSHSAFER")
# mylog('minimal', ['[Notification] Sending report by PUSHSAFER']) # mylog('minimal', ['[Notification] Sending report by PUSHSAFER'])
# send_pushsafer (msg) # send_pushsafer (msg)
# else : # else :
# mylog('verbose', ['[Notification] Skip PUSHSAFER']) # mylog('verbose', ['[Notification] Skip PUSHSAFER'])
# # Update MQTT entities
# if conf.REPORT_MQTT and check_config('mqtt'):
# updateState("Send: MQTT")
# mylog('minimal', ['[Notification] Establishing MQTT thread'])
# mqtt_start(db)
# else :
# mylog('verbose', ['[Notification] Skip MQTT'])
# else :
# mylog('verbose', ['[Notification] No changes to report'])
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------