Skip to content
Draft
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 appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,7 @@
['name' => 'Workspace#publicFolder', 'url' => '/public/workspace', 'verb' => 'GET'],
/** @see Controller\WorkspaceController::direct() */
['name' => 'Workspace#direct', 'url' => '/workspace/direct', 'verb' => 'POST'],
/** @see Controller\VersionsController::index() */
['name' => 'Versions#index', 'url' => '/versions/{fileId}', 'verb' => 'GET'],
]
];
3 changes: 3 additions & 0 deletions composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
'OCA\\Text\\Controller\\SettingsController' => $baseDir . '/../lib/Controller/SettingsController.php',
'OCA\\Text\\Controller\\TSessionAwareController' => $baseDir . '/../lib/Controller/TSessionAwareController.php',
'OCA\\Text\\Controller\\UserApiController' => $baseDir . '/../lib/Controller/UserApiController.php',
'OCA\\Text\\Controller\\VersionsController' => $baseDir . '/../lib/Controller/VersionsController.php',
'OCA\\Text\\Controller\\WorkspaceController' => $baseDir . '/../lib/Controller/WorkspaceController.php',
'OCA\\Text\\Cron\\Cleanup' => $baseDir . '/../lib/Cron/Cleanup.php',
'OCA\\Text\\DAV\\WorkspacePlugin' => $baseDir . '/../lib/DAV/WorkspacePlugin.php',
Expand Down Expand Up @@ -85,6 +86,7 @@
'OCA\\Text\\Migration\\Version090000Date20260819110024' => $baseDir . '/../lib/Migration/Version090000Date20260819110024.php',
'OCA\\Text\\Migration\\Version090000Date20260820132113' => $baseDir . '/../lib/Migration/Version090000Date20260820132113.php',
'OCA\\Text\\Migration\\Version100000Date20261011000000' => $baseDir . '/../lib/Migration/Version100000Date20261011000000.php',
'OCA\\Text\\Model\\VersionEnd' => $baseDir . '/../lib/Model/VersionEnd.php',
'OCA\\Text\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php',
'OCA\\Text\\Service\\AiTagService' => $baseDir . '/../lib/Service/AiTagService.php',
'OCA\\Text\\Service\\ApiService' => $baseDir . '/../lib/Service/ApiService.php',
Expand All @@ -97,6 +99,7 @@
'OCA\\Text\\Service\\LockService' => $baseDir . '/../lib/Service/LockService.php',
'OCA\\Text\\Service\\NotificationService' => $baseDir . '/../lib/Service/NotificationService.php',
'OCA\\Text\\Service\\SessionService' => $baseDir . '/../lib/Service/SessionService.php',
'OCA\\Text\\Service\\VersionAccessService' => $baseDir . '/../lib/Service/VersionAccessService.php',
'OCA\\Text\\Service\\WorkspaceService' => $baseDir . '/../lib/Service/WorkspaceService.php',
'OCA\\Text\\TextFile' => $baseDir . '/../lib/TextFile.php',
'OCA\\Text\\YjsMessage' => $baseDir . '/../lib/YjsMessage.php',
Expand Down
3 changes: 3 additions & 0 deletions composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class ComposerStaticInitText
'OCA\\Text\\Controller\\SettingsController' => __DIR__ . '/..' . '/../lib/Controller/SettingsController.php',
'OCA\\Text\\Controller\\TSessionAwareController' => __DIR__ . '/..' . '/../lib/Controller/TSessionAwareController.php',
'OCA\\Text\\Controller\\UserApiController' => __DIR__ . '/..' . '/../lib/Controller/UserApiController.php',
'OCA\\Text\\Controller\\VersionsController' => __DIR__ . '/..' . '/../lib/Controller/VersionsController.php',
'OCA\\Text\\Controller\\WorkspaceController' => __DIR__ . '/..' . '/../lib/Controller/WorkspaceController.php',
'OCA\\Text\\Cron\\Cleanup' => __DIR__ . '/..' . '/../lib/Cron/Cleanup.php',
'OCA\\Text\\DAV\\WorkspacePlugin' => __DIR__ . '/..' . '/../lib/DAV/WorkspacePlugin.php',
Expand Down Expand Up @@ -100,6 +101,7 @@ class ComposerStaticInitText
'OCA\\Text\\Migration\\Version090000Date20260819110024' => __DIR__ . '/..' . '/../lib/Migration/Version090000Date20260819110024.php',
'OCA\\Text\\Migration\\Version090000Date20260820132113' => __DIR__ . '/..' . '/../lib/Migration/Version090000Date20260820132113.php',
'OCA\\Text\\Migration\\Version100000Date20261011000000' => __DIR__ . '/..' . '/../lib/Migration/Version100000Date20261011000000.php',
'OCA\\Text\\Model\\VersionEnd' => __DIR__ . '/..' . '/../lib/Model/VersionEnd.php',
'OCA\\Text\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php',
'OCA\\Text\\Service\\AiTagService' => __DIR__ . '/..' . '/../lib/Service/AiTagService.php',
'OCA\\Text\\Service\\ApiService' => __DIR__ . '/..' . '/../lib/Service/ApiService.php',
Expand All @@ -112,6 +114,7 @@ class ComposerStaticInitText
'OCA\\Text\\Service\\LockService' => __DIR__ . '/..' . '/../lib/Service/LockService.php',
'OCA\\Text\\Service\\NotificationService' => __DIR__ . '/..' . '/../lib/Service/NotificationService.php',
'OCA\\Text\\Service\\SessionService' => __DIR__ . '/..' . '/../lib/Service/SessionService.php',
'OCA\\Text\\Service\\VersionAccessService' => __DIR__ . '/..' . '/../lib/Service/VersionAccessService.php',
'OCA\\Text\\Service\\WorkspaceService' => __DIR__ . '/..' . '/../lib/Service/WorkspaceService.php',
'OCA\\Text\\TextFile' => __DIR__ . '/..' . '/../lib/TextFile.php',
'OCA\\Text\\YjsMessage' => __DIR__ . '/..' . '/../lib/YjsMessage.php',
Expand Down
60 changes: 60 additions & 0 deletions lib/Controller/VersionsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

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

