π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
initial develop
Fendy Heryanto15f1c8c6ea18
diff --git a/packages/nocodb/src/db/BaseModelSqlv2/attachment-url-upload-preparator.ts b/packages/nocodb/src/db/BaseModelSqlv2/attachment-url-upload-preparator.tsindex cca1217cfe..645476297c 100644--- a/packages/nocodb/src/db/BaseModelSqlv2/attachment-url-upload-preparator.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2/attachment-url-upload-preparator.ts@@ -4,7 +4,13 @@ import { type AttachmentUrlUploadJobData, JobTypes } from '~/interface/Jobs';import { EMIT_EVENT } from '~/constants';import Noco from '~/Noco';import { dataWrapper } from '~/helpers/dbHelpers';-import { type Column } from '~/models';+import { type Column, FileReference } from '~/models';+import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';+import {+ constructFilePath,+ getFileNameFromUrl,+} from '~/helpers/attachmentHelpers';+import { extractProps } from '~/helpers/extractProps';export class AttachmentUrlUploadPreparator {async prepareAttachmentUrlUpload(@@ -46,6 +52,44 @@ export class AttachmentUrlUploadPreparator {}// only process when temp id existsif (attachmentData.some((attr) => attr.id?.startsWith('temp_'))) {+ const storageAdapter = await NcPluginMgrv2.storageAdapter();+ attachmentData = await Promise.all(+ attachmentData.map(async (attr) => {+ if (attr.id?.startsWith('temp_')) {+ const filePaths = constructFilePath(baseModel.context, {+ columnId: col.id,+ modelId: baseModel.model.id,+ scope: undefined,+ fileName: getFileNameFromUrl({+ url: attr.url,+ scope: undefined,+ }),+ });+ const uploadedPath = storageAdapter.getUploadedPath(+ filePaths.storageDest,+ );+ const id = await FileReference.insert(baseModel.context, {+ storage: storageAdapter.name,+ file_url: uploadedPath.url ?? uploadedPath.path,+ file_size: null,+ fk_user_id: req?.user?.id ?? 'anonymous',+ source_id: baseModel.model.source_id,+ fk_model_id: baseModel.model.id,+ fk_column_id: col.id,+ is_external: !(await baseModel.getSource()).isMeta(),+ });+ return {+ id,+ url: attr.url,+ status: 'uploading',+ type: 'url_request',+ ...filePaths,+ };+ } else {+ return attr;+ }+ }),+ );postInsertOps.push(async (recordId) => {Noco.eventEmitter.emit(EMIT_EVENT.HANDLE_ATTACHMENT_URL_UPLOAD, {jobName: JobTypes.AttachmentUrlUpload,@@ -65,7 +109,12 @@ export class AttachmentUrlUploadPreparator {const columnKeyName = dataWrapper(data).getColumnKeyName(col);// remove temp_ ids so it doesn't get recorded in auditdata[columnKeyName] = JSON.stringify(- attachmentData.filter((dt) => !dt.id?.startsWith('temp_')),+ attachmentData.map((attr) => {+ if (!('status' in attr)) {+ return attr;+ }+ return extractProps(attr, ['id', 'url', 'status', 'type']);+ }),);}}diff --git a/packages/nocodb/src/helpers/attachmentHelpers.ts b/packages/nocodb/src/helpers/attachmentHelpers.tsindex 336dca5c3f..c484b7c70f 100644--- a/packages/nocodb/src/helpers/attachmentHelpers.ts+++ b/packages/nocodb/src/helpers/attachmentHelpers.ts@@ -3,6 +3,7 @@ import fs from 'fs';import mime from 'mime/lite';import slash from 'slash';import { PublicAttachmentScope } from 'nocodb-sdk';+import { nanoid } from 'nanoid';import type { NcContext } from 'nocodb-sdk';import type { Column } from '~/models';import { getToolDir } from '~/utils/nc-config';@@ -88,3 +89,65 @@ export const validateNumberOfFilesInCell = async (_number: number,_column: Column,) => {};++// 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, '_');+};++export const getFileNameFromUrl = (param: { url: string; scope?: string }) => {+ let filename = param.url.split('/').pop()?.split('?')[0] || 'attachment';+ filename = param.scope+ ? `${normalizeFilename(path.parse(filename).name)}${path.extname(filename)}`+ : `${normalizeFilename(path.parse(filename).name)}_${nanoid(+ 5,+ )}${path.extname(filename)}`;+ return filename;+};++export interface AttachmentFilePathConstructed {+ workspaceId?: string;+ baseId: string;+ modelId: string;+ columnId: string;+ scope?: string;++ filePath: string;+ destPath: string;+ fileName: string;+ storageDest: string;+}++export const constructFilePath = (+ context: NcContext,+ param: {+ fileName: string;+ modelId: string;+ columnId: string;+ scope?: string;+ },+) => {+ const filePath = path.join(+ ...[+ context.workspace_id,+ context.base_id,+ param.modelId,+ param.columnId,+ param.scope ? nanoid(5) : undefined,+ ].filter((k) => k),+ );++ const destPath = path.join(...['nc', param.scope ?? 'uploads', filePath]);++ return {+ workspaceId: context.workspace_id,+ baseId: context.base_id,+ modelId: param.modelId,+ columnId: param.columnId,+ scope: param.scope,+ filePath,+ destPath,+ fileName: param.fileName,+ storageDest: slash(path.join(destPath, param.fileName)),+ } as AttachmentFilePathConstructed;+};diff --git a/packages/nocodb/src/models/FileReference.ts b/packages/nocodb/src/models/FileReference.tsindex cbf50c35d9..642390e092 100644--- a/packages/nocodb/src/models/FileReference.ts+++ b/packages/nocodb/src/models/FileReference.ts@@ -60,6 +60,40 @@ export default class FileReference {return id;}+ // used when url downloaded+ public static async updateById(+ context: NcContext,+ id: string,+ fileRefObj: Partial<FileReference>,+ ncMeta = Noco.ncMeta,+ ) {+ const updateObj = extractProps(fileRefObj, [+ 'storage',+ 'file_url',+ 'file_size',+ 'fk_user_id',+ 'source_id',+ 'fk_model_id',+ 'fk_column_id',+ 'is_external',+ 'deleted',+ ]);++ await ncMeta.metaUpdate(+ context.workspace_id,+ context.base_id,+ MetaTable.FILE_REFERENCES,+ updateObj,+ id,+ );++ if (context.workspace_id && !updateObj.deleted) {+ await this.updateWorkspaceCache(context, updateObj.file_size);+ }++ return id;+ }+public static async delete(context: NcContext,fileReferenceId: string | string[],diff --git a/packages/nocodb/src/plugins/GenericS3/GenericS3.ts b/packages/nocodb/src/plugins/GenericS3/GenericS3.tsindex 19af76e42d..45493441ea 100644--- a/packages/nocodb/src/plugins/GenericS3/GenericS3.ts+++ b/packages/nocodb/src/plugins/GenericS3/GenericS3.ts@@ -272,4 +272,8 @@ export default class GenericS3 implements IStorageAdapterV2 {return stream;}++ getUploadedPath(path: string): { path?: string; url?: string } {+ return { path };+ }}diff --git a/packages/nocodb/src/plugins/gcs/Gcs.ts b/packages/nocodb/src/plugins/gcs/Gcs.tsindex d10741faff..189a9c1d16 100644--- a/packages/nocodb/src/plugins/gcs/Gcs.ts+++ b/packages/nocodb/src/plugins/gcs/Gcs.ts@@ -229,4 +229,14 @@ export default class Gcs implements IStorageAdapterV2 {return stream;}++ getUploadedPath(path: string): { path?: string; url?: string } {+ // TODO: verify this+ return {+ url: this.storageClient+ .bucket(this.bucketName)+ .file(this.patchKey(path))+ .publicUrl(),+ };+ }}diff --git a/packages/nocodb/src/plugins/linode/LinodeObjectStorage.ts b/packages/nocodb/src/plugins/linode/LinodeObjectStorage.tsindex 105ceda0b7..783b0f93c3 100644--- a/packages/nocodb/src/plugins/linode/LinodeObjectStorage.ts+++ b/packages/nocodb/src/plugins/linode/LinodeObjectStorage.ts@@ -41,4 +41,10 @@ export default class LinodeObjectStoragethis.s3Client = new S3Client(s3Options);}++ getUploadedPath(path: string): { path?: string; url?: string } {+ return {+ url: `https://${this.input.bucket}.${this.input.region}.linodeobjects.com/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/minio/Minio.ts b/packages/nocodb/src/plugins/minio/Minio.tsindex 3122cd31e1..0a288e1d29 100644--- a/packages/nocodb/src/plugins/minio/Minio.ts+++ b/packages/nocodb/src/plugins/minio/Minio.ts@@ -297,4 +297,19 @@ export default class Minio implements IStorageAdapterV2 {return stream;}++ getUploadedPath(path: string): { path?: string; url?: string } {+ let url: string;+ // TODO: verify this+ if (this.input.useSSL && this.input.port === 443) {+ url = `https://${this.input.endPoint}/${path}`;+ } else if (!this.input.useSSL && this.input.port === 80) {+ url = `http://${this.input.endPoint}/${path}`;+ } else {+ url = `http${this.input.useSSL ? 's' : ''}://${this.input.endPoint}:${+ this.input.port+ }/${path}`;+ }+ return { path, url };+ }}diff --git a/packages/nocodb/src/plugins/ovhCloud/OvhCloud.ts b/packages/nocodb/src/plugins/ovhCloud/OvhCloud.tsindex 5a07f2ec73..a62b443f67 100644--- a/packages/nocodb/src/plugins/ovhCloud/OvhCloud.ts+++ b/packages/nocodb/src/plugins/ovhCloud/OvhCloud.ts@@ -41,4 +41,10 @@ export default class OvhCloud extends GenericS3 implements IStorageAdapterV2 {this.s3Client = new S3Client(s3Options);}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ return {+ url: `https://s3.${this.input.region}.cloud.ovh.net/${this.input.bucket}/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/r2/R2.ts b/packages/nocodb/src/plugins/r2/R2.tsindex fb9e46ae4c..d67a48a83f 100644--- a/packages/nocodb/src/plugins/r2/R2.ts+++ b/packages/nocodb/src/plugins/r2/R2.ts@@ -46,4 +46,10 @@ export default class R2 extends GenericS3 implements IStorageAdapterV2 {this.s3Client = new S3Client(s3Options);}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ return {+ url: `${this.input.hostname}/${this.input.bucket}/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/s3/S3.ts b/packages/nocodb/src/plugins/s3/S3.tsindex 1e87b3b044..ca02b75133 100644--- a/packages/nocodb/src/plugins/s3/S3.ts+++ b/packages/nocodb/src/plugins/s3/S3.ts@@ -92,4 +92,11 @@ export default class S3 extends GenericS3 implements IStorageAdapterV2 {throw error;}}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ const usePath = path.startsWith('/') ? path.replace(/$\/+/, '') : path;+ return {+ url: `https://${this.input.bucket}.s3.${this.input.region}.amazonaws.com/${usePath}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/scaleway/ScalewayObjectStorage.ts b/packages/nocodb/src/plugins/scaleway/ScalewayObjectStorage.tsindex a344669639..ab34854c83 100644--- a/packages/nocodb/src/plugins/scaleway/ScalewayObjectStorage.ts+++ b/packages/nocodb/src/plugins/scaleway/ScalewayObjectStorage.ts@@ -43,4 +43,10 @@ export default class ScalewayObjectStoragethis.s3Client = new S3Client(s3Options);}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ return {+ url: `https://s3.${this.input.region}.scw.cloud/${this.input.bucket}/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/spaces/Spaces.ts b/packages/nocodb/src/plugins/spaces/Spaces.tsindex bb0a254a02..b9b83c719f 100644--- a/packages/nocodb/src/plugins/spaces/Spaces.ts+++ b/packages/nocodb/src/plugins/spaces/Spaces.ts@@ -64,4 +64,12 @@ export default class Spaces extends GenericS3 implements IStorageAdapterV2 {this.s3Client = new S3Client(s3Options);}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ return {+ url: `https://${this.input.bucket}.${+ this.input.region || 'nyc3'+ }.digitaloceanspaces.com/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/storage/Local.ts b/packages/nocodb/src/plugins/storage/Local.tsindex 86baf5c332..2b5b404672 100644--- a/packages/nocodb/src/plugins/storage/Local.ts+++ b/packages/nocodb/src/plugins/storage/Local.ts@@ -155,4 +155,13 @@ export default class Local implements IStorageAdapterV2 {test(): Promise<boolean> {return Promise.resolve(false);}+ getUploadedPath(filePath: string): { path?: string; url?: string } {+ const usePath = filePath.startsWith('/')+ ? filePath.replace(/$\/+/, '')+ : filePath;++ return {+ path: path.join('download', usePath),+ };+ }}diff --git a/packages/nocodb/src/plugins/upcloud/UpoCloud.ts b/packages/nocodb/src/plugins/upcloud/UpoCloud.tsindex d743de5152..2d57db03f4 100644--- a/packages/nocodb/src/plugins/upcloud/UpoCloud.ts+++ b/packages/nocodb/src/plugins/upcloud/UpoCloud.ts@@ -44,4 +44,13 @@ export default class UpoCloud extends GenericS3 implements IStorageAdapterV2 {this.s3Client = new S3Client(s3Options);}++ override getUploadedPath(path: string): { path?: string; url?: string } {+ const updatedEndpoint = this.input.endpoint.startsWith('https://')+ ? this.input.endpoint+ : `https://${this.input.endpoint}`;+ return {+ url: `${updatedEndpoint}/${this.input.bucket}/${path}`,+ };+ }}diff --git a/packages/nocodb/src/plugins/vultr/Vultr.ts b/packages/nocodb/src/plugins/vultr/Vultr.tsindex 83dcf88564..6b91e9d27b 100644--- a/packages/nocodb/src/plugins/vultr/Vultr.ts+++ b/packages/nocodb/src/plugins/vultr/Vultr.ts@@ -40,4 +40,12 @@ export default class Vultr extends GenericS3 implements IStorageAdapterV2 {this.s3Client = new S3Client(s3Options);}+ override getUploadedPath(path: string): { path?: string; url?: string } {+ const updatedEndpoint = this.input.hostname.startsWith('https://')+ ? this.input.hostname+ : `https://${this.input.hostname}`;+ return {+ url: `${updatedEndpoint}/${this.input.bucket}/${path}`,+ };+ }}diff --git a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts b/packages/nocodb/src/services/v3/data-attachment-v3.service.tsindex 74535f72ff..21dd42a7ad 100644--- a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts+++ b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts@@ -5,12 +5,17 @@ import axios from 'axios';import { nanoid } from 'nanoid';import slash from 'slash';import { AuditV1OperationTypes, ncIsNull } from 'nocodb-sdk';-import type { DataUpdatePayload } from 'nocodb-sdk';+import type { DataUpdatePayload, NcContext } from 'nocodb-sdk';import type {AttachmentBase64UploadParam,AttachmentUrlUploadParam,} from '~/types/data-columns/attachment';-import { validateNumberOfFilesInCell } from '~/helpers/attachmentHelpers';+import type { AttachmentFilePathConstructed } from '~/helpers/attachmentHelpers';+import { extractProps } from '~/helpers/extractProps';+import {+ constructFilePath,+ validateNumberOfFilesInCell,+} from '~/helpers/attachmentHelpers';import { extractColsMetaForAudit, generateAuditV1Payload } from '~/utils';import { NcError } from '~/helpers/ncError';import { DataV3Service } from '~/services/v3/data-v3.service';@@ -54,35 +59,36 @@ export class DataAttachmentV3Service {for (const attachment of attachments) {try {- if (attachment.id && !attachment.id.startsWith('temp_')) {+ if (+ attachment.id &&+ 'status' in attachment &&+ attachment.status !== 'uploading'+ ) {processedAttachments.push(attachment);- } else if (attachment.url) {+ } else if (+ attachment.url &&+ 'status' in attachment &&+ attachment.status === 'uploading' &&+ attachment.type === 'url_request'+ ) {// 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,++ const downloadedAttachment = await this.downloadAndStoreAttachment(+ context,+ {+ filePath: attachment,+ url: attachment.url,+ scope,+ },+ );++ // update fileSize, url due to fileName, etc+ await FileReference.updateById(context, attachment.id, {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,+ id: attachment.id,url: ncIsNull(downloadedAttachment.url)? undefined: downloadedAttachment.url,@@ -138,9 +144,12 @@ export class DataAttachmentV3Service {}),data: { [column.title]: processedAttachments },old_data: {- [column.title]: attachments.filter(- (attr) => attr.id && !attr.id.startsWith('temp_'),- ),+ [column.title]: attachments.map((attr) => {+ if (!('status' in attr)) {+ return attr;+ }+ return extractProps(attr, ['id', 'url', 'status', 'type']);+ }),},},req: req ?? ({ user: context.user } as any),@@ -325,15 +334,18 @@ export class DataAttachmentV3Service {});}- protected async downloadAndStoreAttachment({- url,- filePath,- scope,- }: {- url: string;- filePath: string;- scope: string;- }) {+ protected async downloadAndStoreAttachment(+ context: NcContext,+ {+ url,+ filePath,+ scope,+ }: {+ url: string;+ filePath: AttachmentFilePathConstructed;+ scope: string;+ },+ ) {// Configure axios for downloadconst response = await axios({method: 'GET',@@ -361,26 +373,27 @@ export class DataAttachmentV3Service {const mimeType = contentType.split(';')[0].trim();// Extract filename from URL or content-disposition header- let filename = url.split('/').pop()?.split('?')[0] || 'attachment';+ let filename;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)}`;}}- 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 filePathConstructed = filename+ ? constructFilePath(context, { ...filePath, fileName: filename })+ : filePath;const resultAttachmentUrl = await storageAdapter.fileCreateByStream(- slash(path.join(destPath, filename)),+ filePathConstructed.storageDest,response.data.pipe(passthrough),);const fileSize = contentLength ? Number(contentLength) : totalBytes;@@ -388,7 +401,7 @@ export class DataAttachmentV3Service {return {storageName: storageAdapter.name,url: resultAttachmentUrl,- path: path.join('download', filePath, filename),+ path: path.join('download', filePathConstructed.filePath, filename),filename,mimeType,fileSize,diff --git a/packages/nocodb/src/types/data-columns/attachment.ts b/packages/nocodb/src/types/data-columns/attachment.tsindex b4e06d31c9..9be0e2dd3f 100644--- a/packages/nocodb/src/types/data-columns/attachment.ts+++ b/packages/nocodb/src/types/data-columns/attachment.ts@@ -1,3 +1,4 @@+import type { AttachmentFilePathConstructed } from '~/helpers/attachmentHelpers';import type { NcContext, NcRequest, PublicAttachmentScope } from 'nocodb-sdk';// Attachment data types for v3 API@@ -24,10 +25,18 @@ export interface AttachmentUrlUploadParam {column_name: string;};recordId: string;- attachments: {- id?: string;- url: string;- }[];+ attachments: (+ | {+ id?: string;+ url: string;+ }+ | ({+ id?: string;+ url: string;+ status?: string;+ type?: string;+ } & AttachmentFilePathConstructed)+ )[];}export interface AttachmentBase64UploadParam {diff --git a/packages/nocodb/src/types/nc-plugin/lib/IStorageAdapterV2.ts b/packages/nocodb/src/types/nc-plugin/lib/IStorageAdapterV2.tsindex a38f0a79f8..b52c5ad2cd 100644--- a/packages/nocodb/src/types/nc-plugin/lib/IStorageAdapterV2.ts+++ b/packages/nocodb/src/types/nc-plugin/lib/IStorageAdapterV2.ts@@ -40,4 +40,8 @@ export default interface IStorageAdapterV2<): Promise<Readable>;getDirectoryList(path: string): Promise<string[]>;scanFiles(_globPattern: string): Promise<Readable>;+ getUploadedPath(path: string): {+ path?: string;+ url?: string;+ };}