From d995bfc08173dde43142ba9022e61c22d6a0def9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 12 Dec 2024 06:33:48 +0100 Subject: [PATCH] Update all owner events so they support all channels --- app/Events/RegisteredUser.php | 5 +- app/Handlers/Events/AdminEventHandler.php | 79 ++++++++----------- app/Handlers/Events/UserEventHandler.php | 72 ++++++++--------- .../Admin/NotificationController.php | 2 +- .../Controllers/Auth/RegisterController.php | 4 +- app/Http/Controllers/HomeController.php | 1 + app/Notifications/Admin/UserInvitation.php | 68 +++++++++++----- app/Notifications/Admin/UserRegistration.php | 69 +++++++++++----- .../Admin/VersionCheckResult.php | 53 ++++++++++--- .../Notifiables/OwnerNotifiable.php | 4 + .../ReturnsAvailableChannels.php | 50 ++++++++++-- .../Test/TestNotificationSlack.php | 20 ++--- app/User.php | 5 +- config/services.php | 4 +- 14 files changed, 270 insertions(+), 166 deletions(-) diff --git a/app/Events/RegisteredUser.php b/app/Events/RegisteredUser.php index 0a4d116d8f..4b1d28490b 100644 --- a/app/Events/RegisteredUser.php +++ b/app/Events/RegisteredUser.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Events; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\User; use Illuminate\Queue\SerializesModels; @@ -35,12 +36,14 @@ class RegisteredUser extends Event use SerializesModels; public User $user; + public OwnerNotifiable $owner; /** * Create a new event instance. This event is triggered when a new user registers. */ - public function __construct(User $user) + public function __construct(OwnerNotifiable $owner, User $user) { $this->user = $user; + $this->owner = $owner; } } diff --git a/app/Handlers/Events/AdminEventHandler.php b/app/Handlers/Events/AdminEventHandler.php index c10d278af5..75c3e5f937 100644 --- a/app/Handlers/Events/AdminEventHandler.php +++ b/app/Handlers/Events/AdminEventHandler.php @@ -24,17 +24,15 @@ declare(strict_types=1); namespace FireflyIII\Handlers\Events; use FireflyIII\Events\Admin\InvitationCreated; -use FireflyIII\Events\AdminRequestedTestMessage; use FireflyIII\Events\NewVersionAvailable; use FireflyIII\Events\Test\TestNotificationChannel; use FireflyIII\Notifications\Admin\UserInvitation; use FireflyIII\Notifications\Admin\VersionCheckResult; -use FireflyIII\Notifications\Test\TestNotificationDiscord; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Notifications\Test\TestNotificationEmail; use FireflyIII\Notifications\Test\TestNotificationNtfy; use FireflyIII\Notifications\Test\TestNotificationPushover; use FireflyIII\Notifications\Test\TestNotificationSlack; -use FireflyIII\Repositories\User\UserRepositoryInterface; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; @@ -49,30 +47,23 @@ class AdminEventHandler if (false === $sendMail) { return; } + try { + $owner = new OwnerNotifiable(); + Notification::send($owner, new UserInvitation($owner, $event->invitee)); + } catch (\Exception $e) { // @phpstan-ignore-line + $message = $e->getMessage(); + if (str_contains($message, 'Bcc')) { + app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $all = $repository->all(); - foreach ($all as $user) { - if ($repository->hasRole($user, 'owner')) { - try { - Notification::send($user, new UserInvitation($event->invitee)); - } catch (\Exception $e) { // @phpstan-ignore-line - $message = $e->getMessage(); - if (str_contains($message, 'Bcc')) { - app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - if (str_contains($message, 'RFC 2822')) { - app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); - } + return; } + if (str_contains($message, 'RFC 2822')) { + app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + + return; + } + app('log')->error($e->getMessage()); + app('log')->error($e->getTraceAsString()); } } @@ -86,29 +77,23 @@ class AdminEventHandler return; } - /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $all = $repository->all(); - foreach ($all as $user) { - if ($repository->hasRole($user, 'owner')) { - try { - Notification::send($user, new VersionCheckResult($event->message)); - } catch (\Exception $e) {// @phpstan-ignore-line - $message = $e->getMessage(); - if (str_contains($message, 'Bcc')) { - app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + try { + $owner = new OwnerNotifiable(); + Notification::send($owner, new VersionCheckResult($event->message)); + } catch (\Exception $e) {// @phpstan-ignore-line + $message = $e->getMessage(); + if (str_contains($message, 'Bcc')) { + app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - return; - } - if (str_contains($message, 'RFC 2822')) { - app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); - } + return; } + if (str_contains($message, 'RFC 2822')) { + app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + + return; + } + app('log')->error($e->getMessage()); + app('log')->error($e->getTraceAsString()); } } @@ -119,7 +104,7 @@ class AdminEventHandler { Log::debug(sprintf('Now in sendTestNotification("%s")', $event->channel)); - switch($event->channel) { + switch ($event->channel) { case 'email': $class = TestNotificationEmail::class; break; diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index e534a662e5..7d2e377716 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -82,8 +82,8 @@ class UserEventHandler $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = $event->user; - $count = $repository->count(); + $user = $event->user; + $count = $repository->count(); // only act when there is 1 user in the system and he has no admin rights. if (1 === $count && !$repository->hasRole($user, 'owner')) { @@ -115,13 +115,13 @@ class UserEventHandler */ public function createGroupMembership(RegisteredUser $event): void { - $user = $event->user; - $groupExists = true; - $groupTitle = $user->email; - $index = 1; + $user = $event->user; + $groupExists = true; + $groupTitle = $user->email; + $index = 1; /** @var UserGroup $group */ - $group = null; + $group = null; // create a new group. while (true === $groupExists) { // @phpstan-ignore-line @@ -131,7 +131,7 @@ class UserEventHandler break; } - $groupTitle = sprintf('%s-%d', $user->email, $index); + $groupTitle = sprintf('%s-%d', $user->email, $index); ++$index; if ($index > 99) { throw new FireflyException('Email address can no longer be used for registrations.'); @@ -139,7 +139,7 @@ class UserEventHandler } /** @var null|UserRole $role */ - $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); + $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); if (null === $role) { throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); } @@ -165,7 +165,7 @@ class UserEventHandler $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = $event->user; + $user = $event->user; if ($repository->hasRole($user, 'demo')) { // set user back to English. app('preferences')->setForUser($user, 'language', 'en_US'); @@ -186,7 +186,7 @@ class UserEventHandler return; // do not email demo user. } - $list = app('preferences')->getForUser($user, 'login_ip_history', [])->data; + $list = app('preferences')->getForUser($user, 'login_ip_history', [])->data; if (!is_array($list)) { $list = []; } @@ -220,31 +220,25 @@ class UserEventHandler public function sendAdminRegistrationNotification(RegisteredUser $event): void { - $sendMail = (bool)app('fireflyconfig')->get('notification_admin_new_reg', true)->data; + $sendMail = (bool) app('fireflyconfig')->get('notification_admin_new_reg', true)->data; if ($sendMail) { - /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $all = $repository->all(); - foreach ($all as $user) { - if ($repository->hasRole($user, 'owner')) { - try { - Notification::send($user, new AdminRegistrationNotification($event->user)); - } catch (\Exception $e) { // @phpstan-ignore-line - $message = $e->getMessage(); - if (str_contains($message, 'Bcc')) { - app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + $owner = $event->owner; + try { + Notification::send($owner, new AdminRegistrationNotification($event->owner, $event->user)); + } catch (\Exception $e) { // @phpstan-ignore-line + $message = $e->getMessage(); + if (str_contains($message, 'Bcc')) { + app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - return; - } - if (str_contains($message, 'RFC 2822')) { - app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); - } + return; } + if (str_contains($message, 'RFC 2822')) { + app('log')->warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + + return; + } + app('log')->error($e->getMessage()); + app('log')->error($e->getTraceAsString()); } } } @@ -285,7 +279,7 @@ class UserEventHandler $oldEmail = $event->oldEmail; $user = $event->user; $token = app('preferences')->getForUser($user, 'email_change_undo_token', 'invalid'); - $hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $oldEmail)); + $hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $oldEmail)); $url = route('profile.undo-email-change', [$token->data, $hashed]); try { @@ -347,7 +341,7 @@ class UserEventHandler */ public function sendRegistrationMail(RegisteredUser $event): void { - $sendMail = (bool)app('fireflyconfig')->get('notification_user_new_reg', true)->data; + $sendMail = (bool) app('fireflyconfig')->get('notification_user_new_reg', true)->data; if ($sendMail) { try { Notification::send($event->user, new UserRegistrationNotification()); @@ -375,7 +369,7 @@ class UserEventHandler public function storeUserIPAddress(ActuallyLoggedIn $event): void { app('log')->debug('Now in storeUserIPAddress'); - $user = $event->user; + $user = $event->user; if ($user->hasRole('demo')) { app('log')->debug('Do not log demo user logins'); @@ -392,8 +386,8 @@ class UserEventHandler return; } - $inArray = false; - $ip = request()->ip(); + $inArray = false; + $ip = request()->ip(); app('log')->debug(sprintf('User logging in from IP address %s', $ip)); // update array if in array @@ -421,7 +415,7 @@ class UserEventHandler $preference = array_values($preference); /** @var bool $send */ - $send = app('preferences')->getForUser($user, 'notification_user_login', true)->data; + $send = app('preferences')->getForUser($user, 'notification_user_login', true)->data; app('preferences')->setForUser($user, 'login_ip_history', $preference); if (false === $inArray && true === $send) { diff --git a/app/Http/Controllers/Admin/NotificationController.php b/app/Http/Controllers/Admin/NotificationController.php index b64444d5f4..6d2286ceaf 100644 --- a/app/Http/Controllers/Admin/NotificationController.php +++ b/app/Http/Controllers/Admin/NotificationController.php @@ -77,7 +77,7 @@ class NotificationController extends Controller // validate pushover if ('' === $pushoverAppToken || '' === $pushoverUserToken) { - Log::warning('No Pushover token, channel is disabled.'); + Log::warning('[a] No Pushover token, channel is disabled.'); $forcedAvailability['pushover'] = false; } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index b84453522f..418fa13e61 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers\Auth; use FireflyIII\Events\RegisteredUser; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Support\Http\Controllers\CreateStuff; use FireflyIII\User; @@ -94,7 +95,8 @@ class RegisterController extends Controller $this->validator($request->all())->validate(); $user = $this->createUser($request->all()); app('log')->info(sprintf('Registered new user %s', $user->email)); - event(new RegisteredUser($user)); + $owner = new OwnerNotifiable(); + event(new RegisteredUser($owner, $user)); $this->guard()->login($user); diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 0370161be8..bfc3762b08 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -25,6 +25,7 @@ namespace FireflyIII\Http\Controllers; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; +use FireflyIII\Events\NewVersionAvailable; use FireflyIII\Events\RequestedVersionCheckStatus; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; diff --git a/app/Notifications/Admin/UserInvitation.php b/app/Notifications/Admin/UserInvitation.php index bec827d92b..60a6123c90 100644 --- a/app/Notifications/Admin/UserInvitation.php +++ b/app/Notifications/Admin/UserInvitation.php @@ -25,11 +25,16 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Admin; use FireflyIII\Models\InvitedUser; -use FireflyIII\Support\Notifications\UrlValidator; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; +use FireflyIII\Notifications\ReturnsAvailableChannels; +use FireflyIII\Notifications\ReturnsSettings; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; +use Illuminate\Support\Facades\Log; +use NotificationChannels\Pushover\PushoverMessage; +use Ntfy\Message; /** * Class UserInvitation @@ -38,14 +43,16 @@ class UserInvitation extends Notification { use Queueable; - private InvitedUser $invitee; + private InvitedUser $invitee; + private OwnerNotifiable $owner; /** * Create a new notification instance. */ - public function __construct(InvitedUser $invitee) + public function __construct(OwnerNotifiable $owner, InvitedUser $invitee) { $this->invitee = $invitee; + $this->owner = $owner; } /** @@ -57,7 +64,7 @@ class UserInvitation extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toArray($notifiable) + public function toArray(OwnerNotifiable $notifiable) { return [ ]; @@ -72,12 +79,11 @@ class UserInvitation extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toMail($notifiable) + public function toMail(OwnerNotifiable $notifiable) { return (new MailMessage()) ->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) - ->subject((string)trans('email.invitation_created_subject')) - ; + ->subject((string) trans('email.invitation_created_subject')); } /** @@ -89,13 +95,45 @@ class UserInvitation extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toSlack($notifiable) + public function toSlack(OwnerNotifiable $notifiable) { return (new SlackMessage())->content( - (string)trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) + (string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) ); } + public function toPushover(OwnerNotifiable $notifiable): PushoverMessage + { + Log::debug('Now in toPushover() for UserInvitation'); + + return PushoverMessage::create((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])) + ->title((string) trans('email.invitation_created_subject')); + } + + public function toNtfy(OwnerNotifiable $notifiable): Message + { + Log::debug('Now in toNtfy() for UserInvitation'); + $settings = ReturnsSettings::getSettings('ntfy', 'owner', null); + + // overrule config. + config(['ntfy-notification-channel.server' => $settings['ntfy_server']]); + config(['ntfy-notification-channel.topic' => $settings['ntfy_topic']]); + + if ($settings['ntfy_auth']) { + // overrule auth as well. + config(['ntfy-notification-channel.authentication.enabled' => true]); + config(['ntfy-notification-channel.authentication.username' => $settings['ntfy_user']]); + config(['ntfy-notification-channel.authentication.password' => $settings['ntfy_pass']]); + } + + $message = new Message(); + $message->topic($settings['ntfy_topic']); + $message->title((string) trans('email.invitation_created_subject')); + $message->body((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])); + + return $message; + } + /** * Get the notification's delivery channels. * @@ -105,16 +143,8 @@ class UserInvitation extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function via($notifiable) + public function via(OwnerNotifiable $notifiable) { - - - - $slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; - if (UrlValidator::isValidWebhookURL($slackUrl)) { - return ['mail', 'slack']; - } - - return ['mail']; + return ReturnsAvailableChannels::returnChannels('owner'); } } diff --git a/app/Notifications/Admin/UserRegistration.php b/app/Notifications/Admin/UserRegistration.php index 759e200d82..acb81fd110 100644 --- a/app/Notifications/Admin/UserRegistration.php +++ b/app/Notifications/Admin/UserRegistration.php @@ -24,12 +24,17 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Admin; -use FireflyIII\Support\Notifications\UrlValidator; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; +use FireflyIII\Notifications\ReturnsAvailableChannels; +use FireflyIII\Notifications\ReturnsSettings; use FireflyIII\User; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; +use Illuminate\Support\Facades\Log; +use NotificationChannels\Pushover\PushoverMessage; +use Ntfy\Message; /** * Class UserRegistration @@ -38,26 +43,24 @@ class UserRegistration extends Notification { use Queueable; - private User $user; + private OwnerNotifiable $owner; + private User $user; /** * Create a new notification instance. */ - public function __construct(User $user) + public function __construct(OwnerNotifiable $owner, User $user) { $this->user = $user; + $this->owner = $owner; } /** * Get the array representation of the notification. * - * @param mixed $notifiable - * - * @return array - * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toArray($notifiable) + public function toArray(OwnerNotifiable $notifiable) { return [ ]; @@ -72,12 +75,11 @@ class UserRegistration extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toMail($notifiable) + public function toMail(OwnerNotifiable $notifiable) { return (new MailMessage()) ->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id]) - ->subject((string)trans('email.registered_subject_admin')) - ; + ->subject((string) trans('email.registered_subject_admin')); } /** @@ -89,9 +91,41 @@ class UserRegistration extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toSlack($notifiable) + public function toSlack(OwnerNotifiable $notifiable) { - return (new SlackMessage())->content((string)trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id])); + return (new SlackMessage())->content((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id])); + } + + public function toPushover(OwnerNotifiable $notifiable): PushoverMessage + { + Log::debug('Now in toPushover() for UserRegistration'); + + return PushoverMessage::create((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email])) + ->title((string) trans('email.registered_subject_admin')); + } + + public function toNtfy(OwnerNotifiable $notifiable): Message + { + Log::debug('Now in toNtfy() for (Admin) UserRegistration'); + $settings = ReturnsSettings::getSettings('ntfy', 'owner', null); + + // overrule config. + config(['ntfy-notification-channel.server' => $settings['ntfy_server']]); + config(['ntfy-notification-channel.topic' => $settings['ntfy_topic']]); + + if ($settings['ntfy_auth']) { + // overrule auth as well. + config(['ntfy-notification-channel.authentication.enabled' => true]); + config(['ntfy-notification-channel.authentication.username' => $settings['ntfy_user']]); + config(['ntfy-notification-channel.authentication.password' => $settings['ntfy_pass']]); + } + + $message = new Message(); + $message->topic($settings['ntfy_topic']); + $message->title((string) trans('email.registered_subject_admin')); + $message->body((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]) ); + + return $message; } /** @@ -103,13 +137,8 @@ class UserRegistration extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function via($notifiable) + public function via(OwnerNotifiable $notifiable) { - $slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; - if (UrlValidator::isValidWebhookURL($slackUrl)) { - return ['mail', 'slack']; - } - - return ['mail']; + return ReturnsAvailableChannels::returnChannels('owner'); } } diff --git a/app/Notifications/Admin/VersionCheckResult.php b/app/Notifications/Admin/VersionCheckResult.php index 7ee75e8933..07edf5ef27 100644 --- a/app/Notifications/Admin/VersionCheckResult.php +++ b/app/Notifications/Admin/VersionCheckResult.php @@ -24,11 +24,17 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Admin; +use FireflyIII\Notifications\Notifiables\OwnerNotifiable; +use FireflyIII\Notifications\ReturnsAvailableChannels; +use FireflyIII\Notifications\ReturnsSettings; use FireflyIII\Support\Notifications\UrlValidator; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; +use Illuminate\Support\Facades\Log; +use NotificationChannels\Pushover\PushoverMessage; +use Ntfy\Message; /** * Class VersionCheckResult @@ -56,7 +62,7 @@ class VersionCheckResult extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toArray($notifiable) + public function toArray(OwnerNotifiable $notifiable) { return [ ]; @@ -71,7 +77,7 @@ class VersionCheckResult extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toMail($notifiable) + public function toMail(OwnerNotifiable $notifiable) { return (new MailMessage()) ->markdown('emails.new-version', ['message' => $this->message]) @@ -88,7 +94,7 @@ class VersionCheckResult extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function toSlack($notifiable) + public function toSlack(OwnerNotifiable $notifiable) { return (new SlackMessage())->content($this->message) ->attachment(static function ($attachment): void { @@ -97,6 +103,38 @@ class VersionCheckResult extends Notification ; } + public function toPushover(OwnerNotifiable $notifiable): PushoverMessage + { + Log::debug('Now in toPushover() for VersionCheckResult'); + + return PushoverMessage::create($this->message) + ->title((string) trans('email.new_version_email_subject')); + } + + public function toNtfy(OwnerNotifiable $notifiable): Message + { + Log::debug('Now in toNtfy() for VersionCheckResult'); + $settings = ReturnsSettings::getSettings('ntfy', 'owner', null); + + // overrule config. + config(['ntfy-notification-channel.server' => $settings['ntfy_server']]); + config(['ntfy-notification-channel.topic' => $settings['ntfy_topic']]); + + if ($settings['ntfy_auth']) { + // overrule auth as well. + config(['ntfy-notification-channel.authentication.enabled' => true]); + config(['ntfy-notification-channel.authentication.username' => $settings['ntfy_user']]); + config(['ntfy-notification-channel.authentication.password' => $settings['ntfy_pass']]); + } + + $message = new Message(); + $message->topic($settings['ntfy_topic']); + $message->title((string) trans('email.new_version_email_subject')); + $message->body($this->message); + + return $message; + } + /** * Get the notification's delivery channels. * @@ -106,13 +144,8 @@ class VersionCheckResult extends Notification * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function via($notifiable) + public function via(OwnerNotifiable $notifiable) { - $slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; - if (UrlValidator::isValidWebhookURL($slackUrl)) { - return ['mail', 'slack']; - } - - return ['mail']; + return ReturnsAvailableChannels::returnChannels('owner'); } } diff --git a/app/Notifications/Notifiables/OwnerNotifiable.php b/app/Notifications/Notifiables/OwnerNotifiable.php index fb71610a37..71c66314c0 100644 --- a/app/Notifications/Notifiables/OwnerNotifiable.php +++ b/app/Notifications/Notifiables/OwnerNotifiable.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Notifiables; use Illuminate\Notifications\Notification; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use NotificationChannels\Pushover\PushoverReceiver; @@ -41,6 +42,7 @@ class OwnerNotifiable public function routeNotificationForPushover() { + Log::debug('Return settings for routeNotificationForPushover'); $pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; $pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; return PushoverReceiver::withUserKey($pushoverUserToken) @@ -59,8 +61,10 @@ class OwnerNotifiable { $method = 'routeNotificationFor' . Str::studly($driver); if (method_exists($this, $method)) { + Log::debug(sprintf('Redirect for settings to "%s".', $method)); return $this->{$method}($notification); // @phpstan-ignore-line } + Log::debug(sprintf('No method "%s" found, return generic settings.', $method)); return match ($driver) { 'mail' => (string) config('firefly.site_owner'), diff --git a/app/Notifications/ReturnsAvailableChannels.php b/app/Notifications/ReturnsAvailableChannels.php index 2fa3c1b8eb..db71c533ca 100644 --- a/app/Notifications/ReturnsAvailableChannels.php +++ b/app/Notifications/ReturnsAvailableChannels.php @@ -24,23 +24,57 @@ declare(strict_types=1); namespace FireflyIII\Notifications; use FireflyIII\Support\Notifications\UrlValidator; +use Illuminate\Support\Facades\Log; +use NotificationChannels\Pushover\PushoverChannel; +use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel; class ReturnsAvailableChannels { - public static function returnChannels(string $type): array { + public static function returnChannels(string $type): array + { $channels = ['mail']; - if('owner' === $type) { - $slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; - if (UrlValidator::isValidWebhookURL($slackUrl)) { - $channels[] = 'slack'; - } - // only the owner can get notifications over - } + if ('owner' === $type) { + return self::returnOwnerChannels(); + } return $channels; } + private static function returnOwnerChannels(): array + { + + $channels = ['mail']; + $slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data; + if (UrlValidator::isValidWebhookURL($slackUrl)) { + $channels[] = 'slack'; + } + + // validate presence of of Ntfy settings. + if ('' !== (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) { + Log::debug('Enabled ntfy.'); + $channels[] = NtfyChannel::class; + } + if ('' === (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) { + Log::warning('No topic name for Ntfy, channel is disabled.'); + } + + // pushover + $pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; + $pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; + if ('' === $pushoverAppToken || '' === $pushoverUserToken) { + Log::warning('[b] No Pushover token, channel is disabled.'); + } + if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) { + Log::debug('Enabled pushover.'); + $channels[] = PushoverChannel::class; + } + + Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels))); + // only the owner can get notifications over + return $channels; + } + } diff --git a/app/Notifications/Test/TestNotificationSlack.php b/app/Notifications/Test/TestNotificationSlack.php index a98db18790..bf20f6eb54 100644 --- a/app/Notifications/Test/TestNotificationSlack.php +++ b/app/Notifications/Test/TestNotificationSlack.php @@ -25,13 +25,11 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Test; use FireflyIII\Notifications\Notifiables\OwnerNotifiable; -use FireflyIII\User; use Illuminate\Bus\Queueable; -use Illuminate\Notifications\Notification; -//use Illuminate\Notifications\Slack\SlackMessage; -use Illuminate\Support\Facades\Log; - use Illuminate\Notifications\Messages\SlackMessage; +use Illuminate\Notifications\Notification; + +//use Illuminate\Notifications\Slack\SlackMessage; /** * Class TestNotification @@ -47,7 +45,7 @@ class TestNotificationSlack extends Notification */ public function __construct(OwnerNotifiable $owner) { - $this->owner =$owner; + $this->owner = $owner; } /** @@ -75,14 +73,8 @@ class TestNotificationSlack extends Notification */ public function toSlack(OwnerNotifiable $notifiable) { - // since it's an admin notification, grab the URL from fireflyconfig - $url = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data; - if ('' !== $url) { - return new SlackMessage()->content((string)trans('email.admin_test_subject'))->to($url); - //return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url); - - } - Log::error('Empty slack URL, cannot send notification.'); + return new SlackMessage()->content((string) trans('email.admin_test_subject')); + //return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url); } /** diff --git a/app/User.php b/app/User.php index a5165facac..5f31cdfb27 100644 --- a/app/User.php +++ b/app/User.php @@ -429,10 +429,7 @@ class User extends Authenticatable } // not the best way to do this, but alas. - if ($notification instanceof UserInvitation) { - return $res; - } - if ($notification instanceof UserRegistration) { + if ($notification instanceof UserRegistration) { return $res; } if ($notification instanceof VersionCheckResult) { diff --git a/config/services.php b/config/services.php index e0c77d2d54..7925115627 100644 --- a/config/services.php +++ b/config/services.php @@ -62,7 +62,7 @@ return [ 'secret' => env('MANDRILL_SECRET'), ], 'pushover' => [ - 'token' => env('PUSHOVER_APP_TOKEN', ''), - 'user_token' => env('PUSHOVER_USER_TOKEN', ''), + 'token' => 'fake_token', + 'user_token' => 'fake_token', ], ];