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

Add ntfy Notifications via Webhooks #1579

Merged
merged 8 commits into from
Jul 18, 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
49 changes: 49 additions & 0 deletions app/Actions/Notifications/SendNtfyTestNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace App\Actions\Notifications;

use Filament\Notifications\Notification;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\WebhookServer\WebhookCall;

class SendNtfyTestNotification
{
use AsAction;

public function handle(array $webhooks)
{
if (! count($webhooks)) {
Notification::make()
->title('You need to add ntfy urls!')
->warning()
->send();

return;
}

foreach ($webhooks as $webhook) {
$webhookCall = WebhookCall::create()
->url($webhook['url'])
->payload([
'topic' => $webhook['topic'],
'message' => 'πŸ‘‹ Testing the ntfy notification channel.',
])
->doNotSign();

// Only add authentication if username and password are provided
if (! empty($webhook['username']) && ! empty($webhook['password'])) {
$authHeader = 'Basic '.base64_encode($webhook['username'].':'.$webhook['password']);
$webhookCall->withHeaders([
'Authorization' => $authHeader,
]);
}

$webhookCall->dispatch();
}

Notification::make()
->title('Test ntfy notification sent.')
->success()
->send();
}
}
59 changes: 59 additions & 0 deletions app/Filament/Pages/Settings/NotificationPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Actions\Notifications\SendGotifyTestNotification;
use App\Actions\Notifications\SendHealthCheckTestNotification;
use App\Actions\Notifications\SendMailTestNotification;
use App\Actions\Notifications\SendNtfyTestNotification;
use App\Actions\Notifications\SendPushoverTestNotification;
use App\Actions\Notifications\SendSlackTestNotification;
use App\Actions\Notifications\SendTelegramTestNotification;
Expand Down Expand Up @@ -277,6 +278,64 @@ public function form(Form $form): Form
'md' => 2,
]),

Forms\Components\Section::make('Ntfy')
->schema([
Forms\Components\Toggle::make('ntfy_enabled')
->label('Enable Ntfy webhook notifications')
->reactive()
->columnSpanFull(),
Forms\Components\Grid::make([
'default' => 1,
])
->hidden(fn (Forms\Get $get) => $get('ntfy_enabled') !== true)
->schema([
Forms\Components\Fieldset::make('Triggers')
->schema([
Forms\Components\Toggle::make('ntfy_on_speedtest_run')
->label('Notify on every speedtest run')
->columnSpanFull(),
Forms\Components\Toggle::make('ntfy_on_threshold_failure')
->label('Notify on threshold failures')
->columnSpanFull(),
]),
Forms\Components\Repeater::make('ntfy_webhooks')
->label('Webhooks')
->schema([
Forms\Components\TextInput::make('url')
->maxLength(2000)
->placeholder('Your ntfy server url')
->required()
->url(),
Forms\Components\TextInput::make('topic')
->label('Topic')
->placeholder('Your ntfy Topic')
->maxLength(200)
->required(),
Forms\Components\TextInput::make('username')
->label('Username')
->placeholder('Username for Basic Auth (optional)')
->maxLength(200),
Forms\Components\TextInput::make('password')
->label('Password')
->placeholder('Password for Basic Auth (optional)')
->password()
->maxLength(200),
])
->columnSpanFull(),
Forms\Components\Actions::make([
Forms\Components\Actions\Action::make('test ntfy')
->label('Test Ntfy webhook')
->action(fn (Forms\Get $get) => SendNtfyTestNotification::run(webhooks: $get('ntfy_webhooks')))
->hidden(fn (Forms\Get $get) => ! count($get('ntfy_webhooks'))),
]),
]),
])
->compact()
->columns([
'default' => 1,
'md' => 2,
]),