namespace OCA\Text\Controller;

use OCA\Text\Service\VersionAccessService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IRequest;
use OCP\IUserSession;

class VersionsController extends OCSController {
public function __construct(
string $appName,
IRequest $request,
private readonly VersionAccessService $versionAccessService,
private readonly IRootFolder $rootFolder,
private readonly IUserSession $userSession,
) {
parent::__construct($appName, $request);
}

/**
* The current file and its retained versions, for choosing what to compare
*
* Every refusal is the same 404, so the answer does not tell a missing
* file from one the user may not compare.
*/
#[NoAdminRequired]
public function index(int $fileId): DataResponse {
$user = $this->userSession->getUser();
if ($user === null) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
try {
$file = $this->versionAccessService->resolveFile($user, $fileId);
$versions = $this->versionAccessService->listVersions($user, $file);
} catch (NotFoundException) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
$path = $this->rootFolder->getUserFolder($user->getUID())->getRelativePath($file->getPath());
return new DataResponse([
'fileId' => $fileId,
'path' => $path,
'versions' => $versions,
// Without Files Versions there is only ever the current file
'versionsAvailable' => $this->versionAccessService->hasVersions(),
]);
}
}
44 changes: 44 additions & 0 deletions lib/Model/VersionEnd.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

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

namespace OCA\Text\Model;

use JsonSerializable;

