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
2 changes: 2 additions & 0 deletions core/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use OC\Core\Sharing\Recipient\UserShareRecipientType;
use OC\DirectEditing\Listeners\UserDeletedTokenCleanupListener as UserDeletedDirectEditingTokenCleanupListener;
use OC\DirectEditing\Listeners\UserDisabledTokenCleanupListener as UserDisabledDirectEditingTokenCleanupListener;
use OC\TaskProcessing\Listeners\UserDeletedTaskCleanupListener;
use OC\OCM\OCMDiscoveryHandler;
use OC\TagManager;
use OCA\Circles\Events\DestroyingCircleEvent;
Expand Down Expand Up @@ -130,6 +131,7 @@ public function register(IRegistrationContext $context): void {
// Direct Editing
$context->registerEventListener(UserDeletedEvent::class, UserDeletedDirectEditingTokenCleanupListener::class);
$context->registerEventListener(UserChangedEvent::class, UserDisabledDirectEditingTokenCleanupListener::class);
$context->registerEventListener(UserDeletedEvent::class, UserDeletedTaskCleanupListener::class);

$registry = Server::get(ISharingRegistry::class);

Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -2446,6 +2446,7 @@
'OC\\Talk\\ConversationOptions' => $baseDir . '/lib/private/Talk/ConversationOptions.php',
'OC\\TaskProcessing\\Db\\Task' => $baseDir . '/lib/private/TaskProcessing/Db/Task.php',
'OC\\TaskProcessing\\Db\\TaskMapper' => $baseDir . '/lib/private/TaskProcessing/Db/TaskMapper.php',
'OC\\TaskProcessing\\Listeners\\UserDeletedTaskCleanupListener' => $baseDir . '/lib/private/TaskProcessing/Listeners/UserDeletedTaskCleanupListener.php',
'OC\\TaskProcessing\\Manager' => $baseDir . '/lib/private/TaskProcessing/Manager.php',
'OC\\TaskProcessing\\RemoveOldTasksBackgroundJob' => $baseDir . '/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php',
'OC\\TaskProcessing\\SynchronousBackgroundJob' => $baseDir . '/lib/private/TaskProcessing/SynchronousBackgroundJob.php',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -2487,6 +2487,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Talk\\ConversationOptions' => __DIR__ . '/../../..' . '/lib/private/Talk/ConversationOptions.php',
'OC\\TaskProcessing\\Db\\Task' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/Db/Task.php',
'OC\\TaskProcessing\\Db\\TaskMapper' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/Db/TaskMapper.php',
'OC\\TaskProcessing\\Listeners\\UserDeletedTaskCleanupListener' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/Listeners/UserDeletedTaskCleanupListener.php',
'OC\\TaskProcessing\\Manager' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/Manager.php',
'OC\\TaskProcessing\\RemoveOldTasksBackgroundJob' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php',
'OC\\TaskProcessing\\SynchronousBackgroundJob' => __DIR__ . '/../../..' . '/lib/private/TaskProcessing/SynchronousBackgroundJob.php',
Expand Down
4 changes: 4 additions & 0 deletions lib/private/Setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
use OC\Setup\OCI;
use OC\Setup\PostgreSQL;
use OC\Setup\Sqlite;
use OC\TaskProcessing\RemoveOldTasksBackgroundJob as RemoveOldTaskProcessingTasksBackgroundJob;
use OC\TextProcessing\RemoveOldTasksBackgroundJob;
use OC\TextToImage\RemoveOldTasksBackgroundJob as RemoveOldTextToImageTasksBackgroundJob;
use OC\User\BackgroundJobs\CleanupDeletedUsers;
use OC\User\BackgroundJobs\CleanupLoginTokens;
use OC\User\Session;
Expand Down Expand Up @@ -534,6 +536,8 @@ public static function installBackgroundJobs(): void {
$jobList->add(Rotate::class);
$jobList->add(BackgroundCleanupJob::class);
$jobList->add(RemoveOldTasksBackgroundJob::class);
$jobList->add(RemoveOldTextToImageTasksBackgroundJob::class);
$jobList->add(RemoveOldTaskProcessingTasksBackgroundJob::class);
$jobList->add(CleanupDeletedUsers::class);
$jobList->add(CleanupLoginTokens::class);
$jobList->add(GenerateMetadataJob::class);
Expand Down
12 changes: 12 additions & 0 deletions lib/private/TaskProcessing/Db/TaskMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,18 @@ public function deleteOlderThan(int $timeout, bool $force = false): int {
return $qb->executeStatement();
}

/**
* @param string $userId
* @return int the number of deleted tasks
* @throws Exception
*/
public function deleteByUser(string $userId): int {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->tableName)
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId)));
return $qb->executeStatement();
}

