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

feat: add ntfy as notification method #377

Merged
merged 3 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
62 changes: 61 additions & 1 deletion endpoints/cronjobs/sendnotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
$webhookNotificationsEnabled = false;
$pushoverNotificationsEnabled = false;
$discordNotificationsEnabled = false;
$ntfyNotificationsEnabled = false;

// Get notification settings (how many days before the subscription ends should the notification be sent)
$query = "SELECT days FROM notification_settings WHERE user_id = :userId";
Expand Down Expand Up @@ -102,6 +103,19 @@
$pushover['token'] = $row["token"];
}

// Check if Nrfy notifications are enabled and get the settings
$query = "SELECT * FROM ntfy_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();

if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$ntfyNotificationsEnabled = $row['enabled'];
$ntfy['host'] = $row["host"];
$ntfy['topic'] = $row["topic"];
$ntfy['headers'] = $row["headers"];
}

// Check if Webhook notifications are enabled and get the settings
$query = "SELECT * FROM webhook_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
Expand All @@ -120,7 +134,9 @@
}
}

$notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled || $webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled;
$notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||
$webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled ||
$ntfyNotificationsEnabled;

// If no notifications are enabled, no need to run
if (!$notificationsEnabled) {
Expand Down Expand Up @@ -429,6 +445,50 @@
}
}

// Ntfy notifications if enabled
if ($ntfyNotificationsEnabled) {
foreach ($notify as $userId => $perUser) {
// Get name of user from household table
$stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
$user = $result->fetchArray(SQLITE3_ASSOC);

if ($user['name']) {
$message = $user['name'] . ", the following subscriptions are up for renewal:\n";
} else {
$message = "The following subscriptions are up for renewal:\n";
}

foreach ($perUser as $subscription) {
$dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days";
$message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n";
}

$headers = json_decode($ntfy["headers"], true);
$customheaders = array_map(function($key, $value) {
return "$key: $value";
}, array_keys($headers), $headers);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $ntfy['host'] . '/' . $ntfy['topic']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

if ($response === false) {
echo "Error sending notifications: " . curl_error($ch) . "<br />";
} else {
echo "Ntfy Notifications sent<br />";
}
}
}

// Webhook notifications if enabled
if ($webhookNotificationsEnabled) {
// Get webhook payload and turn it into a json object
Expand Down
3 changes: 3 additions & 0 deletions endpoints/db/migrate.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ function errorHandler($severity, $message, $file, $line) {
}

foreach ($requiredMigrations as $migration) {
if (!file_exists($migration)) {
$migration = '../../' . $migration;
}
require_once $migration;

$stmtInsert = $db->prepare('INSERT INTO migrations (migration) VALUES (:migration)');
Expand Down
84 changes: 84 additions & 0 deletions endpoints/notifications/saventfynotifications.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

require_once '../../includes/connect_endpoint.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
die(json_encode([
"success" => false,
"message" => translate('session_expired', $i18n)
]));
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);

if (
!isset($data["topic"]) || $data["topic"] == "" ||
!isset($data["host"]) || $data["host"] == ""
) {
$response = [
"success" => false,
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
$enabled = $data["enabled"];
$host = $data["host"];
$topic = $data["topic"];
$headers = $data["headers"];

$query = "SELECT COUNT(*) FROM ntfy_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
$stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
$result = $stmt->execute();

if ($result === false) {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
$row = $result->fetchArray();
$count = $row[0];
if ($count == 0) {
$query = "INSERT INTO ntfy_notifications (enabled, host, topic, headers, user_id)
VALUES (:enabled, :host, :topic, :headers, :userId)";
} else {
$query = "UPDATE ntfy_notifications
SET enabled = :enabled, host = :host, topic = :topic, headers = :headers WHERE user_id = :userId";
}

$stmt = $db->prepare($query);
$stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
$stmt->bindValue(':host', $host, SQLITE3_TEXT);
$stmt->bindValue(':topic', $topic, SQLITE3_TEXT);
$stmt->bindValue(':headers', $headers, SQLITE3_TEXT);
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);

if ($stmt->execute()) {
$response = [
"success" => true,
"message" => translate('notifications_settings_saved', $i18n)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
}
}
}

} else {
$response = [
"success" => false,
"message" => translate('invalid_request_method', $i18n)
];
echo json_encode($response);
}

?>
6 changes: 6 additions & 0 deletions endpoints/notifications/savepushovernotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@
}
}
}
} else {
$response = [
"success" => false,
"message" => translate('invalid_request_method', $i18n)
];
echo json_encode($response);
}

?>
70 changes: 70 additions & 0 deletions endpoints/notifications/testntfynotifications.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

require_once '../../includes/connect_endpoint.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
die(json_encode([
"success" => false,
"message" => translate('session_expired', $i18n)
]));
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);

if (
!isset($data["host"]) || $data["host"] == "" ||
!isset($data["topic"]) || $data["topic"] == ""
) {
$response = [
"success" => false,
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
$host = $data["host"];
$topic = $data["topic"];
$headers = json_decode($data["headers"], true);
$customheaders = array_map(function($key, $value) {
return "$key: $value";
}, array_keys($headers), $headers);

$url = "$host/$topic";

// Set the message parameters
$message = translate('test_notification', $i18n);

$ch = curl_init();

// Set the URL and other options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);

// Execute the request
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Check if the message was sent successfully
if ($response === false) {
die(json_encode([
"success" => false,
"message" => translate('notification_failed', $i18n)
]));
} else {
print_r($response);
}

die(json_encode([
"success" => true,
"message" => translate('notification_sent_successfuly', $i18n)
]));
}

}