Forms\Components\Section::make('Mail')
->schema([
Forms\Components\Toggle::make('mail_enabled')
Expand Down
68 changes: 68 additions & 0 deletions app/Listeners/Ntfy/SendSpeedtestCompletedNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace App\Listeners\Ntfy;

use App\Events\SpeedtestCompleted;
use App\Helpers\Number;
use App\Settings\NotificationSettings;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Spatie\WebhookServer\WebhookCall;

class SendSpeedtestCompletedNotification
{
/**
* Handle the event.
*/
public function handle(SpeedtestCompleted $event): void
{
$notificationSettings = new NotificationSettings();

if (! $notificationSettings->ntfy_enabled) {
return;
}

if (! $notificationSettings->ntfy_on_speedtest_run) {
return;
}

if (! count($notificationSettings->ntfy_webhooks)) {
Log::warning('Ntfy urls not found, check Ntfy notification channel settings.');

return;
}

$payload =
view('ntfy.speedtest-completed', [
'id' => $event->result->id,
'service' => Str::title($event->result->service),
'serverName' => $event->result->server_name,
'serverId' => $event->result->server_id,
'isp' => $event->result->isp,
'ping' => round($event->result->ping).' ms',
'download' => Number::toBitRate(bits: $event->result->download_bits, precision: 2),
'upload' => Number::toBitRate(bits: $event->result->upload_bits, precision: 2),
'packetLoss' => $event->result->packet_loss,
'url' => url('/admin/results'),
])->render();

foreach ($notificationSettings->ntfy_webhooks as $url) {
$webhookCall = WebhookCall::create()
->url($url['url'])
->payload([
'topic' => $url['topic'],
'message' => $payload,
])
->doNotSign();

// Only add authentication if username and password are provided
if (! empty($url['username']) && ! empty($url['password'])) {
$authHeader = 'Basic '.base64_encode($url['username'].':'.$url['password']);
$webhookCall->withHeaders([
'Authorization' => $authHeader,
]);
}
$webhookCall->dispatch();
}
}
}
143 changes: 143 additions & 0 deletions app/Listeners/Ntfy/SendSpeedtestThresholdNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace App\Listeners\Ntfy;

use App\Events\SpeedtestCompleted;
use App\Helpers\Number;
use App\Settings\NotificationSettings;
use App\Settings\ThresholdSettings;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Spatie\WebhookServer\WebhookCall;

class SendSpeedtestThresholdNotification
{
/**
* Handle the event.
*/
public function handle(SpeedtestCompleted $event): void
{
$notificationSettings = new NotificationSettings();

if (! $notificationSettings->ntfy_enabled) {
return;
}

if (! $notificationSettings->ntfy_on_threshold_failure) {
return;
}

if (! count($notificationSettings->ntfy_webhooks)) {
Log::warning('Ntfy urls not found, check Ntfy notification channel settings.');

return;
}

$thresholdSettings = new ThresholdSettings();

if (! $thresholdSettings->absolute_enabled) {
return;
}

$failed = [];

if ($thresholdSettings->absolute_download > 0) {
array_push($failed, $this->absoluteDownloadThreshold(event: $event, thresholdSettings: $thresholdSettings));
}

if ($thresholdSettings->absolute_upload > 0) {
array_push($failed, $this->absoluteUploadThreshold(event: $event, thresholdSettings: $thresholdSettings));
}

if ($thresholdSettings->absolute_ping > 0) {
array_push($failed, $this->absolutePingThreshold(event: $event, thresholdSettings: $thresholdSettings));
}

$failed = array_filter($failed);

if (! count($failed)) {
Log::warning('Failed ntfy thresholds not found, won\'t send notification.');

return;
}

$payload =
view('ntfy.speedtest-threshold', [
'id' => $event->result->id,
'service' => Str::title($event->result->service),
'serverName' => $event->result->server_name,
'serverId' => $event->result->server_id,
'isp' => $event->result->isp,
'metrics' => $failed,
'url' => url('/admin/results'),
])->render();

foreach ($notificationSettings->ntfy_webhooks as $url) {
$webhookCall = WebhookCall::create()
->url($url['url'])
->payload([
'topic' => $url['topic'],
'message' => $payload,
])
->doNotSign();

// Only add authentication if username and password are provided
if (! empty($url['username']) && ! empty($url['password'])) {
$authHeader = 'Basic '.base64_encode($url['username'].':'.$url['password']);
$webhookCall->withHeaders([
'Authorization' => $authHeader,
]);
}

$webhookCall->dispatch();
}
}

/**
* Build Ntfy notification if absolute download threshold is breached.
*/
protected function absoluteDownloadThreshold(SpeedtestCompleted $event, ThresholdSettings $thresholdSettings): bool|array
{
if (! absoluteDownloadThresholdFailed($thresholdSettings->absolute_download, $event->result->download)) {
return false;
}

return [
'name' => 'Download',
'threshold' => $thresholdSettings->absolute_download.' Mbps',
'value' => Number::toBitRate(bits: $event->result->download_bits, precision: 2),
];
}

/**
* Build Ntfy notification if absolute upload threshold is breached.
*/
protected function absoluteUploadThreshold(SpeedtestCompleted $event, ThresholdSettings $thresholdSettings): bool|array
{
if (! absoluteUploadThresholdFailed($thresholdSettings->absolute_upload, $event->result->upload)) {
return false;
}

return [
'name' => 'Upload',
'threshold' => $thresholdSettings->absolute_upload.' Mbps',
'value' => Number::toBitRate(bits: $event->result->upload_bits, precision: 2),
];
}

/**
* Build Ntfy notification if absolute ping threshold is breached.
*/
protected function absolutePingThreshold(SpeedtestCompleted $event, ThresholdSettings $thresholdSettings): bool|array
{
if (! absolutePingThresholdFailed($thresholdSettings->absolute_ping, $event->result->ping)) {
return false;
}

return [
'name' => 'Ping',
'threshold' => $thresholdSettings->absolute_ping.' ms',
'value' => round($event->result->ping, 2).' ms',
];
}
}
8 changes: 8 additions & 0 deletions app/Settings/NotificationSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ class NotificationSettings extends Settings

public ?array $discord_webhooks;

public bool $ntfy_enabled;

public bool $ntfy_on_speedtest_run;

public bool $ntfy_on_threshold_failure;

public ?array $ntfy_webhooks;

public bool $pushover_enabled;

public bool $pushover_on_speedtest_run;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

use Spatie\LaravelSettings\Migrations\SettingsMigration;

return new class extends SettingsMigration
{
public function up(): void
{
$this->migrator->add('notification.ntfy_enabled', false);
$this->migrator->add('notification.ntfy_on_speedtest_run', false);
$this->migrator->add('notification.ntfy_on_threshold_failure', false);
$this->migrator->add('notification.ntfy_webhooks', null);
}
};
12 changes: 12 additions & 0 deletions resources/views/ntfy/speedtest-completed.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Speedtest Completed - #{{ $id }}

A new speedtest was completed using {{ $service }}.

Server name: {{ $serverName }}
Server ID: {{ $serverId }}
ISP: {{ $isp }}
Ping: {{ $ping }}
Download: {{ $download }}
Upload: {{ $upload }}
Packet Loss: {{ $packetLoss }} %
URL: {{ $url }}
8 changes: 8 additions & 0 deletions resources/views/ntfy/speedtest-threshold.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Speedtest Threshold Breached - #{{ $id }}

A new speedtest was completed using {{ $service }} on {{ $isp }}** but a threshold was breached.

@foreach ($metrics as $item)
- {{ $item['name'] }} {{ $item['threshold'] }}: {{ $item['value'] }}
@endforeach
- URL: {{ $url }}