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(dav): expose Nextcloud groups to Contact's system addressbook contacts #40997

Open
wants to merge 2 commits 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
3 changes: 3 additions & 0 deletions apps/dav/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
'OCA\\DAV\\BackgroundJob\\PruneOutdatedSyncTokensJob' => $baseDir . '/../lib/BackgroundJob/PruneOutdatedSyncTokensJob.php',
'OCA\\DAV\\BackgroundJob\\RefreshWebcalJob' => $baseDir . '/../lib/BackgroundJob/RefreshWebcalJob.php',
'OCA\\DAV\\BackgroundJob\\RegisterRegenerateBirthdayCalendars' => $baseDir . '/../lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php',
'OCA\\DAV\\BackgroundJob\\SyncSystemAddressBookAfterUsersChange' => $baseDir . '/../lib/BackgroundJob/SyncSystemAddressBookAfterUsersChange.php',
'OCA\\DAV\\BackgroundJob\\UpdateCalendarResourcesRoomsBackgroundJob' => $baseDir . '/../lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php',
'OCA\\DAV\\BackgroundJob\\UploadCleanup' => $baseDir . '/../lib/BackgroundJob/UploadCleanup.php',
'OCA\\DAV\\BackgroundJob\\UserStatusAutomation' => $baseDir . '/../lib/BackgroundJob/UserStatusAutomation.php',
Expand Down Expand Up @@ -258,8 +259,10 @@
'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => $baseDir . '/../lib/Listener/CalendarShareUpdateListener.php',
'OCA\\DAV\\Listener\\CardListener' => $baseDir . '/../lib/Listener/CardListener.php',
'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => $baseDir . '/../lib/Listener/ClearPhotoCacheListener.php',
'OCA\\DAV\\Listener\\GroupChangeListener' => $baseDir . '/../lib/Listener/GroupChangeListener.php',
'OCA\\DAV\\Listener\\SubscriptionListener' => $baseDir . '/../lib/Listener/SubscriptionListener.php',
'OCA\\DAV\\Listener\\TrustedServerRemovedListener' => $baseDir . '/../lib/Listener/TrustedServerRemovedListener.php',
'OCA\\DAV\\Listener\\UserChangeListener' => $baseDir . '/../lib/Listener/UserChangeListener.php',
'OCA\\DAV\\Listener\\UserPreferenceListener' => $baseDir . '/../lib/Listener/UserPreferenceListener.php',
'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndex.php',
'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php',
Expand Down
3 changes: 3 additions & 0 deletions apps/dav/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class ComposerStaticInitDAV
'OCA\\DAV\\BackgroundJob\\PruneOutdatedSyncTokensJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/PruneOutdatedSyncTokensJob.php',
'OCA\\DAV\\BackgroundJob\\RefreshWebcalJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/RefreshWebcalJob.php',
'OCA\\DAV\\BackgroundJob\\RegisterRegenerateBirthdayCalendars' => __DIR__ . '/..' . '/../lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php',
'OCA\\DAV\\BackgroundJob\\SyncSystemAddressBookAfterUsersChange' => __DIR__ . '/..' . '/../lib/BackgroundJob/SyncSystemAddressBookAfterUsersChange.php',
'OCA\\DAV\\BackgroundJob\\UpdateCalendarResourcesRoomsBackgroundJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php',
'OCA\\DAV\\BackgroundJob\\UploadCleanup' => __DIR__ . '/..' . '/../lib/BackgroundJob/UploadCleanup.php',
'OCA\\DAV\\BackgroundJob\\UserStatusAutomation' => __DIR__ . '/..' . '/../lib/BackgroundJob/UserStatusAutomation.php',
Expand Down Expand Up @@ -273,8 +274,10 @@ class ComposerStaticInitDAV
'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarShareUpdateListener.php',
'OCA\\DAV\\Listener\\CardListener' => __DIR__ . '/..' . '/../lib/Listener/CardListener.php',
'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => __DIR__ . '/..' . '/../lib/Listener/ClearPhotoCacheListener.php',
'OCA\\DAV\\Listener\\GroupChangeListener' => __DIR__ . '/..' . '/../lib/Listener/GroupChangeListener.php',
'OCA\\DAV\\Listener\\SubscriptionListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionListener.php',
'OCA\\DAV\\Listener\\TrustedServerRemovedListener' => __DIR__ . '/..' . '/../lib/Listener/TrustedServerRemovedListener.php',
'OCA\\DAV\\Listener\\UserChangeListener' => __DIR__ . '/..' . '/../lib/Listener/UserChangeListener.php',
'OCA\\DAV\\Listener\\UserPreferenceListener' => __DIR__ . '/..' . '/../lib/Listener/UserPreferenceListener.php',
'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndex.php',
'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php',
Expand Down
19 changes: 12 additions & 7 deletions apps/dav/lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@
use OCA\DAV\Events\CardUpdatedEvent;
use OCA\DAV\Events\SubscriptionCreatedEvent;
use OCA\DAV\Events\SubscriptionDeletedEvent;
use OCA\DAV\Listener\GroupChangeListener;
use OCA\DAV\Listener\UserChangeListener;
use OCP\Accounts\UserUpdatedEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\Events\TrustedServerRemovedEvent;
Expand Down Expand Up @@ -102,6 +104,10 @@
use OCP\Config\BeforePreferenceSetEvent;
use OCP\Contacts\IManager as IContactsManager;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Group\Events\BeforeGroupChangedEvent;
use OCP\Group\Events\BeforeGroupDeletedEvent;
use OCP\Group\Events\UserAddedEvent;
use OCP\Group\Events\UserRemovedEvent;
use OCP\IUser;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -195,6 +201,12 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(BeforePreferenceDeletedEvent::class, UserPreferenceListener::class);
$context->registerEventListener(BeforePreferenceSetEvent::class, UserPreferenceListener::class);

