Skip to content

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

refactor in preparation for cell append

Fendy Heryanto91f2ccf05d23
diff --git a/packages/nocodb/src/interface/Jobs.ts b/packages/nocodb/src/interface/Jobs.ts
index 3317fdc27b..1cdd4120f7 100644
--- a/packages/nocodb/src/interface/Jobs.ts
+++ b/packages/nocodb/src/interface/Jobs.ts
@@ -1,3 +1,4 @@
+import type { AttachmentUrlUploadParam } from '~/types/data-columns/attachment';
import type {
AttachmentResType,
PublicAttachmentScope,
@@ -228,18 +229,4 @@ export interface SyncDataSyncModuleJobData extends JobData {
req: NcRequest;
}
-export interface AttachmentUrlUploadJobData extends JobData {
- context: NcContext;
- scope?: PublicAttachmentScope;
- modelId: string;
- column: {
- id: string;
- title: string;
- column_name: string;
- };
- recordId: string;
- attachments: {
- id?: string;
- url: string;
- }[];
-}
+export type AttachmentUrlUploadJobData = AttachmentUrlUploadParam & JobData;
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 c3f4a20cee..efec3a5b03 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,184 +1,15 @@
-import path from 'path';
-import { PassThrough } from 'stream';
-import axios from 'axios';
-import { forwardRef, Inject, Injectable } from '@nestjs/common';
-import slash from 'slash';
-import { nanoid } from 'nanoid';
-import { IJobsService } from '../../jobs-service.interface';
+import { Injectable } from '@nestjs/common';
import type { Job } from 'bull';
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 { 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, '_');
-};
+import { DataAttachmentV3Service } from '~/services/v3/data-attachment-v3.service';
@Injectable()
export class AttachmentUrlUploadProcessor {
constructor(
- @Inject(forwardRef(() => 'JobsService'))
- private readonly jobsService: IJobsService,
+ private readonly dataAttachmentV3Service: DataAttachmentV3Service,
) {}
async job(job: Job<AttachmentUrlUploadJobData>) {
- const { context, modelId, column, recordId, scope, attachments } = job.data;
-
- const baseModel = await getBaseModelSqlFromModelId({
- context: context,
- modelId: modelId,
- });
- await baseModel.model.getColumns(context);
- const processedAttachments = [];
- const generateThumbnailAttachments = [];
-
- for (const attachment of attachments) {
- try {
- if (attachment.id && !attachment.id.startsWith('temp_')) {
- processedAttachments.push(attachment);
- } else if (attachment.url) {
- // If attachment has URL, download and process it
- const downloadedAttachment = await this.downloadAndStoreAttachment({
- filePath: path.join(
- ...[
- 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 ?? downloadedAttachment.path,
- 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,
- path: downloadedAttachment.path,
- 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);
- }
- }
- // direct update to prevent prepare noco data again
- await baseModel
- .dbDriver(baseModel.getTnPath(baseModel.model))
- .update({
- [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({
- url,
- filePath,
- scope,
- }: {
- url: string;
- filePath: string;
- scope: string;
- }) {
- // Configure axios for download
- const response = await axios({
- method: 'GET',
- url: url,
- responseType: 'stream',
- maxRedirects: NC_ATTACHMENT_URL_MAX_REDIRECT,
- maxContentLength: NC_ATTACHMENT_FIELD_SIZE,
- });
-
- // Extract file information from response headers
- const contentType =
- response.headers['content-type'] || 'application/octet-stream';
- 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) {
- const filenameMatch = contentDisposition.match(
- /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
- );
- if (filenameMatch && filenameMatch[1]) {
- 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)}`;
-
- const destPath = path.join(...['nc', scope ?? 'uploads', filePath]);
- const resultAttachmentUrl = await storageAdapter.fileCreateByStream(
- slash(path.join(destPath, filename)),
- response.data.pipe(passthrough),
- );
- const fileSize = contentLength ? Number(contentLength) : totalBytes;
-
- return {
- storageName: storageAdapter.name,
- url: resultAttachmentUrl,
- path: path.join('download', filePath, filename),
- filename,
- mimeType,
- fileSize,
- };
+ await this.dataAttachmentV3Service.handleUrlUploadCellUpdate(job.data);
}
}
diff --git a/packages/nocodb/src/modules/noco.module.ts b/packages/nocodb/src/modules/noco.module.ts
index 38f1e434a7..c2fd3d56a2 100644
--- a/packages/nocodb/src/modules/noco.module.ts
+++ b/packages/nocodb/src/modules/noco.module.ts
@@ -154,6 +154,7 @@ import { AttachmentUrlUploadHandler } from '~/services/emit-handler/attachment-u
/* ACL */
import { AclMiddleware } from '~/middlewares/extract-ids/extract-ids.middleware';
+import { DataAttachmentV3Service } from '~/services/v3/data-attachment-v3.service';
export const nocoModuleMetadata = {
imports: [
@@ -327,6 +328,7 @@ export const nocoModuleMetadata = {
PublicDatasService,
PublicDatasExportService,
DataV3Service,
+ DataAttachmentV3Service,
// use custom provider to avoid circular dependency
{
@@ -378,6 +380,7 @@ export const nocoModuleMetadata = {
BulkDataAliasService,
DataTableService,
DataV3Service,
+ DataAttachmentV3Service,
AttachmentUrlUploadHandler,
],
diff --git a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts
new file mode 100644
index 0000000000..104abe1263
--- /dev/null
+++ b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts
@@ -0,0 +1,182 @@
+import path from 'path';
+import { PassThrough } from 'stream';
+import { forwardRef, Inject, Injectable } from '@nestjs/common';
+import axios from 'axios';
+import { nanoid } from 'nanoid';
+import slash from 'slash';
+import type { AttachmentUrlUploadParam } from '~/types/data-columns/attachment';
+import {
+ NC_ATTACHMENT_FIELD_SIZE,
+ NC_ATTACHMENT_URL_MAX_REDIRECT,
+} from '~/constants';
+import { _wherePk, getBaseModelSqlFromModelId } from '~/helpers/dbHelpers';
+import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';
+import { JobTypes } from '~/interface/Jobs';
+import { FileReference } from '~/models';
+import { IJobsService } from '~/modules/jobs/jobs-service.interface';
+import { RootScopes } from '~/utils/globals';
+
+// 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, '_');
+};
+
+const thumbnailMimes = ['image/'];
+
+@Injectable()
+export class DataAttachmentV3Service {
+ constructor(
+ @Inject(forwardRef(() => 'JobsService'))
+ private readonly jobsService: IJobsService,
+ ) {}
+ async handleUrlUploadCellUpdate(param: AttachmentUrlUploadParam) {
+ const { context, modelId, column, recordId, scope, attachments } = param;
+
+ const baseModel = await getBaseModelSqlFromModelId({
+ context: context,
+ modelId: modelId,
+ });
+ await baseModel.model.getColumns(context);
+ const processedAttachments = [];
+ const generateThumbnailAttachments = [];
+
+ for (const attachment of attachments) {
+ try {
+ if (attachment.id && !attachment.id.startsWith('temp_')) {
+ processedAttachments.push(attachment);
+ } else if (attachment.url) {
+ // If attachment has URL, download and process it
+ const downloadedAttachment = await this.downloadAndStoreAttachment({
+ filePath: path.join(
+ ...[
+ 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 ?? downloadedAttachment.path,
+ 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,
+ path: downloadedAttachment.path,
+ 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);
+ }
+ }
+ // direct update to prevent prepare noco data again
+ await baseModel
+ .dbDriver(baseModel.getTnPath(baseModel.model))
+ .update({
+ [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,
+ });
+ }
+ }
+
+ protected async downloadAndStoreAttachment({
+ url,
+ filePath,
+ scope,
+ }: {
+ url: string;
+ filePath: string;
+ scope: string;
+ }) {
+ // Configure axios for download
+ const response = await axios({
+ method: 'GET',
+ url: url,
+ responseType: 'stream',
+ maxRedirects: NC_ATTACHMENT_URL_MAX_REDIRECT,
+ maxContentLength: NC_ATTACHMENT_FIELD_SIZE,
+ });
+
+ // Extract file information from response headers
+ const contentType =
+ response.headers['content-type'] || 'application/octet-stream';
+ 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) {
+ const filenameMatch = contentDisposition.match(
+ /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
+ );
+ if (filenameMatch && filenameMatch[1]) {
+ 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)}`;
+
+ const destPath = path.join(...['nc', scope ?? 'uploads', filePath]);
+ const resultAttachmentUrl = await storageAdapter.fileCreateByStream(
+ slash(path.join(destPath, filename)),
+ response.data.pipe(passthrough),
+ );
+ const fileSize = contentLength ? Number(contentLength) : totalBytes;
+
+ return {
+ storageName: storageAdapter.name,
+ url: resultAttachmentUrl,
+ path: path.join('download', filePath, filename),
+ filename,
+ mimeType,
+ fileSize,
+ };
+ }
+}
diff --git a/packages/nocodb/src/types/data-columns/attachment.ts b/packages/nocodb/src/types/data-columns/attachment.ts
index 55580b1893..b2214b12be 100644
--- a/packages/nocodb/src/types/data-columns/attachment.ts
+++ b/packages/nocodb/src/types/data-columns/attachment.ts
@@ -1,3 +1,5 @@
+import type { NcContext, PublicAttachmentScope } from 'nocodb-sdk';
+
// Attachment data types for v3 API
export interface DataAttachmentRequestUrl {
url: string;
@@ -7,13 +9,22 @@ export interface DataAttachmentRequestId {
id: string;
}
-export type DataAttachmentRequest = DataAttachmentRequestUrl | DataAttachmentRequestId;
+export type DataAttachmentRequest =
+ | DataAttachmentRequestUrl
+ | DataAttachmentRequestId;
-export interface DataAttachmentResponse {
- id: string;
- url: string;
- title?: string;
- mimetype?: string;
- size?: number;
- path?: string;
-}
\ No newline at end of file
+export interface AttachmentUrlUploadParam {
+ context: NcContext;
+ scope?: PublicAttachmentScope;
+ modelId: string;
+ column: {
+ id: string;
+ title: string;
+ column_name: string;
+ };
+ recordId: string;
+ attachments: {
+ id?: string;
+ url: string;
+ }[];
+}