Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/attachments extra attrs #535

Merged
merged 24 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
994c885
feat(api): add attachment extra attributes
marrouchi Jan 8, 2025
7be6115
feat(frontend): apply frontend updates (context)
marrouchi Jan 8, 2025
6783103
fix(api): unit test
marrouchi Jan 8, 2025
9e96055
feat: update migration to populate subscriber avatar attachments
marrouchi Jan 8, 2025
65fad2f
feat: update migration to populate user avatar attachments
marrouchi Jan 8, 2025
e8c917a
feat: migrate setting attachments
marrouchi Jan 9, 2025
e859cf1
feat: add migration to populate block attachment new attributes
marrouchi Jan 9, 2025
39213e8
refactor: channels design to allow attachment ownership
marrouchi Jan 15, 2025
90aad93
fix: update migration to populate the message attachments with extra …
marrouchi Jan 15, 2025
bdf1763
refactor: rename owner to createdBy
marrouchi Jan 15, 2025
0b4a108
fix: minor
marrouchi Jan 15, 2025
505cd24
feat: add the access attribute
marrouchi Jan 16, 2025
3f9dd69
refactor: rename context to resourceRef
marrouchi Jan 16, 2025
c27f37a
feat: rename enum instead of string
marrouchi Jan 16, 2025
4fac5d4
feat: enforce security to access own attachment
marrouchi Jan 16, 2025
359049f
refactor: use enums
marrouchi Jan 16, 2025
a355ef0
fix: console channel session.web
marrouchi Jan 16, 2025
36b0544
fix: media library
marrouchi Jan 17, 2025
f736356
fix: carousel display + refactor attachment url
marrouchi Jan 17, 2025
8d1bb47
feat: enhance attachment display in inbox
marrouchi Jan 17, 2025
356b16a
fix: rename payload to ensure consistency
marrouchi Jan 17, 2025
b74c4a4
fix: migration
marrouchi Jan 17, 2025
3ed8bbc
feat: make storage mode configurable env var
MohamedAliBouhaouala Jan 17, 2025
bb2d0d4
Merge pull request #583 from Hexastack/feat/storage-mode-env-var
marrouchi Jan 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/src/attachment/attachment.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { MongooseModule } from '@nestjs/mongoose';
import { PassportModule } from '@nestjs/passport';

import { config } from '@/config';
import { UserModule } from '@/user/user.module';

import { AttachmentController } from './controllers/attachment.controller';
import { AttachmentRepository } from './repositories/attachment.repository';
Expand All @@ -25,6 +26,7 @@ import { AttachmentService } from './services/attachment.service';
PassportModule.register({
session: true,
}),
UserModule,
],
providers: [AttachmentRepository, AttachmentService],
controllers: [AttachmentController],
Expand Down
85 changes: 71 additions & 14 deletions api/src/attachment/controllers/attachment.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import fs from 'fs';

import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException } from '@nestjs/common/exceptions';
import { NotFoundException } from '@nestjs/common/exceptions/not-found.exception';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { MongooseModule } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { Request } from 'express';

