Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
feat(files): enable locking and unlocking of edited files with improved handling and UI integration
johaven24ad66b034e3
diff --git a/backend/src/applications/files/constants/cache.ts b/backend/src/applications/files/constants/cache.tsindex de2ac3f3..8cefd4d2 100644--- a/backend/src/applications/files/constants/cache.ts+++ b/backend/src/applications/files/constants/cache.ts@@ -9,6 +9,7 @@ export const CACHE_TASK_PREFIX = 'ftask' as constexport const CACHE_TASK_TTL = 86400 as const // one day// cache token key = `flock|token?:${uuid}|path:${path}|ownerId?:${number}|spaceId?:${number}|...props` => FileLockexport const CACHE_LOCK_PREFIX = 'flock' as const-export const CACHE_LOCK_DEFAULT_TIMEOUT = 28800 as const // 8 hours in seconds+export const CACHE_LOCK_DEFAULT_TTL = 28800 as const // 8 hours in seconds+export const CACHE_LOCK_FILE_TTL = 3600 as const// cache only office = `office|${fileId}` => docKeyexport const CACHE_ONLY_OFFICE = 'foffice' as constdiff --git a/backend/src/applications/files/constants/operations.ts b/backend/src/applications/files/constants/operations.tsindex 4dffbaaf..eef5eaf6 100644--- a/backend/src/applications/files/constants/operations.ts+++ b/backend/src/applications/files/constants/operations.ts@@ -14,7 +14,9 @@ export enum FILE_OPERATION {DOWNLOAD = 'download',UPLOAD = 'upload',TOUCH = 'touch',- THUMBNAIL = 'thumbnail'+ THUMBNAIL = 'thumbnail',+ LOCK = 'lock',+ UNLOCK = 'unlock'}export enum FILE_MODE {diff --git a/backend/src/applications/files/files.controller.ts b/backend/src/applications/files/files.controller.tsindex e2003ccb..3a725905 100644--- a/backend/src/applications/files/files.controller.ts+++ b/backend/src/applications/files/files.controller.ts@@ -11,16 +11,18 @@ import {Delete,Get,Head,+ Lock,Logger,Move,ParseIntPipe,+ Patch,Post,- Put,Query,Req,Res,Search,StreamableFile,+ Unlock,UseGuards} from '@nestjs/common'import { FastifyReply } from 'fastify'@@ -36,6 +38,7 @@ import { UserModel } from '../users/models/user.model'import { FILE_OPERATION } from './constants/operations'import { FILES_ROUTE } from './constants/routes'import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto, SearchFilesDto } from './dto/file-operations.dto'+import { FileLockProps } from './interfaces/file-props.interface'import { FileTask } from './models/file-task'import { FileContent } from './schemas/file-content.interface'import { FileRecent } from './schemas/file-recent.interface'@@ -78,7 +81,7 @@ export class FilesController {return this.filesMethods.upload(req)}- @Put(`${FILES_ROUTE.OPERATION}/${FILE_OPERATION.UPLOAD}/*`)+ @Patch(`${FILES_ROUTE.OPERATION}/${FILE_OPERATION.UPLOAD}/*`)async uploadOverwrite(@Req() req: FastifySpaceRequest): Promise<void> {return this.filesMethods.upload(req)}@@ -124,6 +127,16 @@ export class FilesController {return res.send(thumb)}+ @Lock(`${FILES_ROUTE.OPERATION}/*`)+ async lock(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv): Promise<FileLockProps> {+ return this.filesMethods.lock(user, space)+ }++ @Unlock(`${FILES_ROUTE.OPERATION}/*`)+ async unlock(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv): Promise<void> {+ return this.filesMethods.unlock(user, space)+ }+// TASKS OPERATIONS@Post(`${FILES_ROUTE.TASK_OPERATION}/${FILE_OPERATION.DOWNLOAD}/*`)diff --git a/backend/src/applications/files/services/files-lock-manager.service.ts b/backend/src/applications/files/services/files-lock-manager.service.tsindex 63daef5b..1b2f39ae 100644--- a/backend/src/applications/files/services/files-lock-manager.service.ts+++ b/backend/src/applications/files/services/files-lock-manager.service.ts@@ -12,7 +12,7 @@ import { Cache } from '../../../infrastructure/cache/services/cache.service'import { UserModel } from '../../users/models/user.model'import { DEPTH, LOCK_DEPTH, LOCK_PREFIX, LOCK_SCOPE } from '../../webdav/constants/webdav'import { WebDAVLock } from '../../webdav/interfaces/webdav.interface'-import { CACHE_LOCK_DEFAULT_TIMEOUT, CACHE_LOCK_PREFIX } from '../constants/cache'+import { CACHE_LOCK_DEFAULT_TTL, CACHE_LOCK_PREFIX } from '../constants/cache'import { FileDBProps } from '../interfaces/file-db-props.interface'import { FileLock } from '../interfaces/file-lock.interface'import { FileLockProps } from '../interfaces/file-props.interface'@@ -60,7 +60,7 @@ export class FilesLockManager {}throw new Error(e)}- ttl ??= CACHE_LOCK_DEFAULT_TIMEOUT+ ttl ??= CACHE_LOCK_DEFAULT_TTLconst key = `${CACHE_LOCK_PREFIX}|${this.genSuffixKey(dbFile, { depth: depth, token: token })}`const expiration = Math.floor(currentTimeStamp() + ttl)const lock: FileLock = {@@ -76,6 +76,33 @@ export class FilesLockManager {return [true, lock]}+ async createOrRefresh(user: UserModel, dbFile: FileDBProps, depth: LOCK_DEPTH, ttl?: number): Promise<[boolean, FileLock]> {+ // Returns: [created, lock]+ ttl ??= CACHE_LOCK_DEFAULT_TTL+ const locks = await this.getLocksByPath(dbFile)+ // Check the existing lock and refresh it if needed+ if (locks.length > 0) {+ for (const lock of locks) {+ if (lock.owner.id === user.id) {+ // Refresh if more than half of the TTL has passed+ const mustRefresh = lock.expiration - currentTimeStamp() < ttl / 2+ if (mustRefresh) {+ this.refreshLockTimeout(lock, ttl).catch((e: Error) => this.logger.error(`${this.createOrRefresh.name} - ${e}`))+ }+ } else {+ throw new LockConflict(lock, 'Conflicting lock')+ }+ }+ return [false, locks[0]]+ }+ // Create the lock+ const [ok, lock] = await this.create(user, dbFile, depth, null, ttl)+ if (!ok) {+ throw new LockConflict(lock, 'Conflicting lock')+ }+ return [true, lock]+ }+removeLock(key: string): Promise<boolean> {this.logger.verbose(`${this.removeLock.name} - ${key}`)return this.cache.del(key)diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.tsindex 3a9915ca..f2615b3e 100644--- a/backend/src/applications/files/services/files-manager.service.ts+++ b/backend/src/applications/files/services/files-manager.service.ts@@ -23,6 +23,7 @@ import { realTrashPathFromSpace } from '../../spaces/utils/paths'import { canAccessToSpace, haveSpaceEnvPermissions } from '../../spaces/utils/permissions'import { UserModel } from '../../users/models/user.model'import { DEPTH, LOCK_DEPTH } from '../../webdav/constants/webdav'+import { CACHE_LOCK_FILE_TTL } from '../constants/cache'import { tarGzExtension } from '../constants/compress'import { COMPRESSION_EXTENSION, DEFAULT_HIGH_WATER_MARK } from '../constants/files'import { FILE_OPERATION } from '../constants/operations'@@ -31,6 +32,7 @@ import { CompressFileDto } from '../dto/file-operations.dto'import { FileTaskEvent } from '../events/file-task-event'import { FileDBProps } from '../interfaces/file-db-props.interface'import { FileLock } from '../interfaces/file-lock.interface'+import { FileLockProps } from '../interfaces/file-props.interface'import { FileError } from '../models/file-error'import { LockConflict } from '../models/file-lock-error'import {@@ -179,14 +181,16 @@ export class FilesManager {async saveMultipart(user: UserModel, space: SpaceEnv, req: FastifySpaceRequest) {/* Accepted methods:- POST: create new resource- PUT: create or update new resource (even if a parent path does not exist)+ POST: creates new resource+ PUT: creates or fully replaces a resource at the given URI (even if intermediate paths do not exist)+ PATCH: updates the content of a single existing resource without creating it*/const overwrite = req.method === HTTP_METHOD.PUT+ const patch = req.method === HTTP_METHOD.PATCHconst realParentPath = dirName(space.realPath)if (!overwrite) {- if (await isPathExists(space.realPath)) {+ if (!patch && (await isPathExists(space.realPath))) {throw new FileError(HttpStatus.BAD_REQUEST, 'Resource already exists')}if (!(await isPathExists(realParentPath))) {@@ -200,9 +204,11 @@ export class FilesManager {const basePath = realParentPath + path.sepfor await (const part of req.files()) {- // part.filename may contain a path like foo/bar.txt- const dstFile = path.resolve(basePath, part.filename)- // prevent path traversal+ // If the request uses the PATCH method, the file name corresponds to the space+ const partFileName = patch ? fileName(space.realPath) : part.filename+ // `part.filename` may contain a path like foo/bar.txt+ const dstFile = path.resolve(basePath, partFileName)+ // Prevent path traversalif (!dstFile.startsWith(basePath)) {throw new FileError(HttpStatus.FORBIDDEN, 'Location is not allowed')}@@ -210,33 +216,38 @@ export class FilesManager {const dstDir = dirName(dstFile)if (overwrite) {- // prevent errors when an uploaded file would replace a directory with the same name- // only applies in `overwrite` cases+ // Prevent errors when an uploaded file would replace a directory with the same name+ // Only applies in `overwrite` casesif ((await isPathExists(dstFile)) && (await isPathIsDir(dstFile))) {// If a directory already exists at the destination path, delete it to allow overwriting with the uploaded file- const dstUrl = path.join(path.dirname(space.url), part.filename)+ const dstUrl = path.join(path.dirname(space.url), partFileName)const dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))await this.delete(user, dstSpace)} else if ((await isPathExists(dstDir)) && !(await isPathIsDir(dstDir))) {// If the destination's parent exists but is a file, remove it so we can create the directory- const dstUrl = path.join(path.dirname(space.url), path.dirname(part.filename))+ const dstUrl = path.join(path.dirname(space.url), path.dirname(partFileName))const dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))await this.delete(user, dstSpace)}}- // make dir in space+ // Create the directory in the spaceif (!(await isPathExists(dstDir))) {await makeDir(dstDir, true)}- // create lock- const dbFile = { ...space.dbFile, path: path.join(dirName(space.dbFile.path), part.filename) }- const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, DEPTH.RESOURCE)- if (!ok) throw new LockConflict(fileLock, 'Conflicting lock')- // do+ // Create or refresh lock+ const dbFile = { ...space.dbFile, path: path.join(dirName(space.dbFile.path), partFileName) }+ const [created, fileLock] = await this.filesLockManager.createOrRefresh(user, dbFile, DEPTH.RESOURCE, CACHE_LOCK_FILE_TTL)+ // Dotry {await writeFromStream(dstFile, part.file)} finally {- await this.filesLockManager.removeLock(fileLock.key)+ if (created) {+ await this.filesLockManager.removeLock(fileLock.key)+ }+ }+ if (patch) {+ // Only one resource can be updated with the PATCH method.+ break}}}@@ -606,4 +617,34 @@ export class FilesManager {throw new FileError(HttpStatus.BAD_REQUEST, 'File is not an image')}}++ async lock(user: UserModel, space: SpaceEnv): Promise<FileLockProps> {+ const rExists = await isPathExists(space.realPath)+ if (!rExists) {+ this.logger.warn('Lock refresh must specify an existing resource')+ throw new FileError(HttpStatus.BAD_REQUEST, 'Lock refresh must specify an existing resource')+ }+ const [_created, lock] = await this.filesLockManager.createOrRefresh(user, space.dbFile, DEPTH.RESOURCE, CACHE_LOCK_FILE_TTL)+ return this.filesLockManager.convertLockToFileLockProps(lock)+ }++ async unlock(user: UserModel, space: SpaceEnv): Promise<void> {+ if (!(await isPathExists(space.realPath))) {+ this.logger.warn(`Unable to unlock: ${space.url} - resource does not exist`)+ throw new FileError(HttpStatus.BAD_REQUEST, 'Unlock must specify an existing resource')+ }+ const fileLocks = await this.filesLockManager.getLocksByPath(space.dbFile)+ if (fileLocks.length === 0) {+ this.logger.warn(`Unable to find lock: ${space.url} - resource does not exist`)+ return+ }+ for (const lock of fileLocks) {+ if (lock.owner.id === user.id) {+ // Refresh if more than half of the TTL has passed+ await this.filesLockManager.removeLock(lock.key)+ } else {+ throw new LockConflict(lock, 'Conflicting lock')+ }+ }+ }}diff --git a/backend/src/applications/files/services/files-methods.service.ts b/backend/src/applications/files/services/files-methods.service.tsindex beca6504..36849b0c 100644--- a/backend/src/applications/files/services/files-methods.service.ts+++ b/backend/src/applications/files/services/files-methods.service.ts@@ -14,6 +14,7 @@ import { SpacesManager } from '../../spaces/services/spaces-manager.service'import { UserModel } from '../../users/models/user.model'import { FILE_OPERATION } from '../constants/operations'import { CompressFileDto, CopyMoveFileDto, DownloadFileDto, MakeFileDto } from '../dto/file-operations.dto'+import { FileLockProps } from '../interfaces/file-props.interface'import { FileError } from '../models/file-error'import { LockConflict } from '../models/file-lock-error'import { checkFileName, dirName, fileName, isPathExists, sanitizeName } from '../utils/files'@@ -148,6 +149,22 @@ export class FilesMethods {}}+ async lock(user: UserModel, space: SpaceEnv): Promise<FileLockProps> {+ try {+ return await this.filesManager.lock(user, space)+ } catch (e) {+ this.handleError(space, FILE_OPERATION.LOCK, e)+ }+ }++ async unlock(user: UserModel, space: SpaceEnv): Promise<void> {+ try {+ return await this.filesManager.unlock(user, space)+ } catch (e) {+ this.handleError(space, FILE_OPERATION.UNLOCK, e)+ }+ }+private async copyMove(user: UserModel,space: SpaceEnv,diff --git a/backend/src/applications/shares/services/shares-manager.service.spec.ts b/backend/src/applications/shares/services/shares-manager.service.spec.tsindex 31b32199..471e0659 100644--- a/backend/src/applications/shares/services/shares-manager.service.spec.ts+++ b/backend/src/applications/shares/services/shares-manager.service.spec.ts@@ -7,6 +7,7 @@import { HttpException, HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'import * as commonFunctions from '../../../common/functions'+import { intersectPermissions } from '../../../common/shared'import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'import { LINK_TYPE } from '../../links/constants/links'@@ -39,7 +40,14 @@ jest.mock('../../../common/functions', () => {return {...actual,generateShortUUID: jest.fn(),- hashPassword: jest.fn(),+ hashPassword: jest.fn()+ }+})++jest.mock('../../../common/shared', () => {+ const actual = jest.requireActual('../../../common/shared')+ return {+ ...actual,intersectPermissions: jest.fn()}})@@ -225,7 +233,7 @@ describe(SharesManager.name, () => {}jest.spyOn(service, 'getLinkFromSpaceOrShare').mockResolvedValueOnce(baseLink)jest.spyOn(service, 'getShareLink').mockResolvedValueOnce({ file: { permissions: 'SHARE_PERMS' } } as any)- ;(commonFunctions.intersectPermissions as jest.Mock).mockReturnValue('INTERSECTED')+ ;(intersectPermissions as jest.Mock).mockReturnValue('INTERSECTED')linksQueriesMock.updateLinkFromSpaceOrShare.mockResolvedValueOnce(undefined)const dto: any = {diff --git a/backend/src/applications/shares/services/shares-manager.service.ts b/backend/src/applications/shares/services/shares-manager.service.tsindex 280a52c6..b420e8bd 100644--- a/backend/src/applications/shares/services/shares-manager.service.ts+++ b/backend/src/applications/shares/services/shares-manager.service.ts@@ -13,10 +13,10 @@ import {diffCollection,differencePermissions,generateShortUUID,- hashPassword,- intersectPermissions+ hashPassword} from '../../../common/functions'import type { Entries, StorageQuota } from '../../../common/interfaces'+import { intersectPermissions } from '../../../common/shared'import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'import type { FileProps } from '../../files/interfaces/file-props.interface'import { FileError } from '../../files/models/file-error'diff --git a/backend/src/applications/spaces/guards/space.guard.spec.ts b/backend/src/applications/spaces/guards/space.guard.spec.tsindex 3704751b..5847083e 100644--- a/backend/src/applications/spaces/guards/space.guard.spec.ts+++ b/backend/src/applications/spaces/guards/space.guard.spec.ts@@ -7,7 +7,7 @@import { createMock, DeepMocked } from '@golevelup/ts-jest'import { ExecutionContext, HttpException, HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'-import { intersectPermissions } from '../../../common/functions'+import { intersectPermissions } from '../../../common/shared'import { Cache } from '../../../infrastructure/cache/services/cache.service'import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'diff --git a/backend/src/applications/spaces/utils/permissions.ts b/backend/src/applications/spaces/utils/permissions.tsindex 36b45026..49564f72 100644--- a/backend/src/applications/spaces/utils/permissions.ts+++ b/backend/src/applications/spaces/utils/permissions.ts@@ -4,7 +4,7 @@* See the LICENSE file for licensing details*/-import { intersectPermissions } from '../../../common/functions'+import { intersectPermissions } from '../../../common/shared'import { USER_PERMISSION } from '../../users/constants/user'import type { UserModel } from '../../users/models/user.model'import { SPACE_ALIAS, SPACE_OPERATION, SPACE_PERMS_SEP, SPACE_REPOSITORY } from '../constants/spaces'diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.tsindex 5486292f..be9c519a 100644--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts@@ -4,7 +4,7 @@ import { FastifyReply } from 'fastify'import { urlToPath } from '../../../common/functions'import { decodeUrl } from '../../../common/shared'import { HTTP_METHOD } from '../../applications.constants'-import { CACHE_LOCK_DEFAULT_TIMEOUT } from '../../files/constants/cache'+import { CACHE_LOCK_DEFAULT_TTL } from '../../files/constants/cache'import { DEPTH, HEADER, LOCK_SCOPE, OPTIONS_HEADERS, PROPSTAT } from '../constants/webdav'import { FastifyDAVRequest } from '../interfaces/webdav.interface'import * as IfHeaderUtils from '../utils/if-header'@@ -232,7 +232,7 @@ describe(WebDAVProtocolGuard.name, () => {const res = makeRes()const ctx = makeCtx(req, res)await expect(guard.canActivate(ctx)).resolves.toBe(true)- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TIMEOUT)+ expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.EXCLUSIVE)expect(req.dav.lock.owner).toContain('Custom Owner')expect(req.dav.depth).toBe(DEPTH.RESOURCE)@@ -253,7 +253,7 @@ describe(WebDAVProtocolGuard.name, () => {})it('clamps timeout Second-N to default when N exceeds default', async () => {- const big = CACHE_LOCK_DEFAULT_TIMEOUT + 1000+ const big = CACHE_LOCK_DEFAULT_TTL + 1000const req = baseReq(HTTP_METHOD.LOCK, {headers: { [HEADER.TIMEOUT]: `Second-${big}` },body: '<lockinfo xmlns="DAV:"><lockscope><exclusive/></lockscope></lockinfo>'@@ -261,7 +261,7 @@ describe(WebDAVProtocolGuard.name, () => {const res = makeRes()const ctx = makeCtx(req, res)await expect(guard.canActivate(ctx)).resolves.toBe(true)- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TIMEOUT)+ expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)})it('invalid timeout -> NaN (no fallback), depth=infinity', async () => {@@ -308,7 +308,7 @@ describe(WebDAVProtocolGuard.name, () => {try {await expect(guard.canActivate(ctx)).resolves.toBe(true)- expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TIMEOUT)+ expect(req.dav.lock.timeout).toBe(CACHE_LOCK_DEFAULT_TTL)expect(req.dav.ifHeaders).toBeUndefined()} finally {spyIf.mockRestore()diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.tsindex a0fdd81b..8a8f9575 100644--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts@@ -10,7 +10,7 @@ import { FastifyReply } from 'fastify'import { urlToPath } from '../../../common/functions'import { decodeUrl } from '../../../common/shared'import { HTTP_METHOD } from '../../applications.constants'-import { CACHE_LOCK_DEFAULT_TIMEOUT } from '../../files/constants/cache'+import { CACHE_LOCK_DEFAULT_TTL } from '../../files/constants/cache'import { USER_PERMISSION } from '../../users/constants/user'import {ALLOW_EMPTY_BODY_METHODS,@@ -160,15 +160,15 @@ export class WebDAVProtocolGuard implements CanActivate {// timeout: 'Infinite, Second-4100000000' | 'Second-4100000000' | 'Infinite'const timeout = req.headers[HEADER.TIMEOUT] as stringif (timeout.toLowerCase() === 'infinite') {- req.dav.lock.timeout = CACHE_LOCK_DEFAULT_TIMEOUT+ req.dav.lock.timeout = CACHE_LOCK_DEFAULT_TTL} else {try {const timeoutSplit = timeout.split('-')const seconds = parseInt(timeoutSplit[timeoutSplit.length - 1], 10)- req.dav.lock.timeout = seconds > CACHE_LOCK_DEFAULT_TIMEOUT ? CACHE_LOCK_DEFAULT_TIMEOUT : seconds+ req.dav.lock.timeout = seconds > CACHE_LOCK_DEFAULT_TTL ? CACHE_LOCK_DEFAULT_TTL : seconds} catch (e) {this.logger.warn(`${this.lockMethod.name} - unable to set timeout, use the default value : ${e}`)- req.dav.lock.timeout = CACHE_LOCK_DEFAULT_TIMEOUT+ req.dav.lock.timeout = CACHE_LOCK_DEFAULT_TTL}}}diff --git a/backend/src/applications/webdav/services/webdav-methods.service.ts b/backend/src/applications/webdav/services/webdav-methods.service.tsindex 4743b73c..35ced70f 100644--- a/backend/src/applications/webdav/services/webdav-methods.service.ts+++ b/backend/src/applications/webdav/services/webdav-methods.service.ts@@ -112,7 +112,7 @@ export class WebDAVMethods {@IfHeaderDecorator()async unlock(req: FastifyDAVRequest, res: FastifyReply) {if (!(await isPathExists(req.space.realPath))) {- this.logger.warn(`Unable to unlock ${req.dav.url} : resource does not exist`)+ this.logger.warn(`Unable to unlock: ${req.dav.url} - resource does not exist`)return res.status(HttpStatus.NOT_FOUND).send(req.dav.url)}diff --git a/backend/src/common/functions.ts b/backend/src/common/functions.tsindex 1b6cb385..41f6cc1c 100755--- a/backend/src/common/functions.ts+++ b/backend/src/common/functions.ts@@ -123,15 +123,6 @@ export function uniquePermissions(permissions: string, permissionsSeparator: str].join(permissionsSeparator)}-export function intersectPermissions(aPermissions: string, bPermissions: string, permissionsSeparator: string = SPACE_PERMS_SEP): string {- const aPerms = aPermissions.split(permissionsSeparator)- const bPerms = bPermissions.split(permissionsSeparator)- return aPerms- .filter((p: string) => p !== '' && p !== 'null' && bPerms.indexOf(p) > -1)- .sort()- .join(permissionsSeparator)-}-export function differencePermissions(aPermissions: string, bPermissions: string, permissionsSeparator: string = SPACE_PERMS_SEP): string[] {const aPerms = aPermissions.split(permissionsSeparator)const bPerms = bPermissions.split(permissionsSeparator)diff --git a/backend/src/common/shared.ts b/backend/src/common/shared.tsindex 51d0744c..7b9fb0bf 100644--- a/backend/src/common/shared.ts+++ b/backend/src/common/shared.ts@@ -4,6 +4,8 @@* See the LICENSE file for licensing details*/+import { SPACE_PERMS_SEP } from '../applications/spaces/constants/spaces'+export const SERVER_NAME = 'Sync-in' as const// eslint-disable-next-line no-control-regex@@ -93,3 +95,12 @@ export function objectPropertyFromString(obj: any, property: string): any {export function capitalizeString(value: string): string {return value.charAt(0).toUpperCase() + value.slice(1)}++export function intersectPermissions(aPermissions: string, bPermissions: string, permissionsSeparator: string = SPACE_PERMS_SEP): string {+ const aPerms = aPermissions.split(permissionsSeparator)+ const bPerms = bPermissions.split(permissionsSeparator)+ return aPerms+ .filter((p: string) => p !== '' && p !== 'null' && bPerms.indexOf(p) > -1)+ .sort()+ .join(permissionsSeparator)+}diff --git a/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.html b/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.htmlindex 93e6e23b..257a6d5c 100644--- a/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.html+++ b/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.html@@ -6,7 +6,7 @@<div class="modal-header"><h4 class="modal-title">- <fa-icon [icon]="isEditing ? icons.faPen : icons.faEye"></fa-icon>+ <fa-icon [icon]="isReadonly() ? icons.faEye : icons.faPen"></fa-icon><span class="ms-2">{{ currentFile.name }}</span></h4><button (click)="onMinimize()" aria-label="Minimize" class="btn-minimize btn-minimize-white" type="button"></button>@@ -31,10 +31,9 @@<app-files-viewer-text[currentHeight]="currentHeight"[file]="currentFile"- [mode]="mode"[isWriteable]="isWriteable"[modalClosing]="modalClosing()"- (readonlyChange)="onReadonlyChange($event)">+ [(isReadonly)]="isReadonly"></app-files-viewer-text>}}diff --git a/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.ts b/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.tsindex db8ba868..a9e6a2db 100644--- a/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.ts+++ b/frontend/src/app/applications/files/components/dialogs/files-viewer-dialog.component.ts@@ -4,7 +4,7 @@* See the LICENSE file for licensing details*/-import { Component, computed, inject, Input, OnDestroy, OnInit, signal } from '@angular/core'+import { Component, computed, inject, Input, model, OnDestroy, OnInit, signal } from '@angular/core'import { FaIconComponent } from '@fortawesome/angular-fontawesome'import { faEye, faPen } from '@fortawesome/free-solid-svg-icons'import { FILE_MODE } from '@sync-in-server/backend/src/applications/files/constants/operations'@@ -37,7 +37,7 @@ export class FilesViewerDialogComponent implements OnInit, OnDestroy {@Input({ required: true }) isWriteable: boolean@Input({ required: true }) hookedShortMime: stringmodalClosing = signal<boolean>(false)- protected isEditing = false+ protected isReadonly = model<boolean>(true)protected currentHeight: numberprotected readonly SHORT_MIME = SHORT_MIMEprotected readonly icons = { faEye, faPen }@@ -48,7 +48,7 @@ export class FilesViewerDialogComponent implements OnInit, OnDestroy {private readonly offsetTop = 42ngOnInit() {- this.isEditing = this.mode === FILE_MODE.EDIT+ this.isReadonly.set(this.mode === FILE_MODE.VIEW)this.openedFile = { id: this.currentFile.id, name: this.currentFile.name, mimeUrl: this.currentFile.mimeUrl }this.onResize()}@@ -72,10 +72,6 @@ export class FilesViewerDialogComponent implements OnInit, OnDestroy {this.layout.minimizeDialog(this.openedFile.id, { name: this.openedFile.name, mimeUrl: this.openedFile.mimeUrl })}- onReadonlyChange(state: boolean) {- this.isEditing = !state- }-private onResize() {this.currentHeight = window.innerHeight - this.offsetTop}diff --git a/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.html b/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.htmlindex 88ff01f2..ec86e30a 100644--- a/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.html+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.html@@ -12,7 +12,7 @@[adaptivePosition]="true"class="d-none d-sm-block btn btn-sm btn-secondary me-1"type="button"- [disabled]="!isReadable() || !isWriteable()">+ [disabled]="!isSupported() || !isWriteable()"><fa-icon [icon]="isReadonly() ? icons.faLock : icons.faLockOpen"></fa-icon></button><button@@ -34,8 +34,7 @@(ngModelChange)="lineWrapping.set($event)"[tooltip]="'Line Wrap' | translate:locale.language"class="d-none d-sm-block btn btn-sm btn-custom me-1"- type="button"- [disabled]="!isReadable()">+ type="button"><fa-icon [icon]="icons.faArrowsLeftRightToLine"></fa-icon></button><button@@ -44,8 +43,7 @@(ngModelChange)="toggleSearch()"[tooltip]="'Search' | translate:locale.language"class="d-none d-sm-block btn btn-sm btn-custom"- type="button"- [disabled]="!isReadable()">+ type="button"><fa-icon [icon]="icons.faMagnifyingGlass"></fa-icon></button>@if (warnOnUnsavedChanges()) {@@ -54,7 +52,7 @@type="button"l10nTranslate>Save And Exit</button>- <button (click)="layout.closeDialog()"+ <button (click)="onClose()"class="btn btn-sm btn-danger me-2"data-dismiss="modal" type="button"l10nTranslate>Close Without Savingdiff --git a/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.ts b/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.tsindex 11a8a8bd..e7161211 100644--- a/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.ts+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-text.component.ts@@ -13,9 +13,9 @@ import {inject,input,linkedSignal,+ model,OnDestroy,OnInit,- output,signal,untracked,viewChild,@@ -27,14 +27,16 @@ import { languages } from '@codemirror/language-data'import { closeSearchPanel, openSearchPanel } from '@codemirror/search'import { FaIconComponent } from '@fortawesome/angular-fontawesome'import { faArrowsLeftRightToLine, faFloppyDisk, faLock, faLockOpen, faMagnifyingGlass, faSpinner } from '@fortawesome/free-solid-svg-icons'-import { FILE_MODE } from '@sync-in-server/backend/src/applications/files/constants/operations'+import type { FileLockProps } from '@sync-in-server/backend/src/applications/files/interfaces/file-props.interface'import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'import { ButtonCheckboxDirective } from 'ngx-bootstrap/buttons'import { TooltipModule } from 'ngx-bootstrap/tooltip'+import { firstValueFrom } from 'rxjs'import { AppWindow, themeDark } from '../../../../layout/layout.interfaces'import { LayoutService } from '../../../../layout/layout.service'import { FileModel } from '../../models/file.model'import { FilesUploadService } from '../../services/files-upload.service'+import { FilesService } from '../../services/files.service'@Component({selector: 'app-files-viewer-text',@@ -71,13 +73,11 @@ import { FilesUploadService } from '../../services/files-upload.service'export class FilesViewerTextComponent implements OnInit, OnDestroy {editor = viewChild<CodeEditor>('editor')currentHeight = input.required<number>()- file = input.required<FileModel>()- mode = input.required<FILE_MODE>()+ file = model.required<FileModel>()isWriteable = input.required<boolean>()+ isReadonly = model.required<boolean>()modalClosing = input.required<boolean>()- readonlyChange = output<boolean>()- protected isReadonly = linkedSignal(() => this.mode() === FILE_MODE.VIEW)- protected isReadable = signal(false)+ protected isSupported = signal(false)protected isModified = signal(false)protected isSaving = signal(false)protected lineWrapping = signal(false)@@ -87,11 +87,13 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {protected readonly languages: LanguageDescription[] = languagesprotected currentTheme: any = 'light'protected readonly icons = { faFloppyDisk, faLock, faLockOpen, faMagnifyingGlass, faSpinner, faArrowsLeftRightToLine }- protected readonly locale = inject<L10nLocale>(L10N_LOCALE)protected isSearchPanelOpen = signal(false)protected readonly layout = inject(LayoutService)+ protected readonly locale = inject<L10nLocale>(L10N_LOCALE)+ private readonly canLock = linkedSignal(() => this.isWriteable() && !this.isReadonly())private isContentReady = falseprivate readonly http = inject(HttpClient)+ private readonly filesServices = inject(FilesService)private readonly filesUpload = inject(FilesUploadService)private subscription = this.layout.switchTheme.subscribe((layout: string) => (this.currentTheme = layout === themeDark ? 'dark' : 'light'))private readonly maxSize = 5242880 // 5MB@@ -109,11 +111,19 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {this.layout.restoreDialog(fileId)}} else {- this.layout.closeDialog(null, fileId)+ this.onClose()}})effect(() => {- this.readonlyChange.emit(this.isReadonly())+ this.isReadonly()+ // Reset search state when open to enable/disable the replace function+ const isSearchPanelIsOpen = untracked(() => this.isSearchPanelOpen())+ if (isSearchPanelIsOpen) {+ setTimeout(() => {+ this.toggleSearch()+ this.toggleSearch()+ }, 100)+ }})}@@ -131,6 +141,9 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {} else if (this.isModified()) {event.stopPropagation()this.warnOnUnsavedChanges.set(true)+ } else {+ event.stopPropagation()+ this.onClose()}return}@@ -150,27 +163,27 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {}}- ngOnInit() {+ async ngOnInit() {const language: LanguageDescription = LanguageDescription.matchFilename(languages, this.file().name)if (language?.name || this.file().size <= this.maxSize) {this.currentLanguage = language?.name- this.isReadable.set(true)- this.http.get(this.file().dataUrl, { responseType: 'text' }).subscribe((data: string) => (this.content = data))+ this.isSupported.set(true)+ await this.lockFile()+ this.loadContent()} else {- this.isReadable.set(false)+ this.isReadonly.set(true)+ this.isSupported.set(false)this.content = this.layout.translateString('This file contains binary data that can not be read')}}- toggleReadonly() {- this.isReadonly.update((state) => !state)- // Reset search state when open to enable/disable the replace function- if (this.isSearchPanelOpen()) {- setTimeout(() => {- this.toggleSearch()- this.toggleSearch()- }, 100)+ async toggleReadonly() {+ if (this.isReadonly()) {+ await this.lockFile()+ } else {+ await this.unlockFile()}+ this.isReadonly.update((state) => !state)}save(exit = false) {@@ -181,7 +194,7 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {this.isSaving.set(false)this.warnOnUnsavedChanges.set(false)if (exit) {- this.layout.closeDialog(null, this.file().id)+ this.onClose()}},error: (e: HttpErrorResponse) => {@@ -209,7 +222,50 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {}}+ onClose() {+ this.unlockFile().then(() => this.layout.closeDialog(null, this.file().id))+ }+ngOnDestroy() {this.subscription.unsubscribe()}++ private loadContent() {+ this.http.get(this.file().dataUrl, { responseType: 'text' }).subscribe({+ next: (data: string) => (this.content = data),+ error: (e: HttpErrorResponse) => this.layout.sendNotification('error', 'Unable to open document', this.file().name, e)+ })+ }++ private async lockFile() {+ if (!this.canLock()) return+ try {+ const lock: FileLockProps = await firstValueFrom(this.filesServices.lock(this.file()))+ this.file.update((f) => {+ f.lock = lock+ return f+ })+ } catch (e) {+ this.lockError(e as HttpErrorResponse)+ }+ }++ private async unlockFile() {+ if (!this.canLock()) return+ try {+ await firstValueFrom(this.filesServices.unlock(this.file()))+ this.file.update((f) => {+ delete f.lock+ return f+ })+ } catch (e) {+ this.lockError(e as HttpErrorResponse)+ }+ }++ private lockError(e: HttpErrorResponse) {+ this.isReadonly.set(true)+ this.isSupported.set(false)+ this.layout.sendNotification('warning', this.file().name, e.error.message)+ }}diff --git a/frontend/src/app/applications/files/services/files-upload.service.ts b/frontend/src/app/applications/files/services/files-upload.service.tsindex e5c980e4..f7620afb 100644--- a/frontend/src/app/applications/files/services/files-upload.service.ts+++ b/frontend/src/app/applications/files/services/files-upload.service.ts@@ -65,12 +65,13 @@ export class FilesUploadService {}}- uploadOneFile(file: FileModel, content: string, overwrite: boolean) {+ uploadOneFile(file: FileModel, content: string, updateContent = false, overwrite = false) {const url = `${API_FILES_OPERATION_UPLOAD}/${file.path}`- const fileContent = new File([new Blob([content])], file.name.normalize(), { type: file.mime.replace('-', '/') })+ const fileName = (file?.root?.alias || file.name).normalize()+ const fileContent = new File([new Blob([content])], fileName, { type: file.mime.replace('-', '/') })const formData = new FormData()formData.append('file', fileContent)- return this.http.request<void>(overwrite ? 'put' : 'post', url, { body: formData })+ return this.http.request<void>(updateContent ? 'patch' : overwrite ? 'put' : 'post', url, { body: formData })}private uploadFiles(url: string, form: FormData, overwrite: boolean) {diff --git a/frontend/src/app/applications/files/services/files.service.ts b/frontend/src/app/applications/files/services/files.service.tsindex b81779e8..37053471 100644--- a/frontend/src/app/applications/files/services/files.service.ts+++ b/frontend/src/app/applications/files/services/files.service.ts@@ -26,6 +26,7 @@ import type {MakeFileDto,SearchFilesDto} from '@sync-in-server/backend/src/applications/files/dto/file-operations.dto'+import type { FileLockProps } from '@sync-in-server/backend/src/applications/files/interfaces/file-props.interface'import type { FileTree } from '@sync-in-server/backend/src/applications/files/interfaces/file-tree.interface'import type { FileTask } from '@sync-in-server/backend/src/applications/files/models/file-task'import type { FileContent } from '@sync-in-server/backend/src/applications/files/schemas/file-content.interface'@@ -215,6 +216,14 @@ export class FilesService {)}+ lock(file: FileModel): Observable<FileLockProps> {+ return this.http.request<FileLockProps>('lock', file.dataUrl)+ }++ unlock(file: FileModel): Observable<void> {+ return this.http.request<void>('unlock', file.dataUrl)+ }+async openOverwriteDialog(files: File[] | FileModel[], renamedTo?: string): Promise<boolean> {const overwriteDialog: BsModalRef<FilesOverwriteDialogComponent> = this.layout.openDialog(FilesOverwriteDialogComponent, null, {initialState: {@@ -227,15 +236,15 @@ export class FilesService {})}- async openViewerDialog(mode: FILE_MODE, currentFile: FileModel, directoryFiles: FileModel[], permissions: string) {- this.http.head(currentFile.dataUrl).subscribe({+ async openViewerDialog(mode: FILE_MODE, file: FileModel, directoryFiles: FileModel[], permissions: string) {+ this.http.head(file.dataUrl).subscribe({next: async () => {let hookedShortMime: stringtry {- hookedShortMime = await this.viewerHook(mode, currentFile)+ hookedShortMime = await this.viewerHook(mode, file)} catch {// OnlyOffice isn't enabled, falling back to download- this.download(currentFile)+ this.download(file)return}const isWriteable = permissions.indexOf(SPACE_OPERATION.MODIFY) > -1@@ -243,9 +252,9 @@ export class FilesService {mode = FILE_MODE.VIEW}this.layout.openDialog(FilesViewerDialogComponent, 'full', {- id: currentFile.id, // only used to manage the modal+ id: file.id, // only used to manage the modalinitialState: {- currentFile: currentFile,+ currentFile: file,directoryFiles: directoryFiles,mode: mode,isWriteable: isWriteable,@@ -253,27 +262,26 @@ export class FilesService {} satisfies Partial<FilesViewerDialogComponent>})},- error: (err: HttpErrorResponse) => {- console.error(err.message)- this.layout.sendNotification('error', 'Unable to open document', currentFile?.name)+ error: (e: HttpErrorResponse) => {+ this.layout.sendNotification('error', 'Unable to open document', file?.name, e)}})}- private async viewerHook(mode: FILE_MODE, currentFile: FileModel): Promise<string> {+ private async viewerHook(mode: FILE_MODE, file: FileModel): Promise<string> {const onlyOfficeEnabled = await this.getOnlyOfficeStatus()- if (currentFile.shortMime === SHORT_MIME.DOCUMENT && !onlyOfficeEnabled) {- if (currentFile.mime.startsWith('text-')) {+ if (file.shortMime === SHORT_MIME.DOCUMENT && !onlyOfficeEnabled) {+ if (file.mime.startsWith('text-')) {return SHORT_MIME.TEXT}throw new Error('Feature not enabled')}- if (currentFile.shortMime === SHORT_MIME.PDF) {+ if (file.shortMime === SHORT_MIME.PDF) {if (mode === FILE_MODE.EDIT && onlyOfficeEnabled) {return SHORT_MIME.DOCUMENT}}- return currentFile.shortMime+ return file.shortMime}private async getOnlyOfficeStatus(): Promise<boolean> {diff --git a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts b/frontend/src/app/applications/spaces/components/spaces-browser.component.tsindex f14bc03f..fb1a993e 100644--- a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts+++ b/frontend/src/app/applications/spaces/components/spaces-browser.component.ts@@ -44,6 +44,7 @@ import { type FileTask, FileTaskStatus } from '@sync-in-server/backend/src/appliimport { SHARE_TYPE } from '@sync-in-server/backend/src/applications/shares/constants/shares'import { SPACE_OPERATION, SPACE_REPOSITORY } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'import type { SpaceFiles } from '@sync-in-server/backend/src/applications/spaces/interfaces/space-files.interface'+import { intersectPermissions } from '@sync-in-server/backend/src/common/shared'import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'import { BsDropdownModule } from 'ngx-bootstrap/dropdown'import { BsModalRef } from 'ngx-bootstrap/modal'@@ -439,7 +440,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroyif (this.selection[0].isDir) {this.browse(this.selection[0])} else if (editMode && this.selection[0].isEditable) {- this.openViewerDialog(FILE_MODE.EDIT)+ this.shortcutEdit()} else if (this.selection[0].isViewable) {this.openViewerDialog(FILE_MODE.VIEW)} else {@@ -448,7 +449,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy}shortcutEdit() {- if (this.selection[0]?.lock?.isExclusive) {+ if (this.selection[0]?.lock?.isExclusive && this.selection[0]?.lock?.ownerLogin !== this.store.user.getValue().login) {this.layout.sendNotification('info', 'The file is locked', this.selection[0].lock.owner)return}@@ -700,7 +701,7 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroyprivate setFilePermissionsAndSpace(): Partial<FileSpace> {if (this.selection[0]?.root && this.selection[0].root.permissions.indexOf(SPACE_OPERATION.SHARE_OUTSIDE) === -1) {- // space case, if file is a space root without the share permissions+ // Space case, if the file is a space root without the share outside permissionsthis.layout.sendNotification('warning', this.selection[0].name, 'You do not have share permission')return null}@@ -724,8 +725,14 @@ export class SpacesBrowserComponent implements OnInit, AfterViewInit, OnDestroy}private openViewerDialog(mode: FILE_MODE) {- const permissions = this.selection[0]?.root ? this.selection[0].root.permissions : this.spacePermissions- this.filesService.openViewerDialog(mode, this.selection[0], this.files, permissions).catch(console.error)+ const f = this.selection[0]+ let permissions: string+ if (this.inSharesList) {+ permissions = f.root.permissions+ } else {+ permissions = f?.root ? intersectPermissions(this.spacePermissions, f?.root.permissions) : this.spacePermissions+ }+ this.filesService.openViewerDialog(mode, f, this.files, permissions).catch(console.error)}private focusOn(selectName: string) {