id ?? 0); } public const LAST_ERROR_KEY = 'mailbox:last_error'; /** * The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path * is off for them. * * @return array|null */ public static function configuration(): ?array { return Settings::tenant()?->mailbox(); } public static function isConfigured(): bool { return self::configuration() !== null; } /** * @param list $senders addresses or domains * @return list * * @throws ChannelSyncException */ public function fetch(array $senders): array { $config = self::configuration(); if ($config === null) { throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.'); } try { $client = (new ClientManager)->make([ 'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true, 'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap', ]); $client->connect(); $folder = $client->getFolderByPath($config['folder']); $mails = []; foreach ($senders as $sender) { $messages = $folder->query() ->whereSince(CarbonImmutable::today()->subDays($config['lookback_days'])) ->whereFrom($sender) ->leaveUnread() ->get(); foreach ($messages as $message) { $mails[] = $this->toPortalMail($message); } } $client->disconnect(); } catch (Throwable $exception) { Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage()); throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception); } Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String()); Cache::forget(self::key(self::LAST_ERROR_KEY)); return $mails; } private function toPortalMail(Message $message): PortalMail { $text = $message->getTextBody(); if (trim($text) === '') { $text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody())); } $from = $message->getFrom()->first(); $date = $message->getDate()->first(); return new PortalMail( messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)), from: (string) ($from->mail ?? ''), subject: (string) $message->getSubject()->first(), text: $text, receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(), ); } }