Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat(backend/frontend:files): improve file locking logic, enhance compatibility across apps such as WebDAV and Collabora and OnlyOffice

johaven9eb5a17b26cc
diff --git a/backend/src/applications/files/interfaces/file-lock.interface.ts b/backend/src/applications/files/interfaces/file-lock.interface.ts
index 08389866..9d8312d4 100644
--- a/backend/src/applications/files/interfaces/file-lock.interface.ts
+++ b/backend/src/applications/files/interfaces/file-lock.interface.ts
@@ -4,9 +4,22 @@
* See the LICENSE file for licensing details
*/
+import { SERVER_NAME } from '../../../common/shared'
import { Owner } from '../../users/interfaces/owner.interface'
-import { LOCK_DEPTH } from '../../webdav/constants/webdav'
-import { WebDAVLock } from '../../webdav/interfaces/webdav.interface'
+import { LOCK_DEPTH, LOCK_SCOPE, WEBDAV_APP_LOCK } from '../../webdav/constants/webdav'
+import { COLLABORA_APP_LOCK } from '../modules/collabora-online/collabora-online.constants'
+import { ONLY_OFFICE_APP_LOCK } from '../modules/only-office/only-office.constants'
+
+export type LOCK_APP = typeof WEBDAV_APP_LOCK | typeof COLLABORA_APP_LOCK | typeof ONLY_OFFICE_APP_LOCK | typeof SERVER_NAME
+
+// Optional lock parameters
+export interface FileLockOptions {
+ // Only locktype write is currently implemented in RFC
+ lockRoot: string // Used with webdav (uri)
+ lockToken: string
+ lockScope: LOCK_SCOPE
+ lockInfo?: string // Provided by some WebDAV clients to identify the locking application.
+}
export interface FileLock {
owner: Owner
@@ -14,5 +27,6 @@ export interface FileLock {
key: string
depth: LOCK_DEPTH
expiration: number
- davLock?: WebDAVLock
+ app: LOCK_APP // Known application (internal)
+ options?: FileLockOptions
}
diff --git a/backend/src/applications/files/interfaces/file-props.interface.ts b/backend/src/applications/files/interfaces/file-props.interface.ts
index a08e4bc0..bedfda14 100644
--- a/backend/src/applications/files/interfaces/file-props.interface.ts
+++ b/backend/src/applications/files/interfaces/file-props.interface.ts
@@ -12,8 +12,9 @@ import type { Owner } from '../../users/interfaces/owner.interface'
import type { File } from '../schemas/file.interface'
export interface FileLockProps {
- owner: string
- ownerLogin: string
+ owner: Owner
+ app: string
+ info?: string
isExclusive: boolean
}
diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.ts b/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.ts
index 20ab304a..937f1a01 100644
--- a/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.ts
+++ b/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.ts
@@ -19,8 +19,10 @@ import { haveSpaceEnvPermissions } from '../../../spaces/utils/permissions'
import type { UserModel } from '../../../users/models/user.model'
import { getAvatarBase64 } from '../../../users/utils/avatar'
import { DEPTH, LOCK_SCOPE } from '../../../webdav/constants/webdav'
-import { WebDAVLock } from '../../../webdav/interfaces/webdav.interface'
import { FILE_MODE } from '../../constants/operations'
+import { FileLockOptions } from '../../interfaces/file-lock.interface'
+import { FileLockProps } from '../../interfaces/file-props.interface'
+import { LockConflict } from '../../models/file-lock-error'
import { FilesLockManager } from '../../services/files-lock-manager.service'
import {
copyFileContent,
@@ -35,10 +37,10 @@ import {
writeFromStream
} from '../../utils/files'
import {
+ COLLABORA_APP_LOCK,
COLLABORA_HEADERS,
COLLABORA_LOCK_ACTION,
COLLABORA_ONLINE_EXTENSIONS,
- COLLABORA_OWNER_LOCK,
COLLABORA_TOKEN_QUERY_PARAM_NAME,
COLLABORA_URI,
COLLABORA_WOPI_SRC_QUERY_PARAM_NAME
@@ -65,18 +67,29 @@ export class CollaboraOnlineManager {
if (!COLLABORA_ONLINE_EXTENSIONS.has(fileExtension)) {
throw new HttpException('Document not supported', HttpStatus.BAD_REQUEST)
}
- const mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
+ let hasLock: false | FileLockProps = false
+ let mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
if (mode === FILE_MODE.EDIT) {
// Check lock conflicts
try {
- await this.filesLockManager.checkConflicts(space.dbFile, DEPTH.RESOURCE, { userId: user.id, lockScope: LOCK_SCOPE.SHARED })
- } catch {
- throw new HttpException('The file is locked', HttpStatus.LOCKED)
+ await this.filesLockManager.checkConflicts(space.dbFile, DEPTH.RESOURCE, {
+ userId: user.id,
+ app: COLLABORA_APP_LOCK,
+ lockScope: LOCK_SCOPE.SHARED
+ })
+ } catch (e) {
+ if (e instanceof LockConflict) {
+ hasLock = this.filesLockManager.convertLockToFileLockProps(e.lock)
+ mode = FILE_MODE.VIEW
+ } else {
+ this.logger.error(`${this.getSettings.name} - ${e}`)
+ throw new HttpException('Unable to check file lock', HttpStatus.INTERNAL_SERVER_ERROR)
+ }
}
}
const dbFileHash = genUniqHashFromFileDBProps(space.dbFile)
const authToken: string = await this.genAuthToken(user, space, dbFileHash)
- return { documentServerUrl: this.getDocumentUrl(dbFileHash, authToken), mode: mode }
+ return { documentServerUrl: this.getDocumentUrl(dbFileHash, authToken), mode: mode, hasLock: hasLock }
}
async checkFileInfo(req: FastifyCollaboraOnlineSpaceRequest): Promise<CollaboraOnlineCheckFileInfo> {
@@ -149,17 +162,17 @@ export class CollaboraOnlineManager {
const [ok, fileLock] = await this.filesLockManager.create(
req.user,
req.space.dbFile,
+ COLLABORA_APP_LOCK,
DEPTH.RESOURCE,
{
- lockroot: null,
- locktoken: reqLockToken,
- lockscope: LOCK_SCOPE.SHARED, // Collabora uses one lock for the session
- owner: `${COLLABORA_OWNER_LOCK} - ${req.user.fullName} (${req.user.email})`
- } satisfies WebDAVLock,
+ lockRoot: null,
+ lockToken: reqLockToken,
+ lockScope: LOCK_SCOPE.SHARED // Collabora uses one lock for the session
+ } satisfies FileLockOptions,
this.expiration
)
if (!ok) {
- this.lockConflict(res, fileLock.davLock.locktoken)
+ this.lockConflict(res, fileLock.options.lockToken)
return
}
break
@@ -177,7 +190,7 @@ export class CollaboraOnlineManager {
case COLLABORA_LOCK_ACTION.GET_LOCK: {
const lock = await this.filesLockManager.getLocksByPath(req.space.dbFile)
if (lock.length) {
- res.header(COLLABORA_HEADERS.LockToken, lock[0].davLock.locktoken)
+ res.header(COLLABORA_HEADERS.LockToken, lock[0].options.lockToken)
}
break
}
diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.constants.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.constants.ts
index 86bb408e..8e220f8f 100644
--- a/backend/src/applications/files/modules/collabora-online/collabora-online.constants.ts
+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.constants.ts
@@ -8,7 +8,7 @@ export const COLLABORA_URI = 'browser/dist/cool.html'
export const COLLABORA_CONTEXT = 'CollaboraOnlineEnvironment' as const
export const COLLABORA_WOPI_SRC_QUERY_PARAM_NAME = 'WOPISrc' as const
export const COLLABORA_TOKEN_QUERY_PARAM_NAME = 'access_token' as const
-export const COLLABORA_OWNER_LOCK = 'Collabora' as const
+export const COLLABORA_APP_LOCK = 'Collabora' as const
export const COLLABORA_HEADERS = {
Action: 'x-wopi-override',
diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.dtos.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.dtos.ts
index 05741a48..7d246439 100644
--- a/backend/src/applications/files/modules/collabora-online/collabora-online.dtos.ts
+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.dtos.ts
@@ -5,10 +5,12 @@
*/
import type { FILE_MODE } from '../../constants/operations'
+import type { FileLockProps } from '../../interfaces/file-props.interface'
export interface CollaboraOnlineReqDto {
documentServerUrl: string
mode: FILE_MODE
+ hasLock: false | FileLockProps
}
export interface CollaboraSaveDocumentDto {
diff --git a/backend/src/applications/files/modules/only-office/only-office-manager.service.ts b/backend/src/applications/files/modules/only-office/only-office-manager.service.ts
index 66d25a8e..e7779373 100644
--- a/backend/src/applications/files/modules/only-office/only-office-manager.service.ts
+++ b/backend/src/applications/files/modules/only-office/only-office-manager.service.ts
@@ -25,9 +25,11 @@ import { haveSpaceEnvPermissions } from '../../../spaces/utils/permissions'
import type { UserModel } from '../../../users/models/user.model'
import { getAvatarBase64 } from '../../../users/utils/avatar'
import { DEPTH, LOCK_SCOPE } from '../../../webdav/constants/webdav'
-import { WebDAVLock } from '../../../webdav/interfaces/webdav.interface'
import { FILE_MODE } from '../../constants/operations'
import type { FileDBProps } from '../../interfaces/file-db-props.interface'
+import { FileLockOptions } from '../../interfaces/file-lock.interface'
+import { FileLockProps } from '../../interfaces/file-props.interface'
+import { LockConflict } from '../../models/file-lock-error'
import { FilesLockManager } from '../../services/files-lock-manager.service'
import {
copyFileContent,
@@ -41,12 +43,12 @@ import {
writeFromStream
} from '../../utils/files'
import {
+ ONLY_OFFICE_APP_LOCK,
ONLY_OFFICE_CACHE_KEY,
ONLY_OFFICE_CONVERT_ERROR,
ONLY_OFFICE_CONVERT_EXTENSIONS,
ONLY_OFFICE_EXTENSIONS,
ONLY_OFFICE_INTERNAL_URI,
- ONLY_OFFICE_OWNER_LOCK,
ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME
} from './only-office.constants'
import { OnlyOfficeReqDto } from './only-office.dtos'
@@ -81,20 +83,31 @@ export class OnlyOfficeManager {
if (!ONLY_OFFICE_EXTENSIONS.has(fileExtension)) {
throw new HttpException('Document not supported', HttpStatus.BAD_REQUEST)
}
- const mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
+ let hasLock: false | FileLockProps = false
+ let mode: FILE_MODE = haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY) ? FILE_MODE.EDIT : FILE_MODE.VIEW
if (mode === FILE_MODE.EDIT) {
// Check lock conflicts
try {
- await this.filesLockManager.checkConflicts(space.dbFile, DEPTH.RESOURCE, { userId: user.id, lockScope: LOCK_SCOPE.SHARED })
- } catch {
- throw new HttpException('The file is locked', HttpStatus.LOCKED)
+ await this.filesLockManager.checkConflicts(space.dbFile, DEPTH.RESOURCE, {
+ userId: user.id,
+ app: ONLY_OFFICE_APP_LOCK,
+ lockScope: LOCK_SCOPE.SHARED
+ })
+ } catch (e) {
+ if (e instanceof LockConflict) {
+ hasLock = this.filesLockManager.convertLockToFileLockProps(e.lock)
+ mode = FILE_MODE.VIEW
+ } else {
+ this.logger.error(`${this.getSettings.name} - ${e}`)
+ throw new HttpException('Unable to check file lock', HttpStatus.INTERNAL_SERVER_ERROR)
+ }
}
}
const isMobile: boolean = this.mobileRegex.test(req.headers['user-agent'])
const authToken: string = await this.genAuthToken(user)
const fileUrl = this.buildUrl(API_ONLY_OFFICE_DOCUMENT, space.url, authToken)
const callBackUrl = this.buildUrl(API_ONLY_OFFICE_CALLBACK, space.url, authToken)
- const config: OnlyOfficeReqDto = await this.genConfiguration(user, space, mode, fileUrl, fileExtension, callBackUrl, isMobile)
+ const config: OnlyOfficeReqDto = await this.genConfiguration(user, space, mode, fileUrl, fileExtension, callBackUrl, isMobile, hasLock)
config.config.token = await this.genPayloadToken(config.config)
return config
}
@@ -104,17 +117,20 @@ export class OnlyOfficeManager {
try {
switch (callBackData.status) {
case 1:
+ // users connect / disconnect
await this.checkFileLock(user, space, callBackData)
this.logger.debug(`document is being edited : ${space.url}`)
break
case 2:
+ // No active users on the document
await this.checkFileLock(user, space, callBackData)
if (callBackData.notmodified) {
this.logger.debug(`document was edited but closed with no changes : ${space.url}`)
} else {
- this.logger.debug(`document was edited but not saved (let's do it) : ${space.url}`)
+ this.logger.debug(`document was edited and closed but not saved (let's do it) : ${space.url}`)
await this.saveDocument(space, callBackData.url)
}
+ await this.removeFileLock(user.id, space)
await this.removeDocumentKey(space)
break
case 3:
@@ -122,6 +138,7 @@ export class OnlyOfficeManager {
await this.saveDocument(space, callBackData.url)
break
case 4:
+ // No active users on the document
await this.removeFileLock(user.id, space)
await this.removeDocumentKey(space)
this.logger.debug(`document was closed with no changes : ${space.url}`)
@@ -151,10 +168,13 @@ export class OnlyOfficeManager {
fileUrl: string,
fileExtension: string,
callBackUrl: string,
- isMobile: boolean
+ isMobile: boolean,
+ hasLock: false | FileLockProps
): Promise<OnlyOfficeReqDto> {
+ const canEdit = mode === FILE_MODE.EDIT
const documentType = ONLY_OFFICE_EXTENSIONS.get(fileExtension)
return {
+ hasLock: hasLock,
documentServerUrl: this.externalOnlyOfficeServer || `${this.contextManager.headerOriginUrl()}${ONLY_OFFICE_INTERNAL_URI}`,
config: {
type: isMobile ? 'mobile' : 'desktop',
@@ -167,12 +187,12 @@ export class OnlyOfficeManager {
key: await this.getDocumentKey(space),
permissions: {
download: true,
- edit: mode === FILE_MODE.EDIT,
+ edit: canEdit,
changeHistory: false,
- comment: true,
- fillForms: true,
+ comment: canEdit,
+ fillForms: canEdit,
print: true,
- review: mode === FILE_MODE.EDIT
+ review: canEdit
},
url: fileUrl
},
@@ -240,11 +260,17 @@ export class OnlyOfficeManager {
private async checkFileLock(user: UserModel, space: SpaceEnv, callBackData: OnlyOfficeCallBack) {
for (const action of callBackData.actions) {
if (action.type === 0) {
- // disconnect
- await this.removeFileLock(parseInt(action.userid), space)
+ // Disconnect
+ // Remove the lock if no other users are active on the document
+ if (!Array.isArray(callBackData.users)) {
+ await this.removeFileLock(parseInt(action.userid), space)
+ }
} else if (action.type === 1) {
- // connect
- await this.createFileLock(user, space)
+ // Connect
+ // Create the lock if it's the first user to open the document
+ if (Array.isArray(callBackData.users) && callBackData.users.length === 1) {
+ await this.createFileLock(user, space)
+ }
}
}
}
@@ -253,13 +279,13 @@ export class OnlyOfficeManager {
const [ok, _fileLock] = await this.filesLockManager.create(
user,
space.dbFile,
+ ONLY_OFFICE_APP_LOCK,
DEPTH.RESOURCE,
{
- lockroot: null,
- locktoken: null,
- lockscope: LOCK_SCOPE.SHARED,
- owner: `${ONLY_OFFICE_OWNER_LOCK} - ${user.fullName} (${user.email})`
- } satisfies WebDAVLock,
+ lockRoot: null,
+ lockToken: null,
+ lockScope: LOCK_SCOPE.SHARED
+ } satisfies FileLockOptions,
this.expiration
)
if (!ok) {
@@ -284,6 +310,7 @@ export class OnlyOfficeManager {
}
private async getDocumentKey(space: SpaceEnv): Promise<string> {
+ // Uniq key to identify the document in OnlyOffice
const cacheKey = this.getCacheKey(space.dbFile)
const existingDocKey: string = await this.cache.get(cacheKey)
if (existingDocKey) {
diff --git a/backend/src/applications/files/modules/only-office/only-office.constants.ts b/backend/src/applications/files/modules/only-office/only-office.constants.ts
index 83d0c76f..9b08f187 100644
--- a/backend/src/applications/files/modules/only-office/only-office.constants.ts
+++ b/backend/src/applications/files/modules/only-office/only-office.constants.ts
@@ -7,7 +7,7 @@
export const ONLY_OFFICE_INTERNAL_URI = '/onlyoffice' // used by nginx as a proxy
export const ONLY_OFFICE_CONTEXT = 'OnlyOfficeEnvironment' as const
export const ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME = 'token' as const
-export const ONLY_OFFICE_OWNER_LOCK = 'OnlyOffice' as const
+export const ONLY_OFFICE_APP_LOCK = 'OnlyOffice' as const
export const ONLY_OFFICE_CACHE_KEY = 'foffice' as const
export const ONLY_OFFICE_EXTENSIONS = new Map<string, 'word' | 'cell' | 'slide' | 'pdf' | 'diagram'>([
diff --git a/backend/src/applications/files/modules/only-office/only-office.dtos.ts b/backend/src/applications/files/modules/only-office/only-office.dtos.ts
index 2dfb3ac8..622f3079 100644
--- a/backend/src/applications/files/modules/only-office/only-office.dtos.ts
+++ b/backend/src/applications/files/modules/only-office/only-office.dtos.ts
@@ -4,9 +4,11 @@
* See the LICENSE file for licensing details
*/
-import { OnlyOfficeConfig } from './only-office.interface'
+import type { FileLockProps } from '../../interfaces/file-props.interface'
+import type { OnlyOfficeConfig } from './only-office.interface'
export interface OnlyOfficeReqDto {
documentServerUrl: string
config: OnlyOfficeConfig
+ hasLock: false | FileLockProps
}
diff --git a/backend/src/applications/files/services/files-lock-manager.service.ts b/backend/src/applications/files/services/files-lock-manager.service.ts
index 40b32bd0..9698d313 100644
--- a/backend/src/applications/files/services/files-lock-manager.service.ts
+++ b/backend/src/applications/files/services/files-lock-manager.service.ts
@@ -11,10 +11,9 @@ import { currentTimeStamp } from '../../../common/shared'
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_TTL, CACHE_LOCK_PREFIX } from '../constants/cache'
import { FileDBProps } from '../interfaces/file-db-props.interface'
-import { FileLock } from '../interfaces/file-lock.interface'
+import { FileLock, FileLockOptions, LOCK_APP } from '../interfaces/file-lock.interface'
import { FileLockProps } from '../interfaces/file-props.interface'
import { LockConflict } from '../models/file-lock-error'
import { files } from '../schemas/files.schema'
@@ -28,32 +27,28 @@ export class FilesLockManager {
* They do not contain a token key or a davLock property
* They are exclusive only
* They must have a depth of 'infinity' (all children) or '0' (root and root members)
- - The locks created from WebDAV or OnlyOffice are stored with a token and a davLock property
+ - The locks created from WebDAV or OnlyOffice or CollaboraOnline are stored with a token and a davLock property
* They must have a depth of 'infinity' (all children) or '0' (root and root members)
- * They can be exclusive (WebDAV) or shared (OnlyOffice)
+ * They can be exclusive (WebDAV) or shared (OnlyOffice, CollaboraOnline)
* If created with WebDAV, they are stored with a token and a davLock property
* If created with OnlyOffice, they are stored with no token and a davLock property whose `locktoken` & `lockroot` properties are `null`
+ * If created with CollaboraOnline, they are stored with token and a davLock property whose `lockroot` property is `null`
Cache token key format = `flock|token?:${uuid}|path:${path}|ownerId?:${number}|spaceId?:${number}|...props` => FileLock
*/
private readonly logger = new Logger(FilesLockManager.name)
constructor(private readonly cache: Cache) {}
- async create(user: UserModel, dbFile: FileDBProps, depth: LOCK_DEPTH, davLock?: WebDAVLock, ttl?: number): Promise<[boolean, FileLock]> {
- let token: string
- let lockscope: LOCK_SCOPE
- if (davLock) {
- // webdav | onlyoffice | collabora online context
- davLock.locktoken = davLock.locktoken || this.genDAVToken()
- token = davLock.locktoken
- lockscope = davLock.lockscope
- } else {
- // api context
- token = null
- lockscope = null
- }
+ async create(
+ user: UserModel,
+ dbFile: FileDBProps,
+ app: LOCK_APP,
+ depth: LOCK_DEPTH,
+ options?: FileLockOptions,
+ ttl?: number
+ ): Promise<[boolean, FileLock]> {
try {
- await this.checkConflicts(dbFile, depth, { lockScope: lockscope })
+ await this.checkConflicts(dbFile, depth, { app: app, lockScope: options?.lockScope })
} catch (e) {
if (e instanceof LockConflict) {
return [false, e.lock]
@@ -61,22 +56,23 @@ export class FilesLockManager {
throw new Error(e)
}
ttl ??= CACHE_LOCK_DEFAULT_TTL
- const key = `${CACHE_LOCK_PREFIX}|${this.genSuffixKey(dbFile, { depth: depth, token: token })}`
+ const key = `${CACHE_LOCK_PREFIX}|${this.genSuffixKey(dbFile, { depth: depth, token: options?.lockToken })}`
const expiration = Math.floor(currentTimeStamp() + ttl)
const lock: FileLock = {
owner: user.asOwner(),
dbFilePath: dbFile.path,
key: key,
+ app: app,
depth: depth,
expiration: expiration,
- davLock: davLock
+ options: options
}
this.logger.verbose(`${this.create.name} - ${key}`)
await this.cache.set(key, lock, ttl)
return [true, lock]
}
- async createOrRefresh(user: UserModel, dbFile: FileDBProps, depth: LOCK_DEPTH, ttl?: number): Promise<[boolean, FileLock]> {
+ async createOrRefresh(user: UserModel, dbFile: FileDBProps, app: LOCK_APP, depth: LOCK_DEPTH, ttl?: number): Promise<[boolean, FileLock]> {
// Returns: [created, lock]
ttl ??= CACHE_LOCK_DEFAULT_TTL
const locks = await this.getLocksByPath(dbFile)
@@ -96,7 +92,7 @@ export class FilesLockManager {
return [false, locks[0]]
}
// Create the lock
- const [ok, lock] = await this.create(user, dbFile, depth, null, ttl)
+ const [ok, lock] = await this.create(user, dbFile, app, depth, null, ttl)
if (!ok) {
throw new LockConflict(lock, 'Conflicting lock')
}
@@ -182,18 +178,18 @@ export class FilesLockManager {
async checkConflicts(
dbFile: FileDBProps,
depth: LOCK_DEPTH,
- options?: { userId?: number; lockScope?: LOCK_SCOPE; lockTokens?: string[] }
+ options?: { userId?: number; app?: LOCK_APP; lockScope?: LOCK_SCOPE; lockTokens?: string[] }
): Promise<void> {
/* Checks if a file could be modified, created, moved, or deleted
Throws a `LockConflict` error when there are parent locks (depth: 0) or child locks (depth: infinite) that prevent modification
Returns on the first conflict (compliant with the RFC 4918)
*/
for await (const l of this.searchParentLocks(dbFile, { includeRoot: true, depth: DEPTH.INFINITY })) {
- if (options?.lockScope && options?.lockScope === LOCK_SCOPE.SHARED && l.davLock.lockscope === LOCK_SCOPE.SHARED) {
- // Only compatible with shared locks (even by the same owner)
+ if (options?.lockScope && options?.lockScope === LOCK_SCOPE.SHARED && l.options.lockScope === LOCK_SCOPE.SHARED && options?.app === l.app) {
+ // Only compatible with shared locks (with the same owner and the same application)
continue
}
- if (options?.userId === l.owner.id && (!l.davLock || (options?.lockTokens?.length && options.lockTokens.indexOf(l.davLock.locktoken) > -1))) {
+ if (options?.userId === l.owner.id && (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken) > -1))) {
// Owner owns this lock (no davLock if the lock was created from api)
continue
}
@@ -203,7 +199,7 @@ export class FilesLockManager {
}
if (depth === DEPTH.INFINITY) {
for await (const l of this.searchChildLocks(dbFile)) {
- if (options?.userId === l.owner.id && (!l.davLock || (options?.lockTokens?.length && options.lockTokens.indexOf(l.davLock.locktoken) > -1))) {
+ if (options?.userId === l.owner.id && (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken) > -1))) {
// Owner owns this lock (no davLock if the lock was created from api)
continue
}
@@ -230,12 +226,17 @@ export class FilesLockManager {
convertLockToFileLockProps(lock: FileLock): FileLockProps {
if (!lock) return null
return {
- owner: lock?.davLock?.owner || `${lock.owner.fullName} (${lock.owner.email})`,
- ownerLogin: lock.owner.login,
- isExclusive: lock?.davLock?.lockscope ? lock?.davLock?.lockscope === LOCK_SCOPE.EXCLUSIVE : true
+ owner: lock.owner,
+ app: lock?.app,
+ info: lock?.options?.lockInfo,
+ isExclusive: lock?.options?.lockScope ? lock?.options?.lockScope === LOCK_SCOPE.EXCLUSIVE : true
}
}
+ genDAVToken(): string {
+ return `${LOCK_PREFIX}${crypto.randomUUID()}`
+ }
+
private async *searchParentLocks(dbFile: FileDBProps, options: { includeRoot?: boolean; depth?: LOCK_DEPTH } = {}): AsyncGenerator<FileLock> {
const props = this.genSuffixKey(dbFile, { ignorePath: true })
let path = dbFile.path
@@ -272,10 +273,6 @@ export class FilesLockManager {
return this.cache.keys(`${CACHE_LOCK_PREFIX}*${depth ? `|depth:${depth}` : ''}|path:${path}|${props}`)
}
- private genDAVToken(): string {
- return `${LOCK_PREFIX}${crypto.randomUUID()}`
- }
-
private genSuffixKey(dbFile: FileDBProps, options: { ignorePath?: boolean; depth?: LOCK_DEPTH; token?: string } = {}): string {
// return -> `depth:infinity|path:code/sync-in|spaceId:1` | `token:xxx|depth:0|path:code/sync-in.ts|ownerId:1`
// ignorePath -> `spaceId:1`
diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.ts
index 23fd0e86..f6b16041 100644
--- a/backend/src/applications/files/services/files-manager.service.ts
+++ b/backend/src/applications/files/services/files-manager.service.ts
@@ -14,6 +14,7 @@ import { Readable } from 'node:stream'
import { extract as extractTar } from 'tar'
import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/auth-request.interface'
import { generateThumbnail } from '../../../common/image'
+import { SERVER_NAME } from '../../../common/shared'
import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'
import { HTTP_METHOD } from '../../applications.constants'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'
@@ -126,7 +127,7 @@ export class FilesManager {
})
} else {
// Create lock if there is no webdav context
- const [ok, lock] = await this.filesLockManager.create(user, space.dbFile, DEPTH.RESOURCE)
+ const [ok, lock] = await this.filesLockManager.create(user, space.dbFile, SERVER_NAME, DEPTH.RESOURCE)
if (!ok) {
throw new LockConflict(lock, 'Conflicting lock')
}
@@ -246,7 +247,7 @@ export class FilesManager {
const dbFile = { ...space.dbFile, path: path.join(dirName(space.dbFile.path), partFileName) }
// Use a short TTL for the PATCH method (which is also used for refreshing)
const ttl = patch ? CACHE_LOCK_FILE_TTL : undefined
- const [created, fileLock] = await this.filesLockManager.createOrRefresh(user, dbFile, DEPTH.RESOURCE, ttl)
+ const [created, fileLock] = await this.filesLockManager.createOrRefresh(user, dbFile, SERVER_NAME, DEPTH.RESOURCE, ttl)
// Do
try {
await writeFromStream(dstFile, part.file)
@@ -476,7 +477,7 @@ export class FilesManager {
const rPath = await uniqueFilePathFromDir(space.realPath)
const dbFile = space.dbFile
dbFile.path = path.join(dirName(dbFile.path), fileName(space.realPath))
- const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, DEPTH.RESOURCE)
+ const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, SERVER_NAME, DEPTH.RESOURCE)
if (!ok) {
throw new LockConflict(fileLock, 'Conflicting lock')
}
@@ -542,7 +543,7 @@ export class FilesManager {
if (dto.compressInDirectory) {
const dbFile = space.dbFile
dbFile.path = path.join(dirName(dbFile.path), fileName(dstPath))
- const [ok, lock] = await this.filesLockManager.create(user, dbFile, DEPTH.RESOURCE)
+ const [ok, lock] = await this.filesLockManager.create(user, dbFile, SERVER_NAME, DEPTH.RESOURCE)
if (!ok) {
throw new LockConflict(lock, 'Conflicting lock')
}
@@ -591,7 +592,7 @@ export class FilesManager {
// create lock
const dbFile = space.dbFile
dbFile.path = path.join(dirName(dbFile.path), fileName(dstPath))
- const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, DEPTH.INFINITY)
+ const [ok, fileLock] = await this.filesLockManager.create(user, dbFile, SERVER_NAME, DEPTH.INFINITY)
if (!ok) {
throw new LockConflict(fileLock, 'Conflicting lock')
}
@@ -635,7 +636,7 @@ export class FilesManager {
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)
+ const [_created, lock] = await this.filesLockManager.createOrRefresh(user, space.dbFile, SERVER_NAME, DEPTH.RESOURCE, CACHE_LOCK_FILE_TTL)
return this.filesLockManager.convertLockToFileLockProps(lock)
}
diff --git a/backend/src/applications/webdav/constants/webdav.ts b/backend/src/applications/webdav/constants/webdav.ts
index 1588b953..a7fe4cf1 100644
--- a/backend/src/applications/webdav/constants/webdav.ts
+++ b/backend/src/applications/webdav/constants/webdav.ts
@@ -14,6 +14,7 @@ export const NS_PREFIX = 'D'
export const LOCK_PREFIX = 'urn:uuid:'
export const XML_CONTENT_TYPE = 'application/xml; charset=utf-8'
export const HTML_CONTENT_TYPE = 'text/html; charset=utf-8'
+export const WEBDAV_APP_LOCK = 'WebDAV' as const
export const ALLOWED_WEBDAV_METHODS: string = [
HTTP_STANDARD_METHOD.OPTIONS,
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
index be9c519a..149fda77 100644
--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.spec.ts
@@ -248,7 +248,7 @@ describe(WebDAVProtocolGuard.name, () => {
await expect(guard.canActivate(ctx)).resolves.toBe(true)
expect(req.dav.lock.timeout).toBe(10)
expect(req.dav.lock.lockscope).toBe(LOCK_SCOPE.SHARED)
- expect(req.dav.lock.owner).toMatch(/^WebDAV - /)
+ expect(req.dav.lock.owner).toMatch(/^me/)
expect(req.dav.depth).toBe(DEPTH.INFINITY)
})
diff --git a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
index 8a8f9575..9637480b 100644
--- a/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
+++ b/backend/src/applications/webdav/guards/webdav-protocol.guard.ts
@@ -189,9 +189,7 @@ export class WebDAVProtocolGuard implements CanActivate {
throw new HttpException('Invalid or undefined lockscope', HttpStatus.BAD_REQUEST)
}
if (req.dav.body['lockinfo']['owner'] && typeof req.dav.body['lockinfo']['owner'] === 'string') {
- req.dav.lock.owner = `${req.dav.body['lockinfo']['owner']} ${req.user.fullName} (${req.user.email})`
- } else {
- req.dav.lock.owner = `WebDAV - ${req.user.fullName} (${req.user.email})`
+ req.dav.lock.owner = req.dav.body['lockinfo']['owner'].trim()
}
const depth: DEPTH = ((req.headers[HEADER.DEPTH] as any) || '').toLowerCase()
req.dav.depth = [DEPTH.INFINITY, DEPTH.RESOURCE].indexOf(depth) === -1 ? DEPTH.INFINITY : depth
diff --git a/backend/src/applications/webdav/interfaces/webdav.interface.ts b/backend/src/applications/webdav/interfaces/webdav.interface.ts
index 05429728..41dca8a3 100644
--- a/backend/src/applications/webdav/interfaces/webdav.interface.ts
+++ b/backend/src/applications/webdav/interfaces/webdav.interface.ts
@@ -21,16 +21,6 @@ export interface WebDAVContext {
copyMove?: { overwrite: boolean; destination: string; isMove: boolean }
}
-export interface WebDAVLock {
- // webdav uri (null if used with OnlyOffice)
- lockroot: string
- locktoken: string
- lockscope: LOCK_SCOPE
- // owner extra info provided during lock creation
- owner: string
- // locktype: 'write' => already handled by default
-}
-
export interface FastifyDAVRequest extends FastifyAuthenticatedRequest {
body: any
dav?: WebDAVContext
diff --git a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
index 3cea21c0..316dd771 100644
--- a/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
+++ b/backend/src/applications/webdav/services/webdav-methods.service.spec.ts
@@ -6,6 +6,7 @@
import { HttpException, HttpStatus } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
+import { FileLock } from '../../files/interfaces/file-lock.interface'
import { FilesLockManager } from '../../files/services/files-lock-manager.service'
import { FilesManager } from '../../files/services/files-manager.service'
import { dirName, isPathExists } from '../../files/utils/files'
@@ -273,15 +274,14 @@ describe(WebDAVMethods.name, () => {
true,
{
dbFilePath: _dbFile?.path,
- davLock: {
- lockroot: davLock.lockroot,
- locktoken: davLock.locktoken,
- lockscope: davLock.lockscope,
- owner: davLock.owner,
- depth: _depth,
- timeout: _timeout
+ depth: _depth,
+ options: {
+ lockRoot: davLock.lockroot,
+ lockToken: davLock.locktoken,
+ lockScope: davLock.lockscope,
+ lockInfo: davLock.owner
}
- }
+ } satisfies Partial<FileLock>
] as any
})
diff --git a/backend/src/applications/webdav/services/webdav-methods.service.ts b/backend/src/applications/webdav/services/webdav-methods.service.ts
index 1d5a40db..71805d87 100644
--- a/backend/src/applications/webdav/services/webdav-methods.service.ts
+++ b/backend/src/applications/webdav/services/webdav-methods.service.ts
@@ -7,7 +7,7 @@
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { currentTimeStamp, encodeUrl } from '../../../common/shared'
-import { FileLock } from '../../files/interfaces/file-lock.interface'
+import { FileLock, FileLockOptions } from '../../files/interfaces/file-lock.interface'
import { FileError } from '../../files/models/file-error'
import { LockConflict } from '../../files/models/file-lock-error'
import { FilesLockManager } from '../../files/services/files-lock-manager.service'
@@ -28,10 +28,11 @@ import {
PROPPATCH_SUPPORTED_PROPS,
PROPSTAT,
STANDARD_PROPS,
+ WEBDAV_APP_LOCK,
XML_CONTENT_TYPE
} from '../constants/webdav'
import { IfHeaderDecorator } from '../decorators/if-header.decorator'
-import { FastifyDAVRequest, WebDAVLock } from '../interfaces/webdav.interface'
+import { FastifyDAVRequest } from '../interfaces/webdav.interface'
import { extractAllTokens, extractOneToken } from '../utils/if-header'
import { DAV_ERROR_RES, LOCK_DISCOVERY, LOCK_PROP, MULTI_STATUS, PROP, PROP_STAT } from '../utils/webdav'
import { xmlBuild } from '../utils/xml'
@@ -84,14 +85,21 @@ export class WebDAVMethods {
}
}
- const davLock: WebDAVLock = {
- lockroot: req.dav.url,
- locktoken: null, // created later
- lockscope: req.dav.lock.lockscope,
- owner: req.dav.lock.owner
+ const lockOptions: FileLockOptions = {
+ lockRoot: req.dav.url,
+ lockToken: this.filesLockManager.genDAVToken(),
+ lockScope: req.dav.lock.lockscope,
+ lockInfo: req.dav.lock?.owner
}
- const [ok, fileLock] = await this.filesLockManager.create(req.user, req.space.dbFile, req.dav.depth, davLock, req.dav.lock.timeout)
+ const [ok, fileLock] = await this.filesLockManager.create(
+ req.user,
+ req.space.dbFile,
+ WEBDAV_APP_LOCK,
+ req.dav.depth,
+ lockOptions,
+ req.dav.lock.timeout
+ )
if (ok) {
// Locking unmapped URLs: must create an empty resource (that is not a collection)
if (!rExists) {
@@ -100,12 +108,12 @@ export class WebDAVMethods {
}
const lockProp = LOCK_PROP([fileLock])
return res
- .header('lock-token', `<${davLock.locktoken}>`)
+ .header('lock-token', `<${lockOptions.lockToken}>`)
.type(XML_CONTENT_TYPE)
.status(rExists ? HttpStatus.OK : HttpStatus.CREATED)
.send(xmlBuild(lockProp))
} else {
- return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, fileLock.davLock?.lockroot || fileLock.dbFilePath)
+ return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, fileLock.options?.lockRoot || fileLock.dbFilePath)
}
}
@@ -396,12 +404,12 @@ export class WebDAVMethods {
if (condition.token) {
const token = await this.filesLockManager.getLockByToken(condition.token.value)
- const match = token && lastPath.startsWith(token.davLock?.lockroot)
+ const match = token && lastPath.startsWith(token.options?.lockRoot)
if (condition.token.mustMatch !== match) {
if (!token) {
errors.push(`lock token not found`)
} else {
- errors.push(`lock token url mismatch (${lastPath} is not a child of ${token.davLock?.lockroot})`)
+ errors.push(`lock token url mismatch (${lastPath} is not a child of ${token.options?.lockRoot})`)
}
continue
}
@@ -466,7 +474,7 @@ export class WebDAVMethods {
// Remove the last part to avoid exposing the path
const errorMsg = e.message.split(',')[0]
if (e instanceof LockConflict) {
- return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, e.lock.davLock?.lockroot || e.lock.dbFilePath)
+ return DAV_ERROR_RES(HttpStatus.LOCKED, PRECONDITION.LOCK_CONFLICT, res, e.lock.options?.lockRoot || e.lock.dbFilePath)
} else if (e instanceof FileError) {
return res.status(e.httpCode).send(errorMsg)
}
diff --git a/backend/src/applications/webdav/utils/webdav.ts b/backend/src/applications/webdav/utils/webdav.ts
index 14fb17db..9623bea7 100644
--- a/backend/src/applications/webdav/utils/webdav.ts
+++ b/backend/src/applications/webdav/utils/webdav.ts
@@ -69,10 +69,10 @@ export function LOCK_DISCOVERY(locks: FileLock[]) {
activeLocks.push({
[`${NS_PREFIX}:activelock`]: {
[`${NS_PREFIX}:locktype`]: { [`${NS_PREFIX}:write`]: null },
- [`${NS_PREFIX}:lockscope`]: { [`${NS_PREFIX}:${lock.davLock?.lockscope || LOCK_SCOPE.EXCLUSIVE}`]: null },
- [`${NS_PREFIX}:locktoken`]: { [`${NS_PREFIX}:href`]: lock.davLock?.locktoken || SERVER_NAME },
- [`${NS_PREFIX}:lockroot`]: { [`${NS_PREFIX}:href`]: encodeUrl(lock.davLock?.lockroot || lock.dbFilePath) },
- [`${NS_PREFIX}:owner`]: lock.davLock?.owner || 'WebDAV',
+ [`${NS_PREFIX}:lockscope`]: { [`${NS_PREFIX}:${lock.options?.lockScope || LOCK_SCOPE.EXCLUSIVE}`]: null },
+ [`${NS_PREFIX}:locktoken`]: { [`${NS_PREFIX}:href`]: lock.options?.lockToken || SERVER_NAME },
+ [`${NS_PREFIX}:lockroot`]: { [`${NS_PREFIX}:href`]: encodeUrl(lock.options?.lockRoot || lock.dbFilePath) },
+ [`${NS_PREFIX}:owner`]: lock.options?.lockInfo,
[`${NS_PREFIX}:timeout`]: `Second-${Math.floor(lock.expiration - currentTimeStamp())}`,
[`${NS_PREFIX}:depth`]: lock.depth
}
diff --git a/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.html b/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.html
index dc40a7b1..5e015049 100755
--- a/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.html
+++ b/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.html
@@ -19,11 +19,7 @@
<span class="mb-2" l10nTranslate>The file is edited by</span>
}
<img class="avatar-img mb-2" [src]="userAvatarUrl" alt="">
- @if (isLockOwner) {
- <b l10nTranslate>me</b>
- } @else {
- <b>{{ file?.lock?.owner }}</b>
- }
+ <b>{{ file.lock | fileLockFormatPipe }}</b>
</div>
@if (hasExclusiveLock && !isLockOwner && isFileOwner) {
<div class="text-align-center mt-3 mb-1">
@@ -33,7 +29,7 @@
</div>
<div class="modal-footer">
<button (click)="layout.closeDialog()" class="btn btn-sm btn-secondary" data-dismiss="modal" type="button" l10nTranslate>
- {{ hasExclusiveLock ? 'Cancel' : 'Close' | translate:locale.language }}
+ {{ hasExclusiveLock ? 'Cancel' : 'Close' }}
</button>
@if (hasExclusiveLock) {
@if (isLockOwner || isFileOwner) {
diff --git a/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.ts b/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.ts
index 20a6b338..4f110311 100644
--- a/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.ts
+++ b/frontend/src/app/applications/files/components/dialogs/files-lock-dialog.component.ts
@@ -8,7 +8,7 @@ import { HttpErrorResponse } from '@angular/common/http'
import { Component, HostListener, inject, Input, OnInit } from '@angular/core'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faLock, faUnlock } from '@fortawesome/free-solid-svg-icons'
-import { L10N_LOCALE, L10nLocale, L10nTranslateDirective, L10nTranslatePipe } from 'angular-l10n'
+import { L10N_LOCALE, L10nLocale, L10nTranslateDirective } from 'angular-l10n'
import { firstValueFrom } from 'rxjs'
import { LayoutService } from '../../../../layout/layout.service'
import { StoreService } from '../../../../store/store.service'
@@ -16,10 +16,11 @@ import { SpacesBrowserService } from '../../../spaces/services/spaces-browser.se
import { userAvatarUrl } from '../../../users/user.functions'
import { FileModel } from '../../models/file.model'
import { FilesService } from '../../services/files.service'
+import { FileLockFormatPipe } from '../utils/file-lock.utils'
@Component({
selector: 'app-files-lock-dialog',
- imports: [FaIconComponent, L10nTranslateDirective, L10nTranslatePipe],
+ imports: [FaIconComponent, L10nTranslateDirective, FileLockFormatPipe],
templateUrl: 'files-lock-dialog.component.html'
})
export class FilesLockDialogComponent implements OnInit {
@@ -40,8 +41,8 @@ export class FilesLockDialogComponent implements OnInit {
ngOnInit() {
this.hasExclusiveLock = this.file.lock.isExclusive
this.isFileOwner = this.spacesBrowserService.inPersonalSpace || this.file.root?.owner?.login === this.userLogin
- this.isLockOwner = this.file.lock.ownerLogin === this.userLogin
- this.userAvatarUrl = userAvatarUrl(this.file.lock.ownerLogin)
+ this.isLockOwner = this.file.lock.owner.login === this.userLogin
+ this.userAvatarUrl = userAvatarUrl(this.file.lock.owner.login)
}
@HostListener('document:keyup.enter')
diff --git a/frontend/src/app/applications/files/components/sidebar/files-selection.component.html b/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
index 65558fad..eca58ad5 100644
--- a/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
+++ b/frontend/src/app/applications/files/components/sidebar/files-selection.component.html
@@ -147,7 +147,7 @@
<div (click)="openLockDialog(f)"
class="badge rounded-pill white-space bg-maroon cursor-pointer mb-2">
<fa-icon [icon]="f.lock.isExclusive ? icons.faLock : icons.faUnlock"></fa-icon>
- <span>&nbsp;{{ f.lock.owner }}</span>
+ <span>&nbsp;{{ f.lock | fileLockFormatPipe }}</span>
</div>
}
@for (space of f.spaces; track space.id) {
diff --git a/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts b/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
index 791333fb..4781813c 100755
--- a/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
+++ b/frontend/src/app/applications/files/components/sidebar/files-selection.component.ts
@@ -24,6 +24,7 @@ import { UserAvatarComponent } from '../../../users/components/utils/user-avatar
import { USER_PATH } from '../../../users/user.constants'
import { FileModel } from '../../models/file.model'
import { FilesService } from '../../services/files.service'
+import { FileLockFormatPipe, fileLockPropsToString } from '../utils/file-lock.utils'
import { FilePermissionsComponent } from '../utils/file-permissions.component'
import { FilesViewerMediaComponent } from '../viewers/files-viewer-media.component'
@@ -40,7 +41,8 @@ import { FilesViewerMediaComponent } from '../viewers/files-viewer-media.compone
FilesViewerMediaComponent,
UserAvatarComponent,
FilePermissionsComponent,
- AsyncPipe
+ AsyncPipe,
+ FileLockFormatPipe
],
styles: ['.card {width: 100%; background: transparent; border: none}']
})
@@ -61,6 +63,7 @@ export class FilesSelectionComponent {
faArrowsAlt,
faSpinner
}
+ protected readonly fileLockPropsToString = fileLockPropsToString
private readonly router = inject(Router)
private readonly layout = inject(LayoutService)
private readonly filesService = inject(FilesService)
diff --git a/frontend/src/app/applications/files/components/sidebar/files-tree.component.ts b/frontend/src/app/applications/files/components/sidebar/files-tree.component.ts
index bd6922d7..80cd13d0 100644
--- a/frontend/src/app/applications/files/components/sidebar/files-tree.component.ts
+++ b/frontend/src/app/applications/files/components/sidebar/files-tree.component.ts
@@ -326,7 +326,7 @@ export class FilesTreeComponent implements OnInit, OnDestroy {
this.dstAllowed = true
return
}
- if (f.lock && f.lock.ownerLogin !== this.store.user.getValue().login) {
+ if (f.lock && f.lock.owner.login !== this.store.user.getValue().login) {
this.errorMsg = 'You can not move a locked file'
this.srcAllowed = false
this.dstAllowed = true
diff --git a/frontend/src/app/applications/files/components/utils/file-lock.utils.ts b/frontend/src/app/applications/files/components/utils/file-lock.utils.ts
new file mode 100644
index 00000000..b0c9b6e6
--- /dev/null
+++ b/frontend/src/app/applications/files/components/utils/file-lock.utils.ts
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Pipe, PipeTransform } from '@angular/core'
+import type { FileLockProps } from '@sync-in-server/backend/src/applications/files/interfaces/file-props.interface'
+
+export function fileLockPropsToString(lock: FileLockProps): string {
+ const lockInfo = `${lock.info ? `${lock.info}` : ''}${lock.app ? ` ${lock.app}` : ''}`
+ return `${lock.owner.fullName} (${lock.owner.email})${lockInfo ? ` - ${lockInfo}` : ''}`
+}
+
+@Pipe({
+ name: 'fileLockFormatPipe',
+ pure: true,
+ standalone: true
+})
+export class FileLockFormatPipe implements PipeTransform {
+ transform(lock: FileLockProps): string {
+ if (!lock) return 'unknown'
+ return fileLockPropsToString(lock)
+ }
+}
diff --git a/frontend/src/app/applications/files/components/viewers/files-viewer-collabora-online.component.ts b/frontend/src/app/applications/files/components/viewers/files-viewer-collabora-online.component.ts
index da20876d..7c5e8b86 100644
--- a/frontend/src/app/applications/files/components/viewers/files-viewer-collabora-online.component.ts
+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-collabora-online.component.ts
@@ -8,12 +8,13 @@ import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Component, inject, input, model, OnDestroy, OnInit } from '@angular/core'
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'
import { FILE_MODE } from '@sync-in-server/backend/src/applications/files/constants/operations'
-import { COLLABORA_OWNER_LOCK } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.constants'
+import { COLLABORA_APP_LOCK } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.constants'
import type { CollaboraOnlineReqDto } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.dtos'
import { API_COLLABORA_ONLINE_SETTINGS } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.routes'
import { LayoutService } from '../../../../layout/layout.service'
import { StoreService } from '../../../../store/store.service'
import { FileModel } from '../../models/file.model'
+import { fileLockPropsToString } from '../utils/file-lock.utils'
@Component({
selector: 'app-files-viewer-collabora-online',
@@ -57,12 +58,24 @@ export class FilesViewerCollaboraOnlineComponent implements OnInit, OnDestroy {
this.layout.sendNotification('error', 'Unable to open document', 'Settings are missing')
return
}
+ if (data.hasLock) {
+ if (!this.file().lock) {
+ this.file().createLock(data.hasLock)
+ } else if (!this.file().lock.isExclusive) {
+ // If a lock already exists and is exclusive, a notification was previously fired
+ this.layout.sendNotification('info', 'The file is locked', fileLockPropsToString(data.hasLock))
+ }
+ }
this.isReadonly.set(data.mode === FILE_MODE.VIEW)
- if (!this.isReadonly()) {
+ if (!this.isReadonly() && !this.file().lock) {
// Set lock on file
this.file().createLock({
- owner: `${COLLABORA_OWNER_LOCK} - ${this.store.user.getValue().fullName} (${this.store.user.getValue().email})`,
- ownerLogin: this.store.user.getValue().login,
+ owner: {
+ login: this.store.user.getValue().login,
+ fullName: this.store.user.getValue().fullName,
+ email: this.store.user.getValue().email
+ },
+ app: COLLABORA_APP_LOCK,
isExclusive: false
})
}
@@ -76,7 +89,9 @@ export class FilesViewerCollaboraOnlineComponent implements OnInit, OnDestroy {
}
ngOnDestroy() {
- // Remove lock
- this.file().removeLock()
+ if (!this.isReadonly() && this.file().lock && this.file().lock.owner.login === this.store.user.getValue().login) {
+ // Remove lock
+ this.file().removeLock()
+ }
}
}
diff --git a/frontend/src/app/applications/files/components/viewers/files-viewer-only-office.component.ts b/frontend/src/app/applications/files/components/viewers/files-viewer-only-office.component.ts
index 069b1bb0..d5c53e3f 100644
--- a/frontend/src/app/applications/files/components/viewers/files-viewer-only-office.component.ts
+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-only-office.component.ts
@@ -7,12 +7,13 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Component, inject, input, model, OnDestroy, OnInit } from '@angular/core'
import { FILE_MODE } from '@sync-in-server/backend/src/applications/files/constants/operations'
-import { ONLY_OFFICE_OWNER_LOCK } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.constants'
+import { ONLY_OFFICE_APP_LOCK } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.constants'
import type { OnlyOfficeReqDto } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.dtos'
import { API_ONLY_OFFICE_SETTINGS } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.routes'
import { LayoutService } from '../../../../layout/layout.service'
import { StoreService } from '../../../../store/store.service'
import { FileModel } from '../../models/file.model'
+import { fileLockPropsToString } from '../utils/file-lock.utils'
import { OnlyOfficeComponent } from '../utils/only-office.component'
@Component({
@@ -59,12 +60,24 @@ export class FilesViewerOnlyOfficeComponent implements OnInit, OnDestroy {
this.layout.sendNotification('error', 'Unable to open document', 'Settings are missing')
return
}
+ if (data.hasLock) {
+ if (!this.file().lock) {
+ this.file().createLock(data.hasLock)
+ } else if (!this.file().lock.isExclusive) {
+ // If a lock already exists and is exclusive, a notification was previously fired
+ this.layout.sendNotification('info', 'The file is locked', fileLockPropsToString(data.hasLock))
+ }
+ }
this.isReadonly.set(data.config.editorConfig.mode === FILE_MODE.VIEW)
- if (!this.isReadonly()) {
+ if (!this.isReadonly() && !this.file().lock) {
// Set lock on file
this.file().createLock({
- owner: `${ONLY_OFFICE_OWNER_LOCK} - ${this.store.user.getValue().fullName} (${this.store.user.getValue().email})`,
- ownerLogin: this.store.user.getValue().login,
+ owner: {
+ login: this.store.user.getValue().login,
+ fullName: this.store.user.getValue().fullName,
+ email: this.store.user.getValue().email
+ },
+ app: ONLY_OFFICE_APP_LOCK,
isExclusive: false
})
}
@@ -79,11 +92,6 @@ export class FilesViewerOnlyOfficeComponent implements OnInit, OnDestroy {
})
}
- ngOnDestroy() {
- // Remove lock
- this.file().removeLock()
- }
-
loadError(e: { title: string; message: string }): void {
this.layout.closeDialog()
this.layout.sendNotification('error', e.title, e.message)
@@ -92,4 +100,11 @@ export class FilesViewerOnlyOfficeComponent implements OnInit, OnDestroy {
onSave() {
this.file().updateHTimeAgo()
}
+
+ ngOnDestroy() {
+ if (!this.isReadonly() && this.file().lock && this.file().lock.owner.login === this.store.user.getValue().login) {
+ // Remove lock
+ this.file().removeLock()
+ }
+ }
}
diff --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.ts
index a8008c2e..db02f268 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
@@ -46,6 +46,7 @@ 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'
+import { fileLockPropsToString } from '../utils/file-lock.utils'
@Component({
selector: 'app-files-viewer-text',
@@ -301,7 +302,7 @@ export class FilesViewerTextComponent implements OnInit, OnDestroy {
f.lock = lock
return f
})
- this.layout.sendNotification('info', 'The file is locked', lock.owner)
+ this.layout.sendNotification('info', 'The file is locked', fileLockPropsToString(lock))
} else {
this.layout.sendNotification('warning', this.file().name, e.error.message)
}
diff --git a/frontend/src/app/applications/files/services/files.service.ts b/frontend/src/app/applications/files/services/files.service.ts
index b0e63310..2c0502a8 100644
--- a/frontend/src/app/applications/files/services/files.service.ts
+++ b/frontend/src/app/applications/files/services/files.service.ts
@@ -48,6 +48,7 @@ import { FilesLockDialogComponent } from '../components/dialogs/files-lock-dialo
import { FilesOverwriteDialogComponent } from '../components/dialogs/files-overwrite-dialog.component'
import { FilesViewerDialogComponent } from '../components/dialogs/files-viewer-dialog.component'
import { FilesViewerSelectDialog } from '../components/dialogs/files-viewer-select-dialog.component'
+import { fileLockPropsToString } from '../components/utils/file-lock.utils'
import { MAX_TEXT_FILE_SIZE, SHORT_MIME } from '../files.constants'
import { FileContentModel } from '../models/file-content.model'
import { FileRecentModel } from '../models/file-recent.model'
@@ -295,15 +296,14 @@ export class FilesService {
this.http.head(file.dataUrl).subscribe({
next: async () => {
// This check is only used for the text viewer; other viewers are read-only or enforce permissions on the backend.
- const isLockedByOther = file?.lock?.isExclusive && file.lock?.ownerLogin !== this.store.user.getValue().login
- const isWriteable = !isLockedByOther && permissions.indexOf(SPACE_OPERATION.MODIFY) > -1
+ const isWriteable = file?.lock?.isExclusive && permissions.indexOf(SPACE_OPERATION.MODIFY) > -1
const mode: FILE_MODE = isWriteable ? FILE_MODE.EDIT : FILE_MODE.VIEW
let hookedShortMime: string
try {
hookedShortMime = await this.viewerHook(file, isWriteable)
- if (isLockedByOther) {
- this.layout.sendNotification('info', 'The file is locked', file.lock.owner)
+ if (file?.lock?.isExclusive) {
+ this.layout.sendNotification('info', 'The file is locked', fileLockPropsToString(file.lock))
}
} catch {
// No office editors are enabled, falling back to download
diff --git a/frontend/src/app/applications/spaces/components/spaces-browser.component.html b/frontend/src/app/applications/spaces/components/spaces-browser.component.html
index f051259a..6aef1efd 100644
--- a/frontend/src/app/applications/spaces/components/spaces-browser.component.html
+++ b/frontend/src/app/applications/spaces/components/spaces-browser.component.html
@@ -242,7 +242,7 @@
<span class="label-bottom-right">
@if (f.lock) {
<span (click)="openLockDialog(f)"
- tooltip="{{f.lock.owner}}"
+ tooltip="{{f.lock | fileLockFormatPipe}}"
placement="auto"
[style.font-size.px]="galleryMode.textSize"
class="badge rounded-pill bg-maroon cursor-pointer">
@@ -389,7 +389,7 @@
@case ('info') {
@if (f.lock) {
<span (click)="openLockDialog(f)"
- tooltip="{{f.lock.owner}}"
+ tooltip="{{f.lock | fileLockFormatPipe}}"
placement="auto"
class="badge rounded-pill bg-maroon cursor-pointer me-1">
<fa-icon [icon]="f.lock.isExclusive ? icons.faLock : icons.faLockOpen"></fa-icon>
diff --git a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts b/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
index e72c0197..2592eea6 100644
--- a/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
+++ b/frontend/src/app/applications/spaces/components/spaces-browser.component.ts
@@ -71,6 +71,7 @@ import { FilesCompressionDialogComponent } from '../../files/components/dialogs/
import { FilesNewDialogComponent } from '../../files/components/dialogs/files-new-dialog.component'
import { FilesTrashDialogComponent } from '../../files/components/dialogs/files-trash-dialog.component'
import { FilesTrashEmptyDialogComponent } from '../../files/components/dialogs/files-trash-empty-dialog.component'
+import { FileLockFormatPipe } from '../../files/components/utils/file-lock.utils'
import { FilePermissionsComponent } from '../../files/components/utils/file-permissions.component'
import { FileEvent } from '../../files/interfaces/file-event.interface'
import { FileModel } from '../../files/models/file.model'
@@ -107,7 +108,8 @@ import { SpaceAnchorFileDialogComponent } from './dialogs/space-anchor-file-dial
UserAvatarComponent,
UploadFilesDirective,
FilePermissionsComponent,
- TapDirective
+ TapDirective,
+ FileLockFormatPipe
],
templateUrl: 'spaces-browser.component.html'
})
diff --git a/frontend/src/app/applications/users/components/user-account.component.ts b/frontend/src/app/applications/users/components/user-account.component.ts
index a9543d5a..99eb6bb2 100644
--- a/frontend/src/app/applications/users/components/user-account.component.ts
+++ b/frontend/src/app/applications/users/components/user-account.component.ts
@@ -10,8 +10,8 @@ import { Component, inject, OnDestroy } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { FaIconComponent } from '@fortawesome/angular-fontawesome'
import { faCopy, faKey } from '@fortawesome/free-solid-svg-icons'
-import { COLLABORA_OWNER_LOCK } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.constants'
-import { ONLY_OFFICE_OWNER_LOCK } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.constants'
+import { COLLABORA_APP_LOCK } from '@sync-in-server/backend/src/applications/files/modules/collabora-online/collabora-online.constants'
+import { ONLY_OFFICE_APP_LOCK } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.constants'
import { USER_PASSWORD_MIN_LENGTH } from '@sync-in-server/backend/src/applications/users/constants/user'
import { UserAppPassword } from '@sync-in-server/backend/src/applications/users/interfaces/user-secrets.interface'
import { WEBDAV_BASE_PATH } from '@sync-in-server/backend/src/applications/webdav/constants/routes'
@@ -66,8 +66,8 @@ export class UserAccountComponent implements OnDestroy {
protected readonly passwordMinLength = USER_PASSWORD_MIN_LENGTH
protected readonly icons = { faCopy, faKey }
protected readonly editors: Record<string, keyof FileEditorProvider> = {
- [COLLABORA_OWNER_LOCK]: 'collabora',
- [ONLY_OFFICE_OWNER_LOCK]: 'onlyoffice'
+ [COLLABORA_APP_LOCK]: 'collabora',
+ [ONLY_OFFICE_APP_LOCK]: 'onlyoffice'
}
protected user: UserType
protected userAvatar: string = null