/**
* @param int $timeout
* @param bool $force If true, ignore the allow_cleanup flag
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

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

namespace OC\TaskProcessing\Listeners;

use OC\TaskProcessing\Manager;
use OC\TextProcessing\Db\TaskMapper as TextProcessingTaskMapper;
use OC\TextToImage\Manager as TextToImageManager;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\User\Events\UserDeletedEvent;
use Psr\Log\LoggerInterface;
use Throwable;

/**
* Cleans up the AI tasks of a deleted user in the task processing,
* text processing and text to image tables, together with the
* files they generated in appdata.
*
* @template-implements IEventListener<UserDeletedEvent>
*/
class UserDeletedTaskCleanupListener implements IEventListener {
public function __construct(
private Manager $taskProcessingManager,
private TextProcessingTaskMapper $textProcessingTaskMapper,
private TextToImageManager $textToImageManager,
private LoggerInterface $logger,
) {
}

#[\Override]
public function handle(Event $event): void {
if (!($event instanceof UserDeletedEvent)) {
// Unrelated
return;
}

$uid = $event->getUser()->getUID();

/**
* Catch any exception during each of these steps as a failure here
* should not block the deletion of the user account.
*/
try {
$this->taskProcessingManager->deleteUserTasks($uid);
} catch (Throwable $e) {
$this->logger->warning('Could not clean up task processing tasks after user deletion: ' . $e->getMessage(), ['exception' => $e]);
}
try {
$this->textProcessingTaskMapper->deleteByUser($uid);
} catch (Throwable $e) {
$this->logger->warning('Could not clean up text processing tasks after user deletion: ' . $e->getMessage(), ['exception' => $e]);
}
try {
$this->textToImageManager->deleteUserTasks($uid);
} catch (Throwable $e) {
$this->logger->warning('Could not clean up text to image tasks after user deletion: ' . $e->getMessage(), ['exception' => $e]);
}
}
}
28 changes: 28 additions & 0 deletions lib/private/TaskProcessing/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -1200,6 +1200,34 @@ public function deleteTask(Task $task): void {
$this->taskMapper->delete($taskEntity);
}

/**
* Delete all tasks of a user together with the files of their finished
* tasks stored in appdata
*/
public function deleteUserTasks(string $userId): void {
$fileIds = [];
foreach ($this->taskMapper->findByUserAndTaskType($userId) as $task) {
try {
$fileIds = array_merge($fileIds, $this->extractFileIdsFromTask($task->toPublicTask()));
} catch (\Throwable $e) {
// The task type is unknown, e.g. because its provider app was disabled,
// so the file ids cannot be extracted. The row is still deleted and the
// files are picked up by the aging cleanup later.
$this->logger->warning('Failed to extract file ids of a task of deleted user ' . $userId, ['exception' => $e]);
}
}
$this->taskMapper->deleteByUser($userId);
foreach ($fileIds as $fileId) {
try {
// only look for output files stored in appData/TaskProcessing/
$file = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/core/TaskProcessing/');
$file?->delete();
} catch (\Throwable $e) {
$this->logger->warning('Failed to delete a file of a task of deleted user ' . $userId, ['exception' => $e]);
}
}
}

private function notifyTaskStatus(Task $task, int $status): void {
$userId = $task->getUserId();
if ($userId !== null
Expand Down
12 changes: 12 additions & 0 deletions lib/private/TextProcessing/Db/TaskMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,18 @@ public function deleteOlderThan(int $timeout): int {
return $qb->executeStatement();
}

/**
* @param string $userId
* @return int the number of deleted tasks
* @throws Exception
*/
public function deleteByUser(string $userId): int {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->tableName)
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId)));
return $qb->executeStatement();
}

#[\Override]
public function update(Entity $entity): Entity {
$entity->setLastUpdated($this->timeFactory->now()->getTimestamp());
Expand Down
18 changes: 18 additions & 0 deletions lib/private/TextToImage/Db/TaskMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,24 @@ public function deleteOlderThan(int $timeout): array {
return $deletedTasks;
}

/**
* @param string $userId
* @return Task[] the deleted tasks
* @throws Exception
*/
public function deleteByUser(string $userId): array {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->tableName)
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId)));
$deletedTasks = $this->findEntities($qb);
$qb = $this->db->getQueryBuilder();
$qb->delete($this->tableName)
->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId)));
$qb->executeStatement();
return $deletedTasks;
}

#[\Override]
public function update(Entity $entity): Entity {
$entity->setLastUpdated($this->timeFactory->getDateTime());
Expand Down
21 changes: 21 additions & 0 deletions lib/private/TextToImage/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,27 @@ public function deleteTask(Task $task): void {
]);
}

/**
* Delete all tasks of a user together with their result folders in appdata
*/
public function deleteUserTasks(string $userId): void {
$deletedTasks = $this->taskMapper->deleteByUser($userId);
try {
$folder = $this->appData->getFolder('text2image');
} catch (NotFoundException) {
return;
}
foreach ($deletedTasks as $task) {
try {
$folder->getFolder((string)$task->getId())->delete();
} catch (NotFoundException) {
// noop
} catch (NotPermittedException $e) {
$this->logger->warning('Failed to delete text to image task files of deleted user ' . $userId, ['exception' => $e]);
}
}
}

/**
* Get a task from its id
*
Expand Down
11 changes: 11 additions & 0 deletions tests/lib/SetupTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
use OC\Installer;
use OC\Setup;
use OC\SystemConfig;
use OCP\BackgroundJob\IJobList;
use OCP\Defaults;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IL10N;
use OCP\L10N\IFactory as IL10NFactory;
use OCP\Security\ISecureRandom;
use OCP\Server;
use Psr\Log\LoggerInterface;

class SetupTest extends \Test\TestCase {
Expand Down Expand Up @@ -131,6 +133,15 @@ public function testGetSupportedDatabaseException(): void {
$this->setupClass->getSupportedDatabases();
}

public function testInstallBackgroundJobsRegistersAiTasksCleanupJobs(): void {
Setup::installBackgroundJobs();

$jobList = Server::get(IJobList::class);
self::assertTrue($jobList->has(\OC\TaskProcessing\RemoveOldTasksBackgroundJob::class, null));
self::assertTrue($jobList->has(\OC\TextProcessing\RemoveOldTasksBackgroundJob::class, null));
self::assertTrue($jobList->has(\OC\TextToImage\RemoveOldTasksBackgroundJob::class, null));
}

#[\PHPUnit\Framework\Attributes\DataProvider('findWebRootProvider')]
public function testFindWebRootCli(string $url, string|false $expected): void {
$cliState = \OC::$CLI;
Expand Down
Loading
Loading