?>
2 changes: 2 additions & 0 deletions includes/i18n/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "Bot Avatar URL",
"pushover" => "Pushover",
"pushover_user_key" => "Pushover User Key",
'host' => "Host",
'topic' => "Topic",
"categories" => "Kategorien",
"save_category" => "Kategorie speichern",
"delete_category" => "Kategorie löschen",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "Discord Bot Avatar URL",
"pushover" => "Pushover",
"pushover_user_key" => "Pushover User Key",
'host' => "Host",
'topic' => "Θέμα",
"categories" => "Κατηγορίες",
"save_category" => "Αποθήκευση κατηγορίας",
"delete_category" => "Διαγραφή κατηγορίας",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "Discord Bot Avatar URL",
"pushover" => "Pushover",
"pushover_user_key" => "Pushover User Key",
'host' => "Host",
'topic' => "Topic",
"categories" => "Categories",
"save_category" => "Save Category",
"delete_category" => "Delete Category",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/es.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL del avatar del bot",
"pushover" => "Pushover",
"pushover_user_key" => "Clave de usuario",
'host' => "Host",
'topic' => "Topico",
"categories" => "Categorías",
"save_category" => "Guardar Categoría",
"delete_category" => "Eliminar Categoría",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL de l'avatar du bot Discord",
"pushover" => "Pushover",
"pushover_user_key" => "Clé utilisateur Pushover",
'host' => "Hôte",
'topic' => "Sujet",
"categories" => "Catégories",
"save_category" => "Enregistrer la catégorie",
"delete_category" => "Supprimer la catégorie",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/it.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@
"discord_bot_avatar_url" => "URL dell'avatar del bot",
"pushover" => "Pushover",
"pushover_user_key" => "Chiave utente",
'host' => "Host",
'topic' => "Topic",
'categories' => 'Categorie',
'save_category' => 'Salva categoria',
'delete_category' => 'Elimina categoria',
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/jp.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "DiscordボットアバターURL",
"pushover" => "Pushover",
"pushover_user_key" => "Pushoverユーザーキー",
'host' => "ホスト",
'topic' => "トピック",
"categories" => "カテゴリ",
"save_category" => "カテゴリを保存",
"delete_category" => "カテゴリを削除",
Expand Down
4 changes: 3 additions & 1 deletion includes/i18n/ko.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@
"discord_bot_username" => "디스코드 봇 유저명",
"discord_bot_avatar_url" => "디스코드 봇 아바타 URL",
"pushover" => "Pushover",
"pushover_user_key" => "Pushover User Key",
"pushover_user_key" => "Pushover User Key",~
'host' => "호스트",
'topic' => "토픽",
"categories" => "카테고리",
"save_category" => "카테고리 저장",
"delete_category" => "카테고리 삭제",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/pl.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL awatara bota",
"pushover" => "Pushover",
"pushover_user_key" => "Klucz użytkownika",
'host' => "Host",
'topic' => "Temat",
"categories" => "Kategorie",
"save_category" => "Zapisz kategorię",
"delete_category" => "Usuń kategorię",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/pt.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL do Avatar do Bot",
"pushover" => "Pushover",
"pushover_user_key" => "Chave de Utilizador Pushover",
'host' => "Host",
'topic' => "Tópico",
"categories" => "Categorias",
"save_category" => "Guardar Categoria",
"delete_category" => "Apagar Categoria",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/pt_br.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@
"discord_bot_avatar_url" => "URL do Avatar",
"pushover" => "Pushover",
"pushover_user_key" => "Chave do Usuário",
'host' => "Host",
'topic' => "Tópico",
"categories" => "Categorias",
"save_category" => "Salvar categoria",
"delete_category" => "Excluir categoria",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL-адрес аватара бота Discord",
"pushover" => "Pushover",
"pushover_user_key" => "Ключ пользователя Pushover",
'host' => "Хост",
'topic' => "Тема",
"categories" => "Категории",
"save_category" => "Сохранить категорию",
"delete_category" => "Удалить категорию",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/sl.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@
"discord_bot_avatar_url" => "URL avatarja Discordovega bota",
"pushover" => "Pushover",
"pushover_user_key" => "Uporabniški ključ Pushover",
'host' => "Gostitelj",
'topic' => "Tema",
"categories" => "Kategorije",
"save_category" => "Shrani kategorijo",
"delete_category" => "Izbriši kategorijo",
Expand Down
2 changes: 2 additions & 0 deletions includes/i18n/sr.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@
"discord_bot_avatar_url" => "Дискорд бот URL аватара",
"pushover" => "Пушовер",
"pushover_user_key" => "Пушовер кориснички кључ",
'host' => "Домаћин",
'topic' => "Тема",
"categories" => "Категорије",
"save_category" => "Сачувај категорију",
"delete_category" => "Избриши категорију",
Expand Down
Loading