Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions lib/BackgroundJob/ContextChat/ScheduleJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace OCA\Mail\BackgroundJob\ContextChat;

use OCA\Mail\Db\Mailbox;
use OCA\Mail\Exception\ServiceException;
use OCA\Mail\Service\AccountService;
use OCA\Mail\Service\ContextChat\ContextChatSettingsService;
Expand Down Expand Up @@ -69,13 +70,21 @@ protected function run($argument): void {
return;
}

foreach ($mailboxes as $mailbox) {
// Messages fetched by the initial sync don't emit NewMessagesSynchronized, so wait until it ran
$cachedMailboxes = array_filter($mailboxes, static fn (Mailbox $mailbox): bool => $mailbox->isCached());
if ($cachedMailboxes === []) {
$this->logger->debug("No synchronized mailboxes for account <{$accountId}> yet, postponing context chat import");
return;
}

foreach ($cachedMailboxes as $mailbox) {
try {
$this->taskService->findByMailboxId($mailbox->getId());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this removal related to the above cachedMailboxes change?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it makes sure that we do not require the task to exist when scheduling a task

$this->taskService->updateOrCreate($mailbox->getId(), 0);
} catch (DoesNotExistException|MultipleObjectsReturnedException|Exception $e) {
$this->logger->warning("Could not schedule context chat indexing tasks for mailbox <{$mailbox->getId()}>");
} catch (MultipleObjectsReturnedException|Exception $e) {
$this->logger->warning("Could not schedule context chat indexing task for mailbox <{$mailbox->getId()}>", ['exception' => $e]);
}
}

$this->jobList->remove(self::class, $argument);
}
}
4 changes: 4 additions & 0 deletions lib/ContextChat/ContextChatProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace OCA\Mail\ContextChat;

use OCA\Mail\AppInfo\Application;
use OCA\Mail\BackgroundJob\ContextChat\ScheduleJob;
use OCA\Mail\Db\Message;
use OCA\Mail\Db\MessageMapper;
use OCA\Mail\Events\MessageDeletedEvent;
Expand Down Expand Up @@ -124,5 +125,8 @@ public function getItemUrl(string $id): string {
*/
#[\Override]
public function triggerInitialImport(): void {
foreach ($this->accountService->getAllAcounts() as $account) {
$this->jobList->add(ScheduleJob::class, ['accountId' => $account->getId()]);
}
}
}
158 changes: 158 additions & 0 deletions tests/Unit/BackgroundJob/ContextChat/ScheduleJobTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<?php

declare(strict_types=1);

/*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Mail\Tests\Unit\BackgroundJob\ContextChat;

use ChristophWurst\Nextcloud\Testing\TestCase;
use OCA\Mail\Account;
use OCA\Mail\BackgroundJob\ContextChat\ScheduleJob;
use OCA\Mail\Db\ContextChat\Task;
use OCA\Mail\Db\MailAccount;
use OCA\Mail\Db\Mailbox;
use OCA\Mail\Service\AccountService;
use OCA\Mail\Service\ContextChat\ContextChatSettingsService;
use OCA\Mail\Service\ContextChat\TaskService;
use OCA\Mail\Service\MailManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\ContextChat\IContentManager;
use OCP\DB\Exception;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;

class ScheduleJobTest extends TestCase {
private const ARGUMENT = ['accountId' => 42];

private ITimeFactory&MockObject $time;
private TaskService&MockObject $taskService;
private AccountService&MockObject $accountService;
private MailManager&MockObject $mailManager;
private LoggerInterface&MockObject $logger;
private IJobList&MockObject $jobList;
private ContextChatSettingsService&MockObject $settingsService;
private IContentManager&MockObject $contentManager;
private ScheduleJob $job;
private Account $account;

protected function setUp(): void {
parent::setUp();

if (!interface_exists(IContentManager::class)) {
$this->markTestSkipped();
}

$this->time = $this->createMock(ITimeFactory::class);
$this->taskService = $this->createMock(TaskService::class);
$this->accountService = $this->createMock(AccountService::class);
$this->mailManager = $this->createMock(MailManager::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->jobList = $this->createMock(IJobList::class);
$this->settingsService = $this->createMock(ContextChatSettingsService::class);
$this->contentManager = $this->createMock(IContentManager::class);

$this->time->method('getTime')->willReturn(2 * 24 * 60 * 60);
$this->contentManager->method('isContextChatAvailable')->willReturn(true);
$mailAccount = new MailAccount();
$mailAccount->setId(self::ARGUMENT['accountId']);
$mailAccount->setUserId('user');
$this->account = new Account($mailAccount);

$this->job = new ScheduleJob(
$this->time,
$this->taskService,
$this->accountService,
$this->mailManager,
$this->logger,
$this->jobList,
$this->settingsService,
$this->contentManager,
);
$this->job->setArgument(self::ARGUMENT);
$this->job->setLastRun(0);
}

private function createMailbox(int $id, bool $cached): Mailbox {
$mailbox = new Mailbox();
$mailbox->setId($id);
if ($cached) {
$mailbox->setSyncNewToken('new');
$mailbox->setSyncChangedToken('changed');
$mailbox->setSyncVanishedToken('vanished');
}
return $mailbox;
}

public function testResetsCachedMailboxesAndRemovesItself(): void {
$this->accountService->method('findById')->willReturn($this->account);
$this->settingsService->method('isIndexingEnabled')->with('user')->willReturn(true);
$this->mailManager->method('getMailboxes')->willReturn([
$this->createMailbox(1, true),
$this->createMailbox(2, false),
$this->createMailbox(3, true),
]);
$scheduled = [];
$this->taskService->expects($this->exactly(2))
->method('updateOrCreate')
->willReturnCallback(function (int $mailboxId, int $lastMessageId) use (&$scheduled) {
$scheduled[$mailboxId] = $lastMessageId;
return new Task();
});
$this->jobList->expects($this->once())
->method('remove')
->with(ScheduleJob::class, self::ARGUMENT);

$this->job->start($this->jobList);

$this->assertSame([1 => 0, 3 => 0], $scheduled);
}

public function testRemovesItselfWhenSchedulingATaskFails(): void {
$this->accountService->method('findById')->willReturn($this->account);
$this->settingsService->method('isIndexingEnabled')->willReturn(true);
$this->mailManager->method('getMailboxes')->willReturn([$this->createMailbox(1, true)]);
$this->taskService->method('updateOrCreate')->willThrowException(new Exception());
$this->logger->expects($this->once())->method('warning');
$this->jobList->expects($this->once())
->method('remove')
->with(ScheduleJob::class, self::ARGUMENT);

$this->job->start($this->jobList);
}

public function testPostponesUntilInitialSync(): void {
$this->accountService->method('findById')->willReturn($this->account);
$this->settingsService->method('isIndexingEnabled')->willReturn(true);
$this->mailManager->method('getMailboxes')->willReturn([$this->createMailbox(1, false)]);
$this->taskService->expects($this->never())->method('updateOrCreate');
$this->jobList->expects($this->never())->method('remove');

$this->job->start($this->jobList);
}

public function testPostponesWhileIndexingIsDisabled(): void {
$this->accountService->method('findById')->willReturn($this->account);
$this->settingsService->method('isIndexingEnabled')->willReturn(false);
$this->mailManager->expects($this->never())->method('getMailboxes');
$this->taskService->expects($this->never())->method('updateOrCreate');
$this->jobList->expects($this->never())->method('remove');

$this->job->start($this->jobList);
}

public function testRemovesItselfForDeletedAccount(): void {
$this->accountService->method('findById')->willThrowException(new DoesNotExistException(''));
$this->taskService->expects($this->never())->method('updateOrCreate');
$this->jobList->expects($this->once())
->method('remove')
->with(ScheduleJob::class, self::ARGUMENT);

$this->job->start($this->jobList);
}
}
27 changes: 27 additions & 0 deletions tests/Unit/ContextChat/ContextChatProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use ChristophWurst\Nextcloud\Testing\TestCase;
use OCA\Mail\Account;
use OCA\Mail\BackgroundJob\ContextChat\ScheduleJob;
use OCA\Mail\ContextChat\ContextChatProvider;
use OCA\Mail\Db\MailAccount;
use OCA\Mail\Db\Mailbox;
Expand Down Expand Up @@ -148,6 +149,32 @@ public function testHandleWithContextChat($event) {
$this->contextChatProvider->handle($event);
}

public function testTriggerInitialImportSchedulesEveryAccount(): void {
$first = new MailAccount();
$first->setId(1);
$second = new MailAccount();
$second->setId(2);
$this->accountService->method('getAllAcounts')->willReturn([$first, $second]);
$scheduled = [];
$this->jobList->expects($this->exactly(2))
->method('add')
->willReturnCallback(function (string $job, array $argument) use (&$scheduled): void {
$this->assertSame(ScheduleJob::class, $job);
$scheduled[] = $argument;
});

$this->contextChatProvider->triggerInitialImport();

$this->assertSame([['accountId' => 1], ['accountId' => 2]], $scheduled);
}

public function testTriggerInitialImportWithoutAccounts(): void {
$this->accountService->method('getAllAcounts')->willReturn([]);
$this->jobList->expects($this->never())->method('add');

$this->contextChatProvider->triggerInitialImport();
}

public function testGetId(): void {
$this->assertEquals('mail', $this->contextChatProvider->getId());
}
Expand Down
Loading