Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mail filters #10135

Merged
merged 3 commits into from
Oct 16, 2024
Merged
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
6 changes: 6 additions & 0 deletions REUSE.toml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@ precedence = "aggregate"
SPDX-FileCopyrightText = "2024 Nextcloud GmbH and Nextcloud contributors"
SPDX-License-Identifier = "AGPL-3.0-or-later"

[[annotations]]
path = ["tests/data/mail-filter/*"]
precedence = "aggregate"
SPDX-FileCopyrightText = "2024 Nextcloud GmbH and Nextcloud contributors"
SPDX-License-Identifier = "AGPL-3.0-or-later"

[[annotations]]
path = ".github/CODEOWNERS"
precedence = "aggregate"
Expand Down
59 changes: 59 additions & 0 deletions lib/Controller/FilterController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Controller;

use OCA\Mail\AppInfo\Application;
use OCA\Mail\Service\AccountService;
use OCA\Mail\Service\FilterService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\Route;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\OCSController;
use OCP\IRequest;

class FilterController extends OCSController {
private string $currentUserId;

public function __construct(
IRequest $request,
string $userId,
private FilterService $mailFilterService,
private AccountService $accountService,
) {
parent::__construct(Application::APP_ID, $request);
$this->currentUserId = $userId;
}

#[Route(Route::TYPE_FRONTPAGE, verb: 'GET', url: '/api/filter/{accountId}', requirements: ['accountId' => '[\d]+'])]
public function getFilters(int $accountId) {
$account = $this->accountService->findById($accountId);

if ($account->getUserId() !== $this->currentUserId) {
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}

$result = $this->mailFilterService->parse($account->getMailAccount());

return new JSONResponse($result->getFilters());
}

#[Route(Route::TYPE_FRONTPAGE, verb: 'PUT', url: '/api/filter/{accountId}', requirements: ['accountId' => '[\d]+'])]
public function updateFilters(int $accountId, array $filters) {
$account = $this->accountService->findById($accountId);

if ($account->getUserId() !== $this->currentUserId) {
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}

$this->mailFilterService->update($account->getMailAccount(), $filters);

return new JSONResponse([]);
}
}
29 changes: 29 additions & 0 deletions lib/Exception/FilterParserException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Exception;

use Exception;

class FilterParserException extends Exception {

public static function invalidJson(\Throwable $exception): FilterParserException {
return new self(
'Failed to parse filter state json: ' . $exception->getMessage(),
0,
$exception,
);
}

public static function invalidState(): FilterParserException {
return new self(
'Reached an invalid state',
);
}
}
21 changes: 21 additions & 0 deletions lib/Exception/ImapFlagEncodingException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Exception;

use Exception;

class ImapFlagEncodingException extends Exception {
public static function create($label): ImapFlagEncodingException {
return new self(
'Failed to convert the given label "' . $label . '" to UTF7-IMAP',
0,
);
}
}
28 changes: 28 additions & 0 deletions lib/IMAP/ImapFlag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\IMAP;

use OCA\Mail\Exception\ImapFlagEncodingException;

class ImapFlag {
/**
* @throws ImapFlagEncodingException
*/
public function create(string $label): string {
$flag = str_replace(' ', '_', $label);
$flag = mb_convert_encoding($flag, 'UTF7-IMAP', 'UTF-8');

if ($flag === false) {
throw ImapFlagEncodingException::create($label);
}

return '$' . strtolower(mb_strcut($flag, 0, 63));
}
}
34 changes: 34 additions & 0 deletions lib/Service/AllowedRecipientsService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Service;

use OCA\Mail\Db\MailAccount;

class AllowedRecipientsService {

public function __construct(
private AliasesService $aliasesService,
) {
}

/**
* Return a list of allowed recipients for a given mail account
*
* @return string[] email addresses
*/
public function get(MailAccount $mailAccount): array {
$aliases = array_map(
static fn ($alias) => $alias->getAlias(),
$this->aliasesService->findAll($mailAccount->getId(), $mailAccount->getUserId())
);

return array_merge([$mailAccount->getEmail()], $aliases);
}
}
88 changes: 88 additions & 0 deletions lib/Service/FilterService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Service;

use Horde\ManageSieve\Exception as ManageSieveException;
use JsonException;
use OCA\Mail\Db\MailAccount;
use OCA\Mail\Exception\ClientException;
use OCA\Mail\Exception\CouldNotConnectException;
use OCA\Mail\Exception\FilterParserException;
use OCA\Mail\Exception\OutOfOfficeParserException;
use OCA\Mail\Service\MailFilter\FilterBuilder;
use OCA\Mail\Service\MailFilter\FilterParser;
use OCA\Mail\Service\MailFilter\FilterParserResult;
use OCA\Mail\Service\OutOfOffice\OutOfOfficeParser;
use OCA\Mail\Service\OutOfOffice\OutOfOfficeState;
use Psr\Log\LoggerInterface;

class FilterService {

public function __construct(
private AllowedRecipientsService $allowedRecipientsService,
private OutOfOfficeParser $outOfOfficeParser,
private FilterParser $filterParser,
private FilterBuilder $filterBuilder,
private SieveService $sieveService,
private LoggerInterface $logger,
) {
}

/**
* @throws ClientException
* @throws ManageSieveException
* @throws CouldNotConnectException
* @throws FilterParserException
*/
public function parse(MailAccount $account): FilterParserResult {
$script = $this->sieveService->getActiveScript($account->getUserId(), $account->getId());
return $this->filterParser->parseFilterState($script->getScript());
}

/**
* @throws CouldNotConnectException
* @throws JsonException
* @throws ClientException
* @throws OutOfOfficeParserException
* @throws ManageSieveException
* @throws FilterParserException
*/
public function update(MailAccount $account, array $filters): void {
$script = $this->sieveService->getActiveScript($account->getUserId(), $account->getId());

$oooResult = $this->outOfOfficeParser->parseOutOfOfficeState($script->getScript());
$filterResult = $this->filterParser->parseFilterState($oooResult->getUntouchedSieveScript());

$newScript = $this->filterBuilder->buildSieveScript(
$filters,
$filterResult->getUntouchedSieveScript()
);

$oooState = $oooResult->getState();

if ($oooState instanceof OutOfOfficeState) {
$newScript = $this->outOfOfficeParser->buildSieveScript(
$oooState,
$newScript,
$this->allowedRecipientsService->get($account),
);
}

try {
$this->sieveService->updateActiveScript($account->getUserId(), $account->getId(), $newScript);
} catch (ManageSieveException $e) {
$this->logger->error('Failed to save sieve script: ' . $e->getMessage(), [
'exception' => $e,
'script' => $newScript,
]);
throw $e;
}
}
}
Loading
Loading