Skip to content

Commit

Permalink
Notification rework v0.2
Browse files Browse the repository at this point in the history
  • Loading branch information
jokob-sk committed Oct 6, 2023
1 parent 2476a36 commit eb7b7b5
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 160 deletions.
23 changes: 20 additions & 3 deletions pialert/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@
import conf
from const import *
from logger import mylog
from helper import filePermissions, timeNowTZ, updateState, get_setting_value
from helper import filePermissions, timeNowTZ, updateState, get_setting_value, noti_struc
from api import update_api
from networkscan import process_scan
from initialise import importConfigs
from database import DB, get_all_devices
from reporting import send_notifications
from reporting import get_notifications
from notifications import Notifications
from plugin import run_plugin_scripts, check_and_run_user_event


Expand Down Expand Up @@ -146,8 +147,24 @@ def main ():
# run all plugins registered to be run when new devices are found
pluginsState = run_plugin_scripts(db, 'on_new_device', pluginsState)

# Notification handling
# ----------------------------------------

# send all configured notifications
send_notifications(db)
notiStructure = get_notifications(db)

# Write the notifications into the DB
notification = Notifications(db)

# 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:
pluginsState = run_plugin_scripts(db, 'on_notification', pluginsState)


# Commit SQL
db.commitDB()
Expand Down
6 changes: 2 additions & 4 deletions pialert/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

# pialert modules
import conf
from const import (apiPath, sql_devices_all, sql_events_pending_alert,
sql_settings, sql_plugins_events, sql_plugins_history, sql_plugins_objects,sql_language_strings)
from const import (apiPath, sql_devices_all, sql_events_pending_alert, sql_settings, sql_plugins_events, sql_plugins_history, sql_plugins_objects,sql_language_strings, sql_notifications_all)
from logger import mylog
from helper import write_file

Expand All @@ -19,8 +18,6 @@ def update_api(db, isNotification = False, updateOnlyDataSources = []):

folder = apiPath

# update notifications moved to reporting send_api()

# Save plugins
write_file(folder + 'plugins.json' , json.dumps({"data" : conf.plugins}))

Expand All @@ -33,6 +30,7 @@ def update_api(db, isNotification = False, updateOnlyDataSources = []):
["plugins_history", sql_plugins_history],
["plugins_objects", sql_plugins_objects],
["plugins_language_strings", sql_language_strings],
["notifications", sql_notifications_all],
["custom_endpoint", conf.API_CUSTOM_SQL],
]

Expand Down
1 change: 1 addition & 0 deletions pialert/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
sql_settings = "SELECT * FROM Settings"
sql_plugins_objects = "SELECT * FROM Plugins_Objects"
sql_language_strings = "SELECT * FROM Plugins_Language_Strings"
sql_notifications_all = "SELECT * FROM Notifications"
sql_plugins_events = "SELECT * FROM Plugins_Events"
sql_plugins_history = "SELECT * FROM Plugins_History ORDER BY DateTimeChanged DESC"
sql_new_devices = """SELECT * FROM (
Expand Down
11 changes: 1 addition & 10 deletions pialert/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,17 +620,8 @@ def __init__(self, jsn, columnNames):

#-------------------------------------------------------------------------------
class noti_struc:
def __init__(self, json, text, html, notificationType):
def __init__(self, json, text, html):
self.json = json
self.text = text
self.html = html

# jsonFile = apiPath + f'/notifications_{notificationType}.json'

# mylog('debug', [f"[Notifications] Writing {jsonFile}"])

# if notificationType != '':

# # Update .json file
# with open(jsonFile, 'w') as jsonFile:
# json.dump(self, jsonFile, cls=NotiStrucEncoder, indent=4)
88 changes: 88 additions & 0 deletions pialert/notifications.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
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

#-------------------------------------------------------------------------------
# Notification object handling
#-------------------------------------------------------------------------------
class Notifications:
def __init__(self, db):
self.db = db

# Create Notifications table if missing
self.db.sql.execute("""CREATE TABLE IF NOT EXISTS "Notifications" (
"Index" INTEGER,
"GUID" TEXT UNIQUE,
"DateTimeCreated" TEXT,
"DateTimePushed" TEXT,
"Status" TEXT,
"JSON" TEXT,
"Text" TEXT,
"HTML" TEXT,
"PublishedVia" TEXT,
"Extra" TEXT,
PRIMARY KEY("Index" AUTOINCREMENT)
);
""")

self.save()

# Create a new DB entry if new notiifcations available, otherwise skip
def create(self, JSON, Text, HTML, Extra=""):

# Check if empty JSON
# _json = json.loads(JSON)
# Check if nothing to report
if JSON["internet"] == [] and JSON["new_devices"] == [] and JSON["down_devices"] == [] and JSON["events"] == [] and JSON["plugins"] == []:
self.HasNotifications = False
# end if nothing to report
return self.HasNotifications

# continue and save into DB if notifications available
self.HasNotifications = True

self.GUID = str(uuid.uuid4())
self.DateTimeCreated = timeNowTZ()
self.DateTimePushed = ""
self.Status = "new"
self.JSON = JSON
self.Text = Text
self.HTML = HTML
self.PublishedVia = ""
self.Extra = Extra

self.upsert()

return self.HasNotifications

# Only updates the status
def updateStatus(self, newStatus):
self.Status = newStatus
self.upsert()

# Updates the Published properties
def updatePublishedVia(self, newPublishedVia):
self.PublishedVia = newPublishedVia
self.DateTimePushed = timeNowTZ()
self.upsert()

# TODO Index vs hash to minimize SQL calls, finish CRUD operations, expose via API, use API in plugins

def upsert(self):
self.db.sql.execute("""
INSERT OR REPLACE INTO Notifications (GUID, DateTimeCreated, DateTimePushed, Status, JSON, Text, HTML, PublishedVia, Extra)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (self.GUID, self.DateTimeCreated, self.DateTimePushed, self.Status, json.dumps(self.JSON), self.Text, self.HTML, self.PublishedVia, self.Extra))

self.save()

def save(self):
# Commit changes
self.db.commitDB()
Loading

0 comments on commit eb7b7b5

Please sign in to comment.