|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors |
| 7 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | + */ |
| 9 | + |
| 10 | +namespace OCA\TwoFactorGateway\Listener; |
| 11 | + |
| 12 | +use OCA\TwoFactorGateway\AppInfo\Application; |
| 13 | +use OCA\TwoFactorGateway\Events\WhatsAppAuthenticationErrorEvent; |
| 14 | +use OCP\AppFramework\Utility\ITimeFactory; |
| 15 | +use OCP\EventDispatcher\Event; |
| 16 | +use OCP\EventDispatcher\IEventListener; |
| 17 | +use OCP\IGroupManager; |
| 18 | +use OCP\Notification\IManager; |
| 19 | +use Psr\Log\LoggerInterface; |
| 20 | + |
| 21 | +/** |
| 22 | + * @template-implements IEventListener<Event> |
| 23 | + */ |
| 24 | +class NotificationListener implements IEventListener { |
| 25 | + public function __construct( |
| 26 | + private IManager $notificationManager, |
| 27 | + private IGroupManager $groupManager, |
| 28 | + private ITimeFactory $timeFactory, |
| 29 | + private LoggerInterface $logger, |
| 30 | + ) { |
| 31 | + } |
| 32 | + |
| 33 | + #[\Override] |
| 34 | + public function handle(Event $event): void { |
| 35 | + if (!($event instanceof WhatsAppAuthenticationErrorEvent)) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + $this->notifyAdmins(); |
| 40 | + } |
| 41 | + |
| 42 | + private function notifyAdmins(): void { |
| 43 | + try { |
| 44 | + $adminGroup = $this->groupManager->get('admin'); |
| 45 | + if ($adminGroup === null) { |
| 46 | + $this->logger->error('Admin group not found'); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + $admins = $adminGroup->getUsers(); |
| 51 | + $this->logger->info('Found ' . count($admins) . ' admins to notify'); |
| 52 | + |
| 53 | + foreach ($admins as $user) { |
| 54 | + try { |
| 55 | + $notification = $this->notificationManager->createNotification(); |
| 56 | + $notification |
| 57 | + ->setApp(Application::APP_ID) |
| 58 | + ->setDateTime($this->timeFactory->getDateTime()) |
| 59 | + ->setObject('whatsapp_error', 'authentication') |
| 60 | + ->setSubject('whatsapp_auth_error') |
| 61 | + ->setUser($user->getUID()); |
| 62 | + |
| 63 | + $this->logger->info('About to notify user: ' . $user->getUID()); |
| 64 | + $this->notificationManager->notify($notification); |
| 65 | + $this->logger->info('WhatsApp auth error notification sent to ' . $user->getUID()); |
| 66 | + } catch (\Exception $e) { |
| 67 | + $this->logger->error('Failed to notify user ' . $user->getUID() . ': ' . $e->getMessage(), [ |
| 68 | + 'exception' => $e, |
| 69 | + ]); |
| 70 | + } |
| 71 | + } |
| 72 | + } catch (\Exception $e) { |
| 73 | + $this->logger->error('Error notifying admins about WhatsApp auth error: ' . $e->getMessage(), [ |
| 74 | + 'exception' => $e, |
| 75 | + ]); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments