Skip to content

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

9.4 KB
Raw Blame
import { HttpException, HttpStatus, Injectable, Logger, StreamableFile } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import path from 'node:path'
import { toErrorMessage } from '../../../common/errors.js'
import { FastifySpaceRequest } from '../../spaces/interfaces/space-request.interface.js'
import { SpaceEnv } from '../../spaces/models/space-env.model.js'
import { SpacesManager } from '../../spaces/services/spaces-manager.service.js'
import { UserModel } from '../../users/models/user.model.js'
import { FILE_OPERATION } from '../constants/operations.js'
import type { CompressFileDto, DownloadFileDto, MakeFileDto, ValidatedCopyMoveFileDto } from '../dto/file-operations.dto.js'
import type { CopyMoveFileResponse } from '../interfaces/copy-move-file.interface.js'
import { FileLockProps } from '../interfaces/file-props.interface.js'
import type { FileThumbnail } from '../interfaces/file-thumbnail.interface.js'
import { FileError } from '../models/file-error.js'
import { LockConflict } from '../models/file-lock-error.js'
import { checkFileName, dirName, fileName, getMimeType, isPathExists, isPathInside, isPathIsDir, sanitizeName } from '../utils/files.js'
import { SendFile } from '../utils/send-file.js'
import { FilesManager } from './files-manager.service.js'

@Injectable()
export class FilesMethods {
  private readonly logger = new Logger(FilesMethods.name)

  constructor(
    private readonly spacesManager: SpacesManager,
    private readonly filesManager: FilesManager
  ) {}

  async headOrGet(req: FastifySpaceRequest, res: FastifyReply): Promise<StreamableFile> {
    const sendFile: SendFile = this.filesManager.sendFileFromSpace(req.space)
    try {
      await sendFile.checks()
      return await sendFile.stream(req, res)
    } catch (e) {
      this.handleError(req.space, req.method, e)
    }
  }

  async upload(req: FastifySpaceRequest, res: FastifyReply): Promise<void> {
    try {
      await this.filesManager.saveMultipart(req.user, req.space, req)
    } catch (e) {
      this.handleError(req.space, FILE_OPERATION.UPLOAD, e, undefined, undefined, res)
    }
  }

  async make(user: UserModel, space: SpaceEnv, makeFileDto: MakeFileDto): Promise<void> {
    try {
      if (makeFileDto.type === 'directory') {
        return await this.filesManager.mkDir(user, space)
      } else {
        return await this.filesManager.mkFile(user, space, false, true, true)
      }
    } catch (e) {
      this.handleError(space, `${FILE_OPERATION.MAKE} ${makeFileDto.type}`, e)
    }
  }

  copy(user: UserModel, space: SpaceEnv, copyMoveFileDto: ValidatedCopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
    return this.copyMove(user, space, copyMoveFileDto, false, signal)
  }

  move(user: UserModel, space: SpaceEnv, copyMoveFileDto: ValidatedCopyMoveFileDto, signal?: AbortSignal): Promise<CopyMoveFileResponse> {
    return this.copyMove(user, space, copyMoveFileDto, true, signal)
  }

