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

feat: One-click unsubscribe #8438

Merged
merged 1 commit into from
May 5, 2023
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
5 changes: 5 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,11 @@
'url' => '/integration/microsoft-auth',
'verb' => 'GET',
],
[
'name' => 'list#unsubscribe',
'url' => '/api/list/unsubscribe/{id}',
'verb' => 'POST',
],
],
'resources' => [
'accounts' => ['url' => '/api/accounts'],
Expand Down
112 changes: 112 additions & 0 deletions lib/Controller/ListController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

/*
* @copyright 2023 Christoph Wurst <[email protected]>
*
* @author 2023 Christoph Wurst <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace OCA\Mail\Controller;

use Exception;
use OCA\Mail\AppInfo\Application;
use OCA\Mail\Contracts\IMailManager;
use OCA\Mail\Http\JsonResponse;
use OCA\Mail\IMAP\IMAPClientFactory;
use OCA\Mail\Service\AccountService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\Http\Client\IClientService;
use OCP\IRequest;
use Psr\Log\LoggerInterface;

class ListController extends Controller {
private IMailManager $mailManager;
private AccountService $accountService;
private IMAPClientFactory $clientFactory;
private IClientService $httpClientService;
private LoggerInterface $logger;
private ?string $currentUserId;

public function __construct(IRequest $request,
IMailManager $mailManager,
AccountService $accountService,
IMAPClientFactory $clientFactory,
IClientService $httpClientService,
LoggerInterface $logger,
?string $userId) {
parent::__construct(Application::APP_ID, $request);
$this->mailManager = $mailManager;
$this->accountService = $accountService;
$this->clientFactory = $clientFactory;
$this->request = $request;
$this->httpClientService = $httpClientService;
$this->logger = $logger;
$this->currentUserId = $userId;
}

/**
* @param int $messageId
* @NoAdminRequired
* @UserRateThrottle(limit=10, period=3600)
* @return JsonResponse
*/
public function unsubscribe(int $id): JsonResponse {
try {
$message = $this->mailManager->getMessage($this->currentUserId, $id);
$mailbox = $this->mailManager->getMailbox($this->currentUserId, $message->getMailboxId());
$account = $this->accountService->find($this->currentUserId, $mailbox->getAccountId());
} catch (DoesNotExistException $e) {
return JsonResponse::fail(null, Http::STATUS_NOT_FOUND);
}

$client = $this->clientFactory->getClient($account);
try {
$imapMessage = $this->mailManager->getImapMessage(
$client,
$account,
$mailbox,
$message->getUid(),
true
);
$unsubscribeUrl = $imapMessage->getUnsubscribeUrl();
if ($unsubscribeUrl === null || !$imapMessage->isOneClickUnsubscribe()) {
return JsonResponse::fail(null, Http::STATUS_FORBIDDEN);
}

$httpClient = $this->httpClientService->newClient();
$httpClient->post($unsubscribeUrl, [
'body' => [
'List-Unsubscribe' => 'One-Click'
]
]);
} catch (Exception $e) {
$this->logger->error('Could not unsubscribe mailing list', [
'exception' => $e,
]);
return JsonResponse::error('Unknown error');
} finally {
$client->logout();
}

return JsonResponse::success();
}
}
39 changes: 26 additions & 13 deletions lib/IMAP/ImapMessageFetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
use OCA\Mail\Service\SmimeService;
use OCP\AppFramework\Db\DoesNotExistException;
use function str_starts_with;
use function strtolower;