$context->registerEventListener(BeforeGroupChangedEvent::class, GroupChangeListener::class);
$context->registerEventListener(BeforeGroupDeletedEvent::class, GroupChangeListener::class);
$context->registerEventListener(UserAddedEvent::class, UserChangeListener::class);
$context->registerEventListener(UserUpdatedEvent::class, UserChangeListener::class);
$context->registerEventListener(UserRemovedEvent::class, UserChangeListener::class);

$context->registerNotifierService(Notifier::class);

$context->registerCalendarProvider(CalendarProvider::class);
Expand Down Expand Up @@ -227,13 +239,6 @@ public function registerHooks(HookManager $hm,
}
});

$dispatcher->addListener(UserUpdatedEvent::class, function (UserUpdatedEvent $event) use ($container) {
/** @var SyncService $syncService */
$syncService = \OCP\Server::get(SyncService::class);
$syncService->updateUser($event->getUser());
});


$dispatcher->addListener(CalendarShareUpdatedEvent::class, function (CalendarShareUpdatedEvent $event) use ($container) {
/** @var Backend $backend */
$backend = $container->query(Backend::class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);

/**
* @copyright 2023, Citharel Thomas <[email protected]>
*
* @author Citharel Thomas <[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\DAV\BackgroundJob;

use OCA\DAV\CardDAV\SyncService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\IUser;

class SyncSystemAddressBookAfterUsersChange extends QueuedJob {
private SyncService $syncService;

public function __construct(SyncService $syncService, ITimeFactory $time) {
parent::__construct($time);
$this->syncService = $syncService;
}

/**
* @param IUser[] $argument
* @return void
*/
public function run($argument): void {
foreach ($argument as $user) {
$this->syncService->updateUser($user);
}
}
}
22 changes: 21 additions & 1 deletion apps/dav/lib/CardDAV/Converter.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@
namespace OCA\DAV\CardDAV;

use Exception;
use OCA\DAV\AppInfo\Application;
use OCP\Accounts\IAccountManager;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IURLGenerator;
use OCP\IImage;
use OCP\IUser;
Expand All @@ -42,12 +46,16 @@
/** @var IAccountManager */
private $accountManager;
private IUserManager $userManager;
private IGroupManager $groupManager;
private IConfig $config;

public function __construct(IAccountManager $accountManager,
IUserManager $userManager, IURLGenerator $urlGenerator) {
IUserManager $userManager, IGroupManager $groupManager, IURLGenerator $urlGenerator, IConfig $config) {
$this->accountManager = $accountManager;
$this->userManager = $userManager;
$this->groupManager = $groupManager;
$this->urlGenerator = $urlGenerator;
$this->config = $config;
}

public function createCardFromUser(IUser $user): ?VCard {
Expand Down Expand Up @@ -151,6 +159,18 @@
}
}

