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
5 changes: 5 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use OC\OCM\OCMSignatoryManager;
use OCA\Analytics\Datasource\DatasourceEvent;
use OCA\Circles\Events\CircleDestroyedEvent;
use OCA\Circles\Events\RemovingCircleMemberEvent;
use OCA\Tables\Capabilities;
use OCA\Tables\Config\ConfigLexicon;
use OCA\Tables\Event\RowDeletedEvent;
Expand All @@ -25,6 +26,7 @@
use OCA\Tables\Listener\ReceiverCleanupListener;
use OCA\Tables\Listener\ResourceTypeRegisterListener;
use OCA\Tables\Listener\TablesReferenceListener;
use OCA\Tables\Listener\TeamOwnershipListener;
use OCA\Tables\Listener\UserDeletedListener;
use OCA\Tables\Listener\WhenRowDeletedAuditLogListener;
use OCA\Tables\Listener\WhenTableDeletedAuditLogListener;
Expand Down Expand Up @@ -95,6 +97,7 @@ public function register(IRegistrationContext $context): void {
$context->registerService(ISignatoryManager::class, fn (ContainerInterface $c) => $c->get(OCMSignatoryManager::class));

$context->registerEventListener(BeforeUserDeletedEvent::class, UserDeletedListener::class);
$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
$context->registerEventListener(DatasourceEvent::class, AnalyticsDatasourceListener::class);
$context->registerEventListener(RegisterShareReviewSourceEvent::class, ShareReviewListener::class);
$context->registerEventListener(RenderReferenceEvent::class, TablesReferenceListener::class);
Expand All @@ -108,6 +111,8 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(UserDeletedEvent::class, ReceiverCleanupListener::class);
$context->registerEventListener(GroupDeletedEvent::class, ReceiverCleanupListener::class);
$context->registerEventListener(CircleDestroyedEvent::class, ReceiverCleanupListener::class);
$context->registerEventListener(CircleDestroyedEvent::class, TeamOwnershipListener::class);
$context->registerEventListener(RemovingCircleMemberEvent::class, TeamOwnershipListener::class);
$context->registerEventListener(LocalOCMDiscoveryEvent::class, ResourceTypeRegisterListener::class);

$context->registerSearchProvider(SearchTablesProvider::class);
Expand Down
47 changes: 47 additions & 0 deletions lib/BackgroundJob/RetryTeamTableHandover.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

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

namespace OCA\Tables\BackgroundJob;

use OCA\Tables\Helper\CircleHelper;
use OCA\Tables\Service\TableService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\TimedJob;
use OCP\IUserManager;

class RetryTeamTableHandover extends TimedJob {
public function __construct(
ITimeFactory $time,
private readonly CircleHelper $circleHelper,
private readonly TableService $tableService,
private readonly IJobList $jobList,
private readonly IUserManager $userManager,
) {
parent::__construct($time);
$this->setInterval(15 * 60);
}

/**
* @param array{teamId: string, userId: string} $argument
*/
#[\Override]
public function run($argument): void {
if (!$this->circleHelper->isCirclesEnabled()) {
return;
}
if ($this->userManager->userExists($argument['userId'])) {
$this->jobList->remove(self::class, $argument);
return;
}

$this->tableService->handleTeamStewardDeparture($argument['teamId'], $argument['userId']);
$this->jobList->remove(self::class, $argument);
}
}
14 changes: 10 additions & 4 deletions lib/Controller/ApiTablesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -385,19 +385,25 @@ public function importScheme(int $id, string $title, string $emoji, string $desc
* @param string|null $emoji Emoji for the table
* @param string|null $description Description for the table
* @param string $template Template to use if wanted
* @param string|null $teamId Team to attach the table to
*
* @return DataResponse<Http::STATUS_OK, TablesTable, array{}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
* @return DataResponse<Http::STATUS_OK, TablesTable, array{}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
*
* 200: Tables returned
* 400: Invalid request data
* 403: No permissions
*/
#[NoAdminRequired]
public function create(string $title, ?string $emoji, ?string $description, string $template = 'custom'): DataResponse {
public function create(string $title, ?string $emoji, ?string $description, string $template = 'custom', ?string $teamId = null): DataResponse {
try {
return new DataResponse($this->service->create($title, $template, $emoji, $description)->jsonSerialize());
return new DataResponse($this->service->create($title, $template, $emoji, $description, teamId: $teamId)->jsonSerialize());
} catch (\InvalidArgumentException $e) {
$this->logger->warning('An invalid request occurred: ' . $e->getMessage(), ['exception' => $e]);
return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
} catch (BadRequestError $e) {
return $this->handleBadRequestError($e);
} catch (PermissionError $e) {
return $this->handlePermissionError($e);
} catch (InternalError|Exception $e) {
return $this->handleError($e);
}
Expand Down Expand Up @@ -482,7 +488,7 @@ public function destroy(int $id): DataResponse {
/**
* [api v2] Transfer table
*
* Transfer table from one user to another
* Transfer a table from one user to another. Team-owned tables can only be transferred to a member of that team.
*
* @param int $id Table ID
* @param string $newOwnerUserId New user ID
Expand Down
5 changes: 5 additions & 0 deletions lib/Db/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
* @method setDescription(string $description)
* @method getOwnership(): ?string
* @method setOwnership(string $ownership)
* @method getTeamId(): ?string
* @method setTeamId(?string $teamId)
* @method getOwnerDisplayName(): string
* @method setOwnerDisplayName(string $ownerDisplayName)
* @method getIsShared(): bool
Expand Down Expand Up @@ -73,6 +75,7 @@ class Table extends EntitySuper implements JsonSerializable {
protected ?string $title = null;
protected ?string $emoji = null;
protected ?string $ownership = null;
protected ?string $teamId = null;
protected ?string $createdBy = null;
protected ?string $createdAt = null;
protected ?string $lastEditBy = null;
Expand Down Expand Up @@ -104,6 +107,7 @@ public function __construct() {
$this->addType('uuid', 'string');
$this->addType('archived', 'boolean');
$this->addType('externalId', 'integer');
$this->addType('teamId', 'string');
}

public function setter(string $name, array $args): void {
Expand Down Expand Up @@ -140,6 +144,7 @@ public function jsonSerialize(): array {
'title' => $this->title ?: '',
'emoji' => $this->emoji,
'ownership' => $this->ownership ?: '',
'teamId' => $this->teamId,
'ownerDisplayName' => $this->ownerDisplayName ?: '',
'createdBy' => $this->createdBy ?: '',
'createdAt' => $this->createdAt ?: '',
Expand Down
33 changes: 33 additions & 0 deletions lib/Db/TableMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,39 @@ public function findByUuid(string $uuid): Table {
return $this->findEntity($qb);
}

/**
* @throws DoesNotExistException
* @throws Exception
* @throws MultipleObjectsReturnedException
*/
public function findForUpdate(int $id): Table {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->table)
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
if ($this->db->getDatabaseProvider() !== IDBConnection::PLATFORM_SQLITE) {
$qb->forUpdate();
}
$table = $this->findEntity($qb);
$this->cache[(string)$id] = $table;
return $table;
}

/**
* @return Table[]
* @throws Exception
*/
public function findAllByTeamId(string $teamId, ?string $ownerUserId = null): array {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->table)
->where($qb->expr()->eq('team_id', $qb->createNamedParameter($teamId, IQueryBuilder::PARAM_STR)));
if ($ownerUserId !== null) {
$qb->andWhere($qb->expr()->eq('ownership', $qb->createNamedParameter($ownerUserId, IQueryBuilder::PARAM_STR)));
}
return $this->findEntities($qb);
}

/**
* @param int[] $ids
* @return array<int, Table> indexed by table id
Expand Down
50 changes: 49 additions & 1 deletion lib/Helper/CircleHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@
namespace OCA\Tables\Helper;

use OCA\Circles\CirclesManager;
use OCA\Circles\Db\CircleRequest;
use OCA\Circles\Db\MemberRequest;
use OCA\Circles\Model\Circle;
use OCA\Circles\Model\Member;
use OCA\Circles\Model\Probes\CircleProbe;
use OCA\Tables\Errors\InternalError;
use OCP\App\IAppManager;
use OCP\IL10N;
use OCP\IUserManager;
use OCP\Server;
use Psr\Log\LoggerInterface;
use Throwable;
Expand All @@ -23,6 +27,8 @@
class CircleHelper {
private bool $circlesEnabled;
private ?CirclesManager $circlesManager;
private ?MemberRequest $memberRequest = null;
private ?CircleRequest $circleRequest = null;
private array $circleDisplayNames = [];
private array $federatedUsers = [];
private array $unreachableUserIds = [];
Expand All @@ -34,6 +40,7 @@ public function __construct(
private readonly LoggerInterface $logger,
IAppManager $appManager,
private readonly IL10N $l10n,
private readonly IUserManager $userManager,
) {
$this->circlesEnabled = $appManager->isEnabledForUser('circles');
$this->circlesManager = null;
Expand Down Expand Up @@ -136,7 +143,7 @@ public function getUserIdsInCircle(string $circleId): array {
}

public function circleExists(string $circleId, string $userId): bool {
if (!$this->circlesEnabled) {
if (!$this->circlesEnabled || !$this->userManager->userExists($userId)) {
return false;
}

Expand All @@ -147,4 +154,45 @@ public function circleExists(string $circleId, string $userId): bool {
return in_array($circleId, $userCircleIds, true);
}

public function findSuccessorUserId(string $circleId, string $excludeUserId): ?string {
if (!$this->circlesEnabled) {
throw new InternalError('Cannot find a table owner while Circles is unavailable');
}

try {
// Do not replace the Circles session while a membership event is running.
$circleRequest = $this->circleRequest ??= Server::get(CircleRequest::class);
$circle = $circleRequest->getCircle($circleId);
if ($circle->hasOwner() && $this->isEligibleSuccessor($circle->getOwner(), $excludeUserId)) {
return $circle->getOwner()->getUserId();
}

$memberRequest = $this->memberRequest ??= Server::get(MemberRequest::class);
$successor = null;
$highestLevel = -1;
foreach ($memberRequest->getMembers($circleId) as $member) {
if (!$this->isEligibleSuccessor($member, $excludeUserId)) {
continue;
}
if ($member->getLevel() > $highestLevel) {
$successor = $member->getUserId();
$highestLevel = $member->getLevel();
}
}
return $successor;
} catch (Throwable $e) {
$this->logger->error('Could not find a successor for a team table', ['circleId' => $circleId, 'exception' => $e]);
throw new InternalError('Could not find a successor for a team table', previous: $e);
}
}

private function isEligibleSuccessor(Member $member, string $excludeUserId): bool {
return $member->getUserType() === Member::TYPE_USER
&& $member->isLocal()
&& $member->getStatus() === Member::STATUS_MEMBER
&& $member->getUserId() !== ''
&& $member->getUserId() !== $excludeUserId
&& $this->userManager->userExists($member->getUserId());
}

}
48 changes: 48 additions & 0 deletions lib/Listener/TeamOwnershipListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

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

namespace OCA\Tables\Listener;

use OCA\Circles\Events\CircleDestroyedEvent;
use OCA\Circles\Events\RemovingCircleMemberEvent;
use OCA\Circles\Model\Member;
use OCA\Tables\Service\TableService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use Psr\Log\LoggerInterface;

/** @template-implements IEventListener<Event> */
class TeamOwnershipListener implements IEventListener {
public function __construct(
private readonly TableService $tableService,
private readonly LoggerInterface $logger,
) {
}

public function handle(Event $event): void {
if ($event instanceof CircleDestroyedEvent) {
try {
$this->tableService->deleteTeamOwnedTables($event->getCircle()->getSingleId());
} catch (\Throwable $e) {
$this->logger->error('Could not delete tables owned by a destroyed team: ' . $e->getMessage(), [
'exception' => $e,
]);
}
} elseif ($event instanceof RemovingCircleMemberEvent) {
$member = $event->getMember();
if ($member->getUserType() === Member::TYPE_USER && $member->isLocal()) {
try {
$this->tableService->handleTeamStewardDeparture($event->getCircle()->getSingleId(), $member->getUserId());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

when a user is deleted this runs again after 'UserDeletedListener' already transferred the table. 'findAllByTeamId' finds nothing because the owner has changed, so the second run does nothing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The second listener should handle the case where the circle has no eligible members to become successor. (eg. only non-local members) This is something i am not quite sure on how we should handle this.

} catch (\Throwable $e) {
$this->logger->error('Could not update team-owned tables after a team membership change: ' . $e->getMessage(), [
'exception' => $e,
]);
}
}
}
}
}
Loading
Loading