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(contactsinteraction): allow users to disable contacts interaction addressbook #39372

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
6 changes: 6 additions & 0 deletions apps/contactsinteraction/appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,11 @@
<address-book-plugins>
<plugin>OCA\ContactsInteraction\AddressBookProvider</plugin>
</address-book-plugins>
<plugins>
<plugin>OCA\ContactsInteraction\DAV\Plugin</plugin>
</plugins>
</sabre>
<settings>
<personal>OCA\ContactsInteraction\Settings\Personal</personal>
</settings>
</info>
30 changes: 30 additions & 0 deletions apps/contactsinteraction/appinfo/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2023 Thomas Citharel <nextcloud@tcit.fr>
*
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @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/>.
*
*/
return [
'ocs' => [
['name' => 'config#disable', 'url' => '/config/user/disable', 'verb' => 'POST'],
],
];
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
'OCA\\ContactsInteraction\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
'OCA\\ContactsInteraction\\BackgroundJob\\CleanupJob' => $baseDir . '/../lib/BackgroundJob/CleanupJob.php',
'OCA\\ContactsInteraction\\Card' => $baseDir . '/../lib/Card.php',
'OCA\\ContactsInteraction\\DAV\\Plugin' => $baseDir . '/../lib/DAV/Plugin.php',
'OCA\\ContactsInteraction\\Db\\CardSearchDao' => $baseDir . '/../lib/Db/CardSearchDao.php',
'OCA\\ContactsInteraction\\Db\\RecentContact' => $baseDir . '/../lib/Db/RecentContact.php',
'OCA\\ContactsInteraction\\Db\\RecentContactMapper' => $baseDir . '/../lib/Db/RecentContactMapper.php',
'OCA\\ContactsInteraction\\Listeners\\ContactInteractionListener' => $baseDir . '/../lib/Listeners/ContactInteractionListener.php',
'OCA\\ContactsInteraction\\Listeners\\UserPreferenceListener' => $baseDir . '/../lib/Listeners/UserPreferenceListener.php',
'OCA\\ContactsInteraction\\Migration\\Version010000Date20200304152605' => $baseDir . '/../lib/Migration/Version010000Date20200304152605.php',
'OCA\\ContactsInteraction\\Settings\\Personal' => $baseDir . '/../lib/Settings/Personal.php',
);
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ class ComposerStaticInitContactsInteraction
'OCA\\ContactsInteraction\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
'OCA\\ContactsInteraction\\BackgroundJob\\CleanupJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/CleanupJob.php',
'OCA\\ContactsInteraction\\Card' => __DIR__ . '/..' . '/../lib/Card.php',
'OCA\\ContactsInteraction\\DAV\\Plugin' => __DIR__ . '/..' . '/../lib/DAV/Plugin.php',
'OCA\\ContactsInteraction\\Db\\CardSearchDao' => __DIR__ . '/..' . '/../lib/Db/CardSearchDao.php',
'OCA\\ContactsInteraction\\Db\\RecentContact' => __DIR__ . '/..' . '/../lib/Db/RecentContact.php',
'OCA\\ContactsInteraction\\Db\\RecentContactMapper' => __DIR__ . '/..' . '/../lib/Db/RecentContactMapper.php',
'OCA\\ContactsInteraction\\Listeners\\ContactInteractionListener' => __DIR__ . '/..' . '/../lib/Listeners/ContactInteractionListener.php',
'OCA\\ContactsInteraction\\Listeners\\UserPreferenceListener' => __DIR__ . '/..' . '/../lib/Listeners/UserPreferenceListener.php',
'OCA\\ContactsInteraction\\Migration\\Version010000Date20200304152605' => __DIR__ . '/..' . '/../lib/Migration/Version010000Date20200304152605.php',
'OCA\\ContactsInteraction\\Settings\\Personal' => __DIR__ . '/..' . '/../lib/Settings/Personal.php',
);

public static function getInitializer(ClassLoader $loader)
Expand Down
24 changes: 20 additions & 4 deletions apps/contactsinteraction/lib/AddressBookProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@
use OCA\ContactsInteraction\Db\RecentContactMapper;
use OCA\DAV\CardDAV\Integration\ExternalAddressBook;
use OCA\DAV\CardDAV\Integration\IAddressBookProvider;
use OCP\IConfig;
use OCP\IL10N;

class AddressBookProvider implements IAddressBookProvider {

public function __construct(
private RecentContactMapper $mapper,
private IL10N $l10n,
) {
}
private IConfig $config
) { }

