front end trigger for backend jobs framework

This commit is contained in:
Jokob-sk
2023-01-08 18:31:47 +11:00
parent 8783b89f21
commit 098b87d09e
8 changed files with 147 additions and 21 deletions

View File

@@ -42,10 +42,8 @@ from pytz import timezone
#===============================================================================
# PATHS
#===============================================================================
PIALERT_BACK_PATH = os.path.dirname(os.path.abspath(__file__))
pialertPath = PIALERT_BACK_PATH + "/.." #to fix - remove references and use pialertPath instead
logPath = pialertPath + '/front/log'
pialertPath = '/home/pi/pialert'
logPath = pialertPath + '/front/log'
confPath = "/config/pialert.conf"
dbPath = '/db/pialert.db'
fullConfPath = pialertPath + confPath
@@ -451,6 +449,9 @@ def main ():
# re-load user configuration
importConfig()
# check if there is a front end initiated event which needs to be executed
check_and_run_event()
# proceed if 1 minute passed
if last_run + datetime.timedelta(minutes=1) < time_started :
@@ -798,8 +799,7 @@ def update_devices_MAC_vendors (pArg = ''):
# Update vendors DB (iab oui)
file_print(' Updating vendors DB (iab & oui)')
# update_args = ['sh', PIALERT_BACK_PATH + '/update_vendors.sh', ' > ', logPath + '/update_vendors.log', '2>&1']
update_args = ['sh', PIALERT_BACK_PATH + '/update_vendors.sh', pArg]
update_args = ['sh', pialertPath + '/update_vendors.sh', pArg]
try:
# try runnning a subprocess
@@ -808,10 +808,6 @@ def update_devices_MAC_vendors (pArg = ''):
# An error occured, handle it
file_print(e.output)
# DEBUG
# update_args = ['./vendors_db_update.sh']
# subprocess.call (update_args, shell=True)
# Initialize variables
recordsToUpdate = []
ignored = 0
@@ -1597,7 +1593,7 @@ def performNmapScan(devicesToScan):
# prepare arguments from user supplied ones
nmapArgs = ['nmap'] + NMAP_ARGS.split() + [device["dev_LastIP"]]
progress = ' (' + str(devIndex) + '/' + str(devTotal) + ')'
progress = ' (' + str(devIndex+1) + '/' + str(devTotal) + ')'
try:
# try runnning a subprocess with a forced (timeout + 30 seconds) in case the subprocess hangs
@@ -2016,14 +2012,14 @@ def send_notifications ():
)""")
# Open text Template
template_file = open(PIALERT_BACK_PATH + '/report_template.txt', 'r')
template_file = open(pialertPath + '/back/report_template.txt', 'r')
mail_text = template_file.read()
template_file.close()
# Open html Template
template_file = open(PIALERT_BACK_PATH + '/report_template.html', 'r')
template_file = open(pialertPath + '/back/report_template.html', 'r')
if isNewVersion():
template_file = open(PIALERT_BACK_PATH + '/report_template_new_version.html', 'r')
template_file = open(pialertPath + '/back/report_template_new_version.html', 'r')
mail_html = template_file.read()
template_file.close()
@@ -2191,7 +2187,7 @@ def send_notifications ():
file_print(' Sending report by Email')
send_email (mail_text, mail_html)
else :
file_print(' Skip mail')
file_print(' Skip email')
if REPORT_APPRISE and check_config('apprise'):
updateState("Send: Apprise")
file_print(' Sending report by Apprise')
@@ -2770,7 +2766,8 @@ def upgradeDB ():
('Front_Details_Tab', 'tabDetails'),
('Back_Settings_Imported', round(time.time() * 1000)),
('Back_App_State', 'Initializing'),
('Back_New_Version_Available', False)
('Back_New_Version_Available', False),
('Front_Event', 'none')
]
sql.executemany ("""INSERT INTO Parameters ("par_ID", "par_Value") VALUES (?, ?)""", params)
@@ -3020,6 +3017,48 @@ def hide_email(email):
return email
#-------------------------------------------------------------------------------
def check_and_run_event():
sql.execute(""" select * from Parameters where par_ID = "Front_Event" """)
rows = sql.fetchall()
event, param = ['','']
if len(rows) > 0 and rows[0]['par_Value'] != 'none':
event = rows[0]['par_Value'].split('|')[0]
param = rows[0]['par_Value'].split('|')[1]
else:
return
if event == 'test':
handle_test(param)
# clear event execution flag
sql.execute ("UPDATE Parameters SET par_Value='none' WHERE par_ID='Front_Event'")
# commit to DB
commitDB ()
#-------------------------------------------------------------------------------
def handle_test(testType):
if testType == 'REPORT_MAIL':
test_email()
#-------------------------------------------------------------------------------
def test_email():
# Open text Template
template_file = open(pialertPath + '/back/report_sample_1.txt', 'r')
mail_text_txt = template_file.read()
template_file.close()
# Open html Template
template_file = open(pialertPath + '/back/report_sample_2.html', 'r')
mail_text_html = template_file.read()
template_file.close()
send_email(mail_text_txt, mail_text_html)
#-------------------------------------------------------------------------------
def isNewVersion():
global newVersionAvailable

50
back/report_sample_1.txt Normal file
View File

@@ -0,0 +1,50 @@
Report Date: 2021-12-08 12:30
Server: Synology-NAS
New Devices
----------------------
Name: (name not found)
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.121
Time: 2021-12-08 12:30
More Info: Micro-Star INTL CO., LTD.
Name: (name not found)
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.151
Time: 2021-12-08 12:30
More Info: Espressif Inc.
Events
----------------------
Name: Samsung
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.27
Time: 2021-12-08 12:30
Event: Connected
More Info:
Name: (name not found)
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.6
Time: 2021-12-08 12:30
Event: Disconnected
More Info:
Name: Google-Home-Mini
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.16
Time: 2021-12-08 12:30
Event: Disconnected
More Info:
Name: (name not found)
MAC: 2c:2c:2c:2c:2c:2c
IP: 192.168.1.119
Time: 2021-12-08 12:30
Event: Disconnected
More Info:

View File

@@ -2,7 +2,7 @@
![n8n workflow](https://i.imgur.com/2EGrQjt.png)
### Specify your email template
See [sample JSON](https://github.com/jokob-sk/Pi.Alert/blob/main/docs/webhook_json_sample.json) if you want to see the JSON paths used in the email template below
See [sample JSON](https://github.com/jokob-sk/Pi.Alert/blob/main/back/webhook_json_sample.json) if you want to see the JSON paths used in the email template below
![Email template](https://i.imgur.com/kcVjGm1.png)
### Get your webhook in n8n

View File

@@ -692,6 +692,13 @@ height: 50px;
}
.settings-expand-icon {
font-size: medium;
/* background-color: #272c30; */
margin: 10px;
}
.settings_content input[type=checkbox]
{
width: auto
@@ -712,3 +719,8 @@ height: 50px;
left: 0px;
font-size: large;
}
.pointer
{
cursor:pointer;
}

View File

@@ -500,7 +500,7 @@ the arp-scan will take hours to complete instead of seconds.
'WEBHOOK_URL_name' => 'Target URL',
'WEBHOOK_URL_description' => 'Target URL starting with <code>http://</code> or <code>https://</code>.',
'WEBHOOK_PAYLOAD_name' => 'Payload type',
'WEBHOOK_PAYLOAD_description' => 'The Webhook payload data format for the <code>body</code> > <code>attachments</code> > <code>text</code> attribute in the payload json. See an example of the payload <a target="_blank" href="https://github.com/jokob-sk/Pi.Alert/blob/main/docs/webhook_json_sample.json">here</a>. (e.g.: for discord use <code>html</code>)',
'WEBHOOK_PAYLOAD_description' => 'The Webhook payload data format for the <code>body</code> > <code>attachments</code> > <code>text</code> attribute in the payload json. See an example of the payload <a target="_blank" href="https://github.com/jokob-sk/Pi.Alert/blob/main/back/webhook_json_sample.json">here</a>. (e.g.: for discord use <code>html</code>)',
'WEBHOOK_REQUEST_METHOD_name' => 'Request method',
'WEBHOOK_REQUEST_METHOD_description' => 'The HTTP request method to be used for the webhook call.',

View File

@@ -53,7 +53,7 @@ CommitDB();
<?php echo lang('Navigation_Settings');?>
<a style="cursor:pointer">
<span>
<i id='toggleSettings' onclick="toggleAllSettings()" class="fa fa-angle-double-down"></i>
<i id='toggleSettings' onclick="toggleAllSettings()" class="settings-expand-icon fa fa-angle-double-down"></i>
</span>
</a>
</h1>
@@ -239,10 +239,16 @@ CommitDB();
$eventsList = createArray($set['Events']);
$iconMap = [
"test" => ["To test this configuration you have to save it at first.","fa-vial-circle-check"]
];
if(count($eventsList) > 0)
{
foreach ($eventsList as $event) {
$eventsHtml = $eventsHtml.'<span class="input-group-addon"><i class="fa fa-vial-circle-check" data-toggle="'.$event.'"></i></span>';
$eventsHtml = $eventsHtml.'<span class="input-group-addon">
<i title="'.$iconMap[$event][0].'" class="fa '.$iconMap[$event][1].' pointer" data-myparam="'.$set['Code_Name'].'" data-myevent="'.$event.'"></i>
</span>';
}
}
@@ -444,11 +450,30 @@ CommitDB();
}
</script>
<script defer>
// -----------------------------------------------------------------------------
// handling events on the backend initiated by the front end START
// -----------------------------------------------------------------------------
$(window).on('load', function() {
$('i[data-myevent]').each(function(index, element){
$(element).attr('onclick',
'handleEvent(\"' + $(element).attr('data-myevent') + '|'+ $(element).attr('data-myparam') + '\")'
);
});
});
function handleEvent (value){
setParameter ('Front_Event', value)
}
// -----------------------------------------------------------------------------
// handling events on the backend initiated by the front end END
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
// Show last time settings have been imported
getParam("lastImportedTime", "Back_Settings_Imported", skipCache = true);