/**
* One end of a comparison: the current file or one of its retained versions.
*/
class VersionEnd implements JsonSerializable {
public const string CURRENT = 'current';

public function __construct(
public readonly string $id,
public readonly int $mtime,
public readonly int|float $size,
public readonly string $label,
public readonly ?string $authorId,
public readonly ?string $authorName,
) {
}

/**
* @return array{id: string, mtime: int, size: int|float, label: string, author: array{id: string, displayName: string}|null}
*/
public function jsonSerialize(): array {
return [
'id' => $this->id,
'mtime' => $this->mtime,
'size' => $this->size,
'label' => $this->label,
'author' => $this->authorId === null
? null
: ['id' => $this->authorId, 'displayName' => $this->authorName ?? $this->authorId],
];
}
}
133 changes: 133 additions & 0 deletions lib/Service/VersionAccessService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

declare(strict_types=1);

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

namespace OCA\Text\Service;

use OCA\Files_Versions\Versions\BackendNotFoundException;
use OCA\Files_Versions\Versions\IMetadataVersion;
use OCA\Files_Versions\Versions\IVersion;
use OCA\Files_Versions\Versions\IVersionManager;
use OCA\Text\Model\VersionEnd;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;

/**
* Which Markdown file a user may compare, and its versions.
*/
class VersionAccessService {
public function __construct(
private readonly IRootFolder $rootFolder,
private readonly ContainerInterface $container,
private readonly IUserManager $userManager,
) {
}

/**
* The Markdown file with this id in the user's files, if the user may read
* it and it is not end-to-end encrypted. Its versions are listed as in the
* Versions tab, also where a share disables downloads.
*
* @throws NotFoundException
*/
public function resolveFile(IUser $user, int $fileId): File {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$file = $userFolder->getFirstNodeById($fileId);
if (!$file instanceof File
|| !$file->isReadable()
|| $file->getMimetype() !== 'text/markdown'
|| $this->isEndToEndEncrypted($file, $userFolder)) {
throw new NotFoundException('No comparable file ' . $fileId);
}
return $file;
}

/**
* The current file and its retained versions, newest first.
*
* Backends list the current file as a version with the file's own
* timestamp; it becomes the end `current`.
*
* @return list<VersionEnd>
* @throws NotFoundException When the versions backend cannot find the file
*/
public function listVersions(IUser $user, File $file): array {
try {
$versions = $this->versionManager()?->getVersionsForFile($user, $file) ?? [];
} catch (BackendNotFoundException) {
// A storage that keeps no versions
$versions = [];
}

$currentVersion = null;
$ends = [];
foreach ($versions as $version) {
if ((string)$version->getRevisionId() === (string)$file->getMTime()) {
$currentVersion = $version;
continue;
}
$ends[] = $this->end((string)$version->getRevisionId(), $version->getTimestamp(), $version->getSize(), $version);
}
usort($ends, static fn (VersionEnd $a, VersionEnd $b) => $b->mtime <=> $a->mtime);

$current = $this->end(VersionEnd::CURRENT, $file->getMTime(), $file->getSize(), $currentVersion);
return [$current, ...$ends];
}

private function end(string $id, int $mtime, int|float $size, ?IVersion $metadata): VersionEnd {
$label = '';
$authorId = null;
if ($metadata instanceof IMetadataVersion) {
$label = $metadata->getMetadataValue('label') ?? '';
$author = $metadata->getMetadataValue('author');
$authorId = $author === null || $author === '' ? null : $author;
}
$authorName = $authorId === null ? null : $this->userManager->getDisplayName($authorId);
return new VersionEnd($id, $mtime, $size, $label, $authorId, $authorName);
}

/**
* Whether a folder between the file and the user folder is end-to-end
* encrypted (`isEncrypted()` means end-to-end on a folder).
*/
private function isEndToEndEncrypted(File $file, Folder $userFolder): bool {
$folder = $file->getParent();
while (str_starts_with($folder->getPath(), $userFolder->getPath() . '/')) {
if ($folder->isEncrypted()) {
return true;
}
$folder = $folder->getParent();
}
return false;
}

/**
* Whether files keep versions at all
*/
public function hasVersions(): bool {
return $this->versionManager() !== null;
}

/**
* Files Versions registers its manager only while it is enabled
*/
private function versionManager(): ?IVersionManager {
try {
$manager = $this->container->get(IVersionManager::class);
} catch (ContainerExceptionInterface) {
return null;
}
return $manager instanceof IVersionManager ? $manager : null;
}
}
87 changes: 87 additions & 0 deletions playwright/e2e/version-picker.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import type { Page } from '@playwright/test'

