Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test notification using same code base #174

Closed
wants to merge 49 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
88f0d14
Added link to Wiki in notification
Emmo213 Aug 5, 2024
6c6176e
Clean up
Emmo213 Aug 5, 2024
6655682
Same outcome, different code
Emmo213 Aug 6, 2024
cdf28e3
Same outcome, different code
Emmo213 Aug 6, 2024
20ba65c
Base64 encode the Apprise title and body when submitting the form
Emmo213 Aug 7, 2024
b1fffdc
Checkpoint
Emmo213 Aug 7, 2024
0c5b28e
Cleanup
Emmo213 Aug 7, 2024
d7ea9ba
Cleanup
Emmo213 Aug 7, 2024
33de25d
Linter fixes
Emmo213 Aug 7, 2024
8ab18a7
Use new title or body when sending test notification
Emmo213 Aug 7, 2024
5540dfc
Cleanup
Emmo213 Aug 7, 2024
b6e28d7
Typo
Emmo213 Aug 7, 2024
26dc6ea
Cleanup
Emmo213 Aug 8, 2024
9c4b741
Merge pull request #1 from Emmo213/feat_165_wiki_link_in_notification
Emmo213 Aug 15, 2024
c95c0ff
Changed from Nachtzuster to Emmo213
Emmo213 Aug 15, 2024
c444786
Update README
Emmo213 Aug 15, 2024
eb94ca5
Merge pull request #4 from Emmo213/update_to_emmo213_repo
Emmo213 Aug 15, 2024
34f2708
Merge pull request #2 from Emmo213/issue_33_apprise_linebreak
Emmo213 Aug 15, 2024
ed3cc32
Removed code from other branches
Emmo213 Aug 15, 2024
9a6fdea
Cleanup
Emmo213 Aug 15, 2024
3a17a75
Merge branch 'main' into notification_enhancements
Emmo213 Aug 15, 2024
8175e7e
Merge pull request #3 from Emmo213/notification_enhancements
Emmo213 Aug 15, 2024
4c16981
Also use the test configurations
Emmo213 Aug 15, 2024
fa442a1
Merge branch 'notification_enhancements' of https://github.com/Emmo21…
Emmo213 Aug 15, 2024
3b4c086
Merge pull request #5 from Emmo213/notification_enhancements
Emmo213 Aug 15, 2024
09c5cc5
Backleveled
Emmo213 Aug 15, 2024
dc44af2
Backleveled
Emmo213 Aug 15, 2024
1ed827e
Cleanup
Emmo213 Aug 15, 2024
1d98b05
Update Apprise version to 1.8.1
Emmo213 Aug 15, 2024
889bed8
Update Apprise version to 1.8.1
Emmo213 Aug 15, 2024
fc82ed3
Merge branch 'Nachtzuster:main' into main
Emmo213 Aug 19, 2024
907eaa6
Merge branch 'Nachtzuster:main' into main
Emmo213 Aug 25, 2024
408e775
Changed to use a separate file to launch notification
Emmo213 Sep 17, 2024
e27271d
Merge branch 'notification_enhancements' of https://github.com/Emmo21…
Emmo213 Sep 17, 2024
1ebf7c5
Corrected directory
Emmo213 Sep 17, 2024
8eb4319
Removed unneeded files
Emmo213 Sep 17, 2024
1ee6ab3
Cleanup
Emmo213 Sep 17, 2024
2d938f8
Cleanup
Emmo213 Sep 17, 2024
eab5bd2
Cleanup
Emmo213 Sep 17, 2024
594a3b3
Cleanup
Emmo213 Sep 17, 2024
329ec3f
Linter cleanup
Emmo213 Sep 17, 2024
9de76ef
Will change this in another PR
Emmo213 Sep 18, 2024
408a2fa
Ignore all local databases
Emmo213 Sep 18, 2024
2932748
Merge branch 'Nachtzuster:main' into main
Emmo213 Sep 18, 2024
d75face
Fixed broken link
Emmo213 Sep 18, 2024
691560e
Cleanup
Emmo213 Sep 18, 2024
31123d8
Merge pull request #6 from Emmo213/readme_fix
Emmo213 Sep 18, 2024
de915e0
Merge pull request #7 from Emmo213/main
Emmo213 Sep 24, 2024
749ee3a
Update README.md
Emmo213 Sep 24, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pandas
seaborn
streamlit==1.31.0
plotly
apprise==1.8.0
apprise==1.8.1
paho-mqtt<2.0.0
pytest==7.1.2
scikit-learn
Expand Down
75 changes: 12 additions & 63 deletions scripts/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,13 @@ function syslog_shell_exec($cmd, $sudo_user = null) {
$timezone = $_GET["timezone"];
$model = $_GET["model"];
$sf_thresh = $_GET["sf_thresh"];

if(isset($_GET['data_model_version'])) {
$data_model_version = 2;
} else {
$data_model_version = 1;
}

$only_notify_species_names = $_GET['only_notify_species_names'];
$only_notify_species_names_2 = $_GET['only_notify_species_names_2'];

Expand Down Expand Up @@ -130,6 +132,7 @@ function() {
sleep(3);
}
}

