Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

pretest attachment v3

Fendy Heryanto7d9d048a3cfc
diff --git a/packages/nocodb-sdk/src/lib/arrayHelpers.spec.ts b/packages/nocodb-sdk/src/lib/arrayHelpers.spec.ts
new file mode 100644
index 0000000000..c0c345c6b0
--- /dev/null
+++ b/packages/nocodb-sdk/src/lib/arrayHelpers.spec.ts
@@ -0,0 +1,24 @@
+import { detailedDiff, intersection } from './arrayHelpers';
+
+describe('arrayHelpers', () => {
+ describe('intersection', () => {
+ it('will intersect 2 array', () => {
+ const a = ['a', 'b', 'c'];
+ const b = ['c', 'd', 'e'];
+ const result = intersection(a, b);
+ expect(result).toEqual(['c']);
+ });
+ });
+ describe('detailedDiff', () => {
+ it('will detailed diff 2 array', () => {
+ const a = ['a', 'b', 'c'];
+ const b = ['c', 'd', 'e'];
+ const result = detailedDiff(a, b);
+ expect(result).toEqual({
+ removed: ['a', 'b'],
+ intersected: ['c'],
+ added: ['d', 'e'],
+ });
+ });
+ });
+});
diff --git a/packages/nocodb-sdk/src/lib/arrayHelpers.ts b/packages/nocodb-sdk/src/lib/arrayHelpers.ts
new file mode 100644
index 0000000000..4aa702d98f
--- /dev/null
+++ b/packages/nocodb-sdk/src/lib/arrayHelpers.ts
@@ -0,0 +1,14 @@
+export const uniq = (array: any[]) => {
+ return [...new Set(array)];
+};
+export const intersection = (...arrays: any[][]) => {
+ return arrays.reduce((a, b) => a.filter((c) => b.includes(c)));
+};
+export const detailedDiff = (a: any[], b: any[]) => {
+ const intersected = intersection(a, b);
+ return {
+ removed: a.filter((old) => !intersected.includes(old)),
+ intersected,
+ added: b.filter((n) => !intersected.includes(n)),
+ };
+};
diff --git a/packages/nocodb-sdk/src/lib/index.ts b/packages/nocodb-sdk/src/lib/index.ts
index c5d80c6be6..c02f4ecdcf 100644
--- a/packages/nocodb-sdk/src/lib/index.ts
+++ b/packages/nocodb-sdk/src/lib/index.ts
@@ -68,3 +68,4 @@ export * from '~/lib/geoDataUtils';
export * from '~/lib/stringHelpers';
export * from '~/lib/filter';
export * from '~/lib/dashboard';
+export * from '~/lib/arrayHelpers';
diff --git a/packages/nocodb/src/db/field-handler/handlers/attachment/attachment.general.handler.ts b/packages/nocodb/src/db/field-handler/handlers/attachment/attachment.general.handler.ts
index dcf4b71b8d..421cdc5e58 100644
--- a/packages/nocodb/src/db/field-handler/handlers/attachment/attachment.general.handler.ts
+++ b/packages/nocodb/src/db/field-handler/handlers/attachment/attachment.general.handler.ts
@@ -1,10 +1,11 @@
-import { NcError } from 'src/helpers/catchError';
-import { dataWrapper } from 'src/helpers/dbHelpers';
+import { detailedDiff, type NcContext } from 'nocodb-sdk';
import { ComputedFieldHandler } from '../computed';
-import type { NcContext } from 'nocodb-sdk';
-import type { IBaseModelSqlV2 } from 'src/db/IBaseModelSqlV2';
-import type { MetaService } from 'src/meta/meta.service';
-import type { Column } from '~/models';
+import type { MetaService } from '~/meta/meta.service';
+import type { IBaseModelSqlV2 } from '~/db/IBaseModelSqlV2';
+import { NcError } from '~/helpers/catchError';
+import { dataWrapper } from '~/helpers/dbHelpers';
+import { extractProps } from '~/helpers/extractProps';
+import { type Column, FileReference } from '~/models';
export class AttachmentGeneralHandler extends ComputedFieldHandler {
override async parseUserInput(params: {
@@ -21,6 +22,7 @@ export class AttachmentGeneralHandler extends ComputedFieldHandler {
let oldValue = params.oldData
? dataWrapper(params.oldData).getByColumnNameTitleOrId(params.column)
: '[]';
+ let oldValueMap: Map<string, any>;
let value = params.value;
if (!value) {
return value;
@@ -42,6 +44,7 @@ export class AttachmentGeneralHandler extends ComputedFieldHandler {
if (typeof oldValue === 'string') {
oldValue = JSON.parse(oldValue);
}
+ oldValueMap = new Map(oldValue.map((val) => [val.id, val]));
} catch (e) {
throwError();
}
@@ -52,30 +55,34 @@ export class AttachmentGeneralHandler extends ComputedFieldHandler {
// Confirm that all urls are valid urls
for (const attachment of value ?? []) {
if (attachment.id) {
- const oldAttachmentRow = oldValue.find(
- (attr) => attr.id === attachment.id,
- );
+ const oldAttachmentRow = oldValueMap.get(attachment.id);
if (!oldAttachmentRow) {
throwError(`Attachment id ${attachment.id} not exists on old data`);
}
// if id exists, persist old value
Object.assign(attachment, oldAttachmentRow);
}
- if (!('url' in attachment) && !('path' in attachment)) {
- throwError('Attachment object must contain either url or path');
- }
-
- if (attachment.url) {
- if (attachment.url.startsWith('data:')) {
- throwError(`Attachment urls do not support data urls`);
- }
-
- if (attachment.url.length > 8 * 1024) {
- throwError(`Attachment url '${attachment.url}' is too long`);
- }
- }
}
+ const { removed } = detailedDiff(
+ new Array(oldValueMap.keys),
+ value.map((k) => k.id),
+ );
+ await FileReference.delete(params.options.context, removed);
- return { value };
+ return {
+ value: value.map((attr) => {
+ extractProps(attr, [
+ 'id',
+ 'url',
+ 'path',
+ 'title',
+ 'mimetype',
+ 'size',
+ 'icon',
+ 'width',
+ 'height',
+ ]);
+ }),
+ };
}
}
diff --git a/packages/nocodb/src/interface/Jobs.ts b/packages/nocodb/src/interface/Jobs.ts
index e6e5d3c83c..3317fdc27b 100644
--- a/packages/nocodb/src/interface/Jobs.ts
+++ b/packages/nocodb/src/interface/Jobs.ts
@@ -230,6 +230,7 @@ export interface SyncDataSyncModuleJobData extends JobData {
export interface AttachmentUrlUploadJobData extends JobData {
context: NcContext;
+ scope?: PublicAttachmentScope;
modelId: string;
column: {
id: string;
diff --git a/packages/nocodb/src/modules/jobs/jobs/attachment-url-upload/attachment-url-upload.processor.ts b/packages/nocodb/src/modules/jobs/jobs/attachment-url-upload/attachment-url-upload.processor.ts
index c0d8b454d9..984734a31f 100644
--- a/packages/nocodb/src/modules/jobs/jobs/attachment-url-upload/attachment-url-upload.processor.ts
+++ b/packages/nocodb/src/modules/jobs/jobs/attachment-url-upload/attachment-url-upload.processor.ts
@@ -1,31 +1,48 @@
+import path from 'path';
+import { PassThrough } from 'stream';
import { Process, Processor } from '@nestjs/bull';
import { Job } from 'bull';
import axios from 'axios';
-import { Injectable } from '@nestjs/common';
-import { v4 as uuidv4 } from 'uuid';
-import { _wherePk, getBaseModelSqlFromModelId } from 'src/helpers/dbHelpers';
+import { forwardRef, Inject, Injectable } from '@nestjs/common';
+import slash from 'slash';
+import { nanoid } from 'nanoid';
+import { IJobsService } from '../../jobs-service.interface';
import type { AttachmentUrlUploadJobData } from '~/interface/Jobs';
+import { _wherePk, getBaseModelSqlFromModelId } from '~/helpers/dbHelpers';
+import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';
+import { FileReference } from '~/models';
+import { RootScopes } from '~/utils/globals';
import {
NC_ATTACHMENT_FIELD_SIZE,
NC_ATTACHMENT_URL_MAX_REDIRECT,
} from '~/constants';
-import { AttachmentsService } from '~/services/attachments.service';
-import { JOBS_QUEUE } from '~/interface/Jobs';
+import { JOBS_QUEUE, JobTypes } from '~/interface/Jobs';
+
+const thumbnailMimes = ['image/'];
+
+// ref: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html - extended with some more characters
+const normalizeFilename = (filename: string) => {
+ return filename.replace(/[\\/:*?"<>'`#|%~{}[\]^]/g, '_');
+};
@Injectable()
@Processor(JOBS_QUEUE)
export class AttachmentUrlUploadProcessor {
- constructor(private readonly attachmentsService: AttachmentsService) {}
+ constructor(
+ @Inject(forwardRef(() => 'JobsService'))
+ private readonly jobsService: IJobsService,
+ ) {}
@Process('attachment-url-upload')
async attachmentUrlUpload(job: Job<AttachmentUrlUploadJobData>) {
- const { context, modelId, column, recordId, attachments } = job.data;
+ const { context, modelId, column, recordId, scope, attachments } = job.data;
const baseModel = await getBaseModelSqlFromModelId({
context: context,
modelId: modelId,
});
const processedAttachments = [];
+ const generateThumbnailAttachments = [];
for (const attachment of attachments) {
try {
@@ -34,11 +51,46 @@ export class AttachmentUrlUploadProcessor {
}
// If attachment has URL, download and process it
if (attachment.url) {
- const downloadedAttachment = await this.downloadAndStoreAttachment(
- context,
- attachment.url,
- );
- processedAttachments.push(downloadedAttachment);
+ const downloadedAttachment = await this.downloadAndStoreAttachment({
+ destPath: path.join(
+ ...[
+ 'nc',
+ scope ?? 'uploads',
+ context.workspace_id,
+ context.base_id,
+ modelId,
+ column.id,
+ scope ? nanoid(5) : undefined,
+ ].filter((k) => k),
+ ),
+ url: attachment.url,
+ scope,
+ });
+ const attachmentId = await FileReference.insert(context, {
+ storage: downloadedAttachment.storageName,
+ file_url: downloadedAttachment.url,
+ file_size: downloadedAttachment.fileSize,
+ fk_user_id: context?.user?.id ?? 'anonymous',
+ source_id: baseModel.model.source_id,
+ fk_model_id: modelId,
+ fk_column_id: column.id,
+ is_external: !(await baseModel.getSource()).isMeta(),
+ });
+ const processedAttachment = {
+ id: attachmentId,
+ url: downloadedAttachment.url,
+ title: downloadedAttachment.filename,
+ mimetype: downloadedAttachment.mimeType,
+ size: downloadedAttachment.fileSize,
+ };
+ processedAttachments.push(processedAttachment);
+ if (
+ thumbnailMimes.some((type) =>
+ downloadedAttachment.mimeType.startsWith(type),
+ )
+ ) {
+ generateThumbnailAttachments.push(processedAttachment);
+ }
}
} catch (error) {
console.error(`Failed to process attachment:`, error);
@@ -51,13 +103,28 @@ export class AttachmentUrlUploadProcessor {
[column.column_name]: JSON.stringify(processedAttachments),
})
.where(await _wherePk(baseModel.model.primaryKeys, recordId, true));
+
+ if (generateThumbnailAttachments.length > 0) {
+ await this.jobsService.add(JobTypes.ThumbnailGenerator, {
+ context: {
+ base_id: RootScopes.ROOT,
+ workspace_id: RootScopes.ROOT,
+ },
+ attachments: generateThumbnailAttachments,
+ scope,
+ });
+ }
}
- private async downloadAndStoreAttachment(
- context: any,
- url: string,
- attachmentId: string,
- ) {
+ private async downloadAndStoreAttachment({
+ url,
+ destPath,
+ scope,
+ }: {
+ url: string;
+ destPath: string;
+ scope: string;
+ }) {
// Configure axios for download
const response = await axios({
method: 'GET',
@@ -65,7 +132,6 @@ export class AttachmentUrlUploadProcessor {
responseType: 'stream',
maxRedirects: NC_ATTACHMENT_URL_MAX_REDIRECT,
maxContentLength: NC_ATTACHMENT_FIELD_SIZE,
- timeout: 30000, // 30 seconds timeout
});
// Extract file information from response headers
@@ -74,6 +140,17 @@ export class AttachmentUrlUploadProcessor {
const contentLength = response.headers['content-length'];
const contentDisposition = response.headers['content-disposition'];
+ const passthrough = new PassThrough(); // Track size via the PassThrough stream
+ let totalBytes = 0;
+ if (!contentLength) {
+ passthrough.on('data', (chunk) => {
+ totalBytes += chunk.length;
+ });
+ }
+
+ const storageAdapter = await NcPluginMgrv2.storageAdapter();
+ const mimeType = contentType.split(';')[0].trim();
+
// Extract filename from URL or content-disposition header
let filename = url.split('/').pop()?.split('?')[0] || 'attachment';
if (contentDisposition) {
@@ -84,29 +161,30 @@ export class AttachmentUrlUploadProcessor {
filename = filenameMatch[1].replace(/['"]/g, '');
}
}
+ filename = scope
+ ? `${normalizeFilename(path.parse(filename).name)}${path.extname(
+ filename,
+ )}`
+ : `${normalizeFilename(path.parse(filename).name)}_${nanoid(
+ 5,
+ )}${path.extname(filename)}`;
- // Generate unique filename to avoid conflicts
- const fileExtension = filename.split('.').pop() || '';
- const uniqueFilename = `${uuidv4()}_${filename}`;
+ const nanoId = nanoid(5);
+ const fileDestPath = path.join(destPath, `${nanoId}`);
- // Use attachments service to store the file
- const storedAttachment = await this.attachmentsService.uploadViaURL({
- urls: [
- {
- url: url,
- fileName: uniqueFilename,
- },
- ],
- path: `nc/uploads/${attachmentId}`,
- });
+ const resultAttachmentUrl = await storageAdapter.fileCreateByStream(
+ slash(path.join(fileDestPath, filename)),
+ response.data.pipe(passthrough),
+ );
+
+ const fileSize = contentLength ? Number(contentLength) : totalBytes;
return {
- id: attachmentId,
- url: storedAttachment[0].url,
- title: filename,
- mimetype: contentType,
- size: contentLength ? parseInt(contentLength) : undefined,
- path: storedAttachment[0].path,
+ storageName: storageAdapter.name,
+ url: resultAttachmentUrl,
+ filename,
+ mimeType,
+ fileSize,
};
}
}