import { expect, mergeTests } from '@playwright/test'
import { test as randomUserTest } from '../support/fixtures/random-user.ts'
import { test as uploadFileTest } from '../support/fixtures/upload-file.ts'

const test = mergeTests(randomUserTest, uploadFileTest)

// Choose another version for one end of the open comparison
async function choose(page: Page, end: 'from' | 'to', index: number) {
await page.locator(`[data-comparison-picker="${end}"]`).getByRole('button').click()
await page.getByRole('menuitemradio').nth(index).click()
}

const before = (page: Page) => page.getByRole('article', { name: 'Before' })
const after = (page: Page) => page.getByRole('article', { name: 'After' })

test.describe('Changing the versions compared', () => {
test.use({
fileName: 'picker.md',
fileContent: '# V3',
oldVersions: [
[
{ content: '# V1', mtime: 1691420501 },
{ content: '# V2', mtime: 1691424242 },
],
{ scope: 'test' },
],
})

test('changes either end in Files, side by side and in the list of changes', async ({ open, page, viewer }) => {
await open()
const versions = await viewer.openSidebarTab('Versions')
await versions.getByRole('button').nth(2).click()
await page.getByRole('menuitem', { name: 'Compare to current version' }).click()
await expect(before(page).getByRole('heading', { name: 'V1' })).toBeVisible()

// The older end: V2 instead of V1, slow to load, and the keyboard still comes back
await page.route('**/remote.php/dav/versions/**', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2500))
await route.continue()
})
await choose(page, 'from', 1)
await expect(before(page).getByRole('heading', { name: 'V2' })).toBeVisible()
await expect(after(page).getByRole('heading', { name: 'V3' })).toBeVisible()
await expect(page.locator('[data-comparison-picker="from"]').getByRole('button')).toBeFocused()
await expect(page.locator('[aria-live]').filter({ hasText: 'Comparing' })).toHaveText(/^Comparing .* with the current version$/)
await page.unrouteAll({ behavior: 'wait' })

// The newer end can only be newer than the older one
await page.locator('[data-comparison-picker="to"]').getByRole('button').click()
await expect(page.getByRole('menuitemradio').nth(1)).toBeDisabled()
await expect(page.getByRole('menuitemradio').nth(2)).toBeDisabled()
await page.locator('[data-comparison-picker="to"]').getByRole('button').click()

// The list of changes stays the view when the older end changes again
await page.keyboard.press('d')
await expect(page.locator('[data-comparison-select]')).toHaveCount(1)
await choose(page, 'from', 2)
await expect(page.locator('[data-comparison-select] del')).toHaveText('1')
await expect(before(page)).toHaveCount(0)

// The newer end: V2 instead of the current file
await choose(page, 'to', 1)
await expect(page.locator('[data-comparison-select] ins')).toHaveText('2')
await expect(page.locator('[data-comparison-picker="to"]').getByRole('button')).toBeFocused()
})

test('fits a narrow window', async ({ open, page, viewer }) => {
await open()
const versions = await viewer.openSidebarTab('Versions')
await versions.getByRole('button').nth(2).click()
await page.getByRole('menuitem', { name: 'Compare to current version' }).click()
await page.keyboard.press('d')
await page.setViewportSize({ width: 600, height: 800 })

const header = page.locator('.text-comparison__header')
await expect(header.locator('[data-comparison-picker]')).toHaveCount(2)
const { scrollWidth, clientWidth } = await header.evaluate((el) => ({ scrollWidth: el.scrollWidth, clientWidth: el.clientWidth }))
expect(scrollWidth).toBeLessThanOrEqual(clientWidth)
})
})
Loading
Loading