if ($model != $config['MODEL'] || $language != $config['DATABASE_LANG']){
if(strlen($language) == 2){

Expand Down Expand Up @@ -211,73 +214,18 @@ function() {
$filename = $todaytable['File_Name'];
$date = $todaytable['Date'];
$time = $todaytable['Time'];
$week = $todaytable['Week'];
$latitude = $todaytable['Lat'];
$longitude = $todaytable['Lon'];
$cutoff = $todaytable['Cutoff'];
$sens = $todaytable['Sens'];
$overlap = $todaytable['Overlap'];
}

$title = $_GET['apprise_notification_title'];
$body = $_GET['apprise_notification_body'];

if($config["BIRDNETPI_URL"] != "") {
$filename = $config["BIRDNETPI_URL"]."?filename=".$filename;
} else{
$filename = "http://".$_SERVER['SERVER_NAME']."/"."?filename=".$filename;
}

$friendlyfilename = "[Listen here](".$filename.")";
$title = base64_encode($_GET['apprise_notification_title']);
$body = base64_encode($_GET['apprise_notification_body']);
$command = "sudo -u $user ".$home."/BirdNET-Pi/birdnet/bin/python3 ".$home."/BirdNET-Pi/scripts/test_notification.py --confidence $confidence --name '".$sciname."_".$comname."' --filename $filename --date $date-birdnet-$time --body $body --title $title 2>&1 1>\dev\null";

$attach="";
$exampleimage = "https://live.staticflickr.com/7430/27545810581_8bfa8289a3_c.jpg";
if (strpos($body, '$flickrimage') !== false) {
$attach = "--attach ".$exampleimage;
}
if (strpos($body, '{') === false) {
$exampleimage = "";
}
$apprise_test_config = fopen($home."/BirdNET-Pi/apprise_test.txt", "w") or die("Unable to open file!");
fwrite($apprise_test_config, $_GET['apprise_config']);
fclose($apprise_test_config);

$title = str_replace("\$sciname", $sciname, $title);
$title = str_replace("\$comname", $comname, $title);
$title = str_replace("\$confidencepct", round($confidence*100), $title);
$title = str_replace("\$confidence", $confidence, $title);
$title = str_replace("\$listenurl", $filename, $title);
$title = str_replace("\$friendlyurl", $friendlyfilename, $title);
$title = str_replace("\$date", $date, $title);
$title = str_replace("\$time", $time, $title);
$title = str_replace("\$week", $week, $title);
$title = str_replace("\$latitude", $latitude, $title);
$title = str_replace("\$longitude", $longitude, $title);
$title = str_replace("\$cutoff", $cutoff, $title);
$title = str_replace("\$sens", $sens, $title);
$title = str_replace("\$overlap", $overlap, $title);
$title = str_replace("\$flickrimage", $exampleimage, $title);
$title = str_replace("\$reason", 'Test message', $title);

$body = str_replace("\$sciname", $sciname, $body);
$body = str_replace("\$comname", $comname, $body);
$body = str_replace("\$confidencepct", round($confidence*100), $body);
$body = str_replace("\$confidence", $confidence, $body);
$body = str_replace("\$listenurl", $filename, $body);
$body = str_replace("\$friendlyurl", $friendlyfilename, $body);
$body = str_replace("\$date", $date, $body);
$body = str_replace("\$time", $time, $body);
$body = str_replace("\$week", $week, $body);
$body = str_replace("\$latitude", $latitude, $body);
$body = str_replace("\$longitude", $longitude, $body);
$body = str_replace("\$cutoff", $cutoff, $body);
$body = str_replace("\$sens", $sens, $body);
$body = str_replace("\$overlap", $overlap, $body);
$body = str_replace("\$flickrimage", $exampleimage, $body);
$body = str_replace("\$reason", 'Test message', $body);

$temp = tmpfile();
$tpath = stream_get_meta_data($temp)['uri'];
fwrite($temp, $body);
echo "<pre class=\"bash\">".shell_exec($home."/BirdNET-Pi/birdnet/bin/apprise -vv --plugin-path ".$home."/.apprise/plugins "." -t '".escapeshellcmd($title)."' ".$attach." ".$cf." <".$tpath)."</pre>";
fclose($temp);
$output = shell_exec($command);
#echo $output;

die();
}
Expand All @@ -304,6 +252,7 @@ function() {
}
});
}, false);