/**
* @inheritDoc
Expand All @@ -33,6 +34,9 @@ public function getAppId(): string {
* @inheritDoc
*/
public function fetchAllForAddressBookHome(string $principalUri): array {
if ($this->disabledForPrincipal($principalUri)) {
return [];
}
return [
new AddressBook($this->mapper, $this->l10n, $principalUri)
];
Expand All @@ -42,17 +46,29 @@ public function fetchAllForAddressBookHome(string $principalUri): array {
* @inheritDoc
*/
public function hasAddressBookInAddressBookHome(string $principalUri, string $uri): bool {
return $uri === AddressBook::URI;
return $uri === AddressBook::URI && !$this->disabledForPrincipal($principalUri);
}

/**
* @inheritDoc
*/
public function getAddressBookInAddressBookHome(string $principalUri, string $uri): ?ExternalAddressBook {
if ($uri === AddressBook::URI) {
if ($uri === AddressBook::URI && !$this->disabledForPrincipal($principalUri)) {
return new AddressBook($this->mapper, $this->l10n, $principalUri);
}

return null;
}

private function disabledForPrincipal(string $principalUri): bool {
$userId = $this->principalToUserId($principalUri);
return $userId !== null && $this->config->getUserValue($userId, Application::APP_ID, 'disableContactsInteractionAddressBook', 'no') === 'yes';
}

private function principalToUserId(string $userPrincipal):?string {
if (str_starts_with($userPrincipal, 'principals/users/')) {
return substr($userPrincipal, 17);
}
return null;
}
}
6 changes: 6 additions & 0 deletions apps/contactsinteraction/lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
namespace OCA\ContactsInteraction\AppInfo;

use OCA\ContactsInteraction\Listeners\ContactInteractionListener;
use OCA\ContactsInteraction\Listeners\UserPreferenceListener;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\Config\BeforePreferenceDeletedEvent;
use OCP\Config\BeforePreferenceSetEvent;
use OCP\Contacts\Events\ContactInteractedWithEvent;

class Application extends App implements IBootstrap {
Expand All @@ -24,6 +27,9 @@ public function __construct() {

public function register(IRegistrationContext $context): void {
$context->registerEventListener(ContactInteractedWithEvent::class, ContactInteractionListener::class);

$context->registerEventListener(BeforePreferenceDeletedEvent::class, UserPreferenceListener::class);
$context->registerEventListener(BeforePreferenceSetEvent::class, UserPreferenceListener::class);
}

public function boot(IBootContext $context): void {
Expand Down
110 changes: 110 additions & 0 deletions apps/contactsinteraction/lib/DAV/Plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php
/**
* @copyright 2023, Thomas Citharel <nextcloud@tcit.fr>
*
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @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\ContactsInteraction\DAV;

use OCA\ContactsInteraction\AddressBook;
use OCA\ContactsInteraction\AppInfo\Application;
use OCA\ContactsInteraction\Db\RecentContactMapper;
use OCP\IConfig;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;

/**
* Allows users to disable the feature by deleting the addressbook
*
* @package OCA\DAV\CalDAV\BirthdayCalendar
*/
class Plugin extends ServerPlugin {

protected Server $server;
Fixed Show fixed Hide fixed

Check notice

Code scanning / Psalm

PropertyNotSetInConstructor Note

Property OCA\ContactsInteraction\DAV\Plugin::$server is not defined in constructor of OCA\ContactsInteraction\DAV\Plugin or in any methods called in the constructor

public function __construct(protected IConfig $config, protected RecentContactMapper $recentContactMapper) {
}

/**
* This method should return a list of server-features.
*
* This is for example 'versioning' and is added to the DAV: header
* in an OPTIONS response.
*
* @return string[]
*/
public function getFeatures() {
return ['nc-disable-recently-contacted'];
}

/**
* Returns a plugin name.
*
* Using this name other plugins will be able to access other plugins
* using Sabre\DAV\Server::getPlugin
*
* @return string
*/
public function getPluginName() {
return 'nc-disable-recently-contacted';
}

/**
* This initializes the plugin.
*
* This function is called by Sabre\DAV\Server, after
* addPlugin is called.
*
* This method should set up the required event subscriptions.
*
* @param Server $server
*/
public function initialize(Server $server) {

Check notice

Code scanning / Psalm

MissingReturnType Note

Method OCA\ContactsInteraction\DAV\Plugin::initialize does not have a return type, expecting void
$this->server = $server;

$this->server->on('method:DELETE', [$this, 'httpDelete']);
}

/**
* We intercept this to handle POST requests on contacts homes.
*
* @param RequestInterface $request
* @param ResponseInterface $response
*
* @return bool|void
*/
public function httpDelete(RequestInterface $request, ResponseInterface $response) {
$node = $this->server->tree->getNodeForPath($this->server->getRequestUri());
if (!($node instanceof AddressBook)) {
return;
}

$principalUri = $node->getOwner();
$userId = substr($principalUri, 17);

$this->config->setUserValue($userId, Application::APP_ID, 'disableContactsInteractionAddressBook', 'yes');
$this->recentContactMapper->cleanForUser($userId);

$this->server->httpResponse->setStatus(204);

return false;
}
}
10 changes: 10 additions & 0 deletions apps/contactsinteraction/lib/Db/RecentContactMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,14 @@ public function cleanUp(int $olderThan): void {

$delete->executeStatement();
}

public function cleanForUser(string $userId): void {
$qb = $this->db->getQueryBuilder();

$delete = $qb
->delete($this->getTableName())
->where($qb->expr()->eq('actor_uid', $qb->createNamedParameter($userId)));

$delete->executeStatement();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/
namespace OCA\ContactsInteraction\Listeners;

use OCA\ContactsInteraction\AppInfo\Application;
use OCA\ContactsInteraction\Db\CardSearchDao;
use OCA\ContactsInteraction\Db\RecentContact;
use OCA\ContactsInteraction\Db\RecentContactMapper;
Expand All @@ -16,6 +17,7 @@
use OCP\Contacts\Events\ContactInteractedWithEvent;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IUserManager;
Expand All @@ -35,6 +37,7 @@ public function __construct(
private IDBConnection $dbConnection,
private ITimeFactory $timeFactory,
private IL10N $l10n,
private IConfig $config,
private LoggerInterface $logger,
) {
}
Expand All @@ -54,6 +57,11 @@ public function handle(Event $event): void {
return;
}

if ($this->config->getUserValue($event->getActor()->getUID(), Application::APP_ID, 'disableContactsInteractionAddressBook', 'no') === 'yes') {
$this->logger->debug("Ignoring contact interaction as it's disabled for this user");
return;
}

$this->atomic(function () use ($event) {
$uid = $event->getUid();
$email = $event->getEmail();
Expand All @@ -75,9 +83,9 @@ public function handle(Event $event): void {
$federatedCloudId
);
if (!empty($existingRecentlyContacted)) {
$now = $this->timeFactory->getTime();
$now = $this->timeFactory->now();
foreach ($existingRecentlyContacted as $c) {
$c->setLastContact($now);
$c->setLastContact($now->getTimestamp());
$this->mapper->update($c);
}

Expand All @@ -95,7 +103,7 @@ public function handle(Event $event): void {
if ($federatedCloudId !== null) {
$contact->setFederatedCloudId($federatedCloudId);
}
$contact->setLastContact($this->timeFactory->getTime());
$contact->setLastContact($this->timeFactory->now()->getTimestamp());
$contact->setCard($this->generateCard($contact));

$this->mapper->insert($contact);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\ContactsInteraction\Listeners;

use OCA\ContactsInteraction\AppInfo\Application;
use OCA\ContactsInteraction\Db\RecentContactMapper;
use OCP\BackgroundJob\IJobList;
use OCP\Config\BeforePreferenceDeletedEvent;
use OCP\Config\BeforePreferenceSetEvent;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;

/** @template-implements IEventListener<BeforePreferenceSetEvent|BeforePreferenceDeletedEvent> */
class UserPreferenceListener implements IEventListener {

public function __construct(protected IJobList $jobList, private RecentContactMapper $recentContactMapper) { }

public function handle(Event $event): void {
if (!$event instanceof BeforePreferenceSetEvent && !$event instanceof BeforePreferenceDeletedEvent) {
return;
}

if ($event->getAppId() !== Application::APP_ID || $event->getConfigKey() !== 'disableContactsInteractionAddressBook') {
return;
}

$enabled = $event->getConfigValue() === 'yes';

Check notice

Code scanning / Psalm

PossiblyUndefinedMethod Note

Method OCP\Config\BeforePreferenceDeletedEvent::getConfigValue does not exist
Copy link
Member Author

Choose a reason for hiding this comment

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

indeed 🙈

$event->setValid($enabled);
if (!$enabled) {
$this->recentContactMapper->cleanForUser($event->getUserId());
}
}
}
Loading
Loading