Skip to content

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

chore: refactor

DarkPhoenix2704327442468117
diff --git a/packages/nocodb/src/Noco.ts b/packages/nocodb/src/Noco.ts
index cb8125044d..7be96ef40d 100644
--- a/packages/nocodb/src/Noco.ts
+++ b/packages/nocodb/src/Noco.ts
@@ -8,6 +8,7 @@ import dotenv from 'dotenv';
import requestIp from 'request-ip';
import cookieParser from 'cookie-parser';
import { NcDebug } from 'nc-gui/utils/debug';
+import { definePDFJSModule } from 'unpdf';
import type { INestApplication } from '@nestjs/common';
import type { MetaService } from '~/meta/meta.service';
import type { IEventEmitter } from '~/modules/event-emitter/event-emitter.interface';
@@ -23,7 +24,6 @@ import { getAppUrl } from '~/utils/appUrl';
import { DataReflection, Integration } from '~/models';
import { getRedisURL } from '~/helpers/redisHelpers';
import { RedisIoAdapter } from '~/gateways/RedisIoAdapter';
-import { definePDFJSModule } from 'unpdf';
dotenv.config();
declare const module: any;
diff --git a/packages/nocodb/src/db/BaseModelSqlv2.ts b/packages/nocodb/src/db/BaseModelSqlv2.ts
index ff9f9507f2..1eb54a175e 100644
--- a/packages/nocodb/src/db/BaseModelSqlv2.ts
+++ b/packages/nocodb/src/db/BaseModelSqlv2.ts
@@ -132,6 +132,7 @@ import { MetaTable } from '~/utils/globals';
import { chunkArray } from '~/utils/tsUtils';
import { QUERY_STRING_FIELD_ID_ON_RESULT } from '~/constants';
import NocoSocket from '~/socket/NocoSocket';
+import { supportsThumbnails } from '~/utils/attachmentUtils';
dayjs.extend(utc);
@@ -5579,11 +5580,6 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {
attachmentColumns: Record<string, any>[],
d: Record<string, any>,
) {
- // Helper function to check if attachment supports thumbnails
- const supportsThumbnails = (attachment: any) => {
- return attachment.mimetype?.startsWith('image/') || attachment.mimetype?.startsWith('application/pdf');
- };
-
try {
if (d) {
const promises = [];
diff --git a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/generators/base-thumbnail-generator.ts b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/generators/base-thumbnail-generator.ts
index eb35b027fc..cfb8767aaa 100644
--- a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/generators/base-thumbnail-generator.ts
+++ b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/generators/base-thumbnail-generator.ts
@@ -24,15 +24,16 @@ export abstract class BaseThumbnailGenerator {
try {
// Get the thumbnail buffer from the subclass
const thumbnailBuffer = await this.generateThumbnailBuffer(file);
-
+
const sharp = Noco.sharp;
- if (!sharp) {
- this.logger.warn('Sharp not available, skipping thumbnail generation');
- return null;
- }
const thumbnailPaths = {
- card_cover: path.join('nc', 'thumbnails', relativePath, 'card_cover.jpg'),
+ card_cover: path.join(
+ 'nc',
+ 'thumbnails',
+ relativePath,
+ 'card_cover.jpg',
+ ),
small: path.join('nc', 'thumbnails', relativePath, 'small.jpg'),
tiny: path.join('nc', 'thumbnails', relativePath, 'tiny.jpg'),
};
@@ -42,10 +43,18 @@ export abstract class BaseThumbnailGenerator {
for (const [size, thumbnailPath] of Object.entries(thumbnailPaths)) {
let height;
switch (size) {
- case 'card_cover': height = 512; break;
- case 'small': height = 128; break;
- case 'tiny': height = 64; break;
- default: height = 32; break;
+ case 'card_cover':
+ height = 512;
+ break;
+ case 'small':
+ height = 128;
+ break;
+ case 'tiny':
+ height = 64;
+ break;
+ default:
+ height = 32;
+ break;
}
const resizedImage = await sharpImage
diff --git a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts
index 40480df88b..25ab75d98d 100644
--- a/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts
+++ b/packages/nocodb/src/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor.ts
@@ -8,6 +8,7 @@ import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';
import { getPathFromUrl } from '~/helpers/attachmentHelpers';
import { ImageThumbnailGenerator } from '~/modules/jobs/jobs/thumbnail-generator/generators/image-thumbnail-generator';
import { PdfThumbnailGenerator } from '~/modules/jobs/jobs/thumbnail-generator/generators/pdf-thumbnail-generator';
+import Noco from '~/Noco';
export class ThumbnailGeneratorProcessor {
private logger = new Logger(ThumbnailGeneratorProcessor.name);
@@ -19,6 +20,13 @@ export class ThumbnailGeneratorProcessor {
const results = [];
+ const sharp = Noco.sharp;
+
+ if (!sharp) {
+ this.logger.warn('Sharp not available, skipping thumbnail generation');
+ return results;
+ }
+
for (const attachment of attachments) {
const thumbnail = await this.generateThumbnail(attachment, scope);
@@ -61,19 +69,29 @@ export class ThumbnailGeneratorProcessor {
const fileExtension = attachment.title?.toLowerCase() || '';
switch (true) {
- case mimeType === 'application/pdf' || fileExtension.endsWith('.pdf'):
- return await this.pdfGenerator.generateThumbnails(file, relativePath, storageAdapter);
+ case mimeType === 'application/pdf' || fileExtension.endsWith('.pdf'): {
+ if (Noco.isPdfjsInitialized && Noco.canvas)
+ return await this.pdfGenerator.generateThumbnails(
+ file,
+ relativePath,
+ storageAdapter,
+ );
+ return null;
+ }
case mimeType.startsWith('image/'):
- return await this.imageGenerator.generateThumbnails(file, relativePath, storageAdapter);
-
+ return await this.imageGenerator.generateThumbnails(
+ file,
+ relativePath,
+ storageAdapter,
+ );
default:
this.logger.warn({
- message: `Unknown file type, defaulting to image generator`,
+ message: `Unknown file type, skipping thumbnail generation`,
mimetype: mimeType,
filename: attachment.title,
});
- return await this.imageGenerator.generateThumbnails(file, relativePath, storageAdapter);
+ return null;
}
} catch (error) {
this.logger.error({
diff --git a/packages/nocodb/src/services/attachments.service.ts b/packages/nocodb/src/services/attachments.service.ts
index bc4fa90008..79e8241b5c 100644
--- a/packages/nocodb/src/services/attachments.service.ts
+++ b/packages/nocodb/src/services/attachments.service.ts
@@ -22,6 +22,7 @@ import { IJobsService } from '~/modules/jobs/jobs-service.interface';
import { JobTypes } from '~/interface/Jobs';
import { RootScopes } from '~/utils/globals';
import { validateAndNormaliseLocalPath } from '~/helpers/attachmentHelpers';
+import { supportsThumbnails } from '~/utils/attachmentUtils';
import Noco from '~/Noco';
import { UseWorker } from '~/decorators/use-worker.decorator';
@@ -36,8 +37,6 @@ interface AttachmentObject {
signedUrl?: string;
}
-const thumbnailMimes = ['image/', 'application/pdf'];
-
// 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, '_');
@@ -194,7 +193,7 @@ export class AttachmentsService {
}
const generateThumbnail = attachments.filter((attachment) =>
- thumbnailMimes.some((type) => attachment.mimetype.startsWith(type)),
+ supportsThumbnails(attachment),
);
if (generateThumbnail.length) {
@@ -423,7 +422,7 @@ export class AttachmentsService {
}
const generateThumbnail = attachments.filter((attachment) =>
- thumbnailMimes.some((type) => attachment.mimetype.startsWith(type)),
+ supportsThumbnails(attachment),
);
if (generateThumbnail.length) {
diff --git a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts
index 77f7661f5e..74535f72ff 100644
--- a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts
+++ b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts
@@ -24,14 +24,13 @@ import { JobTypes } from '~/interface/Jobs';
import { Audit, FileReference } from '~/models';
import { IJobsService } from '~/modules/jobs/jobs-service.interface';
import { RootScopes } from '~/utils/globals';
+import { supportsThumbnails } from '~/utils/attachmentUtils';
// 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/', 'application/pdf'];
-
const mb = 1024 * 1024;
@Injectable()
@@ -95,11 +94,7 @@ export class DataAttachmentV3Service {
size: downloadedAttachment.fileSize,
};
processedAttachments.push(processedAttachment);
- if (
- thumbnailMimes.some((type) =>
- downloadedAttachment.mimeType.startsWith(type),
- )
- ) {
+ if (supportsThumbnails({ mimetype: downloadedAttachment.mimeType })) {
generateThumbnailAttachments.push(processedAttachment);
}
}
@@ -260,7 +255,7 @@ export class DataAttachmentV3Service {
size: fileSize,
};
processedAttachments.push(processedAttachment);
- if (thumbnailMimes.some((type) => mimeType.startsWith(type))) {
+ if (supportsThumbnails({ mimetype: mimeType })) {
generateThumbnailAttachments.push(processedAttachment);
}
} catch (error) {
diff --git a/packages/nocodb/src/utils/attachmentUtils.ts b/packages/nocodb/src/utils/attachmentUtils.ts
new file mode 100644
index 0000000000..3e810a4556
--- /dev/null
+++ b/packages/nocodb/src/utils/attachmentUtils.ts
@@ -0,0 +1,61 @@
+/**
+ * Checks if a file is an Office document based on MIME type and file extension
+ * @param mimeType - The MIME type of the file
+ * @param fileExtension - The file extension (with or without leading dot)
+ * @returns true if the file is an Office document, false otherwise
+ */
+export function isOfficeDocument(
+ mimeType: string,
+ fileExtension: string,
+): boolean {
+ const officeMimeTypes = [
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
+ 'application/msword', // .doc
+ 'application/vnd.ms-excel', // .xls
+ 'application/vnd.ms-powerpoint', // .ppt
+ 'application/rtf', // .rtf
+ 'application/vnd.oasis.opendocument.text', // .odt
+ 'application/vnd.oasis.opendocument.spreadsheet', // .ods
+ 'application/vnd.oasis.opendocument.presentation', // .odp
+ ];
+
+ const officeExtensions = [
+ '.docx',
+ '.doc',
+ '.xlsx',
+ '.xls',
+ '.pptx',
+ '.ppt',
+ '.rtf',
+ '.odt',
+ '.ods',
+ '.odp',
+ ];
+
+ // Normalize file extension to lowercase and ensure it starts with a dot
+ const normalizedExtension = fileExtension.toLowerCase().startsWith('.')
+ ? fileExtension.toLowerCase()
+ : `.${fileExtension.toLowerCase()}`;
+
+ return (
+ officeMimeTypes.includes(mimeType) ||
+ officeExtensions.includes(normalizedExtension)
+ );
+}
+
+export const supportsThumbnails = (attachment: any) => {
+ const mimetype = attachment.mimetype || attachment.mimeType;
+ const filename =
+ attachment.title || attachment.filename || attachment.name || '';
+
+ // Extract file extension from filename
+ const fileExtension = filename.includes('.')
+ ? filename.substring(filename.lastIndexOf('.'))
+ : '';
+
+ return (
+ mimetype?.startsWith('image/') || mimetype?.startsWith('application/pdf')
+ );
+};