function sendTestNotification(e) {
document.getElementById("testsuccessmsg").innerHTML = "";
e.classList.add("disabled");
Expand Down
37 changes: 37 additions & 0 deletions scripts/test_notification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import argparse
import base64

from utils.helpers import Detection, ParseFileName
from utils.reporting import apprise


if __name__ == '__main__':

# Parse arguments
parser = argparse.ArgumentParser(
description='Not to be used outside of the BirdNET-Pi application. Used to send a test message through the Apprise notification system.'
)

parser.add_argument('--confidence', required=True)
parser.add_argument('--name', required=True)
parser.add_argument('--filename', required=True)
parser.add_argument('--date', required=True)
parser.add_argument('--title', required=True)
parser.add_argument('--body', required=False)

args = parser.parse_args()
# print(args);

# create fake detection
detections = []
detection = Detection("1.0", "3.0", args.name, args.confidence)
detection.file_name_extr = args.filename
detections.append(detection)

# create fake file
file = ParseFileName(args.date)

# send test notification
title = base64.b64decode(args.title).decode("utf-8")
body = base64.b64decode(args.body).decode("utf-8")
apprise(file, detections, title=title, body=body)
33 changes: 28 additions & 5 deletions scripts/utils/notifications.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import apprise
import html
import os
import requests
import socket
import sqlite3
from datetime import datetime
import requests
import html
import time as timeim

from datetime import datetime

userDir = os.path.expanduser('~')
APPRISE_CONFIG = userDir + '/BirdNET-Pi/apprise.txt'
APPRISE_CONFIG_TEST = userDir + '/BirdNET-Pi/apprise_test.txt'
DB_PATH = userDir + '/BirdNET-Pi/scripts/birds.db'

flickr_images = {}
Expand Down Expand Up @@ -42,7 +44,7 @@ def notify(body, title, attached=""):

def sendAppriseNotifications(species, confidence, confidencepct, path,
date, time, week, latitude, longitude, cutoff,
sens, overlap, settings_dict, db_path=DB_PATH):
sens, overlap, settings_dict, db_path=DB_PATH, test_msg=False):
def render_template(template, reason=""):
ret = template.replace("$sciname", sciName) \
.replace("$comname", comName) \
Expand All @@ -63,10 +65,13 @@ def render_template(template, reason=""):
return ret
# print(sendAppriseNotifications)
# print(settings_dict)
if os.path.exists(APPRISE_CONFIG) and os.path.getsize(APPRISE_CONFIG) > 0:

if (os.path.exists(APPRISE_CONFIG) and os.path.getsize(APPRISE_CONFIG) > 0) or \
(os.path.exists(APPRISE_CONFIG_TEST) and os.path.getsize(APPRISE_CONFIG_TEST)) > 0:

title = html.unescape(settings_dict.get('APPRISE_NOTIFICATION_TITLE'))
body = html.unescape(settings_dict.get('APPRISE_NOTIFICATION_BODY'))

sciName, comName = species.split("_")

APPRISE_ONLY_NOTIFY_SPECIES_NAMES = settings_dict.get('APPRISE_ONLY_NOTIFY_SPECIES_NAMES')
Expand Down Expand Up @@ -121,6 +126,24 @@ def render_template(template, reason=""):
else:
image_url = flickr_images[comName]

if test_msg:
apobj.clear()
config.clear()
config.add(APPRISE_CONFIG_TEST)
apobj.add(config)

notify_body = render_template(body, "Test message")
notify_title = render_template(title, "Test message")
notify(notify_body, notify_title, image_url)

apobj.clear()
config.clear()
config.add(APPRISE_CONFIG)
apobj.add(config)

os.remove(APPRISE_CONFIG_TEST)
return

if settings_dict.get('APPRISE_NOTIFY_EACH_DETECTION') == "1":
notify_body = render_template(body, "detection")
notify_title = render_template(title, "detection")
Expand Down
9 changes: 7 additions & 2 deletions scripts/utils/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,18 +139,23 @@ def write_to_json_file(file: ParseFileName, detections: [Detection]):
log.debug(f'DONE! WROTE {len(detections)} RESULTS.')


def apprise(file: ParseFileName, detections: [Detection]):
def apprise(file: ParseFileName, detections: [Detection], title="", body=""):
species_apprised_this_run = []
conf = get_settings()

if title:
conf['APPRISE_NOTIFICATION_TITLE'] = title
if body:
conf['APPRISE_NOTIFICATION_BODY'] = body

for detection in detections:
# Apprise of detection if not already alerted this run.
if detection.species not in species_apprised_this_run:
try:
sendAppriseNotifications(detection.species, str(detection.confidence), str(detection.confidence_pct),
os.path.basename(detection.file_name_extr), file.date, file.time, str(file.week),
conf['LATITUDE'], conf['LONGITUDE'], conf['CONFIDENCE'], conf['SENSITIVITY'],
conf['OVERLAP'], dict(conf), DB_PATH)
conf['OVERLAP'], dict(conf), DB_PATH, True if title or body else False)
except BaseException as e:
log.exception('Error during Apprise:', exc_info=e)

Expand Down
Loading