import { LoggerService } from '@/logger/logger.service';
import { PluginService } from '@/plugins/plugins.service';
import { ModelRepository } from '@/user/repositories/model.repository';
import { PermissionRepository } from '@/user/repositories/permission.repository';
import { ModelModel } from '@/user/schemas/model.schema';
import { PermissionModel } from '@/user/schemas/permission.schema';
import { ModelService } from '@/user/services/model.service';
import { PermissionService } from '@/user/services/permission.service';
import { NOT_FOUND_ID } from '@/utils/constants/mock';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import {
Expand All @@ -29,6 +39,11 @@ import { attachment, attachmentFile } from '../mocks/attachment.mock';
import { AttachmentRepository } from '../repositories/attachment.repository';
import { Attachment, AttachmentModel } from '../schemas/attachment.schema';
import { AttachmentService } from '../services/attachment.service';
import {
AttachmentAccess,
AttachmentCreatedByRef,
AttachmentResourceRef,
} from '../types';

import { AttachmentController } from './attachment.controller';

Expand All @@ -42,14 +57,30 @@ describe('AttachmentController', () => {
controllers: [AttachmentController],
imports: [
rootMongooseTestModule(installAttachmentFixtures),
MongooseModule.forFeature([AttachmentModel]),
MongooseModule.forFeature([
AttachmentModel,
PermissionModel,
ModelModel,
]),
],
providers: [
AttachmentService,
AttachmentRepository,
PermissionService,
PermissionRepository,
ModelService,
ModelRepository,
LoggerService,
EventEmitter2,
PluginService,
{
provide: CACHE_MANAGER,
useValue: {
del: jest.fn(),
get: jest.fn(),
set: jest.fn(),
},
},
],
}).compile();
attachmentController =
Expand All @@ -62,7 +93,10 @@ describe('AttachmentController', () => {

afterAll(closeInMongodConnection);

afterEach(jest.clearAllMocks);
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});

describe('count', () => {
it('should count attachments', async () => {
Expand All @@ -76,29 +110,52 @@ describe('AttachmentController', () => {

describe('Upload', () => {
it('should throw BadRequestException if no file is selected to be uploaded', async () => {
const promiseResult = attachmentController.uploadFile({
file: [],
});
const promiseResult = attachmentController.uploadFile(
{
file: [],
},
{} as Request,
{ resourceRef: AttachmentResourceRef.BlockAttachment },
);
await expect(promiseResult).rejects.toThrow(
new BadRequestException('No file was selected'),
);
});

it('should upload attachment', async () => {
jest.spyOn(fs.promises, 'writeFile').mockResolvedValue();

jest.spyOn(attachmentService, 'create');
const result = await attachmentController.uploadFile({
file: [attachmentFile],
});
const result = await attachmentController.uploadFile(
{
file: [attachmentFile],
},
{
session: { passport: { user: { id: '9'.repeat(24) } } },
} as unknown as Request,
{ resourceRef: AttachmentResourceRef.BlockAttachment },
);
const [name] = attachmentFile.filename.split('.');
expect(attachmentService.create).toHaveBeenCalledWith({
size: attachmentFile.size,
type: attachmentFile.mimetype,
name: attachmentFile.filename,
channel: {},
location: `/${attachmentFile.filename}`,
name: attachmentFile.originalname,
location: expect.stringMatching(new RegExp(`^/${name}`)),
resourceRef: AttachmentResourceRef.BlockAttachment,
access: AttachmentAccess.Public,
createdByRef: AttachmentCreatedByRef.User,
createdBy: '9'.repeat(24),
});
expect(result).toEqualPayload(
[attachment],
[...IGNORED_TEST_FIELDS, 'url'],
[
{
...attachment,
resourceRef: AttachmentResourceRef.BlockAttachment,
createdByRef: AttachmentCreatedByRef.User,
createdBy: '9'.repeat(24),
},
],
[...IGNORED_TEST_FIELDS, 'location', 'url'],
);
});
});
Expand Down
64 changes: 48 additions & 16 deletions api/src/attachment/controllers/attachment.controller.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { extname } from 'path';

import {
BadRequestException,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
NotFoundException,
Param,
Post,
Query,
Req,
StreamableFile,
UploadedFiles,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileFieldsInterceptor } from '@nestjs/platform-express';
import { CsrfCheck } from '@tekuconcept/nestjs-csrf';
import { Request } from 'express';
import { diskStorage, memoryStorage } from 'multer';
import { v4 as uuidv4 } from 'uuid';

import { config } from '@/config';
import { CsrfInterceptor } from '@/interceptors/csrf.interceptor';
Expand All @@ -38,12 +39,18 @@ import { PageQueryPipe } from '@/utils/pagination/pagination-query.pipe';
import { SearchFilterPipe } from '@/utils/pipes/search-filter.pipe';
import { TFilterQuery } from '@/utils/types/filter.types';

import { AttachmentDownloadDto } from '../dto/attachment.dto';
import {
AttachmentContextParamDto,
AttachmentDownloadDto,
} from '../dto/attachment.dto';
import { AttachmentGuard } from '../guards/attachment-ability.guard';
import { Attachment } from '../schemas/attachment.schema';
import { AttachmentService } from '../services/attachment.service';
import { AttachmentAccess, AttachmentCreatedByRef } from '../types';

@UseInterceptors(CsrfInterceptor)
@Controller('attachment')
@UseGuards(AttachmentGuard)
export class AttachmentController extends BaseController<Attachment> {
constructor(
private readonly attachmentService: AttachmentService,
Expand All @@ -61,7 +68,7 @@ export class AttachmentController extends BaseController<Attachment> {
async filterCount(
@Query(
new SearchFilterPipe<Attachment>({
allowedFields: ['name', 'type'],
allowedFields: ['name', 'type', 'resourceRef'],
}),
)
filters?: TFilterQuery<Attachment>,
Expand Down Expand Up @@ -90,7 +97,9 @@ export class AttachmentController extends BaseController<Attachment> {
async findPage(
@Query(PageQueryPipe) pageQuery: PageQueryDto<Attachment>,
@Query(
new SearchFilterPipe<Attachment>({ allowedFields: ['name', 'type'] }),
new SearchFilterPipe<Attachment>({
allowedFields: ['name', 'type', 'resourceRef'],
}),
)
filters: TFilterQuery<Attachment>,
) {
Expand All @@ -114,26 +123,49 @@ export class AttachmentController extends BaseController<Attachment> {
if (config.parameters.storageMode === 'memory') {
abdou6666 marked this conversation as resolved.
Show resolved Hide resolved
return memoryStorage();
} else {
return diskStorage({
destination: config.parameters.uploadDir,
filename: (req, file, cb) => {
const name = file.originalname.split('.')[0];
const extension = extname(file.originalname);
cb(null, `${name}-${uuidv4()}${extension}`);
},
});
return diskStorage({});
marrouchi marked this conversation as resolved.
Show resolved Hide resolved
}
})(),
}),
)
async uploadFile(
@UploadedFiles() files: { file: Express.Multer.File[] },
@Req() req: Request,
@Query()
{
resourceRef,
access = AttachmentAccess.Public,
}: AttachmentContextParamDto,
): Promise<Attachment[]> {
if (!files || !Array.isArray(files?.file) || files.file.length === 0) {
throw new BadRequestException('No file was selected');
}

return await this.attachmentService.uploadFiles(files);
const userId = req.session?.passport?.user?.id;
if (!userId) {
throw new ForbiddenException(
'Unexpected Error: Only authenticated users are allowed to upload',
);
}

const attachments: Attachment[] = [];
for (const file of files.file) {
marrouchi marked this conversation as resolved.
Show resolved Hide resolved
const attachment = await this.attachmentService.store(file, {
name: file.originalname,
size: file.size,
type: file.mimetype,
resourceRef,
access,
createdBy: userId,
createdByRef: AttachmentCreatedByRef.User,
});

if (attachment) {
attachments.push(attachment);
}
}

return attachments;
}

/**
Expand Down
Loading
Loading