Skip to content
120 changes: 120 additions & 0 deletions lib/Db/EmailLink/EmailLinkAccountQueries.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

/**
* The email link queries per Mail account.
*
* SPDX-License-Identifier: EUPL-1.2
* SPDX-FileCopyrightText: 2026 Conduction B.V.
*
* @category Database
* @package OCA\OpenRegister\Db\EmailLink
*
* @author Conduction Development Team <dev@conduction.nl>
* @copyright 2026 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* @link https://OpenRegister.app
*
* @spec openspec/specs/integration-email/spec.md
*/

declare(strict_types=1);

namespace OCA\OpenRegister\Db\EmailLink;

use OCA\OpenRegister\Db\EmailLink;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use Throwable;

/**
* Reads the links of one Mail account and points a link at another copy of its mail.
*
* Without the link table (deployments on the `_mail` metadata column) an
* account has no links.
*
* @template-extends QBMapper<EmailLink>
*
* @spec openspec/specs/integration-email/spec.md
*/
class EmailLinkAccountQueries extends QBMapper {

/**
* Whether the link table exists, once asked.
*
* @var boolean|null
*/
private ?bool $tableExists = null;

/**
* Constructor.
*
* @param IDBConnection $db The database.
*/
public function __construct(IDBConnection $db) {
parent::__construct(db: $db, tableName: 'openregister_email_links', entityClass: EmailLink::class);
}//end __construct()

/**
* The links to a stored message of one Mail account; outbound links without a local message id are left out.
*
* @param int $mailAccountId The Mail account id.
*
* @return EmailLink[] The links, by id.
*
* @spec openspec/specs/integration-email/spec.md
*/
public function findByMailAccount(int $mailAccountId): array {
if ($this->tableExists() === false) {
return [];
}

$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('mail_account_id', $qb->createNamedParameter($mailAccountId, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->gt('mail_message_id', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
->orderBy('id', 'ASC');

return $this->findEntities(query: $qb);
}//end findByMailAccount()

/**
* Point one link at another local copy of its mail.
*
* @param int $linkId The link id.
* @param int $mailMessageId The copy's Mail message id.
* @param string $mailMessageUid The copy's IMAP uid.
*
* @return int The rows changed, 0 or 1.
*
* @spec openspec/specs/integration-email/spec.md
*/
public function repointToMessage(int $linkId, int $mailMessageId, string $mailMessageUid): int {
$qb = $this->db->getQueryBuilder();
$qb->update($this->getTableName())
->set('mail_message_id', $qb->createNamedParameter($mailMessageId, IQueryBuilder::PARAM_INT))
->set('mail_message_uid', $qb->createNamedParameter($mailMessageUid))
->where($qb->expr()->eq('id', $qb->createNamedParameter($linkId, IQueryBuilder::PARAM_INT)));

return $qb->executeStatement();
}//end repointToMessage()

/**
* Whether the link table is present in this deployment.
*
* @return bool True when it is.
*/
private function tableExists(): bool {
if ($this->tableExists === null) {
try {
$this->tableExists = $this->db->tableExists($this->getTableName());
} catch (Throwable) {
$this->tableExists = false;
}
}

return $this->tableExists;
}//end tableExists()
}//end class
153 changes: 153 additions & 0 deletions lib/Listener/MailMessageLinksListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php

/**
* Keeps email links in step when the Nextcloud Mail app removes, moves or stores messages.
*
* SPDX-License-Identifier: EUPL-1.2
* SPDX-FileCopyrightText: 2026 Conduction B.V.
*
* @category Listener
* @package OCA\OpenRegister\Listener
*
* @author Conduction Development Team <dev@conduction.nl>
* @copyright 2026 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* @link https://OpenRegister.app
*
* @spec openspec/specs/integration-email/spec.md
*/

declare(strict_types=1);

namespace OCA\OpenRegister\Listener;

use OCA\OpenRegister\Service\EmailLinkReconciler;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use Psr\Log\LoggerInterface;
use Throwable;

/**
* Reconciles the email links of the Mail account an event names.
*
* - `BeforeMessageDeletedEvent` on the account's trash: the message is about to
* be expunged, so its links move to another stored copy or are removed.
* - `MessageDeletedEvent`: Mail dropped the cached row of a deleted or moved
* message; links move to a stored copy when there is one.
* - `SynchronizationEvent`: Mail synced the account and may have stored the
* copy of a moved message; links still waiting for one move to it.
*
* Mail's events are read through their getters, so the listener needs no Mail
* class; a failure is logged and never stops Mail.
*
* @template-implements IEventListener<Event>
*
* @spec openspec/specs/integration-email/spec.md
*/
class MailMessageLinksListener implements IEventListener {

/**
* Mail's events this listener handles, by name: Mail may not be installed.
*/
public const EVENTS = [
self::BEFORE_DELETE,
'OCA\\Mail\\Events\\MessageDeletedEvent',
'OCA\\Mail\\Events\\SynchronizationEvent',
];

/**
* Run after Mail's own listeners, which drop or store the cached rows.
*/
public const PRIORITY = -1;

/**
* Mail's event before it deletes a message.
*/
private const BEFORE_DELETE = 'OCA\\Mail\\Events\\BeforeMessageDeletedEvent';

/**
* Constructor.
*
* @param EmailLinkReconciler $reconciler The link reconciliation.
* @param LoggerInterface $logger Logger for diagnostics.
*/
public function __construct(
private readonly EmailLinkReconciler $reconciler,
private readonly LoggerInterface $logger,
) {
}//end __construct()

/**
* Reconcile the links of the event's account.
*
* @param Event $event One of Mail's message events.
*
* @return void
*
* @spec openspec/specs/integration-email/spec.md
*/
public function handle(Event $event): void {
$account = $this->call(subject: $event, method: 'getAccount');
$accountId = $this->call(subject: $account, method: 'getId');
if (is_object($account) === false || is_int($accountId) === false || $accountId <= 0) {
return;
}

try {
$tally = $this->reconcile(event: $event, account: $account, accountId: $accountId);
} catch (Throwable $e) {
$this->logger->warning('[MailMessageLinks] could not reconcile email links of account ' . $accountId . ': ' . $e->getMessage());
return;
}

if ($tally !== null && ($tally['repointed'] > 0 || $tally['removed'] > 0)) {
$this->logger->info(
'[MailMessageLinks] account ' . $accountId . ': ' . $tally['repointed'] . ' email links repointed, ' . $tally['removed'] . ' removed'
);
}
}//end handle()

/**
* Reconcile for one event: a delete from the trash releases that message, any other event repoints.
*
* @param Event $event The event.
* @param object $account Mail's account.
* @param int $accountId The account id.
*
* @return array{kept: int, repointed: int, removed: int}|null What happened, or null when nothing was done.
*/
private function reconcile(Event $event, object $account, int $accountId): ?array {
if (is_a($event, self::BEFORE_DELETE) === false) {
return $this->reconciler->reconcileAccount(mailAccountId: $accountId);
}

$mailboxId = $this->call(subject: $this->call(subject: $event, method: 'getMailbox'), method: 'getId');
$trashId = $this->call(subject: $this->call(subject: $account, method: 'getMailAccount'), method: 'getTrashMailboxId');
$uid = $this->call(subject: $event, method: 'getUid');
if (is_int($mailboxId) === false || $mailboxId !== $trashId || is_int($uid) === false) {
return null;
}

return $this->reconciler->releaseMessage(mailAccountId: $accountId, mailboxId: $mailboxId, uid: $uid);
}//end reconcile()

/**
* Call a getter on a value when it has one.
*
* Mail's entities answer most getters through `__call`, so a callable
* check is used rather than `method_exists()`.
*
* @param mixed $subject The value.
* @param string $method The getter.
*
* @return mixed What it answers, or null.
*/
private function call(mixed $subject, string $method): mixed {
if (is_object($subject) === false || is_callable([$subject, $method]) === false) {
return null;
}

return $subject->$method();
}//end call()
}//end class
Loading