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(backend:users): convert uploaded avatars to PNG during update
johaven47af28b4b7df
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.tsindex 26aa5d07..970f8b81 100755--- a/backend/src/applications/users/services/users-manager.service.spec.ts+++ b/backend/src/applications/users/services/users-manager.service.spec.ts@@ -1,3 +1,4 @@+import { HttpStatus } from '@nestjs/common'import { Test, TestingModule } from '@nestjs/testing'import bcrypt from 'bcryptjs'import fs from 'node:fs/promises'@@ -11,7 +12,6 @@ import { pngMimeType, svgMimeType } from '../../../common/image'import { configuration } from '../../../configuration/config.environment'import { Cache } from '../../../infrastructure/cache/services/cache.service'import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'-import * as filesUtilsModule from '../../files/utils/files'import { fileName, isPathExists } from '../../files/utils/files'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { GROUP_TYPE } from '../constants/group'@@ -36,7 +36,8 @@ jest.mock('../../../common/image', () => {const actual = jest.requireActual('../../../common/image')return {...actual,- generateAvatar: jest.fn(() => Readable.from([Buffer.from('PNGDATA')]))+ generateAvatar: jest.fn(() => Readable.from([Buffer.from('PNGDATA')])),+ convertTempImageToPng: jest.fn(() => Promise.resolve())}})@@ -302,25 +303,37 @@ describe(UsersManager.name, () => {await expect(usersManager.getAvatar(userTest.login, true)).rejects.toThrow('avatar not found')})- it('updateAvatar branches: mime error, stream error, truncated, move fail, success', async () => {+ it('updateAvatar branches: mime error, stream error, truncated, invalid image, convert fail, success', async () => {await ensurePaths()- await expect(usersManager.updateAvatar(mkReq('text/plain', okStream('X')) as any)).rejects.toThrow('Unsupported file type')- await expect(usersManager.updateAvatar(mkReq('image/png', errStream('stream error')) as any)).rejects.toThrow('Unable to upload avatar')+ const convertTempImageToPngMock = imageModule.convertTempImageToPng as jest.MockedFunction<typeof imageModule.convertTempImageToPng>+ await expect(usersManager.updateAvatar(mkReq('text/plain', okStream('X')) as any)).rejects.toMatchObject({+ message: 'Unsupported file type',+ status: HttpStatus.BAD_REQUEST+ })+ await expect(usersManager.updateAvatar(mkReq('image/png', errStream('stream error')) as any)).rejects.toMatchObject({+ message: 'Unable to upload avatar',+ status: HttpStatus.INTERNAL_SERVER_ERROR+ })const t = okStream('OK')t.truncated = true- const mvSpy = jest.spyOn(filesUtilsModule, 'moveFiles').mockResolvedValue(undefined)- await expect(usersManager.updateAvatar(mkReq('image/png', t) as any)).rejects.toThrow('Image is too large')- expect(mvSpy).not.toHaveBeenCalled()+ await expect(usersManager.updateAvatar(mkReq('image/png', t) as any)).rejects.toMatchObject({+ message: 'Image is too large',+ status: HttpStatus.PAYLOAD_TOO_LARGE+ })+ expect(convertTempImageToPngMock).not.toHaveBeenCalled()- jest.spyOn(filesUtilsModule, 'moveFiles').mockRejectedValue(new Error('mv fail'))- await expect(usersManager.updateAvatar(mkReq('image/png', okStream()) as any)).rejects.toThrow('Unable to create avatar')+ convertTempImageToPngMock.mockRejectedValueOnce(new Error('Input buffer contains unsupported image format'))+ await expect(usersManager.updateAvatar(mkReq('image/png', okStream()) as any)).rejects.toMatchObject({+ message: 'Unable to convert or create avatar',+ status: HttpStatus.BAD_REQUEST+ })- const mvSpy2 = jest.spyOn(filesUtilsModule, 'moveFiles').mockResolvedValue(undefined)+ convertTempImageToPngMock.mockResolvedValueOnce(undefined)await expect(usersManager.updateAvatar(mkReq('image/png', okStream()) as any)).resolves.toBeUndefined()const expectedSrc = path.join(userTest.tmpPath, 'avatar.png')const expectedDst = path.join(userTest.homePath, 'avatar.png')- expect(mvSpy2).toHaveBeenCalledWith(expectedSrc, expectedDst, true)+ expect(convertTempImageToPngMock).toHaveBeenLastCalledWith(expectedSrc, expectedDst)})it('setOnlineStatus + browseGroups + getGroup', async () => {diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.tsindex dcbfb06c..ac029fcd 100755--- a/backend/src/applications/users/services/users-manager.service.ts+++ b/backend/src/applications/users/services/users-manager.service.ts@@ -11,10 +11,10 @@ import { FastifyAuthenticatedRequest } from '../../../authentication/interfaces/import { JwtIdentityPayload } from '../../../authentication/interfaces/jwt-payload.interface'import { ACTION } from '../../../common/constants'import { comparePassword, hashPassword } from '../../../common/functions'-import { generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image'+import { convertTempImageToPng, generateAvatar, imgMimeTypePrefix, pngMimeType, svgMimeType } from '../../../common/image'import { createLightSlug, genPassword } from '../../../common/shared'import { configuration, serverConfig } from '../../../configuration/config.environment'-import { isPathExists, moveFiles, sanitizeName } from '../../files/utils/files'+import { isPathExists, removeFiles, sanitizeName } from '../../files/utils/files'import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'import { NotificationsManager } from '../../notifications/services/notifications-manager.service'import { GROUP_TYPE } from '../constants/group'@@ -147,24 +147,27 @@ export class UsersManager {if (!part.mimetype.startsWith(imgMimeTypePrefix)) {throw new HttpException('Unsupported file type', HttpStatus.BAD_REQUEST)}- const dstPath = path.join(req.user.tmpPath, USER_AVATAR_FILE_NAME)+ const tmpPath = path.join(req.user.tmpPath, USER_AVATAR_FILE_NAME)try {- await pipeline(part.file, createWriteStream(dstPath))+ await pipeline(part.file, createWriteStream(tmpPath))} catch (e) {+ void removeFiles(tmpPath)this.logger.error({ tag: this.updateAvatar.name, msg: `${e}` })throw new HttpException('Unable to upload avatar', HttpStatus.INTERNAL_SERVER_ERROR)}if (part.file.truncated) {+ void removeFiles(tmpPath)this.logger.warn({ tag: this.updateAvatar.name, msg: `image is too large` })throw new HttpException('Image is too large', HttpStatus.PAYLOAD_TOO_LARGE)}const avatarPath = path.join(req.user.homePath, USER_AVATAR_FILE_NAME)try {- await moveFiles(dstPath, avatarPath, true)+ await convertTempImageToPng(tmpPath, avatarPath)void saveAvatarMetadata(req.user.login, 'user')} catch (e) {+ void removeFiles(tmpPath)this.logger.error({ tag: this.updateAvatar.name, msg: `${e}` })- throw new HttpException('Unable to create avatar', HttpStatus.INTERNAL_SERVER_ERROR)+ throw new HttpException('Unable to convert or create avatar', HttpStatus.BAD_REQUEST)}}