Update all owner events so they support all channels

This commit is contained in:
James Cole 2024-12-12 06:33:48 +01:00
parent c920070ce2
commit d995bfc081
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
14 changed files with 270 additions and 166 deletions

View File

@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Events; namespace FireflyIII\Events;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -35,12 +36,14 @@ class RegisteredUser extends Event
use SerializesModels; use SerializesModels;
public User $user; public User $user;
public OwnerNotifiable $owner;
/** /**
* Create a new event instance. This event is triggered when a new user registers. * 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->user = $user;
$this->owner = $owner;
} }
} }

View File

@ -24,17 +24,15 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\Admin\InvitationCreated; use FireflyIII\Events\Admin\InvitationCreated;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Events\NewVersionAvailable; use FireflyIII\Events\NewVersionAvailable;
use FireflyIII\Events\Test\TestNotificationChannel; use FireflyIII\Events\Test\TestNotificationChannel;
use FireflyIII\Notifications\Admin\UserInvitation; use FireflyIII\Notifications\Admin\UserInvitation;
use FireflyIII\Notifications\Admin\VersionCheckResult; use FireflyIII\Notifications\Admin\VersionCheckResult;
use FireflyIII\Notifications\Test\TestNotificationDiscord; use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\Test\TestNotificationEmail; use FireflyIII\Notifications\Test\TestNotificationEmail;
use FireflyIII\Notifications\Test\TestNotificationNtfy; use FireflyIII\Notifications\Test\TestNotificationNtfy;
use FireflyIII\Notifications\Test\TestNotificationPushover; use FireflyIII\Notifications\Test\TestNotificationPushover;
use FireflyIII\Notifications\Test\TestNotificationSlack; use FireflyIII\Notifications\Test\TestNotificationSlack;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Notification;
@ -49,30 +47,23 @@ class AdminEventHandler
if (false === $sendMail) { if (false === $sendMail) {
return; 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 */ return;
$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());
}
} }
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; return;
} }
/** @var UserRepositoryInterface $repository */ try {
$repository = app(UserRepositoryInterface::class); $owner = new OwnerNotifiable();
$all = $repository->all(); Notification::send($owner, new VersionCheckResult($event->message));
foreach ($all as $user) { } catch (\Exception $e) {// @phpstan-ignore-line
if ($repository->hasRole($user, 'owner')) { $message = $e->getMessage();
try { if (str_contains($message, 'Bcc')) {
Notification::send($user, new VersionCheckResult($event->message)); app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
} 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; 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());
}
} }
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)); Log::debug(sprintf('Now in sendTestNotification("%s")', $event->channel));
switch($event->channel) { switch ($event->channel) {
case 'email': case 'email':
$class = TestNotificationEmail::class; $class = TestNotificationEmail::class;
break; break;

View File

@ -82,8 +82,8 @@ class UserEventHandler
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
/** @var User $user */ /** @var User $user */
$user = $event->user; $user = $event->user;
$count = $repository->count(); $count = $repository->count();
// only act when there is 1 user in the system and he has no admin rights. // only act when there is 1 user in the system and he has no admin rights.
if (1 === $count && !$repository->hasRole($user, 'owner')) { if (1 === $count && !$repository->hasRole($user, 'owner')) {
@ -115,13 +115,13 @@ class UserEventHandler
*/ */
public function createGroupMembership(RegisteredUser $event): void public function createGroupMembership(RegisteredUser $event): void
{ {
$user = $event->user; $user = $event->user;
$groupExists = true; $groupExists = true;
$groupTitle = $user->email; $groupTitle = $user->email;
$index = 1; $index = 1;
/** @var UserGroup $group */ /** @var UserGroup $group */
$group = null; $group = null;
// create a new group. // create a new group.
while (true === $groupExists) { // @phpstan-ignore-line while (true === $groupExists) { // @phpstan-ignore-line
@ -131,7 +131,7 @@ class UserEventHandler
break; break;
} }
$groupTitle = sprintf('%s-%d', $user->email, $index); $groupTitle = sprintf('%s-%d', $user->email, $index);
++$index; ++$index;
if ($index > 99) { if ($index > 99) {
throw new FireflyException('Email address can no longer be used for registrations.'); throw new FireflyException('Email address can no longer be used for registrations.');
@ -139,7 +139,7 @@ class UserEventHandler
} }
/** @var null|UserRole $role */ /** @var null|UserRole $role */
$role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first();
if (null === $role) { if (null === $role) {
throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?');
} }
@ -165,7 +165,7 @@ class UserEventHandler
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
/** @var User $user */ /** @var User $user */
$user = $event->user; $user = $event->user;
if ($repository->hasRole($user, 'demo')) { if ($repository->hasRole($user, 'demo')) {
// set user back to English. // set user back to English.
app('preferences')->setForUser($user, 'language', 'en_US'); app('preferences')->setForUser($user, 'language', 'en_US');
@ -186,7 +186,7 @@ class UserEventHandler
return; // do not email demo user. 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)) { if (!is_array($list)) {
$list = []; $list = [];
} }
@ -220,31 +220,25 @@ class UserEventHandler
public function sendAdminRegistrationNotification(RegisteredUser $event): void 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) { if ($sendMail) {
/** @var UserRepositoryInterface $repository */ $owner = $event->owner;
$repository = app(UserRepositoryInterface::class); try {
$all = $repository->all(); Notification::send($owner, new AdminRegistrationNotification($event->owner, $event->user));
foreach ($all as $user) { } catch (\Exception $e) { // @phpstan-ignore-line
if ($repository->hasRole($user, 'owner')) { $message = $e->getMessage();
try { if (str_contains($message, 'Bcc')) {
Notification::send($user, new AdminRegistrationNotification($event->user)); app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
} 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; 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());
}
} }
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; $oldEmail = $event->oldEmail;
$user = $event->user; $user = $event->user;
$token = app('preferences')->getForUser($user, 'email_change_undo_token', 'invalid'); $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]); $url = route('profile.undo-email-change', [$token->data, $hashed]);
try { try {
@ -347,7 +341,7 @@ class UserEventHandler
*/ */
public function sendRegistrationMail(RegisteredUser $event): void 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) { if ($sendMail) {
try { try {
Notification::send($event->user, new UserRegistrationNotification()); Notification::send($event->user, new UserRegistrationNotification());
@ -375,7 +369,7 @@ class UserEventHandler
public function storeUserIPAddress(ActuallyLoggedIn $event): void public function storeUserIPAddress(ActuallyLoggedIn $event): void
{ {
app('log')->debug('Now in storeUserIPAddress'); app('log')->debug('Now in storeUserIPAddress');
$user = $event->user; $user = $event->user;
if ($user->hasRole('demo')) { if ($user->hasRole('demo')) {
app('log')->debug('Do not log demo user logins'); app('log')->debug('Do not log demo user logins');
@ -392,8 +386,8 @@ class UserEventHandler
return; return;
} }
$inArray = false; $inArray = false;
$ip = request()->ip(); $ip = request()->ip();
app('log')->debug(sprintf('User logging in from IP address %s', $ip)); app('log')->debug(sprintf('User logging in from IP address %s', $ip));
// update array if in array // update array if in array
@ -421,7 +415,7 @@ class UserEventHandler
$preference = array_values($preference); $preference = array_values($preference);
/** @var bool $send */ /** @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); app('preferences')->setForUser($user, 'login_ip_history', $preference);
if (false === $inArray && true === $send) { if (false === $inArray && true === $send) {

View File

@ -77,7 +77,7 @@ class NotificationController extends Controller
// validate pushover // validate pushover
if ('' === $pushoverAppToken || '' === $pushoverUserToken) { if ('' === $pushoverAppToken || '' === $pushoverUserToken) {
Log::warning('No Pushover token, channel is disabled.'); Log::warning('[a] No Pushover token, channel is disabled.');
$forcedAvailability['pushover'] = false; $forcedAvailability['pushover'] = false;
} }

View File

@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers\Auth;
use FireflyIII\Events\RegisteredUser; use FireflyIII\Events\RegisteredUser;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Http\Controllers\CreateStuff; use FireflyIII\Support\Http\Controllers\CreateStuff;
use FireflyIII\User; use FireflyIII\User;
@ -94,7 +95,8 @@ class RegisterController extends Controller
$this->validator($request->all())->validate(); $this->validator($request->all())->validate();
$user = $this->createUser($request->all()); $user = $this->createUser($request->all());
app('log')->info(sprintf('Registered new user %s', $user->email)); 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); $this->guard()->login($user);

View File

@ -25,6 +25,7 @@ namespace FireflyIII\Http\Controllers;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidFormatException;
use FireflyIII\Events\NewVersionAvailable;
use FireflyIII\Events\RequestedVersionCheckStatus; use FireflyIII\Events\RequestedVersionCheckStatus;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;

View File

@ -25,11 +25,16 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin; namespace FireflyIII\Notifications\Admin;
use FireflyIII\Models\InvitedUser; 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\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/** /**
* Class UserInvitation * Class UserInvitation
@ -38,14 +43,16 @@ class UserInvitation extends Notification
{ {
use Queueable; use Queueable;
private InvitedUser $invitee; private InvitedUser $invitee;
private OwnerNotifiable $owner;
/** /**
* Create a new notification instance. * Create a new notification instance.
*/ */
public function __construct(InvitedUser $invitee) public function __construct(OwnerNotifiable $owner, InvitedUser $invitee)
{ {
$this->invitee = $invitee; $this->invitee = $invitee;
$this->owner = $owner;
} }
/** /**
@ -57,7 +64,7 @@ class UserInvitation extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toArray($notifiable) public function toArray(OwnerNotifiable $notifiable)
{ {
return [ return [
]; ];
@ -72,12 +79,11 @@ class UserInvitation extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toMail($notifiable) public function toMail(OwnerNotifiable $notifiable)
{ {
return (new MailMessage()) return (new MailMessage())
->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) ->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) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toSlack($notifiable) public function toSlack(OwnerNotifiable $notifiable)
{ {
return (new SlackMessage())->content( 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. * Get the notification's delivery channels.
* *
@ -105,16 +143,8 @@ class UserInvitation extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function via($notifiable) public function via(OwnerNotifiable $notifiable)
{ {
return ReturnsAvailableChannels::returnChannels('owner');
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
} }
} }

View File

@ -24,12 +24,17 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin; 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 FireflyIII\User;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/** /**
* Class UserRegistration * Class UserRegistration
@ -38,26 +43,24 @@ class UserRegistration extends Notification
{ {
use Queueable; use Queueable;
private User $user; private OwnerNotifiable $owner;
private User $user;
/** /**
* Create a new notification instance. * Create a new notification instance.
*/ */
public function __construct(User $user) public function __construct(OwnerNotifiable $owner, User $user)
{ {
$this->user = $user; $this->user = $user;
$this->owner = $owner;
} }
/** /**
* Get the array representation of the notification. * Get the array representation of the notification.
* *
* @param mixed $notifiable
*
* @return array
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toArray($notifiable) public function toArray(OwnerNotifiable $notifiable)
{ {
return [ return [
]; ];
@ -72,12 +75,11 @@ class UserRegistration extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toMail($notifiable) public function toMail(OwnerNotifiable $notifiable)
{ {
return (new MailMessage()) return (new MailMessage())
->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id]) ->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) * @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) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function via($notifiable) public function via(OwnerNotifiable $notifiable)
{ {
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; return ReturnsAvailableChannels::returnChannels('owner');
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
} }
} }

View File

@ -24,11 +24,17 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Admin; namespace FireflyIII\Notifications\Admin;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\Support\Notifications\UrlValidator; use FireflyIII\Support\Notifications\UrlValidator;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
/** /**
* Class VersionCheckResult * Class VersionCheckResult
@ -56,7 +62,7 @@ class VersionCheckResult extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toArray($notifiable) public function toArray(OwnerNotifiable $notifiable)
{ {
return [ return [
]; ];
@ -71,7 +77,7 @@ class VersionCheckResult extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toMail($notifiable) public function toMail(OwnerNotifiable $notifiable)
{ {
return (new MailMessage()) return (new MailMessage())
->markdown('emails.new-version', ['message' => $this->message]) ->markdown('emails.new-version', ['message' => $this->message])
@ -88,7 +94,7 @@ class VersionCheckResult extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toSlack($notifiable) public function toSlack(OwnerNotifiable $notifiable)
{ {
return (new SlackMessage())->content($this->message) return (new SlackMessage())->content($this->message)
->attachment(static function ($attachment): void { ->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. * Get the notification's delivery channels.
* *
@ -106,13 +144,8 @@ class VersionCheckResult extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function via($notifiable) public function via(OwnerNotifiable $notifiable)
{ {
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data; return ReturnsAvailableChannels::returnChannels('owner');
if (UrlValidator::isValidWebhookURL($slackUrl)) {
return ['mail', 'slack'];
}
return ['mail'];
} }
} }

View File

@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Notifiables; namespace FireflyIII\Notifications\Notifiables;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use NotificationChannels\Pushover\PushoverReceiver; use NotificationChannels\Pushover\PushoverReceiver;
@ -41,6 +42,7 @@ class OwnerNotifiable
public function routeNotificationForPushover() public function routeNotificationForPushover()
{ {
Log::debug('Return settings for routeNotificationForPushover');
$pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; $pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; $pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
return PushoverReceiver::withUserKey($pushoverUserToken) return PushoverReceiver::withUserKey($pushoverUserToken)
@ -59,8 +61,10 @@ class OwnerNotifiable
{ {
$method = 'routeNotificationFor' . Str::studly($driver); $method = 'routeNotificationFor' . Str::studly($driver);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
Log::debug(sprintf('Redirect for settings to "%s".', $method));
return $this->{$method}($notification); // @phpstan-ignore-line return $this->{$method}($notification); // @phpstan-ignore-line
} }
Log::debug(sprintf('No method "%s" found, return generic settings.', $method));
return match ($driver) { return match ($driver) {
'mail' => (string) config('firefly.site_owner'), 'mail' => (string) config('firefly.site_owner'),

View File

@ -24,23 +24,57 @@ declare(strict_types=1);
namespace FireflyIII\Notifications; namespace FireflyIII\Notifications;
use FireflyIII\Support\Notifications\UrlValidator; use FireflyIII\Support\Notifications\UrlValidator;
use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverChannel;
use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel;
class ReturnsAvailableChannels class ReturnsAvailableChannels
{ {
public static function returnChannels(string $type): array { public static function returnChannels(string $type): array
{
$channels = ['mail']; $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; 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;
}
} }

View File

@ -25,13 +25,11 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Test; namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\User;
use Illuminate\Bus\Queueable; 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\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
//use Illuminate\Notifications\Slack\SlackMessage;
/** /**
* Class TestNotification * Class TestNotification
@ -47,7 +45,7 @@ class TestNotificationSlack extends Notification
*/ */
public function __construct(OwnerNotifiable $owner) public function __construct(OwnerNotifiable $owner)
{ {
$this->owner =$owner; $this->owner = $owner;
} }
/** /**
@ -75,14 +73,8 @@ class TestNotificationSlack extends Notification
*/ */
public function toSlack(OwnerNotifiable $notifiable) public function toSlack(OwnerNotifiable $notifiable)
{ {
// since it's an admin notification, grab the URL from fireflyconfig return new SlackMessage()->content((string) trans('email.admin_test_subject'));
$url = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data; //return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url);
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.');
} }
/** /**

View File

@ -429,10 +429,7 @@ class User extends Authenticatable
} }
// not the best way to do this, but alas. // not the best way to do this, but alas.
if ($notification instanceof UserInvitation) { if ($notification instanceof UserRegistration) {
return $res;
}
if ($notification instanceof UserRegistration) {
return $res; return $res;
} }
if ($notification instanceof VersionCheckResult) { if ($notification instanceof VersionCheckResult) {

View File

@ -62,7 +62,7 @@ return [
'secret' => env('MANDRILL_SECRET'), 'secret' => env('MANDRILL_SECRET'),
], ],
'pushover' => [ 'pushover' => [
'token' => env('PUSHOVER_APP_TOKEN', ''), 'token' => 'fake_token',
'user_token' => env('PUSHOVER_USER_TOKEN', ''), 'user_token' => 'fake_token',
], ],
]; ];