  async delete(user: UserModel, space: SpaceEnv, _dto?: null, signal?: AbortSignal): Promise<void> {
    try {
      return await this.filesManager.delete(user, space, undefined, signal)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.DELETE, e, undefined, signal)
    }
  }

  async downloadFromUrl(user: UserModel, space: SpaceEnv, downloadDto: DownloadFileDto, signal?: AbortSignal): Promise<void> {
    checkFileName(space.realPath)
    try {
      return await this.filesManager.downloadFromUrl(user, space, downloadDto, signal)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.DOWNLOAD, e, undefined, signal)
    }
  }

  async compress(user: UserModel, space: SpaceEnv, compressFileDto: CompressFileDto, signal?: AbortSignal): Promise<void> {
    compressFileDto.name = checkFileName(space.realPath)
    try {
      for (const f of compressFileDto.files) {
        // sanitize file name
        f.name = sanitizeName(f.name)
        // handles the case where the file is an anchored file
        let baseSpace: SpaceEnv
        if (f.path) {
          baseSpace = (await this.spacesManager.spaceEnv(user, f.path.split('/')))!
          f.path = baseSpace.realPath
        } else {
          if (f.rootAlias) {
            baseSpace = (await this.spacesManager.spaceEnv(user, path.join(dirName(space.url), f.rootAlias).split('/')))!
            f.path = baseSpace.realPath
          } else {
            baseSpace = space
            f.path = path.resolve(dirName(space.realPath), f.name)
          }
        }
        if (!isPathInside(baseSpace.realBasePath, f.path, true)) {
          return this.handleError(space, FILE_OPERATION.COMPRESS, new FileError(HttpStatus.FORBIDDEN, `${f.name} not allowed`))
        }
        if (!(await isPathExists(f.path))) {
          return this.handleError(space, FILE_OPERATION.COMPRESS, new FileError(HttpStatus.NOT_FOUND, `${f.name} does not exist`))
        }
      }
      return await this.filesManager.compress(user, space, compressFileDto, signal)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.COMPRESS, e, undefined, signal)
    }
  }

  async decompress(user: UserModel, space: SpaceEnv, _dto?: null, signal?: AbortSignal): Promise<void> {
    try {
      return await this.filesManager.decompress(user, space, signal)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.DECOMPRESS, e, undefined, signal)
    }
  }

  async genThumbnail(space: SpaceEnv, size: number): Promise<FileThumbnail> {
    try {
      return await this.filesManager.generateThumbnail(space, size)
    } catch (e) {
      this.handleError(space, this.genThumbnail.name, e)
    }
  }

  async lock(user: UserModel, space: SpaceEnv): Promise<FileLockProps> {
    try {
      return await this.filesManager.lock(user, space)
    } catch (e) {
      if (e instanceof LockConflict) {
        const fileLockProps = this.filesManager.filesLockManager.convertLockToFileLockProps(e.lock)
        throw new HttpException(fileLockProps, HttpStatus.LOCKED)
      }
      this.handleError(space, FILE_OPERATION.LOCK, e)
    }
  }

  async unlock(user: UserModel, space: SpaceEnv, forceAsFileOwner = false): Promise<void> {
    try {
      return await this.filesManager.unlock(user, space, forceAsFileOwner)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.UNLOCK, e)
    }
  }

  async unlockRequest(user: UserModel, space: SpaceEnv): Promise<void> {
    try {
      return await this.filesManager.unlockRequest(user, space)
    } catch (e) {
      this.handleError(space, FILE_OPERATION.UNLOCK_REQUEST, e)
    }
  }

  async getSize(space: SpaceEnv): Promise<{ size: number }> {
    try {
      return { size: await this.filesManager.getSize(space) }
    } catch (e) {
      this.handleError(space, FILE_OPERATION.GET_SIZE, e)
    }
  }

  private async copyMove(
    user: UserModel,
    space: SpaceEnv,
    copyMoveFileDto: ValidatedCopyMoveFileDto,
    isMove: boolean,
    signal?: AbortSignal
  ): Promise<CopyMoveFileResponse> {
    const dstUrl = path.join(copyMoveFileDto.dstDirectory, copyMoveFileDto.dstName || fileName(space.realPath))
    let dstSpace: SpaceEnv | null | undefined
    try {
      dstSpace = await this.spacesManager.spaceEnv(user, dstUrl.split('/'))
      if (!dstSpace) {
        throw new Error(`Destination space not found: ${dstUrl}`)
      }
      await this.filesManager.copyMove(user, space, dstSpace, isMove, copyMoveFileDto.overwrite ?? false, false, undefined, signal)
      return { path: dirName(dstUrl), name: fileName(dstUrl), mime: getMimeType(dstSpace.realPath, await isPathIsDir(dstSpace.realPath)) }
    } catch (e) {
      this.handleError(space, isMove ? FILE_OPERATION.MOVE : FILE_OPERATION.COPY, e, dstSpace ?? undefined, signal)
    }
  }

  private handleError(
    space: SpaceEnv,
    action: FILE_OPERATION | string,
    error: unknown,
    dstSpace?: SpaceEnv,
    signal?: AbortSignal,
    res?: FastifyReply
  ): never {
    if (signal && this.isCancellationError(error, signal)) {
      throw signal.reason
    }
    this.logger.error({
      tag: this.handleError.name,
      msg: `unable to ${action} ${space.url}${dstSpace?.url ? ` -> ${dstSpace.url}` : ''} : ${toErrorMessage(error)}`
    })
    const normalizedError = error instanceof Error ? error : new Error(toErrorMessage(error))
    // Remove the last part to avoid exposing the path
    const errorMsg = normalizedError.message.split(',')[0]
    if (normalizedError instanceof LockConflict) {
      throw new HttpException('The file is locked', HttpStatus.LOCKED)
    } else if (normalizedError instanceof FileError) {
      // A quota or size limit may reject a multipart upload before its body is fully consumed.
      // Mark the HTTP/1 connection as non-reusable instead of draining the remaining payload.
      if (
        res &&
        res.request.raw.httpVersionMajor === 1 &&
        (normalizedError.httpCode === HttpStatus.INSUFFICIENT_STORAGE || normalizedError.httpCode === HttpStatus.PAYLOAD_TOO_LARGE)
      ) {
        void res.header('Connection', 'close')
      }
      throw new HttpException(errorMsg, normalizedError.httpCode)
    }
    throw new HttpException(errorMsg, HttpStatus.INTERNAL_SERVER_ERROR)
  }

  private isCancellationError(error: unknown, signal?: AbortSignal): boolean {
    if (!signal?.aborted) return false
    if (error === signal.reason) return true
    if (!(error instanceof Error)) return false
    const code = (error as NodeJS.ErrnoException).code
    return error.cause === signal.reason || error.name === 'AbortError' || code === 'ABORT_ERR' || code === 'ERR_CANCELED'
  }
}