if ($this->config->getAppValue(Application::APP_ID, 'system_addressbook_expose_groups', 'no') === 'yes') {
$groupsToInclude = explode(',', $this->config->getAppValue(Application::APP_ID, 'system_addressbook_groups_to_include', ''));
$groupsToIgnore = explode(',', $this->config->getAppValue(Application::APP_ID, 'system_addressbook_groups_to_ignore', ''));
$groupNames = array_reduce($this->groupManager->getUserGroups($user), function ($groupNames, IGroup $group) use ($groupsToInclude, $groupsToIgnore) {
Copy link
Member

Choose a reason for hiding this comment

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

I might be wrong but this could be a use case for https://www.php.net/manual/en/function.array-intersect.php

if (!in_array($group->getGID(), $groupsToIgnore, true) && (empty($groupsToInclude) || in_array($group->getGID(), $groupsToInclude, true))) {

Check notice

Code scanning / Psalm

DocblockTypeContradiction Note

Docblock-defined type non-empty-list for $groupsToInclude is never falsy
$groupNames[] = $group->getDisplayName();
}
return $groupNames;
}, []);
$vCard->add(new Text($vCard, 'CATEGORIES', $groupNames));
}

if ($publish && !empty($cloudId)) {
$vCard->add(new Text($vCard, 'CLOUD', $cloudId));
$vCard->validate();
Expand Down
27 changes: 10 additions & 17 deletions apps/dav/lib/CardDAV/SyncService.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
*/
namespace OCA\DAV\CardDAV;

use OC\Accounts\AccountManager;
use OCP\AppFramework\Db\TTransactional;
use OCP\AppFramework\Http;
use OCP\IDBConnection;
Expand All @@ -42,6 +41,7 @@
use Sabre\DAV\Xml\Service;
use Sabre\HTTP\ClientHttpException;
use Sabre\VObject\Reader;
use Sabre\Xml\ParseException;
use function is_null;

class SyncService {
Expand Down Expand Up @@ -181,6 +181,9 @@ protected function download(string $url, string $userName, string $sharedSecret,
return $client->request('GET', $resourcePath);
}

/**
* @throws \DOMException
*/
private function buildSyncCollectionRequestBody(?string $syncToken): string {
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
Expand All @@ -201,9 +204,9 @@ private function buildSyncCollectionRequestBody(?string $syncToken): string {
/**
* @param string $body
* @return array
* @throws \Sabre\Xml\ParseException
* @throws ParseException
*/
private function parseMultiStatus($body) {
private function parseMultiStatus(string $body): array {
$xml = new Service();

/** @var MultiStatus $multiStatus */
Expand All @@ -217,9 +220,6 @@ private function parseMultiStatus($body) {
return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
}

/**
* @param IUser $user
*/
public function updateUser(IUser $user): void {
$systemAddressBook = $this->getLocalSystemAddressBook();
$addressBookId = $systemAddressBook['id'];
Expand All @@ -228,13 +228,12 @@ public function updateUser(IUser $user): void {
if ($user->isEnabled()) {
$this->atomic(function() use ($addressBookId, $cardId, $user) {
$card = $this->backend->getCard($addressBookId, $cardId);
$vCard = $this->converter->createCardFromUser($user);
if ($card === false) {
$vCard = $this->converter->createCardFromUser($user);
if ($vCard !== null) {
$this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
}
} else {
$vCard = $this->converter->createCardFromUser($user);
if (is_null($vCard)) {
$this->backend->deleteCard($addressBookId, $cardId);
} else {
Expand All @@ -247,21 +246,15 @@ public function updateUser(IUser $user): void {
}
}

/**
* @param IUser|string $userOrCardId
*/
public function deleteUser($userOrCardId) {
public function deleteUser(IUser|string $userOrCardId): void {
$systemAddressBook = $this->getLocalSystemAddressBook();
if ($userOrCardId instanceof IUser) {
$userOrCardId = self::getCardUri($userOrCardId);
}
$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
}

/**
* @return array|null
*/
public function getLocalSystemAddressBook() {
public function getLocalSystemAddressBook(): ?array {
if (is_null($this->localSystemAddressBook)) {
$systemPrincipal = "principals/system/system";
$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
Expand All @@ -272,7 +265,7 @@ public function getLocalSystemAddressBook() {
return $this->localSystemAddressBook;
}

public function syncInstance(\Closure $progressCallback = null) {
public function syncInstance(\Closure $progressCallback = null): void {
$systemAddressBook = $this->getLocalSystemAddressBook();
$this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
$this->updateUser($user);
Expand Down
56 changes: 56 additions & 0 deletions apps/dav/lib/Listener/GroupChangeListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

/**
* @copyright 2023 Thomas Citharel <[email protected]>
*
* @author Thomas Citharel <[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\DAV\Listener;

use OCA\DAV\AppInfo\Application;
use OCA\DAV\BackgroundJob\SyncSystemAddressBookAfterUsersChange;
use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Group\Events\BeforeGroupChangedEvent;
use OCP\Group\Events\BeforeGroupDeletedEvent;
use OCP\IConfig;

/**
* @template-implements IEventListener<BeforeGroupChangedEvent|BeforeGroupDeletedEvent>
*/
class GroupChangeListener implements IEventListener {
public function __construct(private IJobList $jobList, private IConfig $config) {
}

public function handle(Event $event): void {
if (!$this->canSyncBecauseOfGroupChange($event)) {
// Not what we subscribed to
return;
}
/** @var BeforeGroupChangedEvent|BeforeGroupDeletedEvent $event */
$this->jobList->add(SyncSystemAddressBookAfterUsersChange::class, $event->getGroup()->getUsers());
}

private function canSyncBecauseOfGroupChange(Event $event): bool {
return ($event instanceof BeforeGroupChangedEvent || $event instanceof BeforeGroupDeletedEvent) && $this->config->getAppValue(Application::APP_ID, 'system_addressbook_expose_groups', 'no') === 'yes';
}
}
60 changes: 60 additions & 0 deletions apps/dav/lib/Listener/UserChangeListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

/**
* @copyright 2023 Thomas Citharel <[email protected]>
*
* @author Thomas Citharel <[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\DAV\Listener;

use OCA\DAV\AppInfo\Application;
use OCA\DAV\BackgroundJob\SyncSystemAddressBookAfterUsersChange;
use OCP\Accounts\UserUpdatedEvent;
use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Group\Events\UserAddedEvent;
use OCP\Group\Events\UserRemovedEvent;
use OCP\IConfig;

/**
* @template-implements IEventListener<UserUpdatedEvent|UserAddedEvent|UserRemovedEvent>
*/
class UserChangeListener implements IEventListener {
public function __construct(private IJobList $jobList, private IConfig $config) {
}

public function handle(Event $event): void {
if (!($event instanceof UserUpdatedEvent || $event instanceof UserAddedEvent || $event instanceof UserRemovedEvent)) {

Check notice

Code scanning / Psalm

DocblockTypeContradiction Note

Docblock-defined type OCP\Group\Events\UserRemovedEvent for $event is always OCP\Group\Events\UserRemovedEvent
// Not what we subscribed to
return;
}

if ($this->canSyncBecauseOfGroupMembershipChange($event)) {
/** @var UserUpdatedEvent|UserAddedEvent|UserRemovedEvent $event */
$this->jobList->add(SyncSystemAddressBookAfterUsersChange::class, [$event->getUser()]);
}
}

private function canSyncBecauseOfGroupMembershipChange(Event $event): bool {
return $event instanceof UserUpdatedEvent || $this->config->getAppValue(Application::APP_ID, 'system_addressbook_expose_groups', 'no') === 'yes';
}
}
Loading
Loading