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): collabora online integration
johavendabeff62d522
diff --git a/backend/src/app.bootstrap.ts b/backend/src/app.bootstrap.tsindex da5b35f6..574cc7b6 100644--- a/backend/src/app.bootstrap.ts+++ b/backend/src/app.bootstrap.ts@@ -77,7 +77,12 @@ export async function appBootstrap(): Promise<NestFastifyApplication> {app.useStaticAssets({ root: STATIC_PATH, prefixAvoidTrailingSlash: true })/* SECURITY */- await app.register(fastifyHelmet, { contentSecurityPolicy: CONTENT_SECURITY_POLICY(configuration.applications.files.onlyoffice.externalServer) })+ await app.register(fastifyHelmet, {+ contentSecurityPolicy: CONTENT_SECURITY_POLICY(+ configuration.applications.files.onlyoffice.externalServer,+ configuration.applications.files.collabora.externalServer+ )+ })/* COOKIES */// we use csrf secret to unsign csrf cookiediff --git a/backend/src/app.constants.ts b/backend/src/app.constants.tsindex 9821412b..53640026 100644--- a/backend/src/app.constants.ts+++ b/backend/src/app.constants.ts@@ -8,10 +8,10 @@ import { loadVersion } from './app.functions'export const VERSION = loadVersion()export const USER_AGENT = `sync-in-server/${VERSION}`-export const CONTENT_SECURITY_POLICY = (onlyOfficeServer: string) => ({+export const CONTENT_SECURITY_POLICY = (onlyOfficeServer: string, collaboraServer: string) => ({useDefaults: false,directives: {- defaultSrc: ["'self'", onlyOfficeServer || ''],+ defaultSrc: ["'self'", onlyOfficeServer || '', collaboraServer || ''],scriptSrc: ["'self'", "'unsafe-inline'", onlyOfficeServer || ''],styleSrc: ["'self'", "'unsafe-inline'"],imgSrc: ["'self'", 'data:'],diff --git a/backend/src/applications/files/constants/cache.ts b/backend/src/applications/files/constants/cache.tsindex 8cefd4d2..2308b9b9 100644--- a/backend/src/applications/files/constants/cache.ts+++ b/backend/src/applications/files/constants/cache.ts@@ -12,4 +12,3 @@ export const CACHE_LOCK_PREFIX = 'flock' as constexport const CACHE_LOCK_DEFAULT_TTL = 28800 as const // 8 hours in secondsexport const CACHE_LOCK_FILE_TTL = 3600 as const// cache only office = `office|${fileId}` => docKey-export const CACHE_ONLY_OFFICE = 'foffice' as constdiff --git a/backend/src/applications/files/constants/files.ts b/backend/src/applications/files/constants/files.tsindex 4d0e8ea5..15eb29fa 100644--- a/backend/src/applications/files/constants/files.ts+++ b/backend/src/applications/files/constants/files.ts@@ -4,6 +4,7 @@* See the LICENSE file for licensing details*/+export const DEFAULT_CHECKSUM_ALGORITHM = 'sha512-256'export const DEFAULT_HIGH_WATER_MARK = 1024 * 1024export const DEFAULT_MIME_TYPE = 'application/octet-stream'export const EXTRA_MIMES_TYPE = new Map([diff --git a/backend/src/applications/files/constants/operations.ts b/backend/src/applications/files/constants/operations.tsindex 2657b31d..8ba0d8bc 100644--- a/backend/src/applications/files/constants/operations.ts+++ b/backend/src/applications/files/constants/operations.ts@@ -25,3 +25,5 @@ export enum FILE_MODE {VIEW = 'view',EDIT = 'edit'}++export const FORCE_AS_FILE_OWNER = 'forceAsFileOwner' as constdiff --git a/backend/src/applications/files/constants/routes.ts b/backend/src/applications/files/constants/routes.tsindex 549f8f02..a29ccd00 100644--- a/backend/src/applications/files/constants/routes.ts+++ b/backend/src/applications/files/constants/routes.ts@@ -9,17 +9,13 @@ import { FILE_OPERATION } from './operations'export const FILES_ROUTE = {BASE: SPACES_ROUTE.BASE,+ SETTINGS: 'settings',OPERATION: 'operation',TASK_OPERATION: 'task/operation',TASKS: 'tasks',TASKS_DOWNLOAD: 'download',RECENTS: 'recents',- SEARCH: 'search',- ONLY_OFFICE: 'onlyoffice',- ONLY_OFFICE_SETTINGS: 'settings',- ONLY_OFFICE_DOCUMENT: 'document',- ONLY_OFFICE_CALLBACK: 'callback',- ONLY_OFFICE_STATUS: 'status'+ SEARCH: 'search'} as constexport const API_FILES_OPERATION = `${FILES_ROUTE.BASE}/${FILES_ROUTE.OPERATION}`@@ -32,10 +28,6 @@ export const API_FILES_TASK_OPERATION_COMPRESS = `${API_FILES_TASK_OPERATION}/${export const API_FILES_TASK_OPERATION_DECOMPRESS = `${API_FILES_TASK_OPERATION}/${FILE_OPERATION.DECOMPRESS}`export const API_FILES_TASKS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.TASKS}`export const API_FILES_TASKS_DOWNLOAD = `${FILES_ROUTE.BASE}/${FILES_ROUTE.TASKS}/${FILES_ROUTE.TASKS_DOWNLOAD}`+export const API_FILES_SETTINGS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.SETTINGS}`export const API_FILES_RECENTS = `${FILES_ROUTE.BASE}/${FILES_ROUTE.RECENTS}`export const API_FILES_SEARCH = `${FILES_ROUTE.BASE}/${FILES_ROUTE.SEARCH}`-export const API_FILES_ONLY_OFFICE = `${FILES_ROUTE.BASE}/${FILES_ROUTE.ONLY_OFFICE}`-export const API_FILES_ONLY_OFFICE_SETTINGS = `${API_FILES_ONLY_OFFICE}/${FILES_ROUTE.ONLY_OFFICE_SETTINGS}`-export const API_FILES_ONLY_OFFICE_DOCUMENT = `${API_FILES_ONLY_OFFICE}/${FILES_ROUTE.ONLY_OFFICE_DOCUMENT}`-export const API_FILES_ONLY_OFFICE_CALLBACK = `${API_FILES_ONLY_OFFICE}/${FILES_ROUTE.ONLY_OFFICE_CALLBACK}`-export const API_FILES_ONLY_OFFICE_STATUS = `${API_FILES_ONLY_OFFICE}/${FILES_ROUTE.ONLY_OFFICE_STATUS}`diff --git a/backend/src/applications/files/files-only-office.controller.ts b/backend/src/applications/files/files-only-office.controller.tsdeleted file mode 100644index 77f79b37..00000000--- a/backend/src/applications/files/files-only-office.controller.ts+++ /dev/null@@ -1,58 +0,0 @@-/*- * 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 { Body, Controller, Get, HttpCode, HttpStatus, Post, Query, Request, Res, StreamableFile, UseInterceptors } from '@nestjs/common'-import { FastifyReply } from 'fastify'-import { ContextInterceptor } from '../../infrastructure/context/interceptors/context.interceptor'-import { SkipSpaceGuard } from '../spaces/decorators/space-skip-guard.decorator'-import { GetSpace } from '../spaces/decorators/space.decorator'-import { FastifySpaceRequest } from '../spaces/interfaces/space-request.interface'-import { SpaceEnv } from '../spaces/models/space-env.model'-import { GetUser } from '../users/decorators/user.decorator'-import { UserModel } from '../users/models/user.model'-import { FILE_MODE } from './constants/operations'-import { API_FILES_ONLY_OFFICE, FILES_ROUTE } from './constants/routes'-import { OnlyOfficeEnvironment } from './decorators/only-office-environment.decorator'-import { OnlyOfficeReqConfig } from './interfaces/only-office-config.interface'-import { FilesMethods } from './services/files-methods.service'-import { FilesOnlyOfficeManager } from './services/files-only-office-manager.service'--@Controller(API_FILES_ONLY_OFFICE)-@OnlyOfficeEnvironment()-export class FilesOnlyOfficeController {- constructor(- private readonly filesOnlyOfficeManager: FilesOnlyOfficeManager,- private readonly filesMethods: FilesMethods- ) {}-- @Get(`${FILES_ROUTE.ONLY_OFFICE_SETTINGS}/*`)- @UseInterceptors(ContextInterceptor)- onlyOfficeSettings(- @GetUser() user: UserModel,- @GetSpace() space: SpaceEnv,- @Query('mode') mode: FILE_MODE = FILE_MODE.VIEW,- @Request() req: FastifySpaceRequest- ): Promise<OnlyOfficeReqConfig> {- return this.filesOnlyOfficeManager.getSettings(user, space, mode, req)- }-- @Get(`${FILES_ROUTE.ONLY_OFFICE_DOCUMENT}/*`)- onlyOfficeDocument(@Request() req: FastifySpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<StreamableFile> {- return this.filesMethods.headOrGet(req, res)- }-- @Post(`${FILES_ROUTE.ONLY_OFFICE_CALLBACK}/*`)- @HttpCode(HttpStatus.OK)- onlyOfficeCallBack(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body('token') token: string, @Query('fid') fileId: string) {- return this.filesOnlyOfficeManager.callBack(user, space, token, fileId)- }-- @Get(FILES_ROUTE.ONLY_OFFICE_STATUS)- @SkipSpaceGuard()- onlyOfficeStatus(): { enabled: boolean } {- return this.filesOnlyOfficeManager.getStatus()- }-}diff --git a/backend/src/applications/files/files.config.ts b/backend/src/applications/files/files.config.tsindex e4deaf12..a7ab6280 100644--- a/backend/src/applications/files/files.config.ts+++ b/backend/src/applications/files/files.config.ts@@ -5,24 +5,9 @@*/import { Type } from 'class-transformer'-import { IsBoolean, IsInt, IsNotEmpty, IsNotEmptyObject, IsOptional, IsString, ValidateIf, ValidateNested } from 'class-validator'--export class FilesOnlyOfficeConfig {- @IsBoolean()- enabled = false-- @IsOptional()- @IsString()- externalServer: string = null-- @ValidateIf((o: FilesOnlyOfficeConfig) => o.enabled)- @IsString()- @IsNotEmpty()- secret: string-- @IsBoolean()- verifySSL: boolean = false-}+import { IsBoolean, IsInt, IsNotEmpty, IsNotEmptyObject, IsString, ValidateNested } from 'class-validator'+import { CollaboraOnlineConfig } from './modules/collabora-online/collabora-online.config'+import { OnlyOfficeConfig } from './modules/only-office/only-office.config'export class FilesConfig {@IsNotEmpty()@@ -52,6 +37,11 @@ export class FilesConfig {@IsNotEmptyObject()@ValidateNested()- @Type(() => FilesOnlyOfficeConfig)- onlyoffice: FilesOnlyOfficeConfig = new FilesOnlyOfficeConfig()+ @Type(() => OnlyOfficeConfig)+ onlyoffice: OnlyOfficeConfig = new OnlyOfficeConfig()++ @IsNotEmptyObject()+ @ValidateNested()+ @Type(() => CollaboraOnlineConfig)+ collabora: CollaboraOnlineConfig = new CollaboraOnlineConfig()}diff --git a/backend/src/applications/files/files.controller.ts b/backend/src/applications/files/files.controller.tsindex 8d2ce7cd..5b4c33d9 100644--- a/backend/src/applications/files/files.controller.ts+++ b/backend/src/applications/files/files.controller.ts@@ -39,10 +39,11 @@ import { FastifySpaceRequest } from '../spaces/interfaces/space-request.interfacimport { SpaceEnv } from '../spaces/models/space-env.model'import { GetUser } from '../users/decorators/user.decorator'import { UserModel } from '../users/models/user.model'-import { FILE_OPERATION } from './constants/operations'+import { FILE_OPERATION, FORCE_AS_FILE_OWNER } 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 { FileSettings } from './interfaces/file-settings.interface'import { FileTask } from './models/file-task'import { FileContent } from './schemas/file-content.interface'import { FileRecent } from './schemas/file-recent.interface'@@ -145,9 +146,9 @@ export class FilesController {async unlock(@GetUser() user: UserModel,@GetSpace() space: SpaceEnv,- @Query('forceAsOwner', new ParseBoolPipe({ optional: true })) forceAsOwner?: boolean+ @Query(FORCE_AS_FILE_OWNER, new ParseBoolPipe({ optional: true })) forceAsFileOwner?: boolean): Promise<void> {- return this.filesMethods.unlock(user, space, forceAsOwner)+ return this.filesMethods.unlock(user, space, forceAsFileOwner)}@Unlock(`${FILES_ROUTE.OPERATION}/${FILE_OPERATION.UNLOCK_REQUEST}/*`)@@ -198,6 +199,14 @@ export class FilesController {return this.filesTasksManager.createTask(FILE_OPERATION.DELETE, user, space, null, this.filesMethods.delete.name)}+ // SETTINGS++ @Get(FILES_ROUTE.SETTINGS)+ @SkipSpaceGuard()+ filesSettings(): FileSettings {+ return this.filesMethods.fileSettings()+ }+// RECENT FILES@Get(FILES_ROUTE.RECENTS)diff --git a/backend/src/applications/files/files.module.ts b/backend/src/applications/files/files.module.tsindex 005af937..47ef8306 100644--- a/backend/src/applications/files/files.module.ts+++ b/backend/src/applications/files/files.module.ts@@ -5,18 +5,17 @@*/import { Module } from '@nestjs/common'+import { configuration } from '../../configuration/config.environment'import { FilesIndexerMySQL } from './adapters/files-indexer-mysql.service'-import { FilesOnlyOfficeController } from './files-only-office.controller'import { FilesTasksController } from './files-tasks.controller'import { FilesController } from './files.controller'-import { FilesOnlyOfficeGuard } from './guards/files-only-office.guard'-import { FilesOnlyOfficeStrategy } from './guards/files-only-office.strategy'import { FilesIndexer } from './models/files-indexer'+import { CollaboraOnlineModule } from './modules/collabora-online/collabora-online.module'+import { OnlyOfficeModule } from './modules/only-office/only-office.module'import { FilesContentManager } from './services/files-content-manager.service'import { FilesLockManager } from './services/files-lock-manager.service'import { FilesManager } from './services/files-manager.service'import { FilesMethods } from './services/files-methods.service'-import { FilesOnlyOfficeManager } from './services/files-only-office-manager.service'import { FilesParser } from './services/files-parser.service'import { FilesQueries } from './services/files-queries.service'import { FilesRecents } from './services/files-recents.service'@@ -25,7 +24,11 @@ import { FilesSearchManager } from './services/files-search-manager.service'import { FilesTasksManager } from './services/files-tasks-manager.service'@Module({- controllers: [FilesController, FilesTasksController, FilesOnlyOfficeController],+ imports: [+ ...(configuration.applications.files.onlyoffice.enabled ? [OnlyOfficeModule] : []),+ ...(configuration.applications.files.collabora.enabled ? [CollaboraOnlineModule] : [])+ ],+ controllers: [FilesController, FilesTasksController],providers: [FilesMethods,FilesManager,@@ -34,9 +37,6 @@ import { FilesTasksManager } from './services/files-tasks-manager.service'FilesTasksManager,FilesScheduler,FilesRecents,- FilesOnlyOfficeManager,- FilesOnlyOfficeGuard,- FilesOnlyOfficeStrategy,FilesParser,FilesContentManager,{ provide: FilesIndexer, useClass: FilesIndexerMySQL },diff --git a/backend/src/applications/files/guards/files-only-office.guard.ts b/backend/src/applications/files/guards/files-only-office.guard.tsdeleted file mode 100644index 5fec41ba..00000000--- a/backend/src/applications/files/guards/files-only-office.guard.ts+++ /dev/null@@ -1,39 +0,0 @@-/*- * 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 { ExecutionContext, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'-import { AuthGuard, IAuthGuard } from '@nestjs/passport'-import { FastifyRequest } from 'fastify'-import { Observable } from 'rxjs'-import { configuration } from '../../../configuration/config.environment'-import { API_FILES_ONLY_OFFICE_STATUS } from '../constants/routes'--@Injectable()-export class FilesOnlyOfficeGuard extends AuthGuard('filesOnlyOfficeToken') implements IAuthGuard {- private readonly logger = new Logger(FilesOnlyOfficeGuard.name)-- canActivate(ctx: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {- const req: FastifyRequest = ctx.switchToHttp().getRequest()- if (req.originalUrl === API_FILES_ONLY_OFFICE_STATUS) {- // Skip token validation for the status endpoint- return true- }- if (!configuration.applications.files.onlyoffice.enabled) {- this.logger.warn(`${this.canActivate.name} - feature not enabled`)- throw new HttpException('Feature not enabled', HttpStatus.BAD_REQUEST)- }- return super.canActivate(ctx)- }-- handleRequest<TUser = any>(err: any, user: any, info: Error, ctx: ExecutionContext, status?: any): TUser {- const req = this.getRequest(ctx)- req.raw.user = user?.login || 'unauthorized'- if (info) {- this.logger.warn(`<${req.raw.user}> <${req.ip}> ${info}`)- }- return super.handleRequest(err, user, info, ctx, status)- }-}diff --git a/backend/src/applications/files/interfaces/file-settings.interface.ts b/backend/src/applications/files/interfaces/file-settings.interface.tsnew file mode 100644index 00000000..d4cc2c23--- /dev/null+++ b/backend/src/applications/files/interfaces/file-settings.interface.ts@@ -0,0 +1,9 @@+/*+ * 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+ */++export interface FileSettings {+ editor: { collaboraOnline: boolean; onlyOffice: boolean }+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online-environment.decorator.ts b/backend/src/applications/files/modules/collabora-online/collabora-online-environment.decorator.tsnew file mode 100644index 00000000..dde035e5--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online-environment.decorator.ts@@ -0,0 +1,15 @@+/*+ * 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 { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'+import { SpaceGuard } from '../../../spaces/guards/space.guard'+import { COLLABORA_CONTEXT } from './collabora-online.constants'+import { CollaboraOnlineGuard } from './collabora-online.guard'++export const CollaboraOnlineContext = () => SetMetadata(COLLABORA_CONTEXT, true)+export const CollaboraOnlineEnvironment = () => {+ return applyDecorators(CollaboraOnlineContext(), UseGuards(CollaboraOnlineGuard, SpaceGuard))+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.spec.ts b/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.spec.tsnew file mode 100644index 00000000..940ff341--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.spec.ts@@ -0,0 +1,27 @@+/*+ * 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 { JwtService } from '@nestjs/jwt'+import { Test, TestingModule } from '@nestjs/testing'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { FilesLockManager } from '../../services/files-lock-manager.service'+import { CollaboraOnlineManager } from './collabora-online-manager.service'++describe(CollaboraOnlineManager.name, () => {+ let service: CollaboraOnlineManager++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [CollaboraOnlineManager, ContextManager, { provide: JwtService, useValue: {} }, { provide: FilesLockManager, useValue: {} }]+ }).compile()++ service = module.get<CollaboraOnlineManager>(CollaboraOnlineManager)+ })++ it('should be defined', () => {+ expect(service).toBeDefined()+ })+})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.tsnew file mode 100644index 00000000..47d57247--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online-manager.service.ts@@ -0,0 +1,276 @@+/*+ * 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 { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'+import { JwtService } from '@nestjs/jwt'+import { FastifyReply } from 'fastify'+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { convertHumanTimeToSeconds } from '../../../../common/functions'+import { configuration } from '../../../../configuration/config.environment'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { SPACE_OPERATION } from '../../../spaces/constants/spaces'+import type { SpaceEnv } from '../../../spaces/models/space-env.model'+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 { FilesLockManager } from '../../services/files-lock-manager.service'+import {+ copyFileContent,+ fileName,+ fileSize,+ genEtag,+ genUniqHashFromFileDBProps,+ isPathExists,+ isPathIsDir,+ removeFiles,+ uniqueFilePathFromDir,+ writeFromStream+} from '../../utils/files'+import {+ COLLABORA_HEADERS,+ COLLABORA_INTERNAL_URI,+ COLLABORA_LOCK_ACTION,+ COLLABORA_ONLINE_SUPPORTED_EXTENSIONS,+ COLLABORA_OWNER_LOCK,+ COLLABORA_TOKEN_QUERY_PARAM_NAME,+ COLLABORA_URI,+ COLLABORA_WOPI_SRC_QUERY_PARAM_NAME+} from './collabora-online.constants'+import { CollaboraOnlineReqDto, CollaboraSaveDocumentDto } from './collabora-online.dtos'+import { CollaboraOnlineCheckFileInfo, FastifyCollaboraOnlineSpaceRequest, JwtCollaboraOnlinePayload } from './collabora-online.interface'+import { API_COLLABORA_ONLINE_FILES } from './collabora-online.routes'++@Injectable()+export class CollaboraOnlineManager {+ private logger = new Logger(CollaboraOnlineManager.name)+ private readonly externalCollaboraOnlineServer = configuration.applications.files.collabora.externalServer || null+ private readonly expiration = convertHumanTimeToSeconds(configuration.auth.token.refresh.expiration)++ constructor(+ private readonly contextManager: ContextManager,+ private readonly jwt: JwtService,+ private readonly filesLockManager: FilesLockManager+ ) {}++ async getSettings(user: UserModel, space: SpaceEnv, mode: FILE_MODE): Promise<CollaboraOnlineReqDto> {+ await this.checkSpace(space)+ const fileExtension = path.extname(space.realPath).slice(1)+ if (!COLLABORA_ONLINE_SUPPORTED_EXTENSIONS.has(fileExtension)) {+ throw new HttpException('Document not supported', HttpStatus.BAD_REQUEST)+ }+ if (mode === FILE_MODE.EDIT && !haveSpaceEnvPermissions(space, SPACE_OPERATION.MODIFY)) {+ mode = 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)+ }+ }+ const dbFileHash = genUniqHashFromFileDBProps(space.dbFile)+ const authToken: string = await this.genAuthToken(user, space, dbFileHash)+ return { documentServerUrl: this.getDocumentUrl(dbFileHash, authToken), mode: mode }+ }++ async checkFileInfo(req: FastifyCollaboraOnlineSpaceRequest): Promise<CollaboraOnlineCheckFileInfo> {+ const fStats = await fs.stat(req.space.realPath)+ return {+ BaseFileName: fileName(req.space.realPath),+ Version: genEtag(null, req.space.realPath, false),+ OwnerId: `${req.space.dbFile.ownerId || req.user.id}`,+ Size: fStats.size,+ LastModifiedTime: fStats.mtime.toISOString(),+ UserId: `${req.user.id}`,+ UserFriendlyName: `${req.user.fullName} (${req.user.email})`,+ ReadOnly: false,+ UserExtraInfo: { avatar: await getAvatarBase64(req.user.login) },+ UserCanNotWriteRelative: true,+ UserCanWrite: haveSpaceEnvPermissions(req.space, SPACE_OPERATION.MODIFY),+ UserCanRename: false,+ SupportsUpdate: true,+ SupportsRename: false,+ SupportsExport: true,+ SupportsCoauth: true,+ SupportsLocks: true,+ SupportsGetLock: true+ } satisfies CollaboraOnlineCheckFileInfo+ }++ async saveDocument(req: FastifyCollaboraOnlineSpaceRequest): Promise<CollaboraSaveDocumentDto> {+ await this.checkSpace(req.space)+ await this.checkTimeStampFromHeaders(req)+ const tmpFilePath = await uniqueFilePathFromDir(path.join(os.tmpdir(), fileName(req.space.realPath)))+ try {+ await writeFromStream(tmpFilePath, req.raw)+ } catch (e) {+ throw new Error(`unable to save document : ${e.message}`)+ }+ // try to verify the downloaded size+ const contentLength = parseInt(req.headers['content-length'], 10)+ if (!isNaN(contentLength) && contentLength !== 0) {+ const tmpFileSize = await fileSize(tmpFilePath)+ if (tmpFileSize !== contentLength) {+ this.logger.error(`${this.saveDocument.name} - document size differs (${tmpFileSize} != ${contentLength})`)+ throw new HttpException('Size Mismatch', HttpStatus.BAD_REQUEST)+ }+ } else if (contentLength === 0) {+ this.logger.warn(`${this.saveDocument.name} - content length is 0 : ${req.space.url}`)+ }+ // copy contents to avoid inode changes (dbFileHash in some cases)+ try {+ // todo: versioning+ await copyFileContent(tmpFilePath, req.space.realPath)+ await removeFiles(tmpFilePath)+ const fStats = await fs.stat(req.space.realPath)+ return { LastModifiedTime: fStats.mtime.toISOString() } satisfies CollaboraSaveDocumentDto+ } catch (e) {+ this.logger.error(`${this.saveDocument.name} - unable to save document: ${e}`)+ throw new HttpException('Unable to save document', HttpStatus.INTERNAL_SERVER_ERROR)+ }+ }++ async manageLock(req: FastifyCollaboraOnlineSpaceRequest, res: FastifyReply) {+ const lockAction = req.headers[COLLABORA_HEADERS.Action] as COLLABORA_LOCK_ACTION+ switch (lockAction) {+ case COLLABORA_LOCK_ACTION.LOCK: {+ const reqLockToken = this.lockTokenFromHeaders(req)+ const currentLock = await this.filesLockManager.isLockedWithToken(reqLockToken, req.space.dbFile.path)+ if (currentLock) {+ await this.filesLockManager.refreshLockTimeout(currentLock, this.expiration)+ break+ }+ const [ok, fileLock] = await this.filesLockManager.create(+ req.user,+ req.space.dbFile,+ 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,+ this.expiration+ )+ if (!ok) {+ this.lockConflict(res, fileLock.davLock.locktoken)+ return+ }+ break+ }+ case COLLABORA_LOCK_ACTION.UNLOCK: {+ const reqLockToken = this.lockTokenFromHeaders(req)+ const currentLock = await this.filesLockManager.isLockedWithToken(reqLockToken, req.space.dbFile.path)+ if (currentLock) {+ await this.filesLockManager.removeLock(currentLock.key)+ } else {+ throw new HttpException('Lock not found', HttpStatus.CONFLICT)+ }+ break+ }+ 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)+ }+ break+ }+ case COLLABORA_LOCK_ACTION.REFRESH_LOCK: {+ const reqLockToken = this.lockTokenFromHeaders(req)+ const currentLock = await this.filesLockManager.isLockedWithToken(reqLockToken, req.space.dbFile.path)+ if (currentLock) {+ await this.filesLockManager.refreshLockTimeout(currentLock, this.expiration)+ } else {+ throw new HttpException('Lock not found', HttpStatus.CONFLICT)+ }+ break+ }+ default:+ this.logger.warn(`${this.manageLock.name} - Unknown lock action: ${lockAction}`)+ throw new HttpException('Unknown lock action', HttpStatus.BAD_REQUEST)+ }+ }++ private getDocumentUrl(dbFileHash: string, token: string): string {+ const collaboraBase = this.externalCollaboraOnlineServer || `${this.contextManager.headerOriginUrl()}${COLLABORA_INTERNAL_URI}`+ // Example:+ // - external: https://collabora.domain.com+ // - internal (via nginx proxy): https://domain.com/collabora-online++ const editorUrl = new URL(COLLABORA_URI, collaboraBase)+ // → /browser/dist/cool.html++ const wopiSrcUrl = new URL(`${API_COLLABORA_ONLINE_FILES}/${dbFileHash}`, this.contextManager.headerOriginUrl())+ // → https://domain.com/wopi/files/888++ editorUrl.searchParams.set(COLLABORA_WOPI_SRC_QUERY_PARAM_NAME, wopiSrcUrl.toString())+ editorUrl.searchParams.set(COLLABORA_TOKEN_QUERY_PARAM_NAME, token)++ return editorUrl.toString()+ }++ private genAuthToken(user: UserModel, space: SpaceEnv, dbFileHash: string): Promise<string> {+ // use refresh expiration to allow long sessions+ return this.jwt.signAsync(+ {+ identity: {+ id: user.id,+ login: user.login,+ email: user.email,+ fullName: user.fullName,+ language: user.language,+ role: user.role,+ applications: user.applications,+ spaceUrl: space.url,+ dbFileHash: dbFileHash+ } satisfies JwtCollaboraOnlinePayload+ },+ {+ secret: configuration.auth.token.access.secret,+ expiresIn: this.expiration+ }+ )+ }++ private lockTokenFromHeaders(req: FastifyCollaboraOnlineSpaceRequest): string {+ const lockToken = req.headers[COLLABORA_HEADERS.LockToken] as string+ if (!lockToken) {+ throw new HttpException('Lock token is required', HttpStatus.CONFLICT)+ }+ return lockToken+ }++ private lockConflict(res: FastifyReply, currentLockToken: string) {+ res.header(COLLABORA_HEADERS.LockToken, currentLockToken)+ throw new HttpException('The file is locked', HttpStatus.CONFLICT)+ }++ private async checkTimeStampFromHeaders(req: FastifyCollaboraOnlineSpaceRequest) {+ const timestamp = req.headers[COLLABORA_HEADERS.Timestamp] as string+ if (!timestamp) {+ return+ }+ const fStats = await fs.stat(req.space.realPath)+ if (fStats.mtime.toISOString() !== timestamp) {+ throw new HttpException({ LOOLStatusCode: 1010 }, HttpStatus.CONFLICT)+ }+ }++ private async checkSpace(space: SpaceEnv) {+ if (!(await isPathExists(space.realPath))) {+ throw new HttpException('Document not found', HttpStatus.NOT_FOUND)+ }+ if (await isPathIsDir(space.realPath)) {+ throw new HttpException('Document must be a file', HttpStatus.BAD_REQUEST)+ }+ }+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.config.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.config.tsnew file mode 100644index 00000000..bab3fc50--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.config.ts@@ -0,0 +1,16 @@+/*+ * 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 { IsBoolean, IsOptional, IsString } from 'class-validator'++export class CollaboraOnlineConfig {+ @IsBoolean()+ enabled = false++ @IsOptional()+ @IsString()+ externalServer: string = null+}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.tsnew file mode 100644index 00000000..dd950e10--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.constants.ts@@ -0,0 +1,74 @@+/*+ * 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+ */++export const COLLABORA_INTERNAL_URI = '/collabora-online' // used by nginx as a proxy+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 Online' as const++export const COLLABORA_HEADERS = {+ Action: 'x-wopi-override',+ LockToken: 'x-wopi-lock',+ Timestamp: 'x-cool-wopi-timestamp'+} as const++export enum COLLABORA_LOCK_ACTION {+ LOCK = 'LOCK',+ UNLOCK = 'UNLOCK',+ GET_LOCK = 'GET_LOCK',+ REFRESH_LOCK = 'REFRESH_LOCK'+}++export const COLLABORA_ONLINE_SUPPORTED_EXTENSIONS = new Set<string>([+ // ─────────────+ // WORD (Writer)+ // ─────────────+ 'doc',+ 'docx',+ 'docm',+ 'dot',+ 'dotx',+ 'dotm',+ 'odt',+ 'ott',+ 'rtf',+ 'txt',+ 'html',+ 'htm',+ 'fodt',++ // ─────────────+ // CELL (Calc)+ // ─────────────+ 'xls',+ 'xlsx',+ 'xlsm',+ 'xlt',+ 'xltx',+ 'ods',+ 'ots',+ 'csv',+ 'fods',++ // ─────────────+ // SLIDE (Impress)+ // ─────────────+ 'ppt',+ 'pptx',+ 'pptm',+ 'pps',+ 'ppsx',+ 'odp',+ 'otp',+ 'fodp',++ // ─────────────+ // PDF (view / annotations)+ // ─────────────+ 'pdf'+])diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.controller.spec.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.controller.spec.tsnew file mode 100644index 00000000..de6b0bc9--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.controller.spec.ts@@ -0,0 +1,36 @@+/*+ * 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 { Test, TestingModule } from '@nestjs/testing'+import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { SpacesManager } from '../../../spaces/services/spaces-manager.service'+import { FilesMethods } from '../../services/files-methods.service'+import { CollaboraOnlineManager } from './collabora-online-manager.service'+import { CollaboraOnlineController } from './collabora-online.controller'++describe(CollaboraOnlineController.name, () => {+ let controller: CollaboraOnlineController++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ controllers: [CollaboraOnlineController],+ providers: [+ ContextManager,+ ContextInterceptor,+ { provide: CollaboraOnlineManager, useValue: {} },+ { provide: FilesMethods, useValue: {} },+ { provide: SpacesManager, useValue: {} }+ ]+ }).compile()++ controller = module.get<CollaboraOnlineController>(CollaboraOnlineController)+ })++ it('should be defined', () => {+ expect(controller).toBeDefined()+ })+})diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.controller.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.controller.tsnew file mode 100644index 00000000..169228ad--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.controller.ts@@ -0,0 +1,61 @@+/*+ * 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 { Controller, Get, HttpCode, HttpStatus, Post, Query, Request, Res, StreamableFile, UseInterceptors } from '@nestjs/common'+import { FastifyReply } from 'fastify'+import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'+import { SPACE_OPERATION } from '../../../spaces/constants/spaces'+import { OverrideSpacePermission } from '../../../spaces/decorators/space-override-permission.decorator'+import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'+import { FILE_MODE } from '../../constants/operations'+import { FilesMethods } from '../../services/files-methods.service'+import { CollaboraOnlineEnvironment } from './collabora-online-environment.decorator'+import { CollaboraOnlineManager } from './collabora-online-manager.service'+import { CollaboraOnlineReqDto, CollaboraSaveDocumentDto } from './collabora-online.dtos'+import type { CollaboraOnlineCheckFileInfo } from './collabora-online.interface'+import { COLLABORA_ONLINE_ROUTE } from './collabora-online.routes'++@Controller(COLLABORA_ONLINE_ROUTE.BASE)+@CollaboraOnlineEnvironment()+export class CollaboraOnlineController {+ constructor(+ private readonly filesMethods: FilesMethods,+ private readonly filesCollaboraOnlineService: CollaboraOnlineManager+ ) {}++ @Get(`${COLLABORA_ONLINE_ROUTE.SETTINGS}/*`)+ @UseInterceptors(ContextInterceptor)+ collaboraOnlineSettings(@Request() req: FastifySpaceRequest, @Query('mode') mode: FILE_MODE = FILE_MODE.VIEW): Promise<CollaboraOnlineReqDto> {+ return this.filesCollaboraOnlineService.getSettings(req.user, req.space, mode)+ }++ @Get(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash/${COLLABORA_ONLINE_ROUTE.CONTENTS}`)+ collaboraOnlineGetDocumentContent(+ @Request() req: FastifySpaceRequest,+ @Res({ passthrough: true }) res: FastifyReply+ ): Promise<StreamableFile | CollaboraOnlineCheckFileInfo> {+ return this.filesMethods.headOrGet(req, res)+ }++ @Get(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash`)+ collaboraOnlineGetDocumentInfo(@Request() req: FastifySpaceRequest): Promise<StreamableFile | CollaboraOnlineCheckFileInfo> {+ return this.filesCollaboraOnlineService.checkFileInfo(req)+ }++ @Post(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash/${COLLABORA_ONLINE_ROUTE.CONTENTS}`)+ @OverrideSpacePermission(SPACE_OPERATION.MODIFY)+ @HttpCode(HttpStatus.OK)+ collaboraOnlineSaveDocument(@Request() req: FastifySpaceRequest): Promise<CollaboraSaveDocumentDto> {+ return this.filesCollaboraOnlineService.saveDocument(req)+ }++ @Post(`${COLLABORA_ONLINE_ROUTE.FILES}/:dbFileHash`)+ @OverrideSpacePermission(SPACE_OPERATION.MODIFY)+ @HttpCode(HttpStatus.OK)+ collaboraOnlineManageLockOnDocument(@Request() req: FastifySpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<void> {+ return this.filesCollaboraOnlineService.manageLock(req, res)+ }+}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.tsnew file mode 100644index 00000000..05741a48--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.dtos.ts@@ -0,0 +1,16 @@+/*+ * 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 type { FILE_MODE } from '../../constants/operations'++export interface CollaboraOnlineReqDto {+ documentServerUrl: string+ mode: FILE_MODE+}++export interface CollaboraSaveDocumentDto {+ LastModifiedTime: string+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.guard.spec.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.guard.spec.tsnew file mode 100644index 00000000..1e1f1fdb--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.guard.spec.ts@@ -0,0 +1,75 @@+/*+ * 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 { createMock, DeepMocked } from '@golevelup/ts-jest'+import { ExecutionContext } from '@nestjs/common'+import { JwtModule, JwtService } from '@nestjs/jwt'+import { Test, TestingModule } from '@nestjs/testing'+import { PinoLogger } from 'nestjs-pino'+import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { configuration } from '../../../../configuration/config.environment'+import { COLLABORA_TOKEN_QUERY_PARAM_NAME } from './collabora-online.constants'+import { CollaboraOnlineGuard } from './collabora-online.guard'+import { API_COLLABORA_ONLINE_FILES } from './collabora-online.routes'+import { CollaboraOnlineStrategy } from './collabora-online.strategy'++describe(CollaboraOnlineGuard.name, () => {+ let jwtService: JwtService+ let filesCollaboraGuard: CollaboraOnlineGuard+ let context: DeepMocked<ExecutionContext>+ let accessToken: string++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ imports: [JwtModule.register({ global: true })],+ providers: [+ CollaboraOnlineGuard,+ CollaboraOnlineStrategy,+ {+ provide: PinoLogger,+ useValue: {+ assign: () => undefined+ }+ }+ ]+ }).compile()++ jwtService = module.get<JwtService>(JwtService)+ filesCollaboraGuard = module.get<CollaboraOnlineGuard>(CollaboraOnlineGuard)+ context = createMock<ExecutionContext>()+ accessToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {+ secret: configuration.auth.token.access.secret,+ expiresIn: 30+ })+ })++ it('should be defined', () => {+ expect(jwtService).toBeDefined()+ expect(filesCollaboraGuard).toBeDefined()+ expect(accessToken).toBeDefined()+ })++ it('should not pass without a valid token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ url: `${API_COLLABORA_ONLINE_FILES}`,+ raw: { user: '' }+ })+ await expect(filesCollaboraGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })++ it('should pass with a (un)valid token', async () => {+ context.switchToHttp().getRequest.mockReturnValue({+ url: `${API_COLLABORA_ONLINE_FILES}?${COLLABORA_TOKEN_QUERY_PARAM_NAME}=${accessToken}`,+ raw: { user: '' }+ })+ expect(await filesCollaboraGuard.canActivate(context)).toBe(true)+ context.switchToHttp().getRequest.mockReturnValue({+ url: `${API_COLLABORA_ONLINE_FILES}?${COLLABORA_TOKEN_QUERY_PARAM_NAME}=unvalidToken`,+ raw: { user: '' }+ })+ await expect(filesCollaboraGuard.canActivate(context)).rejects.toThrow('Unauthorized')+ })+})diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.guard.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.guard.tsnew file mode 100644index 00000000..d1c5b38f--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.guard.ts@@ -0,0 +1,22 @@+/*+ * 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 { ExecutionContext, Injectable, Logger } from '@nestjs/common'+import { AuthGuard, IAuthGuard } from '@nestjs/passport'++@Injectable()+export class CollaboraOnlineGuard extends AuthGuard('filesCollaboraOnlineToken') implements IAuthGuard {+ private readonly logger = new Logger(CollaboraOnlineGuard.name)++ handleRequest<TUser = any>(err: any, user: any, info: Error, ctx: ExecutionContext, status?: any): TUser {+ const req = this.getRequest(ctx)+ req.raw.user = user?.login || 'unauthorized'+ if (info) {+ this.logger.warn(`<${req.raw.user}> <${req.ip}> ${info}`)+ }+ return super.handleRequest(err, user, info, ctx, status)+ }+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.interface.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.interface.tsnew file mode 100644index 00000000..4274d4bc--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.interface.ts@@ -0,0 +1,39 @@+/*+ * 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 type { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import type { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'++export interface JwtCollaboraOnlinePayload extends JwtIdentityPayload {+ spaceUrl: string+ dbFileHash: string+}++export interface FastifyCollaboraOnlineSpaceRequest extends FastifySpaceRequest {+ user: FastifySpaceRequest['user'] & { spaceUrl?: string; dbFileHash?: string }+ params: FastifySpaceRequest['params'] & { dbFileHash?: string }+}++export interface CollaboraOnlineCheckFileInfo {+ BaseFileName: string+ OwnerId: string+ UserId: string+ UserFriendlyName: string+ Version: string+ Size: number+ LastModifiedTime: string+ ReadOnly: false+ UserExtraInfo: { avatar: string }+ UserCanNotWriteRelative: true+ UserCanWrite: boolean+ UserCanRename: false+ SupportsRename: false+ SupportsUpdate: true+ SupportsExport: boolean+ SupportsCoauth: true+ SupportsLocks: true+ SupportsGetLock: true+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.module.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.module.tsnew file mode 100644index 00000000..0630e69a--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.module.ts@@ -0,0 +1,17 @@+/*+ * 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 { Module } from '@nestjs/common'+import { CollaboraOnlineManager } from './collabora-online-manager.service'+import { CollaboraOnlineController } from './collabora-online.controller'+import { CollaboraOnlineGuard } from './collabora-online.guard'+import { CollaboraOnlineStrategy } from './collabora-online.strategy'++@Module({+ controllers: [CollaboraOnlineController],+ providers: [CollaboraOnlineManager, CollaboraOnlineGuard, CollaboraOnlineStrategy]+})+export class CollaboraOnlineModule {}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.routes.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.routes.tsnew file mode 100644index 00000000..6a4c263f--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.routes.ts@@ -0,0 +1,15 @@+/*+ * 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+ */++export const COLLABORA_ONLINE_ROUTE = {+ BASE: '/wopi',+ FILES: 'files',+ CONTENTS: 'contents',+ SETTINGS: 'settings'+} as const++export const API_COLLABORA_ONLINE_SETTINGS = `${COLLABORA_ONLINE_ROUTE.BASE}/${COLLABORA_ONLINE_ROUTE.SETTINGS}`+export const API_COLLABORA_ONLINE_FILES = `${COLLABORA_ONLINE_ROUTE.BASE}/${COLLABORA_ONLINE_ROUTE.FILES}`diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.strategy.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.strategy.tsnew file mode 100644index 00000000..c6b27584--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.strategy.ts@@ -0,0 +1,35 @@+/*+ * 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 { Injectable } from '@nestjs/common'+import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'+import { PinoLogger } from 'nestjs-pino'+import { ExtractJwt, Strategy } from 'passport-jwt'+import { AuthTokenAccessStrategy } from '../../../../authentication/guards/auth-token-access.strategy'+import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { configuration } from '../../../../configuration/config.environment'+import { UserModel } from '../../../users/models/user.model'+import { COLLABORA_TOKEN_QUERY_PARAM_NAME } from './collabora-online.constants'++@Injectable()+export class CollaboraOnlineStrategy extends PassportStrategy(Strategy, 'filesCollaboraOnlineToken') implements AbstractStrategy {+ constructor(private readonly logger: PinoLogger) {+ super({+ jwtFromRequest: ExtractJwt.fromExtractors([+ AuthTokenAccessStrategy.extractJWTFromCookie,+ ExtractJwt.fromUrlQueryParameter(COLLABORA_TOKEN_QUERY_PARAM_NAME)+ ]),+ secretOrKey: configuration.auth.token.access.secret,+ ignoreExpiration: false,+ passReqToCallback: false+ })+ }++ validate(jwtPayload: JwtPayload): UserModel {+ this.logger.assign({ user: jwtPayload.identity.login })+ return new UserModel(jwtPayload.identity)+ }+}diff --git a/backend/src/applications/files/modules/collabora-online/collabora-online.utils.ts b/backend/src/applications/files/modules/collabora-online/collabora-online.utils.tsnew file mode 100644index 00000000..4b2acfa0--- /dev/null+++ b/backend/src/applications/files/modules/collabora-online/collabora-online.utils.ts@@ -0,0 +1,20 @@+/*+ * 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 { PATH_TO_SPACE_SEGMENTS } from '../../../spaces/utils/routes'+import type { FastifyCollaboraOnlineSpaceRequest } from './collabora-online.interface'++export function COLLABORA_ONLINE_TO_SPACE_SEGMENTS(req: FastifyCollaboraOnlineSpaceRequest): string[] {+ if (req.user.spaceUrl) {+ // `spaceUrl` and `dbFileHash` are set when the authentication token is provided via a query parameter by the Collabora Server+ if (req.user.dbFileHash === req.params.dbFileHash) {+ return req.user.spaceUrl.split('/')+ }+ throw new Error('Collabora Online - DB File Hash mismatch')+ } else {+ return PATH_TO_SPACE_SEGMENTS(req.params['*'])+ }+}diff --git a/backend/src/applications/files/decorators/only-office-environment.decorator.ts b/backend/src/applications/files/modules/only-office/only-office-environment.decorator.tssimilarity index 58%rename from backend/src/applications/files/decorators/only-office-environment.decorator.tsrename to backend/src/applications/files/modules/only-office/only-office-environment.decorator.tsindex 15ce1843..5017a0f5 100644--- a/backend/src/applications/files/decorators/only-office-environment.decorator.ts+++ b/backend/src/applications/files/modules/only-office/only-office-environment.decorator.ts@@ -5,11 +5,11 @@*/import { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'-import { SpaceGuard } from '../../spaces/guards/space.guard'-import { ONLY_OFFICE_CONTEXT } from '../constants/only-office'-import { FilesOnlyOfficeGuard } from '../guards/files-only-office.guard'+import { SpaceGuard } from '../../../spaces/guards/space.guard'+import { ONLY_OFFICE_CONTEXT } from './only-office.constants'+import { OnlyOfficeGuard } from './only-office.guard'export const OnlyOfficeContext = () => SetMetadata(ONLY_OFFICE_CONTEXT, true)export const OnlyOfficeEnvironment = () => {- return applyDecorators(OnlyOfficeContext(), UseGuards(FilesOnlyOfficeGuard, SpaceGuard))+ return applyDecorators(OnlyOfficeContext(), UseGuards(OnlyOfficeGuard, SpaceGuard))}diff --git a/backend/src/applications/files/modules/only-office/only-office-manager.service.spec.ts b/backend/src/applications/files/modules/only-office/only-office-manager.service.spec.tsnew file mode 100644index 00000000..caf6e730--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office-manager.service.spec.ts@@ -0,0 +1,38 @@+/*+ * 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 { HttpService } from '@nestjs/axios'+import { JwtService } from '@nestjs/jwt'+import { Test, TestingModule } from '@nestjs/testing'+import { Cache } from '../../../../infrastructure/cache/services/cache.service'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { UsersManager } from '../../../users/services/users-manager.service'+import { FilesLockManager } from '../../services/files-lock-manager.service'+import { OnlyOfficeManager } from './only-office-manager.service'++describe(OnlyOfficeManager.name, () => {+ let service: OnlyOfficeManager++ beforeAll(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [+ OnlyOfficeManager,+ ContextManager,+ { provide: Cache, useValue: {} },+ { provide: HttpService, useValue: {} },+ { provide: JwtService, useValue: {} },+ { provide: UsersManager, useValue: {} },+ { provide: FilesLockManager, useValue: {} }+ ]+ }).compile()++ service = module.get<OnlyOfficeManager>(OnlyOfficeManager)+ })++ it('should be defined', () => {+ expect(service).toBeDefined()+ })+})diff --git a/backend/src/applications/files/services/files-only-office-manager.service.ts b/backend/src/applications/files/modules/only-office/only-office-manager.service.tssimilarity index 72%rename from backend/src/applications/files/services/files-only-office-manager.service.tsrename to backend/src/applications/files/modules/only-office/only-office-manager.service.tsindex 7a6f0600..8488392f 100644--- a/backend/src/applications/files/services/files-only-office-manager.service.ts+++ b/backend/src/applications/files/modules/only-office/only-office-manager.service.ts@@ -12,39 +12,50 @@ import https from 'https'import crypto from 'node:crypto'import os from 'node:os'import path from 'node:path'-import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'-import { convertHumanTimeToSeconds, generateShortUUID } from '../../../common/functions'-import { configuration } from '../../../configuration/config.environment'-import { Cache } from '../../../infrastructure/cache/services/cache.service'-import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'-import { HTTP_METHOD } from '../../applications.constants'-import { SPACE_OPERATION } from '../../spaces/constants/spaces'-import { FastifySpaceRequest } from '../../spaces/interfaces/space-request.interface'-import type { SpaceEnv } from '../../spaces/models/space-env.model'-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 { CACHE_ONLY_OFFICE } from '../constants/cache'+import { JwtIdentityPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { convertHumanTimeToSeconds } from '../../../../common/functions'+import { configuration } from '../../../../configuration/config.environment'+import { Cache } from '../../../../infrastructure/cache/services/cache.service'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { HTTP_METHOD } from '../../../applications.constants'+import { SPACE_OPERATION } from '../../../spaces/constants/spaces'+import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'+import type { SpaceEnv } from '../../../spaces/models/space-env.model'+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 { FilesLockManager } from '../../services/files-lock-manager.service'import {+ copyFileContent,+ fileSize,+ genEtag,+ genUniqHashFromFileDBProps,+ isPathExists,+ isPathIsDir,+ removeFiles,+ uniqueFilePathFromDir,+ writeFromStream+} from '../../utils/files'+import {+ 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 '../constants/only-office'-import { FILE_MODE } from '../constants/operations'-import { API_FILES_ONLY_OFFICE_CALLBACK, API_FILES_ONLY_OFFICE_DOCUMENT } from '../constants/routes'-import type { FileProps } from '../interfaces/file-props.interface'-import { OnlyOfficeCallBack, OnlyOfficeConfig, OnlyOfficeConvertForm, OnlyOfficeReqConfig } from '../interfaces/only-office-config.interface'-import { copyFileContent, fileSize, getProps, isPathExists, isPathIsDir, removeFiles, uniqueFilePathFromDir, writeFromStream } from '../utils/files'-import { FilesLockManager } from './files-lock-manager.service'-import { FilesQueries } from './files-queries.service'+} from './only-office.constants'+import { OnlyOfficeReqDto } from './only-office.dtos'+import { OnlyOfficeCallBack, OnlyOfficeConfig, OnlyOfficeConvertForm } from './only-office.interface'+import { API_ONLY_OFFICE_CALLBACK, API_ONLY_OFFICE_DOCUMENT } from './only-office.routes'@Injectable()-export class FilesOnlyOfficeManager {- private logger = new Logger(FilesOnlyOfficeManager.name)+export class OnlyOfficeManager {+ private logger = new Logger(OnlyOfficeManager.name)private readonly externalOnlyOfficeServer = configuration.applications.files.onlyoffice.externalServer || nullprivate readonly rejectUnauthorized: boolean = !configuration.applications.files.onlyoffice?.verifySSLprivate readonly convertUrl = this.externalOnlyOfficeServer ? `${this.externalOnlyOfficeServer}/ConvertService.ashx` : null@@ -56,15 +67,14 @@ export class FilesOnlyOfficeManager {private readonly contextManager: ContextManager,private readonly cache: Cache,private readonly jwt: JwtService,- private readonly filesLockManager: FilesLockManager,- private readonly filesQueries: FilesQueries+ private readonly filesLockManager: FilesLockManager) {}getStatus(): { enabled: boolean } {return { enabled: configuration.applications.files.onlyoffice.enabled }}- async getSettings(user: UserModel, space: SpaceEnv, mode: FILE_MODE, req: FastifySpaceRequest): Promise<OnlyOfficeReqConfig> {+ async getSettings(user: UserModel, space: SpaceEnv, mode: FILE_MODE, req: FastifySpaceRequest): Promise<OnlyOfficeReqDto> {if (!(await isPathExists(space.realPath))) {throw new HttpException('Document not found', HttpStatus.NOT_FOUND)}@@ -87,17 +97,15 @@ export class FilesOnlyOfficeManager {}}const isMobile: boolean = this.mobileRegex.test(req.headers['user-agent'])- const fileProps: FileProps = await getProps(space.realPath, space.dbFile.path)- const fileId: string = ((await this.filesQueries.getSpaceFileId(fileProps, space.dbFile)) || fileProps.id).toString()- const userToken: string = await this.genUserToken(user)- const fileUrl = this.getDocumentUrl(space, userToken)- const callBackUrl = this.getCallBackUrl(space, userToken, fileId)- const config: OnlyOfficeReqConfig = await this.genConfiguration(user, space, mode, fileId, fileUrl, fileExtension, callBackUrl, isMobile)+ 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)config.config.token = await this.genPayloadToken(config.config)return config}- async callBack(user: UserModel, space: SpaceEnv, token: string, fileId: string) {+ async callBack(user: UserModel, space: SpaceEnv, token: string) {const callBackData: OnlyOfficeCallBack = await this.jwt.verifyAsync(token, { secret: configuration.applications.files.onlyoffice.secret })try {switch (callBackData.status) {@@ -113,7 +121,7 @@ export class FilesOnlyOfficeManager {this.logger.debug(`document was edited but not saved (let's do it) : ${space.url}`)await this.saveDocument(space, callBackData.url)}- await this.removeDocumentKey(fileId, space)+ await this.removeDocumentKey(space)breakcase 3:this.logger.error(`document cannot be saved, an error has occurred (try to save it) : ${space.url}`)@@ -121,7 +129,7 @@ export class FilesOnlyOfficeManager {breakcase 4:await this.removeFileLock(user.id, space)- await this.removeDocumentKey(fileId, space)+ await this.removeDocumentKey(space)this.logger.debug(`document was closed with no changes : ${space.url}`)breakcase 6:@@ -146,12 +154,11 @@ export class FilesOnlyOfficeManager {user: UserModel,space: SpaceEnv,mode: FILE_MODE,- fileId: string,fileUrl: string,fileExtension: string,callBackUrl: string,isMobile: boolean- ): Promise<OnlyOfficeReqConfig> {+ ): Promise<OnlyOfficeReqDto> {const documentType = ONLY_OFFICE_EXTENSIONS.EDITABLE.get(fileExtension) || ONLY_OFFICE_EXTENSIONS.VIEWABLE.get(fileExtension)return {documentServerUrl: this.externalOnlyOfficeServer || `${this.contextManager.headerOriginUrl()}${ONLY_OFFICE_INTERNAL_URI}`,@@ -163,7 +170,7 @@ export class FilesOnlyOfficeManager {document: {title: path.basename(space.relativeUrl),fileType: fileExtension,- key: await this.getDocumentKey(fileId),+ key: await this.getDocumentKey(space),permissions: {download: true,edit: mode === FILE_MODE.EDIT,@@ -205,22 +212,18 @@ export class FilesOnlyOfficeManager {}}- private getDocumentUrl(space: SpaceEnv, token: string): string {- // user refresh token is used here for long session- return `${this.contextManager.headerOriginUrl()}${API_FILES_ONLY_OFFICE_DOCUMENT}/${space.url}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${token}`- }-- private getCallBackUrl(space: SpaceEnv, token: string, fileId: string): string {- // user refresh token is used here for long session- return `${this.contextManager.headerOriginUrl()}${API_FILES_ONLY_OFFICE_CALLBACK}/${space.url}?fid=${fileId}&${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${token}`+ private buildUrl(basePath: string, spaceUrl: string, token: string): string {+ const url = new URL(`${basePath}/${spaceUrl}`, this.contextManager.headerOriginUrl())+ url.searchParams.set(ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME, token)+ return url.toString()}private genPayloadToken(payload: OnlyOfficeConfig | OnlyOfficeConvertForm): Promise<string> {return this.jwt.signAsync(payload, { secret: configuration.applications.files.onlyoffice.secret, expiresIn: 60 })}- private genUserToken(user: UserModel): Promise<string> {- // use refresh expiration to allow long session+ private genAuthToken(user: UserModel): Promise<string> {+ // use refresh expiration to allow long sessionsreturn this.jwt.signAsync({identity: {@@ -247,12 +250,12 @@ export class FilesOnlyOfficeManager {await this.removeFileLock(parseInt(action.userid), space)} else if (action.type === 1) {// connect- await this.genFileLock(user, space)+ await this.createFileLock(user, space)}}}- private async genFileLock(user: UserModel, space: SpaceEnv): Promise<void> {+ private async createFileLock(user: UserModel, space: SpaceEnv): Promise<void> {const [ok, _fileLock] = await this.filesLockManager.create(user,space.dbFile,@@ -261,12 +264,12 @@ export class FilesOnlyOfficeManager {lockroot: null,locktoken: null,lockscope: LOCK_SCOPE.SHARED,- owner: `OnlyOffice - ${user.fullName} (${user.email})`+ owner: `${ONLY_OFFICE_OWNER_LOCK} - ${user.fullName} (${user.email})`} satisfies WebDAVLock,this.expiration)if (!ok) {- throw new Error('document is locked')+ throw new HttpException('The file is locked', HttpStatus.LOCKED)}}@@ -278,21 +281,21 @@ export class FilesOnlyOfficeManager {}}- private async removeDocumentKey(fileId: string, space: SpaceEnv): Promise<void> {+ private async removeDocumentKey(space: SpaceEnv): Promise<void> {if (!(await this.filesLockManager.isPathLocked(space.dbFile))) {- const cacheKey = this.getCacheKey(fileId)+ const cacheKey = this.getCacheKey(space.dbFile)const r = await this.cache.del(cacheKey)this.logger.debug(`${this.removeDocumentKey.name} - ${cacheKey} ${r ? '' : 'not'} removed`)}}- private async getDocumentKey(fileId: string): Promise<string> {- const cacheKey = this.getCacheKey(fileId)+ private async getDocumentKey(space: SpaceEnv): Promise<string> {+ const cacheKey = this.getCacheKey(space.dbFile)const existingDocKey: string = await this.cache.get(cacheKey)if (existingDocKey) {return existingDocKey}- const docKey = generateShortUUID(64)+ const docKey = genEtag(null, space.realPath, false)await this.cache.set(cacheKey, docKey, this.expiration)this.logger.debug(`${this.getDocumentKey.name} - ${cacheKey} (${docKey}) created`)return docKey@@ -304,11 +307,11 @@ export class FilesOnlyOfficeManager {?md5=duFHKC-5d47s-RRcYn3hAw&expires=1739400549&shardkey=-33120641&filename=output.pptx*/const urlParams = new URLSearchParams(url.split('?').at(-1))- // it is not the md5 of the file but a md5 generated by the combination of the elements of the url+ // it is not the md5 of the file but the md5 generated by the combination of the elements of the urlconst md5: string = urlParams.get('md5')const tmpFilePath = await uniqueFilePathFromDir(path.join(os.tmpdir(), `${md5}-${urlParams.get('filename')}`))- // convert remote file to the local file with the current extension if these extensions aren't equal+ // convert the remote file to the local file with the current extension if these extensions aren't equalconst localExtension = path.extname(space.realPath).slice(1)const remoteExtension = path.extname(urlParams.get('filename')).slice(1)@@ -339,18 +342,17 @@ export class FilesOnlyOfficeManager {// try to verify the downloaded sizeconst contentLength = parseInt(res.headers['content-length'], 10)- if (!isNaN(contentLength)) {- if (contentLength === 0) {- this.logger.debug(`${this.saveDocument.name} - content length is 0 : ${space.url}`)- return- }+ if (!isNaN(contentLength) && contentLength !== 0) {const tmpFileSize = await fileSize(tmpFilePath)if (tmpFileSize !== contentLength) {throw new Error(`document size differs (${tmpFileSize} != ${contentLength})`)}+ } else if (contentLength === 0) {+ this.logger.warn(`${this.saveDocument.name} - content length is 0 : ${space.url}`)}- // copy contents to avoid inode changes (fileId in some cases)+ // copy contents to avoid inode changes (`file.id` in some cases)try {+ // todo: versioningawait copyFileContent(tmpFilePath, space.realPath)await removeFiles(tmpFilePath)} catch (e) {@@ -389,7 +391,7 @@ export class FilesOnlyOfficeManager {}}- private getCacheKey(fileId: string): string {- return `${CACHE_ONLY_OFFICE}|${fileId}`+ private getCacheKey(dbFile: FileDBProps): string {+ return `${ONLY_OFFICE_CACHE_KEY}|${genUniqHashFromFileDBProps(dbFile)}`}}diff --git a/backend/src/applications/files/modules/only-office/only-office.config.ts b/backend/src/applications/files/modules/only-office/only-office.config.tsnew file mode 100644index 00000000..7c7a754d--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.config.ts@@ -0,0 +1,24 @@+/*+ * 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 { IsBoolean, IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator'++export class OnlyOfficeConfig {+ @IsBoolean()+ enabled = false++ @IsOptional()+ @IsString()+ externalServer: string = null++ @ValidateIf((o: OnlyOfficeConfig) => o.enabled)+ @IsString()+ @IsNotEmpty()+ secret: string++ @IsBoolean()+ verifySSL: boolean = false+}diff --git a/backend/src/applications/files/constants/only-office.ts b/backend/src/applications/files/modules/only-office/only-office.constants.tssimilarity index 90%rename from backend/src/applications/files/constants/only-office.tsrename to backend/src/applications/files/modules/only-office/only-office.constants.tsindex 134fa003..b7422610 100644--- a/backend/src/applications/files/constants/only-office.ts+++ b/backend/src/applications/files/modules/only-office/only-office.constants.ts@@ -4,12 +4,14 @@* See the LICENSE file for licensing details*/-export const ONLY_OFFICE_INTERNAL_URI = '/onlyoffice' // used by nginx as proxy-export const ONLY_OFFICE_CONTEXT = 'OnlyOfficeEnvironment'+export const ONLY_OFFICE_INTERNAL_URI = '/onlyoffice' // used by nginx as a proxy+export const ONLY_OFFICE_CONTEXT = 'OnlyOfficeEnvironment' as constexport const ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME = 'token' as const+export const ONLY_OFFICE_OWNER_LOCK = 'OnlyOffice' as const+export const ONLY_OFFICE_CACHE_KEY = 'foffice' as constexport const ONLY_OFFICE_EXTENSIONS = {- VIEWABLE: new Map([+ VIEWABLE: new Map<string, 'word' | 'cell' | 'slide' | 'pdf' | 'diagram'>([// WORD['doc', 'word'],['docm', 'word'],@@ -90,7 +92,7 @@ export const ONLY_OFFICE_EXTENSIONS = {['vstx', 'diagram']]),- EDITABLE: new Map([+ EDITABLE: new Map<string, 'word' | 'cell' | 'slide' | 'pdf'>([// WORD['doc', 'word'],['docm', 'word'],diff --git a/backend/src/applications/files/files-only-office.controller.spec.ts b/backend/src/applications/files/modules/only-office/only-office.controller.spec.tssimilarity index 71%rename from backend/src/applications/files/files-only-office.controller.spec.tsrename to backend/src/applications/files/modules/only-office/only-office.controller.spec.tsindex 630b60fb..d07b104b 100644--- a/backend/src/applications/files/files-only-office.controller.spec.ts+++ b/backend/src/applications/files/modules/only-office/only-office.controller.spec.ts@@ -5,16 +5,16 @@*/import { Test, TestingModule } from '@nestjs/testing'-import { ContextInterceptor } from '../../infrastructure/context/interceptors/context.interceptor'-import { ContextManager } from '../../infrastructure/context/services/context-manager.service'-import { SpacesManager } from '../spaces/services/spaces-manager.service'-import { FILE_MODE } from './constants/operations'-import { FilesOnlyOfficeController } from './files-only-office.controller'-import { FilesMethods } from './services/files-methods.service'-import { FilesOnlyOfficeManager } from './services/files-only-office-manager.service'+import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'+import { ContextManager } from '../../../../infrastructure/context/services/context-manager.service'+import { SpacesManager } from '../../../spaces/services/spaces-manager.service'+import { FILE_MODE } from '../../constants/operations'+import { FilesMethods } from '../../services/files-methods.service'+import { OnlyOfficeManager } from './only-office-manager.service'+import { OnlyOfficeController } from './only-office.controller'-describe(FilesOnlyOfficeController.name, () => {- let controller: FilesOnlyOfficeController+describe(OnlyOfficeController.name, () => {+ let controller: OnlyOfficeControllerconst filesOnlyOfficeManagerMock = {getSettings: jest.fn(),@@ -28,9 +28,9 @@ describe(FilesOnlyOfficeController.name, () => {beforeEach(async () => {jest.clearAllMocks()const module: TestingModule = await Test.createTestingModule({- controllers: [FilesOnlyOfficeController],+ controllers: [OnlyOfficeController],providers: [- { provide: FilesOnlyOfficeManager, useValue: filesOnlyOfficeManagerMock },+ { provide: OnlyOfficeManager, useValue: filesOnlyOfficeManagerMock },{ provide: FilesMethods, useValue: filesMethodsMock },{ provide: SpacesManager, useValue: {} },ContextManager,@@ -38,7 +38,7 @@ describe(FilesOnlyOfficeController.name, () => {]}).compile()- controller = module.get<FilesOnlyOfficeController>(FilesOnlyOfficeController)+ controller = module.get<OnlyOfficeController>(OnlyOfficeController)})it('should be defined', () => {@@ -49,11 +49,11 @@ describe(FilesOnlyOfficeController.name, () => {it('should call manager with default mode "view" when mode is undefined', async () => {const user: any = { id: 1 }const space: any = { id: 'space-1' }- const req: any = { headers: {}, params: {}, query: {} }+ const req: any = { headers: {}, params: {}, query: {}, user, space }const expected = { config: 'ok', mode: FILE_MODE.VIEW }filesOnlyOfficeManagerMock.getSettings.mockResolvedValue(expected)- const result = await controller.onlyOfficeSettings(user, space, undefined as any, req)+ const result = await controller.onlyOfficeSettings(undefined as any, req)expect(filesOnlyOfficeManagerMock.getSettings).toHaveBeenCalledTimes(1)expect(filesOnlyOfficeManagerMock.getSettings).toHaveBeenCalledWith(user, space, FILE_MODE.VIEW, req)@@ -63,11 +63,11 @@ describe(FilesOnlyOfficeController.name, () => {it('should pass provided mode to manager', async () => {const user: any = { id: 2 }const space: any = { id: 'space-2' }- const req: any = { headers: { 'x-test': '1' } }+ const req: any = { headers: { 'x-test': '1' }, user, space }const expected = { config: 'ok', mode: FILE_MODE.EDIT }filesOnlyOfficeManagerMock.getSettings.mockResolvedValue(expected)- const result = await controller.onlyOfficeSettings(user, space, FILE_MODE.EDIT, req)+ const result = await controller.onlyOfficeSettings(FILE_MODE.EDIT, req)expect(filesOnlyOfficeManagerMock.getSettings).toHaveBeenCalledWith(user, space, FILE_MODE.EDIT, req)expect(result).toBe(expected)@@ -94,14 +94,13 @@ describe(FilesOnlyOfficeController.name, () => {const user: any = { id: 3 }const space: any = { id: 'space-3' }const token = 'jwt-token'- const fileId = 'file-123'const expected = { ok: true }filesOnlyOfficeManagerMock.callBack.mockResolvedValue(expected)- const result = await controller.onlyOfficeCallBack(user, space, token, fileId)+ const result = await controller.onlyOfficeCallBack(user, space, token)expect(filesOnlyOfficeManagerMock.callBack).toHaveBeenCalledTimes(1)- expect(filesOnlyOfficeManagerMock.callBack).toHaveBeenCalledWith(user, space, token, fileId)+ expect(filesOnlyOfficeManagerMock.callBack).toHaveBeenCalledWith(user, space, token)expect(result).toBe(expected)})})diff --git a/backend/src/applications/files/modules/only-office/only-office.controller.ts b/backend/src/applications/files/modules/only-office/only-office.controller.tsnew file mode 100644index 00000000..f8c36399--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.controller.ts@@ -0,0 +1,49 @@+/*+ * 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 { Body, Controller, Get, HttpCode, HttpStatus, Post, Query, Request, Res, StreamableFile, UseInterceptors } from '@nestjs/common'+import { FastifyReply } from 'fastify'+import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'+import { SPACE_OPERATION } from '../../../spaces/constants/spaces'+import { OverrideSpacePermission } from '../../../spaces/decorators/space-override-permission.decorator'+import { GetSpace } from '../../../spaces/decorators/space.decorator'+import { FastifySpaceRequest } from '../../../spaces/interfaces/space-request.interface'+import { SpaceEnv } from '../../../spaces/models/space-env.model'+import { GetUser } from '../../../users/decorators/user.decorator'+import { UserModel } from '../../../users/models/user.model'+import { FILE_MODE } from '../../constants/operations'+import { FilesMethods } from '../../services/files-methods.service'+import { OnlyOfficeEnvironment } from './only-office-environment.decorator'+import { OnlyOfficeManager } from './only-office-manager.service'+import type { OnlyOfficeReqDto } from './only-office.dtos'+import { API_ONLY_OFFICE, ONLY_OFFICE_ROUTE } from './only-office.routes'++@Controller(API_ONLY_OFFICE)+@OnlyOfficeEnvironment()+export class OnlyOfficeController {+ constructor(+ private readonly filesMethods: FilesMethods,+ private readonly filesOnlyOfficeManager: OnlyOfficeManager+ ) {}++ @Get(`${ONLY_OFFICE_ROUTE.SETTINGS}/*`)+ @UseInterceptors(ContextInterceptor)+ onlyOfficeSettings(@Query('mode') mode: FILE_MODE = FILE_MODE.VIEW, @Request() req: FastifySpaceRequest): Promise<OnlyOfficeReqDto> {+ return this.filesOnlyOfficeManager.getSettings(req.user, req.space, mode, req)+ }++ @Get(`${ONLY_OFFICE_ROUTE.DOCUMENT}/*`)+ onlyOfficeDocument(@Request() req: FastifySpaceRequest, @Res({ passthrough: true }) res: FastifyReply): Promise<StreamableFile> {+ return this.filesMethods.headOrGet(req, res)+ }++ @Post(`${ONLY_OFFICE_ROUTE.CALLBACK}/*`)+ @OverrideSpacePermission(SPACE_OPERATION.MODIFY)+ @HttpCode(HttpStatus.OK)+ onlyOfficeCallBack(@GetUser() user: UserModel, @GetSpace() space: SpaceEnv, @Body('token') token: string) {+ return this.filesOnlyOfficeManager.callBack(user, space, token)+ }+}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.tsnew file mode 100644index 00000000..2dfb3ac8--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.dtos.ts@@ -0,0 +1,12 @@+/*+ * 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 { OnlyOfficeConfig } from './only-office.interface'++export interface OnlyOfficeReqDto {+ documentServerUrl: string+ config: OnlyOfficeConfig+}diff --git a/backend/src/applications/files/guards/files-only-office.guard.spec.ts b/backend/src/applications/files/modules/only-office/only-office.guard.spec.tssimilarity index 54%rename from backend/src/applications/files/guards/files-only-office.guard.spec.tsrename to backend/src/applications/files/modules/only-office/only-office.guard.spec.tsindex 8a582466..fd6b9556 100644--- a/backend/src/applications/files/guards/files-only-office.guard.spec.ts+++ b/backend/src/applications/files/modules/only-office/only-office.guard.spec.ts@@ -9,16 +9,16 @@ import { ExecutionContext } from '@nestjs/common'import { JwtModule, JwtService } from '@nestjs/jwt'import { Test, TestingModule } from '@nestjs/testing'import { PinoLogger } from 'nestjs-pino'-import { JwtPayload } from '../../../authentication/interfaces/jwt-payload.interface'-import { configuration } from '../../../configuration/config.environment'-import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from '../constants/only-office'-import { API_FILES_ONLY_OFFICE_CALLBACK } from '../constants/routes'-import { FilesOnlyOfficeGuard } from './files-only-office.guard'-import { FilesOnlyOfficeStrategy } from './files-only-office.strategy'+import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { configuration } from '../../../../configuration/config.environment'+import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants'+import { OnlyOfficeGuard } from './only-office.guard'+import { API_ONLY_OFFICE_CALLBACK } from './only-office.routes'+import { OnlyOfficeStrategy } from './only-office.strategy'-describe(FilesOnlyOfficeGuard.name, () => {+describe(OnlyOfficeGuard.name, () => {let jwtService: JwtService- let filesOnlyOfficeGuard: FilesOnlyOfficeGuard+ let filesOnlyOfficeGuard: OnlyOfficeGuardlet context: DeepMocked<ExecutionContext>let accessToken: string@@ -26,8 +26,8 @@ describe(FilesOnlyOfficeGuard.name, () => {const module: TestingModule = await Test.createTestingModule({imports: [JwtModule.register({ global: true })],providers: [- FilesOnlyOfficeGuard,- FilesOnlyOfficeStrategy,+ OnlyOfficeGuard,+ OnlyOfficeStrategy,{provide: PinoLogger,useValue: {@@ -38,7 +38,7 @@ describe(FilesOnlyOfficeGuard.name, () => {}).compile()jwtService = module.get<JwtService>(JwtService)- filesOnlyOfficeGuard = module.get<FilesOnlyOfficeGuard>(FilesOnlyOfficeGuard)+ filesOnlyOfficeGuard = module.get<OnlyOfficeGuard>(OnlyOfficeGuard)context = createMock<ExecutionContext>()accessToken = await jwtService.signAsync({ identity: { id: 1, login: 'foo' } } as JwtPayload, {secret: configuration.auth.token.access.secret,@@ -52,28 +52,22 @@ describe(FilesOnlyOfficeGuard.name, () => {expect(accessToken).toBeDefined()})- it('should not pass if enabled (or not) without a valid token', async () => {- configuration.applications.files.onlyoffice.enabled = false+ it('should not pass without a valid token', async () => {context.switchToHttp().getRequest.mockReturnValue({- url: `${API_FILES_ONLY_OFFICE_CALLBACK}`,+ url: `${API_ONLY_OFFICE_CALLBACK}`,raw: { user: '' }})- expect(() => filesOnlyOfficeGuard.canActivate(context)).toThrow(/feature not enabled/i)- configuration.applications.files.onlyoffice.enabled = trueawait expect(filesOnlyOfficeGuard.canActivate(context)).rejects.toThrow('Unauthorized')})- it('should pass if enabled (or not) with a valid token', async () => {- configuration.applications.files.onlyoffice.enabled = false+ it('should pass with a (un)valid token', async () => {context.switchToHttp().getRequest.mockReturnValue({- url: `${API_FILES_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${accessToken}`,+ url: `${API_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=${accessToken}`,raw: { user: '' }})- expect(() => filesOnlyOfficeGuard.canActivate(context)).toThrow(/feature not enabled/i)- configuration.applications.files.onlyoffice.enabled = trueexpect(await filesOnlyOfficeGuard.canActivate(context)).toBe(true)context.switchToHttp().getRequest.mockReturnValue({- url: `${API_FILES_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=unvalidToken`,+ url: `${API_ONLY_OFFICE_CALLBACK}?${ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME}=unvalidToken`,raw: { user: '' }})await expect(filesOnlyOfficeGuard.canActivate(context)).rejects.toThrow('Unauthorized')diff --git a/backend/src/applications/files/modules/only-office/only-office.guard.ts b/backend/src/applications/files/modules/only-office/only-office.guard.tsnew file mode 100644index 00000000..77c518f5--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.guard.ts@@ -0,0 +1,22 @@+/*+ * 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 { ExecutionContext, Injectable, Logger } from '@nestjs/common'+import { AuthGuard, IAuthGuard } from '@nestjs/passport'++@Injectable()+export class OnlyOfficeGuard extends AuthGuard('filesOnlyOfficeToken') implements IAuthGuard {+ private readonly logger = new Logger(OnlyOfficeGuard.name)++ handleRequest<TUser = any>(err: any, user: any, info: Error, ctx: ExecutionContext, status?: any): TUser {+ const req = this.getRequest(ctx)+ req.raw.user = user?.login || 'unauthorized'+ if (info) {+ this.logger.warn(`<${req.raw.user}> <${req.ip}> ${info}`)+ }+ return super.handleRequest(err, user, info, ctx, status)+ }+}diff --git a/backend/src/applications/files/interfaces/only-office-config.interface.ts b/backend/src/applications/files/modules/only-office/only-office.interface.tssimilarity index 97%rename from backend/src/applications/files/interfaces/only-office-config.interface.tsrename to backend/src/applications/files/modules/only-office/only-office.interface.tsindex 87823497..826a67e7 100644--- a/backend/src/applications/files/interfaces/only-office-config.interface.ts+++ b/backend/src/applications/files/modules/only-office/only-office.interface.ts@@ -4,12 +4,7 @@* See the LICENSE file for licensing details*/-import { FILE_MODE } from '../constants/operations'--export interface OnlyOfficeReqConfig {- documentServerUrl: string- config: OnlyOfficeConfig-}+import { FILE_MODE } from '../../constants/operations'export interface OnlyOfficeConvertForm {key: stringdiff --git a/backend/src/applications/files/modules/only-office/only-office.module.ts b/backend/src/applications/files/modules/only-office/only-office.module.tsnew file mode 100644index 00000000..855d907f--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.module.ts@@ -0,0 +1,17 @@+/*+ * 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 { Module } from '@nestjs/common'+import { OnlyOfficeManager } from './only-office-manager.service'+import { OnlyOfficeController } from './only-office.controller'+import { OnlyOfficeGuard } from './only-office.guard'+import { OnlyOfficeStrategy } from './only-office.strategy'++@Module({+ controllers: [OnlyOfficeController],+ providers: [OnlyOfficeManager, OnlyOfficeGuard, OnlyOfficeStrategy]+})+export class OnlyOfficeModule {}diff --git a/backend/src/applications/files/modules/only-office/only-office.routes.ts b/backend/src/applications/files/modules/only-office/only-office.routes.tsnew file mode 100644index 00000000..abef1aa6--- /dev/null+++ b/backend/src/applications/files/modules/only-office/only-office.routes.ts@@ -0,0 +1,20 @@+/*+ * 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 { SPACES_ROUTE } from '../../../spaces/constants/routes'++export const ONLY_OFFICE_ROUTE = {+ BASE: SPACES_ROUTE.BASE,+ ONLY_OFFICE: 'onlyoffice',+ SETTINGS: 'settings',+ DOCUMENT: 'document',+ CALLBACK: 'callback'+} as const++export const API_ONLY_OFFICE = `${ONLY_OFFICE_ROUTE.BASE}/${ONLY_OFFICE_ROUTE.ONLY_OFFICE}`+export const API_ONLY_OFFICE_SETTINGS = `${API_ONLY_OFFICE}/${ONLY_OFFICE_ROUTE.SETTINGS}`+export const API_ONLY_OFFICE_DOCUMENT = `${API_ONLY_OFFICE}/${ONLY_OFFICE_ROUTE.DOCUMENT}`+export const API_ONLY_OFFICE_CALLBACK = `${API_ONLY_OFFICE}/${ONLY_OFFICE_ROUTE.CALLBACK}`diff --git a/backend/src/applications/files/guards/files-only-office.strategy.ts b/backend/src/applications/files/modules/only-office/only-office.strategy.tssimilarity index 64%rename from backend/src/applications/files/guards/files-only-office.strategy.tsrename to backend/src/applications/files/modules/only-office/only-office.strategy.tsindex a4a15cf5..c933ce2c 100644--- a/backend/src/applications/files/guards/files-only-office.strategy.ts+++ b/backend/src/applications/files/modules/only-office/only-office.strategy.ts@@ -8,14 +8,14 @@ import { Injectable } from '@nestjs/common'import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'import { PinoLogger } from 'nestjs-pino'import { ExtractJwt, Strategy } from 'passport-jwt'-import { AuthTokenAccessStrategy } from '../../../authentication/guards/auth-token-access.strategy'-import { JwtPayload } from '../../../authentication/interfaces/jwt-payload.interface'-import { configuration } from '../../../configuration/config.environment'-import { UserModel } from '../../users/models/user.model'-import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from '../constants/only-office'+import { AuthTokenAccessStrategy } from '../../../../authentication/guards/auth-token-access.strategy'+import { JwtPayload } from '../../../../authentication/interfaces/jwt-payload.interface'+import { configuration } from '../../../../configuration/config.environment'+import { UserModel } from '../../../users/models/user.model'+import { ONLY_OFFICE_TOKEN_QUERY_PARAM_NAME } from './only-office.constants'@Injectable()-export class FilesOnlyOfficeStrategy extends PassportStrategy(Strategy, 'filesOnlyOfficeToken') implements AbstractStrategy {+export class OnlyOfficeStrategy extends PassportStrategy(Strategy, 'filesOnlyOfficeToken') implements AbstractStrategy {constructor(private readonly logger: PinoLogger) {super({jwtFromRequest: ExtractJwt.fromExtractors([diff --git a/backend/src/applications/files/services/files-lock-manager.service.ts b/backend/src/applications/files/services/files-lock-manager.service.tsindex 1b2f39ae..40b32bd0 100644--- a/backend/src/applications/files/services/files-lock-manager.service.ts+++ b/backend/src/applications/files/services/files-lock-manager.service.ts@@ -23,7 +23,7 @@ import { dirName, fileName } from '../utils/files'@Injectable()export class FilesLockManager {/* Philosophy- Currently this manager only handle conflicting locks between multiple users, not between clients+ Currently this manager only handles conflicting locks between multiple users, not between clients- The locks created from api* They do not contain a token key or a davLock property* They are exclusive only@@ -32,7 +32,7 @@ export class FilesLockManager {* They must have a depth of 'infinity' (all children) or '0' (root and root members)* They can be exclusive (WebDAV) or shared (OnlyOffice)* 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 OnlyOffice, they are stored with no token and a davLock property whose `locktoken` & `lockroot` properties are `null`Cache token key format = `flock|token?:${uuid}|path:${path}|ownerId?:${number}|spaceId?:${number}|...props` => FileLock*/private readonly logger = new Logger(FilesLockManager.name)@@ -43,8 +43,8 @@ export class FilesLockManager {let token: stringlet lockscope: LOCK_SCOPEif (davLock) {- // webdav context- davLock.locktoken = this.genDAVToken()+ // webdav | onlyoffice | collabora online context+ davLock.locktoken = davLock.locktoken || this.genDAVToken()token = davLock.locktokenlockscope = davLock.lockscope} else {@@ -126,7 +126,7 @@ export class FilesLockManager {}async isLockedWithToken(token: string, dbFilePath: string): Promise<FileLock> {- // check if url (or any of its parents) is locked by the token+ // check if the url (or any of its parents) is locked by the tokenconst lock = await this.getLockByToken(token)return lock ? (dbFilePath.startsWith(lock.dbFilePath) ? lock : null) : null}@@ -185,12 +185,12 @@ export class FilesLockManager {options?: { userId?: number; lockScope?: LOCK_SCOPE; lockTokens?: string[] }): Promise<void> {/* Checks if a file could be modified, created, moved, or deleted- Throws an `LockConflict` error when there are parent locks (depth: 0) or child locks (depth: infinite) that prevent modification+ Throws a `LockConflict` error when there are parent locks (depth: 0) or child locks (depth: infinite) that prevent modificationReturns 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 same owner)+ // Only compatible with shared locks (even by the same owner)continue}if (options?.userId === l.owner.id && (!l.davLock || (options?.lockTokens?.length && options.lockTokens.indexOf(l.davLock.locktoken) > -1))) {diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.tsindex 28aa1e72..23fd0e86 100644--- a/backend/src/applications/files/services/files-manager.service.ts+++ b/backend/src/applications/files/services/files-manager.service.ts@@ -100,8 +100,8 @@ export class FilesManager {req: FastifyAuthenticatedRequest,options?: { dav?: { depth: LOCK_DEPTH; lockTokens: string[] }; checksumAlg?: string; tmpPath?: string }): Promise<boolean | string> {- // if tmpPath is used, we lock the final destination during the transfer- // space.realPath is replaced by tmpPath (if allowed), if the move operation failed we remove the tmp file+ // If tmpPath is used, we lock the final destination during the transfer+ // space.realPath is replaced by tmpPath (if allowed). If the move operation failed, we remove the tmp fileconst fExists = await isPathExists(space.realPath)const fTmpExists = options?.tmpPath ? await isPathExists(options.tmpPath) : falseif (fExists && req.method === HTTP_METHOD.POST) {@@ -111,7 +111,7 @@ export class FilesManager {throw new FileError(HttpStatus.METHOD_NOT_ALLOWED, 'The location is a directory')}if (options?.tmpPath) {- // ensure tmpPath parent dir exists+ // Ensure tmpPath parent dir existsawait makeDir(dirName(options.tmpPath), true)} else if (!(await isPathExists(dirName(space.realPath)))) {throw new FileError(HttpStatus.CONFLICT, 'Parent must exists')@@ -119,13 +119,13 @@ export class FilesManager {/* File Lock */let fileLock: FileLock | undefinedif (options?.dav) {- // check locks+ // Check locksawait this.filesLockManager.checkConflicts(space.dbFile, options?.dav?.depth || DEPTH.RESOURCE, {userId: user.id,lockTokens: options.dav?.lockTokens})} else {- // create lock if there is no webdav context+ // Create lock if there is no webdav contextconst [ok, lock] = await this.filesLockManager.create(user, space.dbFile, DEPTH.RESOURCE)if (!ok) {throw new LockConflict(lock, 'Conflicting lock')@@ -133,12 +133,12 @@ export class FilesManager {fileLock = lock}try {- // check range+ // Check rangelet startRange = 0if ((fExists || fTmpExists) && req.headers['content-range']) {- // with PUT method, some webdav clients use the `content-range` header,+ // With PUT method, some webdav clients use the `content-range` header,// which is normally reserved for a response to a request containing the `range` header.- // However, for more compatibility let's accept it+ // However, for more compatibility let's accept it.const match = /\d+/.exec(req.headers['content-range'])if (!match.length) {throw new FileError(HttpStatus.BAD_REQUEST, 'Content-range : header is malformed')@@ -639,7 +639,7 @@ export class FilesManager {return this.filesLockManager.convertLockToFileLockProps(lock)}- async unlock(user: UserModel, space: SpaceEnv, forceAsOwner = false): Promise<void> {+ async unlock(user: UserModel, space: SpaceEnv, forceAsFileOwner = false): 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')@@ -650,7 +650,7 @@ export class FilesManager {return}for (const lock of fileLocks) {- if ((forceAsOwner && space.dbFile?.ownerId === user.id) || lock.owner.id === user.id) {+ if ((forceAsFileOwner && space.dbFile?.ownerId === user.id) || lock.owner.id === user.id) {// Refresh if more than half of the TTL has passedawait this.filesLockManager.removeLock(lock.key)} else {diff --git a/backend/src/applications/files/services/files-methods.service.ts b/backend/src/applications/files/services/files-methods.service.tsindex 0833109f..1185facd 100644--- a/backend/src/applications/files/services/files-methods.service.ts+++ b/backend/src/applications/files/services/files-methods.service.ts@@ -8,6 +8,7 @@ import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@import { FastifyReply } from 'fastify'import path from 'node:path'import { Readable } from 'node:stream'+import { configuration } from '../../../configuration/config.environment'import { FastifySpaceRequest } from '../../spaces/interfaces/space-request.interface'import { SpaceEnv } from '../../spaces/models/space-env.model'import { SpacesManager } from '../../spaces/services/spaces-manager.service'@@ -15,6 +16,7 @@ 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 { FileSettings } from '../interfaces/file-settings.interface'import { FileError } from '../models/file-error'import { LockConflict } from '../models/file-lock-error'import { checkFileName, dirName, fileName, isPathExists, sanitizeName } from '../utils/files'@@ -161,9 +163,9 @@ export class FilesMethods {}}- async unlock(user: UserModel, space: SpaceEnv, forceAsOwner = false): Promise<void> {+ async unlock(user: UserModel, space: SpaceEnv, forceAsFileOwner = false): Promise<void> {try {- return await this.filesManager.unlock(user, space, forceAsOwner)+ return await this.filesManager.unlock(user, space, forceAsFileOwner)} catch (e) {this.handleError(space, FILE_OPERATION.UNLOCK, e)}@@ -205,6 +207,15 @@ export class FilesMethods {return { path: dirName(dstUrl), name: fileName(dstUrl) }}+ fileSettings(): FileSettings {+ return {+ editor: {+ collaboraOnline: configuration.applications.files.collabora.enabled,+ onlyOffice: configuration.applications.files.onlyoffice.enabled+ }+ }+ }+private handleError(space: SpaceEnv, action: string, e: any, dstSpace?: SpaceEnv) {this.logger.error(`unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${e}`)// Remove the last part to avoid exposing the pathdiff --git a/backend/src/applications/files/services/files-only-office-manager.service.spec.ts b/backend/src/applications/files/services/files-only-office-manager.service.spec.tsdeleted file mode 100644index 0b7e045d..00000000--- a/backend/src/applications/files/services/files-only-office-manager.service.spec.ts+++ /dev/null@@ -1,43 +0,0 @@-/*- * 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 { HttpService } from '@nestjs/axios'-import { JwtService } from '@nestjs/jwt'-import { Test, TestingModule } from '@nestjs/testing'-import { Cache } from '../../../infrastructure/cache/services/cache.service'-import { ContextManager } from '../../../infrastructure/context/services/context-manager.service'-import { UsersManager } from '../../users/services/users-manager.service'-import { FilesLockManager } from './files-lock-manager.service'-import { FilesOnlyOfficeManager } from './files-only-office-manager.service'-import { FilesQueries } from './files-queries.service'--describe(FilesOnlyOfficeManager.name, () => {- let service: FilesOnlyOfficeManager-- beforeAll(async () => {- const module: TestingModule = await Test.createTestingModule({- providers: [- FilesOnlyOfficeManager,- ContextManager,- { provide: HttpService, useValue: {} },- {- provide: Cache,- useValue: {}- },- { provide: JwtService, useValue: {} },- { provide: UsersManager, useValue: {} },- { provide: FilesLockManager, useValue: {} },- { provide: FilesQueries, useValue: {} }- ]- }).compile()-- service = module.get<FilesOnlyOfficeManager>(FilesOnlyOfficeManager)- })-- it('should be defined', () => {- expect(service).toBeDefined()- })-})diff --git a/backend/src/applications/files/utils/files.ts b/backend/src/applications/files/utils/files.tsindex 85d9ffa2..8f478138 100644--- a/backend/src/applications/files/utils/files.ts+++ b/backend/src/applications/files/utils/files.ts@@ -16,7 +16,8 @@ import { Readable } from 'node:stream'import { pipeline } from 'node:stream/promises'import { formatDateISOString } from '../../../common/functions'import { currentTimeStamp, isValidFileName, regExpPreventPathTraversal } from '../../../common/shared'-import { DEFAULT_HIGH_WATER_MARK, EXTRA_MIMES_TYPE } from '../constants/files'+import { DEFAULT_CHECKSUM_ALGORITHM, DEFAULT_HIGH_WATER_MARK, EXTRA_MIMES_TYPE } from '../constants/files'+import type { FileDBProps } from '../interfaces/file-db-props.interface'import type { FileProps } from '../interfaces/file-props.interface'import { FileError } from '../models/file-error'@@ -102,13 +103,22 @@ export function getMimeType(fPath: string, isDir: boolean): string {return 'file'}-export function genEtag(file?: Pick<FileProps, 'size' | 'mtime'>, rPath?: string): string {+export function genEtag(file?: Pick<FileProps, 'size' | 'mtime'>, rPath?: string, weakPrefix = true): string {if (!file) {if (!rPath) throw new Error('File or path are missing')const stats = statSync(rPath)file = { size: stats.size, mtime: stats.mtime.getTime() }}- return `W/"${file.size.toString(16)}-${file.mtime.toString(16)}"`+ const etag = `${file.size.toString(16)}-${file.mtime.toString(16)}`+ return weakPrefix ? `W/"${etag}"` : etag+}++export function genUniqHashFromFileDBProps(dbFile: FileDBProps) {+ const dbFileString = `${Object.keys(dbFile)+ .sort()+ .map((k) => `${k}=${String(dbFile[k])}`)+ .join('|')}`+ return crypto.createHash(DEFAULT_CHECKSUM_ALGORITHM).update(dbFileString, 'utf-8').digest('hex')}export function removeFiles(rPath: string): Promise<void> {diff --git a/backend/src/applications/spaces/decorators/space-override-permission.decorator.ts b/backend/src/applications/spaces/decorators/space-override-permission.decorator.tsnew file mode 100644index 00000000..bd97b3b4--- /dev/null+++ b/backend/src/applications/spaces/decorators/space-override-permission.decorator.ts@@ -0,0 +1,10 @@+/*+ * 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 { Reflector } from '@nestjs/core'+import { SPACE_OPERATION } from '../constants/spaces'++export const OverrideSpacePermission = Reflector.createDecorator<SPACE_OPERATION>()diff --git a/backend/src/applications/spaces/guards/space.guard.spec.ts b/backend/src/applications/spaces/guards/space.guard.spec.tsindex 5847083e..abe3b765 100644--- a/backend/src/applications/spaces/guards/space.guard.spec.ts+++ b/backend/src/applications/spaces/guards/space.guard.spec.ts@@ -11,8 +11,6 @@ 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'-import { API_FILES_ONLY_OFFICE_CALLBACK } from '../../files/constants/routes'-import { OnlyOfficeContext } from '../../files/decorators/only-office-environment.decorator'import { FilesQueries } from '../../files/services/files-queries.service'import { LinksQueries } from '../../links/services/links-queries.service'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'@@ -26,6 +24,7 @@ import { UsersQueries } from '../../users/services/users-queries.service'import { generateUserTest } from '../../users/utils/test'import { WebDAVContext } from '../../webdav/decorators/webdav-context.decorator'import { SPACE_ALIAS, SPACE_ALL_OPERATIONS, SPACE_OPERATION, SPACE_PERMS_SEP, SPACE_REPOSITORY } from '../constants/spaces'+import { OverrideSpacePermission } from '../decorators/space-override-permission.decorator'import { SkipSpaceGuard } from '../decorators/space-skip-guard.decorator'import { SkipSpacePermissionsCheck } from '../decorators/space-skip-permissions.decorator'import { SpaceEnv } from '../models/space-env.model'@@ -73,6 +72,9 @@ describe(SpaceGuard.name, () => {// mocksspacesManager['setQuotaExceeded'] = jest.fn()userTest = new UserModel(generateUserTest())+ })++ beforeEach(() => {context = createMock<ExecutionContext>()})@@ -333,8 +335,6 @@ describe(SpaceGuard.name, () => {params: { '*': 'files/personal' }})expect(await spacesGuard.canActivate(context)).toBe(true)- // reset context- context = createMock<ExecutionContext>()})it('should fail with quota exceeded', async () => {@@ -408,9 +408,8 @@ describe(SpaceGuard.name, () => {params: { '*': 'webdav/files' }})await expect(spacesGuard.canActivate(context)).rejects.toThrow(HttpException)- // reset context+ // reset mockspyUrlSegment.mockRestore()- context = createMock<ExecutionContext>()})it('should validate (or not) the sync routes', async () => {@@ -431,31 +430,30 @@ describe(SpaceGuard.name, () => {await expect(spacesGuard.canActivate(context)).rejects.toThrow(HttpException)// reset contextspyUrlSegment.mockRestore()- context = createMock<ExecutionContext>()})- it('should require the modify permission when using the POST method on the OnlyOffice callback URL', async () => {+ it('should allow the modify permission when using the POST method with override space permission decorator', async () => {userTest.role = USER_ROLE.USERspacesManager.spaceEnv = jest.fn().mockReturnValue({ enabled: true, envPermissions: `${SPACE_OPERATION.MODIFY}` })- OnlyOfficeContext()(context.getHandler())+ OverrideSpacePermission(SPACE_OPERATION.MODIFY)(context.getHandler())context.switchToHttp().getRequest.mockReturnValue({method: 'POST',user: userTest,- originalUrl: API_FILES_ONLY_OFFICE_CALLBACK,+ originalUrl: '1',params: { '*': 'files/personal/root' }})expect(await spacesGuard.canActivate(context)).toBe(true)+ // reset context+ context = createMock<ExecutionContext>()spacesManager.spaceEnv = jest.fn().mockReturnValue({ enabled: true, envPermissions: `${SPACE_OPERATION.ADD}` })await expect(spacesGuard.canActivate(context)).rejects.toThrow(HttpException)context.switchToHttp().getRequest.mockReturnValue({method: 'POST',user: userTest,- originalUrl: '',+ originalUrl: '2',params: { '*': 'files/personal/root' }})expect(await spacesGuard.canActivate(context)).toBe(true)- // reset context- context = createMock<ExecutionContext>()})it('should pass if skipSpaceGuard context is enabled', async () => {@@ -469,8 +467,6 @@ describe(SpaceGuard.name, () => {await expect(spacesGuard.canActivate(context)).rejects.toMatchObject({ status: HttpStatus.FORBIDDEN })SkipSpaceGuard()(context.getHandler())expect(await spacesGuard.canActivate(context)).toBe(true)- // reset context- context = createMock<ExecutionContext>()})it('coverage only', async () => {diff --git a/backend/src/applications/spaces/guards/space.guard.ts b/backend/src/applications/spaces/guards/space.guard.tsindex 30cc03cf..c2e19eda 100644--- a/backend/src/applications/spaces/guards/space.guard.ts+++ b/backend/src/applications/spaces/guards/space.guard.ts@@ -6,14 +6,14 @@import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'import { Reflector } from '@nestjs/core'-import { HTTP_METHOD } from '../../applications.constants'-import { ONLY_OFFICE_CONTEXT } from '../../files/constants/only-office'-import { API_FILES_ONLY_OFFICE_CALLBACK } from '../../files/constants/routes'+import { COLLABORA_CONTEXT } from '../../files/modules/collabora-online/collabora-online.constants'+import { COLLABORA_ONLINE_TO_SPACE_SEGMENTS } from '../../files/modules/collabora-online/collabora-online.utils'import { SYNC_CONTEXT } from '../../sync/decorators/sync-context.decorator'import { SYNC_PATH_TO_SPACE_SEGMENTS } from '../../sync/utils/routes'import { WEB_DAV_CONTEXT } from '../../webdav/decorators/webdav-context.decorator'import { WEBDAV_PATH_TO_SPACE_SEGMENTS } from '../../webdav/utils/routes'import { SPACE_HTTP_PERMISSION, SPACE_OPERATION } from '../constants/spaces'+import { OverrideSpacePermission } from '../decorators/space-override-permission.decorator'import { SKIP_SPACE_GUARD } from '../decorators/space-skip-guard.decorator'import { SKIP_SPACE_PERMISSIONS_CHECK } from '../decorators/space-skip-permissions.decorator'import { FastifySpaceRequest } from '../interfaces/space-request.interface'@@ -31,14 +31,8 @@ export class SpaceGuard implements CanActivate {private readonly spacesManager: SpacesManager) {}- static checkPermissions(req: FastifySpaceRequest, logger: Logger, onlyOfficeContext = false) {- let permission: SPACE_OPERATION- if (onlyOfficeContext && req.method === HTTP_METHOD.POST && req.originalUrl.startsWith(API_FILES_ONLY_OFFICE_CALLBACK)) {- // special case : onlyoffice callback use post method to update documents- permission = SPACE_OPERATION.MODIFY- } else {- permission = SPACE_HTTP_PERMISSION[req.method]- }+ static checkPermissions(req: FastifySpaceRequest, logger: Logger, overrideSpacePermission?: SPACE_OPERATION) {+ const permission = overrideSpacePermission || SPACE_HTTP_PERMISSION[req.method]if (!haveSpaceEnvPermissions(req.space, permission)) {logger.warn(`is not allowed to ${req.method} on this space path : *${req.space.alias}* (${req.space.id}) : ${req.space.url}`)throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)@@ -57,16 +51,16 @@ export class SpaceGuard implements CanActivate {}async canActivate(ctx: ExecutionContext): Promise<boolean> {- const skipSpaceGuard = this.reflector.getAllAndOverride(SKIP_SPACE_GUARD, [ctx.getHandler(), ctx.getClass()])- if (skipSpaceGuard) {+ if (this.reflector.getAllAndOverride(SKIP_SPACE_GUARD, [ctx.getHandler(), ctx.getClass()])) {return true}- const skipSpacePermissionsCheck = this.reflector.getAllAndOverride(SKIP_SPACE_PERMISSIONS_CHECK, [ctx.getHandler(), ctx.getClass()])+const req: FastifySpaceRequest = ctx.switchToHttp().getRequest()- const onlyOfficeContext = this.reflector.getAllAndOverride(ONLY_OFFICE_CONTEXT, [ctx.getHandler(), ctx.getClass()])const webDAVContext = this.reflector.getAllAndOverride(WEB_DAV_CONTEXT, [ctx.getHandler(), ctx.getClass()])const syncContext = this.reflector.getAllAndOverride(SYNC_CONTEXT, [ctx.getHandler(), ctx.getClass()])- const urlSegments = this.urlSegmentsFromContext(req, webDAVContext, syncContext)+ const collaboraOnlineContext = this.reflector.getAllAndOverride(COLLABORA_CONTEXT, [ctx.getHandler(), ctx.getClass()])++ const urlSegments = this.urlSegmentsFromContext(req, webDAVContext, syncContext, collaboraOnlineContext)this.checkAccessToSpace(req, urlSegments)let space: SpaceEnvtry {@@ -84,26 +78,28 @@ export class SpaceGuard implements CanActivate {}// assign space to requestreq.space = space+ const skipSpacePermissionsCheck = this.reflector.getAllAndOverride(SKIP_SPACE_PERMISSIONS_CHECK, [ctx.getHandler(), ctx.getClass()])if (skipSpacePermissionsCheck === undefined) {- SpaceGuard.checkPermissions(req, this.logger, onlyOfficeContext)+ const overrideSpacePermission: SPACE_OPERATION = this.reflector.getAllAndOverride(OverrideSpacePermission, [ctx.getHandler(), ctx.getClass()])+ SpaceGuard.checkPermissions(req, this.logger, overrideSpacePermission)}return true}- private urlSegmentsFromContext(req: FastifySpaceRequest, webDAVContext: boolean, syncContext: boolean): string[] {- if (webDAVContext || syncContext) {- try {- if (webDAVContext) {- return WEBDAV_PATH_TO_SPACE_SEGMENTS(req.params['*'])- } else {- return SYNC_PATH_TO_SPACE_SEGMENTS(req.params['*'])- }- } catch (e) {- this.logger.warn(`${this.canActivate.name} - ${e}`)- throw new HttpException(e.message, HttpStatus.NOT_FOUND)+ private urlSegmentsFromContext(req: FastifySpaceRequest, webDAVContext: boolean, syncContext: boolean, collaboraOnlineContext: boolean): string[] {+ try {+ if (webDAVContext) {+ return WEBDAV_PATH_TO_SPACE_SEGMENTS(req.params['*'])+ } else if (syncContext) {+ return SYNC_PATH_TO_SPACE_SEGMENTS(req.params['*'])+ } else if (collaboraOnlineContext) {+ return COLLABORA_ONLINE_TO_SPACE_SEGMENTS(req)}+ return PATH_TO_SPACE_SEGMENTS(req.params['*'])+ } catch (e) {+ this.logger.warn(`${this.canActivate.name} - ${e}`)+ throw new HttpException(e.message, HttpStatus.NOT_FOUND)}- return PATH_TO_SPACE_SEGMENTS(req.params['*'])}private checkAccessToSpace(req: FastifySpaceRequest, urlSegments: string[]) {diff --git a/backend/src/applications/webdav/services/webdav-methods.service.ts b/backend/src/applications/webdav/services/webdav-methods.service.tsindex 35ced70f..1d5a40db 100644--- a/backend/src/applications/webdav/services/webdav-methods.service.ts+++ b/backend/src/applications/webdav/services/webdav-methods.service.ts@@ -95,7 +95,7 @@ export class WebDAVMethods {if (ok) {// Locking unmapped URLs: must create an empty resource (that is not a collection)if (!rExists) {- // checkLocks set to false because the conflicts are already checked in `filesLockManager.create` method+ // checkLocks set to false because the conflicts are already checked in the `filesLockManager.create` methodawait this.filesManager.mkFile(req.user, req.space, false, false, false)}const lockProp = LOCK_PROP([fileLock])@@ -341,7 +341,7 @@ export class WebDAVMethods {space: dstSpace} as FastifyDAVRequestif (!(await this.evaluateIfHeaders(fakeDstReq, res))) {- // if there is an error the response is generated inside the `evaluateIfHeaders` function+ // if there is an error, the response is generated inside the `evaluateIfHeaders` functionreturn}try {diff --git a/backend/src/authentication/guards/auth-token-access.guard.ts b/backend/src/authentication/guards/auth-token-access.guard.tsindex c5955145..f145f241 100755--- a/backend/src/authentication/guards/auth-token-access.guard.ts+++ b/backend/src/authentication/guards/auth-token-access.guard.ts@@ -7,7 +7,8 @@import { ExecutionContext, Injectable, Logger } from '@nestjs/common'import { Reflector } from '@nestjs/core'import { AuthGuard, IAuthGuard } from '@nestjs/passport'-import { ONLY_OFFICE_CONTEXT } from '../../applications/files/constants/only-office'+import { COLLABORA_CONTEXT } from '../../applications/files/modules/collabora-online/collabora-online.constants'+import { ONLY_OFFICE_CONTEXT } from '../../applications/files/modules/only-office/only-office.constants'import { WEB_DAV_CONTEXT } from '../../applications/webdav/decorators/webdav-context.decorator'import { AUTH_TOKEN_SKIP } from '../decorators/auth-token-skip.decorator'@@ -23,7 +24,8 @@ export class AuthTokenAccessGuard extends AuthGuard('tokenAccess') implements IAconst authTokenSkip: boolean = this.reflector.getAllAndOverride<boolean>(AUTH_TOKEN_SKIP, [ctx.getHandler(), ctx.getClass()])const webDAVContext: boolean = this.reflector.getAllAndOverride<boolean>(WEB_DAV_CONTEXT, [ctx.getHandler(), ctx.getClass()])const onlyOfficeContext: boolean = this.reflector.getAllAndOverride<boolean>(ONLY_OFFICE_CONTEXT, [ctx.getHandler(), ctx.getClass()])- return authTokenSkip || webDAVContext || onlyOfficeContext || super.canActivate(ctx)+ const collaboraOnlineContext: boolean = this.reflector.getAllAndOverride<boolean>(COLLABORA_CONTEXT, [ctx.getHandler(), ctx.getClass()])+ return authTokenSkip || webDAVContext || onlyOfficeContext || collaboraOnlineContext || super.canActivate(ctx)}handleRequest<TUser = any>(err: any, user: any, info: Error, ctx: ExecutionContext, status?: any): TUser {diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yamlindex 7695f931..dd1d8c88 100755--- a/environment/environment.dist.yaml+++ b/environment/environment.dist.yaml@@ -161,6 +161,14 @@ applications:# If you use https, set to `true`.# default: `false`verifySSL: false+ collaboraOnline:+ # enable collabora online integration+ # default: false+ enabled: false+ # For an external server (e.g., https://collaboraonline.domain.com), remember the url must be accessible from browser!+ # If externalServer is empty (case of official docker compose), we use the local instance+ # default: null+ externalServer:appStore:# repository: `public` | `local`# default: `public`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.htmlindex 67894e8f..dc40a7b1 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@@ -25,7 +25,7 @@<b>{{ file?.lock?.owner }}</b>}</div>- @if (!isLockOwner && isFileOwner) {+ @if (hasExclusiveLock && !isLockOwner && isFileOwner) {<div class="text-align-center mt-3 mb-1"><small l10nTranslate>As the file owner, you can unlock the file or request the current lock owner to release it.</small></div>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.tsindex 10ca9189..20a6b338 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@@ -46,7 +46,7 @@ export class FilesLockDialogComponent implements OnInit {@HostListener('document:keyup.enter')async onEnter() {- if (this.isLockOwner) {+ if (this.isLockOwner || this.isFileOwner) {await this.onUnlock()} else {this.onSendUnLockRequest()@@ -61,8 +61,8 @@ export class FilesLockDialogComponent implements OnInit {async onUnlock() {try {this.submitted = true- await firstValueFrom(this.filesService.unlock(this.file, !this.isLockOwner))- delete this.file.lock+ await firstValueFrom(this.filesService.unlock(this.file, this.isFileOwner))+ this.file.removeLock()this.layout.closeDialog()} catch (e: any) {this.submitted = falsediff --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 257a6d5c..23936add 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@@ -25,7 +25,14 @@<app-files-viewer-media [currentHeight]="currentHeight" [fileUrl]="currentFile.dataUrl"></app-files-viewer-media>}@case (SHORT_MIME.DOCUMENT) {- <app-files-viewer-document [currentHeight]="currentHeight" [file]="currentFile" [mode]="mode"></app-files-viewer-document>+ @if (store.fileSettings().editor.collaboraOnline) {+ <app-files-viewer-collabora-online [currentHeight]="currentHeight" [file]="currentFile" [mode]="mode"></app-files-viewer-collabora-online>+ } @else if (store.fileSettings().editor.onlyOffice) {+ <app-files-viewer-only-office [currentHeight]="currentHeight" [file]="currentFile" [mode]="mode"></app-files-viewer-only-office>+ } @else {+ <!--This case should never happen-->+ <div [style.height.px]="currentHeight" class="d-flex p-4" l10nTranslate>No editor found</div>+ }}@default {<app-files-viewer-textdiff --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 faaf15d3..1ef80b46 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@@ -8,13 +8,16 @@ import { Component, computed, inject, Input, model, OnDestroy, OnInit, signal }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'+import { L10nTranslateDirective } from 'angular-l10n'import { Subscription } from 'rxjs'import { LayoutService } from '../../../../layout/layout.service'+import { StoreService } from '../../../../store/store.service'import { SHORT_MIME } from '../../files.constants'import { FileModel } from '../../models/file.model'-import { FilesViewerDocumentComponent } from '../viewers/files-viewer-document.component'+import { FilesViewerCollaboraOnlineComponent } from '../viewers/files-viewer-collabora-online.component'import { FilesViewerImageComponent } from '../viewers/files-viewer-image.component'import { FilesViewerMediaComponent } from '../viewers/files-viewer-media.component'+import { FilesViewerOnlyOfficeComponent } from '../viewers/files-viewer-only-office.component'import { FilesViewerPdfComponent } from '../viewers/files-viewer-pdf.component'import { FilesViewerTextComponent } from '../viewers/files-viewer-text.component'@@ -24,9 +27,11 @@ import { FilesViewerTextComponent } from '../viewers/files-viewer-text.componentFilesViewerPdfComponent,FilesViewerMediaComponent,FilesViewerTextComponent,- FilesViewerDocumentComponent,FilesViewerImageComponent,- FaIconComponent+ FaIconComponent,+ FilesViewerOnlyOfficeComponent,+ FilesViewerCollaboraOnlineComponent,+ L10nTranslateDirective],templateUrl: 'files-viewer-dialog.component.html'})@@ -43,6 +48,7 @@ export class FilesViewerDialogComponent implements OnInit, OnDestroy {protected readonly icons = { faEye, faPen }protected directoryImages = computed(() => this.directoryFiles.filter((file) => file.isImage))private openedFile: { id: string | number; name: string; mimeUrl: string }+ protected readonly store = inject(StoreService)private readonly layout = inject(LayoutService)private readonly subscription: Subscription = this.layout.resizeEvent.subscribe(() => this.onResize())private readonly offsetTop = 42diff --git a/frontend/src/app/applications/files/components/utils/only-office.component.ts b/frontend/src/app/applications/files/components/utils/only-office.component.tsindex c039233b..88f69168 100644--- a/frontend/src/app/applications/files/components/utils/only-office.component.ts+++ b/frontend/src/app/applications/files/components/utils/only-office.component.ts@@ -5,7 +5,7 @@*/import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges } from '@angular/core'-import type { OnlyOfficeConfig } from '@sync-in-server/backend/src/applications/files/interfaces/only-office-config.interface'+import type { OnlyOfficeConfig } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.interface'import loadScript from './only-office.utils'@Component({@@ -16,7 +16,7 @@ export class OnlyOfficeComponent implements OnInit, OnChanges, OnDestroy {@Input() id: string@Input() documentServerUrl: string@Input() config: OnlyOfficeConfig- @Output() loadError = new EventEmitter<string>()+ @Output() loadError = new EventEmitter<{ title: string; message: string }>()@Output() wasSaved = new EventEmitter<string>()private isFirstOnChanges = true@@ -81,20 +81,19 @@ export class OnlyOfficeComponent implements OnInit, OnChanges, OnDestroy {}private onError(errorCode: number) {- let message: string+ const error = { title: 'Unknown OnlyOffice error', message: `Code: ${errorCode}` }switch (errorCode) {case -2:- message = 'Check the settings'+ error.title = 'Unable to load OnlyOffice editor'+ error.message = 'The document server may be unreachable or the configuration is invalid'breakcase -3:- message = 'DocsAPI is not defined'+ error.title = 'OnlyOffice editor failed to initialize'+ error.message = 'DocsAPI not available'break- default:- message = 'Unknown error !'- errorCode = -1}- this.loadError.emit(message)+ this.loadError.emit(error)}}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.tsnew file mode 100644index 00000000..9b430f3c--- /dev/null+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-collabora-online.component.ts@@ -0,0 +1,72 @@+/*+ * 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 { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'+import { Component, inject, input, Input, 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 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'++@Component({+ selector: 'app-files-viewer-collabora-online',+ template: `+ @if (documentServerUrl) {+ <iframe+ [src]="documentServerUrl"+ [style.height.px]="currentHeight()"+ class="app-viewer-iframe"+ allow="clipboard-read *; clipboard-write *; fullscreen"+ ></iframe>+ }+ `+})+export class FilesViewerCollaboraOnlineComponent implements OnInit, OnDestroy {+ @Input({ required: true }) file: FileModel+ @Input({ required: true }) mode: FILE_MODE+ currentHeight = input<number>()+ protected documentServerUrl: SafeResourceUrl = null+ private readonly http = inject(HttpClient)+ private readonly layout = inject(LayoutService)+ private readonly store = inject(StoreService)+ private readonly sanitizer = inject(DomSanitizer)++ ngOnInit() {+ this.http+ .get<CollaboraOnlineReqDto>(`${API_COLLABORA_ONLINE_SETTINGS}/${this.file.path}`, { params: new HttpParams().set('mode', this.mode) })+ .subscribe({+ next: (data) => {+ if (!data) {+ this.layout.closeDialog()+ this.layout.sendNotification('error', 'Unable to open document', 'Settings are missing')+ return+ }+ if (data.mode === FILE_MODE.EDIT) {+ // 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,+ isExclusive: false+ })+ }+ this.documentServerUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`${data.documentServerUrl}&lang=${this.layout.getCurrentLanguage()}`)+ },+ error: (e: HttpErrorResponse) => {+ this.layout.closeDialog()+ this.layout.sendNotification('error', 'Unable to open document', e.error.message)+ }+ })+ }++ ngOnDestroy() {+ // Remove lock+ this.file.removeLock()+ }+}diff --git a/frontend/src/app/applications/files/components/viewers/files-viewer-document.component.ts b/frontend/src/app/applications/files/components/viewers/files-viewer-document.component.tsdeleted file mode 100644index 2537b9ed..00000000--- a/frontend/src/app/applications/files/components/viewers/files-viewer-document.component.ts+++ /dev/null@@ -1,103 +0,0 @@-/*- * 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 { HttpClient, HttpParams } from '@angular/common/http'-import { Component, inject, input, Input, OnDestroy, OnInit } from '@angular/core'-import { FILE_MODE } from '@sync-in-server/backend/src/applications/files/constants/operations'-import { API_FILES_ONLY_OFFICE_SETTINGS } from '@sync-in-server/backend/src/applications/files/constants/routes'-import type { FileLockProps } from '@sync-in-server/backend/src/applications/files/interfaces/file-props.interface'-import type { OnlyOfficeReqConfig } from '@sync-in-server/backend/src/applications/files/interfaces/only-office-config.interface'-import { SERVER_NAME } from '@sync-in-server/backend/src/common/shared'-import { LayoutService } from '../../../../layout/layout.service'-import { StoreService } from '../../../../store/store.service'-import { FileModel } from '../../models/file.model'-import { OnlyOfficeComponent } from '../utils/only-office.component'--@Component({- selector: 'app-files-viewer-document',- imports: [OnlyOfficeComponent],- styles: [- `- // fix onlyoffice iframe blinking when we hide and show via the windows manager- .doc-placeholder {- display: none !important;- }- `- ],- template: `- @if (documentConfig) {- <div [style.height.px]="currentHeight()">- <app-files-onlyoffice-document- [id]="docId"- [documentServerUrl]="documentConfig.documentServerUrl"- [config]="documentConfig.config"- (loadError)="loadError($event)"- (wasSaved)="onSave()"- ></app-files-onlyoffice-document>- </div>- }- `-})-export class FilesViewerDocumentComponent implements OnInit, OnDestroy {- @Input({ required: true }) file: FileModel- @Input({ required: true }) mode: FILE_MODE- currentHeight = input<number>()- protected docId: string- protected documentConfig: OnlyOfficeReqConfig = null- private readonly http = inject(HttpClient)- private readonly layout = inject(LayoutService)- private readonly store = inject(StoreService)-- ngOnInit() {- this.docId = `viewer-doc-${this.file.id}`- this.http- .get<OnlyOfficeReqConfig>(`${API_FILES_ONLY_OFFICE_SETTINGS}/${this.file.path}`, { params: new HttpParams().set('mode', this.mode) })- .subscribe({- next: (data) => {- if (!data) {- this.layout.closeDialog()- this.layout.sendNotification('error', 'Unable to open document', 'Settings are missing')- return- }- // Do not allow edit if backend only allows 'view' mode- if (this.mode === FILE_MODE.EDIT && data.config.editorConfig.mode !== FILE_MODE.EDIT) {- data.config.editorConfig.mode = FILE_MODE.VIEW- } else {- data.config.editorConfig.mode = this.mode- }- if (this.mode === FILE_MODE.EDIT) {- // Set lock on file- this.file.lock = {- owner: `${SERVER_NAME} - ${this.store.user.getValue().fullName} (${this.store.user.getValue().email})`,- ownerLogin: this.store.user.getValue().login,- isExclusive: false- } satisfies FileLockProps- }- data.config.editorConfig.lang = this.layout.getCurrentLanguage()- data.config.editorConfig.region = this.layout.getCurrentLanguage()- this.documentConfig = data- },- error: (e) => {- this.layout.closeDialog()- this.layout.sendNotification('error', 'Unable to open document', e.error.message)- }- })- }-- ngOnDestroy() {- // remove lock- this.file.lock = null- }-- loadError(errorMessage: string): void {- this.layout.closeDialog()- this.layout.sendNotification('error', 'Unable to open document', errorMessage)- }-- onSave() {- this.file.updateHTimeAgo()- }-}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.tsnew file mode 100644index 00000000..bfca1b5f--- /dev/null+++ b/frontend/src/app/applications/files/components/viewers/files-viewer-only-office.component.ts@@ -0,0 +1,94 @@+/*+ * 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 { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'+import { Component, inject, input, Input, 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 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 { OnlyOfficeComponent } from '../utils/only-office.component'++@Component({+ selector: 'app-files-viewer-only-office',+ imports: [OnlyOfficeComponent],+ styles: [+ `+ // fix onlyoffice iframe blinking when we hide and show via the windows manager+ .doc-placeholder {+ display: none !important;+ }+ `+ ],+ template: `+ @if (documentConfig) {+ <div [style.height.px]="currentHeight()">+ <app-files-onlyoffice-document+ [id]="docId"+ [documentServerUrl]="documentConfig.documentServerUrl"+ [config]="documentConfig.config"+ (loadError)="loadError($event)"+ (wasSaved)="onSave()"+ ></app-files-onlyoffice-document>+ </div>+ }+ `+})+export class FilesViewerOnlyOfficeComponent implements OnInit, OnDestroy {+ @Input({ required: true }) file: FileModel+ @Input({ required: true }) mode: FILE_MODE+ currentHeight = input<number>()+ protected docId: string+ protected documentConfig: OnlyOfficeReqDto = null+ private readonly http = inject(HttpClient)+ private readonly layout = inject(LayoutService)+ private readonly store = inject(StoreService)++ ngOnInit() {+ this.docId = `viewer-doc-${this.file.id}`+ this.http.get<OnlyOfficeReqDto>(`${API_ONLY_OFFICE_SETTINGS}/${this.file.path}`, { params: new HttpParams().set('mode', this.mode) }).subscribe({+ next: (data) => {+ if (!data) {+ this.layout.closeDialog()+ this.layout.sendNotification('error', 'Unable to open document', 'Settings are missing')+ return+ }+ if (data.config.editorConfig.mode === FILE_MODE.EDIT) {+ // 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,+ isExclusive: false+ })+ }+ data.config.editorConfig.lang = this.layout.getCurrentLanguage()+ data.config.editorConfig.region = data.config.editorConfig.lang+ this.documentConfig = data+ },+ error: (e: HttpErrorResponse) => {+ this.layout.closeDialog()+ this.layout.sendNotification('error', 'Unable to open document', e.error.message)+ }+ })+ }++ ngOnDestroy() {+ // Remove lock+ this.file.removeLock()+ }++ loadError(e: { title: string; message: string }): void {+ this.layout.closeDialog()+ this.layout.sendNotification('error', e.title, e.message)+ }++ onSave() {+ this.file.updateHTimeAgo()+ }+}diff --git a/frontend/src/app/applications/files/models/file.model.ts b/frontend/src/app/applications/files/models/file.model.tsindex 828922a6..26d63741 100644--- a/frontend/src/app/applications/files/models/file.model.ts+++ b/frontend/src/app/applications/files/models/file.model.ts@@ -4,13 +4,13 @@* See the LICENSE file for licensing details*/-import { ONLY_OFFICE_EXTENSIONS } from '@sync-in-server/backend/src/applications/files/constants/only-office'import {API_FILES_OPERATION,API_FILES_OPERATION_THUMBNAIL,API_FILES_TASK_OPERATION} from '@sync-in-server/backend/src/applications/files/constants/routes'import type { FileLockProps, FileProps } from '@sync-in-server/backend/src/applications/files/interfaces/file-props.interface'+import { ONLY_OFFICE_EXTENSIONS } from '@sync-in-server/backend/src/applications/files/modules/only-office/only-office.constants'import type { File } from '@sync-in-server/backend/src/applications/files/schemas/file.interface'import { SPACE_OPERATION } from '@sync-in-server/backend/src/applications/spaces/constants/spaces'import { currentTimeStamp, popFromObject } from '@sync-in-server/backend/src/common/shared'@@ -130,6 +130,14 @@ export class FileModel implements File {this.newly = getNewly(mtime)}+ createLock(lock: FileLockProps) {+ this.lock = lock+ }++ removeLock() {+ this.lock = null+ }+private getType(inShare: boolean) {return this.isDir ? (inShare ? mimeDirectoryShare : mimeDirectory) : mimeFile}diff --git a/frontend/src/app/applications/files/services/files.service.ts b/frontend/src/app/applications/files/services/files.service.tsindex ac026d05..4df2fab9 100644--- a/frontend/src/app/applications/files/services/files.service.ts+++ b/frontend/src/app/applications/files/services/files.service.ts@@ -8,13 +8,13 @@ import type { TreeNode } from '@ali-hm/angular-tree-component'import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'import { inject, Injectable } from '@angular/core'import { DomSanitizer } from '@angular/platform-browser'-import { FILE_MODE, FILE_OPERATION } from '@sync-in-server/backend/src/applications/files/constants/operations'+import { FILE_MODE, FILE_OPERATION, FORCE_AS_FILE_OWNER } from '@sync-in-server/backend/src/applications/files/constants/operations'import {- API_FILES_ONLY_OFFICE_STATUS,API_FILES_OPERATION,API_FILES_OPERATION_MAKE,API_FILES_RECENTS,API_FILES_SEARCH,+ API_FILES_SETTINGS,API_FILES_TASK_OPERATION_COMPRESS,API_FILES_TASK_OPERATION_DECOMPRESS,API_FILES_TASK_OPERATION_DOWNLOAD,@@ -28,6 +28,7 @@ import type {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 { FileSettings } from '@sync-in-server/backend/src/applications/files/interfaces/file-settings.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'@@ -224,8 +225,8 @@ export class FilesService {return this.http.request<FileLockProps>(FILE_OPERATION.LOCK, file.dataUrl)}- unlock(file: FileModel, forceAsOwner = false): Observable<void> {- const params = forceAsOwner ? new HttpParams().set('forceAsOwner', 'true') : null+ unlock(file: FileModel, forceAsFileOwner = false): Observable<void> {+ const params = forceAsFileOwner ? new HttpParams().set(FORCE_AS_FILE_OWNER, 'true') : nullreturn this.http.request<void>(FILE_OPERATION.UNLOCK, file.dataUrl, { params: params })}@@ -264,7 +265,7 @@ export class FilesService {try {hookedShortMime = await this.viewerHook(mode, file)} catch {- // OnlyOffice isn't enabled, falling back to download+ // No office editors are enabled, falling back to downloadthis.download(file)return}@@ -294,33 +295,33 @@ export class FilesService {}private async viewerHook(mode: FILE_MODE, file: FileModel): Promise<string> {- const onlyOfficeEnabled = await this.getOnlyOfficeStatus()- if (file.shortMime === SHORT_MIME.DOCUMENT && !onlyOfficeEnabled) {+ const fileSettings = await this.getFileSettings()+ const hasEnabledOfficeEditor = fileSettings ? fileSettings.editor.onlyOffice || fileSettings.editor.collaboraOnline : false+ if (file.shortMime === SHORT_MIME.DOCUMENT && !hasEnabledOfficeEditor) {if (file.mime.startsWith('text-')) {return SHORT_MIME.TEXT}- throw new Error('Feature not enabled')+ throw new Error('No editor found')}if (file.shortMime === SHORT_MIME.PDF) {- if (mode === FILE_MODE.EDIT && onlyOfficeEnabled) {+ if (mode === FILE_MODE.EDIT && hasEnabledOfficeEditor) {return SHORT_MIME.DOCUMENT}}return file.shortMime}- private async getOnlyOfficeStatus(): Promise<boolean> {- if (this.store.filesOnlyOffice().enabled !== null) {- return this.store.filesOnlyOffice().enabled+ private async getFileSettings(): Promise<FileSettings | false> {+ if (this.store.fileSettings() !== null) {+ return this.store.fileSettings()}try {- const status = await firstValueFrom(this.http.get<{ enabled: boolean }>(API_FILES_ONLY_OFFICE_STATUS))- this.store.filesOnlyOffice.set(status)- return status.enabled+ const settings = await firstValueFrom(this.http.get<FileSettings>(API_FILES_SETTINGS))+ this.store.fileSettings.set(settings)+ return settings} catch {- const fallback = { enabled: false }- this.store.filesOnlyOffice.set(fallback)- return fallback.enabled+ this.store.fileSettings.set(null)+ return false}}diff --git a/frontend/src/app/store/store.service.ts b/frontend/src/app/store/store.service.tsindex 89de3d21..90674944 100644--- a/frontend/src/app/store/store.service.ts+++ b/frontend/src/app/store/store.service.ts@@ -6,6 +6,7 @@import { computed, Injectable, Signal, signal, WritableSignal } from '@angular/core'import type { SearchFilesDto } from '@sync-in-server/backend/src/applications/files/dto/file-operations.dto'+import type { FileSettings } from '@sync-in-server/backend/src/applications/files/interfaces/file-settings.interface'import type { FileTask } from '@sync-in-server/backend/src/applications/files/models/file-task'import { AppStoreManifest } from '@sync-in-server/backend/src/applications/sync/interfaces/store-manifest.interface'import type { ServerConfig } from '@sync-in-server/backend/src/configuration/config.interfaces'@@ -44,8 +45,8 @@ export class StoreService {public filesActiveTasks = new BehaviorSubject<FileTask[]>([])public filesEndedTasks = new BehaviorSubject<FileTask[]>([])public filesRecents: WritableSignal<FileRecentModel[]> = signal<FileRecentModel[]>([])- // OnlyOffice- public filesOnlyOffice: WritableSignal<{ enabled: boolean }> = signal({ enabled: null })+ // File Settings+ public fileSettings: WritableSignal<FileSettings> = signal(null)// Searchpublic currentSearch: WritableSignal<SearchFilesDto> = signal<SearchFilesDto>({ content: '', fullText: false })public filesSearch: WritableSignal<FileContentModel[]> = signal<FileContentModel[]>([])diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.jsonindex 7efa0419..84a70188 100644--- a/frontend/src/i18n/de.json+++ b/frontend/src/i18n/de.json@@ -565,7 +565,6 @@"remote": "entfernt","System requirements": "Systemanforderungen","Feature not enabled": "Funktion nicht aktiviert",- "Check the settings": "Überprüfen Sie die Einstellungen","Website": "Website","Documentation": "Dokumentation","Versions": "Versionen",@@ -619,5 +618,11 @@"A new update is available": "Ein neues Update ist verfügbar","Fullscreen": "Vollbild","Dimensions": "Abmessungen",- "Start Slideshow": "Diashow starten"+ "Start Slideshow": "Diashow starten",+ "Unable to load OnlyOffice editor": "OnlyOffice‑Editor konnte nicht geladen werden",+ "The document server may be unreachable or the configuration is invalid": "Der Dokumentenserver ist möglicherweise nicht erreichbar oder die Konfiguration ist ungültig",+ "OnlyOffice editor failed to initialize": "Initialisierung des OnlyOffice‑Editors ist fehlgeschlagen",+ "DocsAPI not available": "DocsAPI ist nicht verfügbar",+ "Unknown OnlyOffice error": "Unbekannter OnlyOffice‑Fehler",+ "No editor found": "Kein Editor gefunden"}\ No newline at end of filediff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.jsonindex 405c382b..39236d7a 100644--- a/frontend/src/i18n/es.json+++ b/frontend/src/i18n/es.json@@ -565,7 +565,6 @@"remote": "remoto","System requirements": "Requisitos del sistema","Feature not enabled": "Funcionalidad no habilitada",- "Check the settings": "Verifique la configuración","Website": "Sitio web","Documentation": "Documentación","Versions": "Versiones",@@ -619,5 +618,11 @@"A new update is available": "Hay una nueva actualización disponible","Fullscreen": "Pantalla completa","Dimensions": "Dimensiones",- "Start Slideshow": "Iniciar presentación"+ "Start Slideshow": "Iniciar presentación",+ "Unable to load OnlyOffice editor": "No se pudo cargar el editor de OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "Es posible que el servidor de documentos no sea accesible o que la configuración sea inválida",+ "OnlyOffice editor failed to initialize": "No se pudo inicializar el editor de OnlyOffice",+ "DocsAPI not available": "DocsAPI no está disponible",+ "Unknown OnlyOffice error": "Error desconocido de OnlyOffice",+ "No editor found": "No se encontró un editor"}\ No newline at end of filediff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.jsonindex 6ad99f46..3976bb0e 100644--- a/frontend/src/i18n/fr.json+++ b/frontend/src/i18n/fr.json@@ -565,7 +565,6 @@"remote": "distant","System requirements": "Configuration requise","Feature not enabled": "Fonctionnalité non activée",- "Check the settings": "Vérifiez les paramètres","Website": "Site Web","Documentation": "Documentation","Versions": "Versions",@@ -619,5 +618,11 @@"A new update is available": "Une nouvelle mise à jour est disponible","Fullscreen": "Plein écran","Dimensions": "Dimensions",- "Start Slideshow": "Démarrer le diaporama"+ "Start Slideshow": "Démarrer le diaporama",+ "Unable to load OnlyOffice editor": "Impossible de charger l’éditeur OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "Le serveur de documents est peut-être injoignable ou la configuration est invalide",+ "OnlyOffice editor failed to initialize": "Échec de l’initialisation de l’éditeur OnlyOffice",+ "DocsAPI not available": "DocsAPI n’est pas disponible",+ "Unknown OnlyOffice error": "Erreur OnlyOffice inconnue",+ "No editor found": "Aucun éditeur trouvé"}\ No newline at end of filediff --git a/frontend/src/i18n/hi.json b/frontend/src/i18n/hi.jsonindex 8f085332..3cecc69a 100644--- a/frontend/src/i18n/hi.json+++ b/frontend/src/i18n/hi.json@@ -565,7 +565,6 @@"remote": "दूरस्थ","System requirements": "सिस्टम आवश्यकताएँ","Feature not enabled": "विशेषता सक्षम नहीं है",- "Check the settings": "सेटिंग्स जाँचें","Website": "वेबसाइट","Documentation": "दस्तावेज़ीकरण","Versions": "संस्करण",@@ -619,5 +618,11 @@"A new update is available": "एक नया अपडेट उपलब्ध है","Fullscreen": "पूर्ण स्क्रीन","Dimensions": "आयाम",- "Start Slideshow": "स्लाइड शो शुरू करें"+ "Start Slideshow": "स्लाइड शो शुरू करें",+ "Unable to load OnlyOffice editor": "OnlyOffice संपादक लोड नहीं हो सका",+ "The document server may be unreachable or the configuration is invalid": "दस्तावेज़ सर्वर उपलब्ध नहीं हो सकता या विन्यास अमान्य है",+ "OnlyOffice editor failed to initialize": "OnlyOffice संपादक प्रारंभ करने में विफल रहा",+ "DocsAPI not available": "DocsAPI उपलब्ध नहीं है",+ "Unknown OnlyOffice error": "अज्ञात OnlyOffice त्रुटि",+ "No editor found": "संपादक नहीं मिला"}\ No newline at end of filediff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.jsonindex a24eb4c7..8d091c7a 100644--- a/frontend/src/i18n/it.json+++ b/frontend/src/i18n/it.json@@ -565,7 +565,6 @@"remote": "remoto","System requirements": "Requisiti di sistema","Feature not enabled": "Funzionalità non abilitata",- "Check the settings": "Controlla le impostazioni","Website": "Sito web","Documentation": "Documentazione","Versions": "Versioni",@@ -619,5 +618,11 @@"A new update is available": "È disponibile un nuovo aggiornamento","Fullscreen": "Schermo intero","Dimensions": "Dimensioni",- "Start Slideshow": "Avvia presentazione"+ "Start Slideshow": "Avvia presentazione",+ "Unable to load OnlyOffice editor": "Impossibile caricare l’editor OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "Il server dei documenti potrebbe non essere raggiungibile o la configurazione non è valida",+ "OnlyOffice editor failed to initialize": "Impossibile inizializzare l’editor OnlyOffice",+ "DocsAPI not available": "DocsAPI non è disponibile",+ "Unknown OnlyOffice error": "Errore sconosciuto di OnlyOffice",+ "No editor found": "Nessun editor trovato"}\ No newline at end of filediff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.jsonindex 443c0afe..daf74272 100644--- a/frontend/src/i18n/ja.json+++ b/frontend/src/i18n/ja.json@@ -565,7 +565,6 @@"remote": "リモート","System requirements": "システム要件","Feature not enabled": "機能が有効ではありません",- "Check the settings": "設定を確認","Website": "ウェブサイト","Documentation": "ドキュメント","Versions": "バージョン",@@ -619,5 +618,11 @@"A new update is available": "新しいアップデートが利用可能です","Fullscreen": "全画面表示","Dimensions": "サイズ",- "Start Slideshow": "スライドショーを開始"+ "Start Slideshow": "スライドショーを開始",+ "Unable to load OnlyOffice editor": "OnlyOffice エディタを読み込めませんでした",+ "The document server may be unreachable or the configuration is invalid": "ドキュメントサーバーに接続できないか、設定が無効です",+ "OnlyOffice editor failed to initialize": "OnlyOffice エディタの初期化に失敗しました",+ "DocsAPI not available": "DocsAPI を利用できません",+ "Unknown OnlyOffice error": "不明な OnlyOffice エラーです",+ "No editor found": "エディタが見つかりません"}\ No newline at end of filediff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.jsonindex c70f7bad..f931fa35 100644--- a/frontend/src/i18n/ko.json+++ b/frontend/src/i18n/ko.json@@ -565,7 +565,6 @@"remote": "원격","System requirements": "시스템 요구 사항","Feature not enabled": "기능이 활성화되어 있지 않습니다",- "Check the settings": "설정을 확인하세요","Website": "웹사이트","Documentation": "문서","Versions": "버전",@@ -619,5 +618,11 @@"A new update is available": "새로운 업데이트가 이용 가능합니다","Fullscreen": "전체 화면","Dimensions": "크기",- "Start Slideshow": "슬라이드 쇼 시작"+ "Start Slideshow": "슬라이드 쇼 시작",+ "Unable to load OnlyOffice editor": "OnlyOffice 편집기를 불러올 수 없습니다",+ "The document server may be unreachable or the configuration is invalid": "문서 서버에 연결할 수 없거나 설정이 잘못되었습니다",+ "OnlyOffice editor failed to initialize": "OnlyOffice 편집기 초기화에 실패했습니다",+ "DocsAPI not available": "DocsAPI 를 사용할 수 없습니다",+ "Unknown OnlyOffice error": "알 수 없는 OnlyOffice 오류",+ "No editor found": "편집기를 찾을 수 없습니다"}\ No newline at end of filediff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.jsonindex ca04c55f..b8afee5b 100644--- a/frontend/src/i18n/pl.json+++ b/frontend/src/i18n/pl.json@@ -565,7 +565,6 @@"remote": "zdalne","System requirements": "Wymagania systemowe","Feature not enabled": "Funkcja nie jest włączona",- "Check the settings": "Sprawdź ustawienia","Website": "Strona internetowa","Documentation": "Dokumentacja","Versions": "Wersje",@@ -619,5 +618,11 @@"A new update is available": "Dostępna jest nowa aktualizacja","Fullscreen": "Pełny ekran","Dimensions": "Wymiary",- "Start Slideshow": "Uruchom pokaz slajdów"+ "Start Slideshow": "Uruchom pokaz slajdów",+ "Unable to load OnlyOffice editor": "Nie można załadować edytora OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "Serwer dokumentów może być niedostępny lub konfiguracja jest nieprawidłowa",+ "OnlyOffice editor failed to initialize": "Nie udało się zainicjować edytora OnlyOffice",+ "DocsAPI not available": "DocsAPI jest niedostępne",+ "Unknown OnlyOffice error": "Nieznany błąd OnlyOffice",+ "No editor found": "Nie znaleziono edytora"}\ No newline at end of filediff --git a/frontend/src/i18n/pt-BR.json b/frontend/src/i18n/pt-BR.jsonindex 8906c74a..01307b73 100644--- a/frontend/src/i18n/pt-BR.json+++ b/frontend/src/i18n/pt-BR.json@@ -565,7 +565,6 @@"remote": "remoto","System requirements": "Requisitos do sistema","Feature not enabled": "Recurso não habilitado",- "Check the settings": "Verifique as configurações","Website": "Site","Documentation": "Documentação","Versions": "Versões",@@ -619,5 +618,11 @@"A new update is available": "Uma nova atualização está disponível","Fullscreen": "Tela cheia","Dimensions": "Dimensões",- "Start Slideshow": "Iniciar apresentação de slides"+ "Start Slideshow": "Iniciar apresentação de slides",+ "Unable to load OnlyOffice editor": "Não foi possível carregar o editor OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "O servidor de documentos pode estar inacessível ou a configuração é inválida",+ "OnlyOffice editor failed to initialize": "Falha ao inicializar o editor OnlyOffice",+ "DocsAPI not available": "DocsAPI não está disponível",+ "Unknown OnlyOffice error": "Erro desconhecido do OnlyOffice",+ "No editor found": "Nenhum editor encontrado"}\ No newline at end of filediff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.jsonindex b1f40530..408a55fd 100644--- a/frontend/src/i18n/pt.json+++ b/frontend/src/i18n/pt.json@@ -565,7 +565,6 @@"remote": "remoto","System requirements": "Requisitos do sistema","Feature not enabled": "Funcionalidade não habilitada",- "Check the settings": "Verifique as configurações","Website": "Site","Documentation": "Documentação","Versions": "Versões",@@ -619,5 +618,11 @@"A new update is available": "Está disponível uma nova atualização","Fullscreen": "Tela cheia","Dimensions": "Dimensões",- "Start Slideshow": "Iniciar apresentação de slides"+ "Start Slideshow": "Iniciar apresentação de slides",+ "Unable to load OnlyOffice editor": "Não foi possível carregar o editor OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "O servidor de documentos pode estar inacessível ou a configuração é inválida",+ "OnlyOffice editor failed to initialize": "Falha ao inicializar o editor OnlyOffice",+ "DocsAPI not available": "DocsAPI não está disponível",+ "Unknown OnlyOffice error": "Erro desconhecido do OnlyOffice",+ "No editor found": "Nenhum editor encontrado"}\ No newline at end of filediff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.jsonindex 0f6be01d..b155eb45 100644--- a/frontend/src/i18n/ru.json+++ b/frontend/src/i18n/ru.json@@ -565,7 +565,6 @@"remote": "удалённый","System requirements": "Системные требования","Feature not enabled": "Функция не включена",- "Check the settings": "Проверьте настройки","Website": "Сайт","Documentation": "Документация","Versions": "Версии",@@ -619,5 +618,11 @@"A new update is available": "Доступно новое обновление","Fullscreen": "Полный экран","Dimensions": "Размеры",- "Start Slideshow": "Запустить слайд‑шоу"+ "Start Slideshow": "Запустить слайд‑шоу",+ "Unable to load OnlyOffice editor": "Не удалось загрузить редактор OnlyOffice",+ "The document server may be unreachable or the configuration is invalid": "Сервер документов может быть недоступен или конфигурация неверна",+ "OnlyOffice editor failed to initialize": "Не удалось инициализировать редактор OnlyOffice",+ "DocsAPI not available": "DocsAPI недоступен",+ "Unknown OnlyOffice error": "Неизвестная ошибка OnlyOffice",+ "No editor found": "Редактор не найден"}\ No newline at end of filediff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.jsonindex 8d55bc92..53496eaf 100644--- a/frontend/src/i18n/tr.json+++ b/frontend/src/i18n/tr.json@@ -565,7 +565,6 @@"remote": "uzak","System requirements": "Sistem gereksinimleri","Feature not enabled": "Özellik etkin değil",- "Check the settings": "Ayarları kontrol edin","Website": "Web sitesi","Documentation": "Dokümantasyon","Versions": "Sürümler",@@ -619,5 +618,11 @@"A new update is available": "Yeni bir güncelleme mevcut","Fullscreen": "Tam ekran","Dimensions": "Boyutlar",- "Start Slideshow": "Slayt gösterisini başlat"+ "Start Slideshow": "Slayt gösterisini başlat",+ "Unable to load OnlyOffice editor": "OnlyOffice düzenleyici yüklenemedi",+ "The document server may be unreachable or the configuration is invalid": "Belge sunucusuna ulaşılamıyor olabilir veya yapılandırma geçersiz",+ "OnlyOffice editor failed to initialize": "OnlyOffice düzenleyici başlatılamadı",+ "DocsAPI not available": "DocsAPI kullanılamıyor",+ "Unknown OnlyOffice error": "Bilinmeyen OnlyOffice hatası",+ "No editor found": "Düzenleyici bulunamadı"}\ No newline at end of filediff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.jsonindex 8e1e8fa2..17a4c3f0 100644--- a/frontend/src/i18n/zh.json+++ b/frontend/src/i18n/zh.json@@ -565,7 +565,6 @@"remote": "远程","System requirements": "系统要求","Feature not enabled": "功能未启用",- "Check the settings": "检查设置","Website": "网站","Documentation": "文档","Versions": "版本",@@ -619,5 +618,11 @@"A new update is available": "有可用的新更新","Fullscreen": "全屏","Dimensions": "尺寸",- "Start Slideshow": "开始幻灯片放映"+ "Start Slideshow": "开始幻灯片放映",+ "Unable to load OnlyOffice editor": "无法加载 OnlyOffice 编辑器",+ "The document server may be unreachable or the configuration is invalid": "文档服务器可能无法访问,或者配置无效",+ "OnlyOffice editor failed to initialize": "OnlyOffice 编辑器初始化失败",+ "DocsAPI not available": "DocsAPI 不可用",+ "Unknown OnlyOffice error": "未知的 OnlyOffice 错误",+ "No editor found": "未找到编辑器"}\ No newline at end of file