class ImapMessageFetcher {
/** @var string[] */
Expand All @@ -70,6 +71,7 @@ class ImapMessageFetcher {
private string $rawReferences = '';
private string $dispositionNotificationTo = '';
private ?string $unsubscribeUrl = null;
private bool $isOneClickUnsubscribe = false;
private ?string $unsubscribeMailto = null;

public function __construct(int $uid,
Expand Down Expand Up @@ -251,6 +253,7 @@ public function fetchMessage(?Horde_Imap_Client_Data_Fetch $fetch = null): IMAPM
$this->rawReferences,
$this->dispositionNotificationTo,
$this->unsubscribeUrl,
$this->isOneClickUnsubscribe,
$this->unsubscribeMailto,
$envelope->in_reply_to,
$isEncrypted,
Expand Down Expand Up @@ -512,19 +515,29 @@ private function parseHeaders(Horde_Imap_Client_Data_Fetch $fetch): void {
$this->dispositionNotificationTo = $dispositionNotificationTo->value_single;
}

$listUnsubscribeHeader = $parsedHeaders->getHeader('list-unsubscribe');
if ($listUnsubscribeHeader !== null) {
$listHeaders = new Horde_ListHeaders();
/** @var Horde_ListHeaders_Base[] $headers */
$headers = $listHeaders->parse($listUnsubscribeHeader->name, $listUnsubscribeHeader->value_single);
foreach ($headers as $header) {
if (str_starts_with($header->url, 'http')) {
$this->unsubscribeUrl = $header->url;
break;
}
if (str_starts_with($header->url, 'mailto')) {
$this->unsubscribeMailto = $header->url;
break;
$dkimSignatureHeader = $parsedHeaders->getHeader('dkim-signature');
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: early return would lead to better readability here and save about 3 brackets 😉

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks. I will take that into account for the follow-up to add the DKIM signature validation.

$hasDkimSignature = $dkimSignatureHeader !== null;

if ($hasDkimSignature) {
$listUnsubscribeHeader = $parsedHeaders->getHeader('list-unsubscribe');
if ($listUnsubscribeHeader !== null) {
$listHeaders = new Horde_ListHeaders();
/** @var Horde_ListHeaders_Base[] $headers */
$headers = $listHeaders->parse($listUnsubscribeHeader->name, $listUnsubscribeHeader->value_single);
foreach ($headers as $header) {
if (str_starts_with($header->url, 'http')) {
$this->unsubscribeUrl = $header->url;

$unsubscribePostHeader = $parsedHeaders->getHeader('List-Unsubscribe-Post');
if ($unsubscribePostHeader !== null) {
$this->isOneClickUnsubscribe = strtolower($unsubscribePostHeader->value_single) === 'list-unsubscribe=one-click';
}
break;
}
if (str_starts_with($header->url, 'mailto')) {
$this->unsubscribeMailto = $header->url;
break;
}
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions lib/Model/IMAPMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class IMAPMessage implements IMessage, JsonSerializable {
private string $rawReferences;
private string $dispositionNotificationTo;
private ?string $unsubscribeUrl;
private bool $isOneClickUnsubscribe;
private ?string $unsubscribeMailto;
private string $rawInReplyTo;
private bool $isEncrypted;
Expand All @@ -103,6 +104,7 @@ public function __construct(int $uid,
string $rawReferences,
string $dispositionNotificationTo,
?string $unsubscribeUrl,
bool $isOneClickUnsubscribe,
?string $unsubscribeMailto,
string $rawInReplyTo,
bool $isEncrypted,
Expand All @@ -129,6 +131,7 @@ public function __construct(int $uid,
$this->rawReferences = $rawReferences;
$this->dispositionNotificationTo = $dispositionNotificationTo;
$this->unsubscribeUrl = $unsubscribeUrl;
$this->isOneClickUnsubscribe = $isOneClickUnsubscribe;
$this->unsubscribeMailto = $unsubscribeMailto;
$this->rawInReplyTo = $rawInReplyTo;
$this->isEncrypted = $isEncrypted;
Expand Down Expand Up @@ -312,6 +315,7 @@ public function jsonSerialize() {
'hasHtmlBody' => $this->hasHtmlMessage,
'dispositionNotificationTo' => $this->getDispositionNotificationTo(),
'unsubscribeUrl' => $this->unsubscribeUrl,
'isOneClickUnsubscribe' => $this->isOneClickUnsubscribe,
'unsubscribeMailto' => $this->unsubscribeMailto,
'scheduling' => $this->scheduling,
];
Expand Down Expand Up @@ -443,6 +447,14 @@ public function isSignatureValid(): bool {
return $this->signatureIsValid;
}

public function getUnsubscribeUrl(): ?string {
return $this->unsubscribeUrl;
}

public function isOneClickUnsubscribe(): bool {
return $this->isOneClickUnsubscribe;
}

/**
* Cast all values from an IMAP message into the correct DB format
*
Expand Down
24 changes: 23 additions & 1 deletion src/components/ThreadEnvelope.vue
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,14 @@
:data="error"
:auto-margin="true"
role="alert" />
<ConfirmModal v-if="message && message.unsubscribeUrl && showListUnsubscribeConfirmation"
<ConfirmModal v-if="message && message.unsubscribeUrl && message.isOneClickUnsubscribe && showListUnsubscribeConfirmation"
:confirm-text="t('mail', 'Unsubscribe')"
:title="t('mail', 'Unsubscribe via link')"
@cancel="showListUnsubscribeConfirmation = false"
@confirm="unsubscribeViaOneClick">
{{ t('mail', 'Unsubscribing will stop all messages from the mailing list {sender}', { sender: from }) }}
</ConfirmModal>
<ConfirmModal v-else-if="message && message.unsubscribeUrl && showListUnsubscribeConfirmation"
:confirm-text="t('mail', 'Unsubscribe')"
:confirm-url="message.unsubscribeUrl"
:title="t('mail', 'Unsubscribe via link')"
Expand Down Expand Up @@ -249,6 +256,7 @@ import NoTrashMailboxConfiguredError from '../errors/NoTrashMailboxConfiguredErr
import { isPgpText } from '../crypto/pgp'
import NcActions from '@nextcloud/vue/dist/Components/NcActions'
import NcActionText from '@nextcloud/vue/dist/Components/NcActionText'
import { unsubscribe } from '../service/ListService'

// Ternary loading state
const LOADING_DONE = 0
Expand Down Expand Up @@ -612,6 +620,20 @@ export default {
return t('mail', 'Could not archive message')
}
},
async unsubscribeViaOneClick() {
try {
this.unsubscribing = true

await unsubscribe(this.envelope.databaseId)
showSuccess(t('mail', 'Unsubscribe request sent'))
} catch (error) {
logger.error('Could not one-click unsubscribe', { error })
showError(t('mail', 'Could not unsubscribe from mailing list'))
} finally {
this.unsubscribing = false
this.showListUnsubscribeConfirmation = false
}
},
async unsubscribeViaMailto() {
const mailto = this.message.unsubscribeMailto
const [email, paramString] = mailto.replace(/^mailto:/, '').split('?')
Expand Down
31 changes: 31 additions & 0 deletions src/service/ListService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @copyright 2023 Christoph Wurst <[email protected]>
*
* @author 2023 Christoph Wurst <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export async function unsubscribe(id) {
const url = generateUrl('/apps/mail/api/list/unsubscribe/{id}', {
id,
})

axios.post(url)
}
Loading