π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: add PDF thumbnail generation migration job for existing attachments
DarkPhoenix270408600db8a5c0
diff --git a/packages/nocodb/src/interface/Jobs.ts b/packages/nocodb/src/interface/Jobs.tsindex 7c1a5790fb..8f92e83252 100644--- a/packages/nocodb/src/interface/Jobs.ts+++ b/packages/nocodb/src/interface/Jobs.ts@@ -13,6 +13,7 @@ export const JOBS_QUEUE = 'jobs';export enum MigrationJobTypes {Attachment = 'attachment',Thumbnail = 'thumbnail',+ PdfThumbnail = 'pdf-thumbnail',RecoverLinks = 'recover-links',CleanupDuplicateColumns = 'cleanup-duplicate-columns',NoOpMigration = 'no-op-migration',diff --git a/packages/nocodb/src/modules/jobs/jobs.module.ts b/packages/nocodb/src/modules/jobs/jobs.module.tsindex 74ce6a2f11..bdaea69c89 100644--- a/packages/nocodb/src/modules/jobs/jobs.module.ts+++ b/packages/nocodb/src/modules/jobs/jobs.module.ts@@ -42,6 +42,7 @@ import { OrderColumnMigration } from '~/modules/jobs/migration-jobs/nc_job_005_oimport { RecoverOrderColumnMigration } from '~/modules/jobs/migration-jobs/nc_job_007_recover_order_column';import { NoOpMigration } from '~/modules/jobs/migration-jobs/nc_job_no_op';import { AuditMigration } from '~/modules/jobs/migration-jobs/nc_job_009_audit_migration';+import { PdfThumbnailMigration } from '~/modules/jobs/migration-jobs/nc_job_010_pdf_thumbnail';// Jobs Module Relatedimport { JobsLogService } from '~/modules/jobs/jobs/jobs-log.service';@@ -132,6 +133,7 @@ export const JobsModuleMetadata = {RecoverOrderColumnMigration,RecoverDisconnectedTableNames,AuditMigration,+ PdfThumbnailMigration,],exports: ['JobsService'],};diff --git a/packages/nocodb/src/modules/jobs/migration-jobs/init-migration-jobs.ts b/packages/nocodb/src/modules/jobs/migration-jobs/init-migration-jobs.tsindex f152fe83e5..5db399899d 100644--- a/packages/nocodb/src/modules/jobs/migration-jobs/init-migration-jobs.ts+++ b/packages/nocodb/src/modules/jobs/migration-jobs/init-migration-jobs.ts@@ -18,6 +18,7 @@ import { OrderColumnMigration } from '~/modules/jobs/migration-jobs/nc_job_005_oimport { RecoverOrderColumnMigration } from '~/modules/jobs/migration-jobs/nc_job_007_recover_order_column';import { NoOpMigration } from '~/modules/jobs/migration-jobs/nc_job_no_op';import { AuditMigration } from '~/modules/jobs/migration-jobs/nc_job_009_audit_migration';+import { PdfThumbnailMigration } from '~/modules/jobs/migration-jobs/nc_job_010_pdf_thumbnail';import { isEE } from '~/utils';@Injectable()@@ -68,6 +69,11 @@ export class InitMigrationJobs {job: MigrationJobTypes.AuditMigration,service: this.auditMigration,},+ // {+ // version: '10',+ // job: MigrationJobTypes.PdfThumbnail,+ // service: this.pdfThumbnailMigration,+ // },];private readonly debugLog = debug('nc:migration-jobs:init');@@ -84,6 +90,7 @@ export class InitMigrationJobs {private readonly recoverDisconnectedTableNames: RecoverDisconnectedTableNames,private readonly noOpMigration: NoOpMigration,private readonly auditMigration: AuditMigration,+ private readonly pdfThumbnailMigration: PdfThumbnailMigration,) {}log = (...msgs: string[]) => {diff --git a/packages/nocodb/src/modules/jobs/migration-jobs/nc_job_010_pdf_thumbnail.ts b/packages/nocodb/src/modules/jobs/migration-jobs/nc_job_010_pdf_thumbnail.tsnew file mode 100644index 0000000000..2c742c13f1--- /dev/null+++ b/packages/nocodb/src/modules/jobs/migration-jobs/nc_job_010_pdf_thumbnail.ts@@ -0,0 +1,347 @@+import path from 'path';+import debug from 'debug';+import { Injectable } from '@nestjs/common';+import PQueue from 'p-queue';+import mime from 'mime/lite';+import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';+import Noco from '~/Noco';+import { RootScopes } from '~/utils/globals';+import { ThumbnailGeneratorProcessor } from '~/modules/jobs/jobs/thumbnail-generator/thumbnail-generator.processor';+import { getPathFromUrl } from '~/helpers/attachmentHelpers';++@Injectable()+export class PdfThumbnailMigration {+ private readonly debugLog = debug('nc:migration-jobs:pdf-thumbnail');++ constructor(+ private readonly thumbnailGeneratorProcessor: ThumbnailGeneratorProcessor,+ ) {}++ log = (...msgs: string[]) => {+ console.log('[nc_job_010_pdf_thumbnail]: ', ...msgs);+ };++ async job() {+ try {+ const isPdfjsInitialized = Noco.isPdfjsInitialized;++ if (!isPdfjsInitialized) {+ this.log(+ `Pdfjs initialization is not supported in this platform at the moment. Skipping thumbnail migration for pdf for now!`,+ );+ return true;+ }++ const ncMeta = Noco.ncMeta;++ const storageAdapter = await NcPluginMgrv2.storageAdapter(ncMeta);++ const temp_file_references_table = 'nc_temp_pdf_references';++ const fileReferencesTableExists =+ await ncMeta.knexConnection.schema.hasTable(temp_file_references_table);++ // fallback scanning all files if temp table is not generated from previous migration+ if (!fileReferencesTableExists) {+ // create temp file references table if not exists+ await ncMeta.knexConnection.schema.createTable(+ temp_file_references_table,+ (table) => {+ table.increments('id').primary();+ table.string('file_path').notNullable();+ table.string('mimetype');+ table.boolean('referenced').defaultTo(false);+ table.boolean('thumbnail_generated').defaultTo(false);++ table.index('file_path');+ },+ );++ const fileScanStream = await storageAdapter.scanFiles('nc/uploads/**');++ const fileReferenceBuffer = [];++ const insertPromises = [];++ let filesCount = 0;++ let err = null;++ fileScanStream.on('data', async (file) => {+ const fileNameWithExt = path.basename(file);++ const mimetype = mime.getType(path.extname(fileNameWithExt).slice(1));++ fileReferenceBuffer.push({+ file_path: file,+ mimetype,+ referenced: true,+ });++ if (fileReferenceBuffer.length >= 100) {+ try {+ const processBuffer = fileReferenceBuffer.splice(0);++ filesCount += processBuffer.length;++ // skip or insert file references+ const toSkip = await ncMeta+ .knexConnection(temp_file_references_table)+ .whereIn(+ 'file_path',+ fileReferenceBuffer.map((f) => f.file_path),+ );++ const toSkipPaths = toSkip.map((f) => f.file_path);++ const toInsert = processBuffer.filter(+ (f) => !toSkipPaths.includes(f.file_path),+ );++ if (toInsert.length > 0) {+ insertPromises.push(+ ncMeta+ .knexConnection(temp_file_references_table)+ .insert(toInsert)+ .catch((e) => {+ this.log(`Error inserting file references`);+ this.log(e);+ err = e;+ }),+ );+ }++ this.log(`Scanned ${filesCount} files`);+ } catch (e) {+ this.log(`There was an error while scanning files`);+ this.log(e);+ err = e;+ }+ }+ });++ try {+ await new Promise((resolve, reject) => {+ fileScanStream.on('end', resolve);+ fileScanStream.on('error', reject);+ });++ await Promise.all(insertPromises);+ } catch (e) {+ this.log(`There was an error while scanning files`);+ this.log(e);+ throw e;+ }++ filesCount += fileReferenceBuffer.length;+ this.log(`Completed scanning with ${filesCount} files`);++ // throw if there was an async error while scanning files+ if (err) {+ throw err;+ }++ if (fileReferenceBuffer.length > 0) {+ await ncMeta+ .knexConnection(temp_file_references_table)+ .insert(fileReferenceBuffer);+ }+ }++ const numberOfPdfToBeProcessed = (+ await ncMeta+ .knexConnection(temp_file_references_table)+ .where('thumbnail_generated', false)+ .andWhere('referenced', true)+ .andWhere('mimetype', 'application/pdf')+ .count('*', { as: 'count' })+ .first()+ )?.count;++ let processedPdfs = 0;++ const limit = 10;+ const parallelLimit = 1;++ const skipPdfs = [];+ let processingPdfs: {+ id: string;+ processed: boolean;+ }[] = [];++ const queue = new PQueue({ concurrency: parallelLimit });++ this.log(+ `Starting pdf thumbnail generation for ${numberOfPdfToBeProcessed} pdfs`,+ );++ const wrapper = async (+ fileReference: {+ id: string;+ file_path: string;+ mimetype: string;+ },+ isUrl: boolean,+ ) => {+ try {+ const attachment: {+ url?: string;+ path?: string;+ mimetype?: string;+ } = {};++ if (isUrl) {+ attachment.url = fileReference.file_path;+ attachment.mimetype = fileReference.mimetype;+ } else {+ attachment.path = path.join(+ 'download',+ fileReference.file_path.replace(/^nc\/uploads\//, ''),+ );+ attachment.mimetype = fileReference.mimetype;+ }++ // manually call thumbnail generator job to control the concurrency+ const thumbnailGenerated = await this.thumbnailGeneratorProcessor.job(+ {+ data: {+ context: {+ base_id: RootScopes.ROOT,+ workspace_id: RootScopes.ROOT,+ },+ attachments: [attachment],+ },+ } as any,+ );++ if (thumbnailGenerated.length > 0) {+ await ncMeta+ .knexConnection(temp_file_references_table)+ .where('id', fileReference.id)+ .update({+ thumbnail_generated: true,+ });+ } else {+ this.log(+ `Error generating thumbnail for file ${fileReference.file_path}`,+ );+ skipPdfs.push(fileReference.id);+ }+ } catch (e) {+ this.log(+ `Error generating thumbnail for file ${fileReference.file_path}`,+ );+ this.log(e);+ skipPdfs.push(fileReference.id);+ } finally {+ processedPdfs += 1;+ this.log(+ `Processed ${processedPdfs} out of ${numberOfPdfToBeProcessed} pdfs`,+ );+ const processingPdf = processingPdfs.find(+ (p) => p.id === fileReference.id,+ );++ if (processingPdf) {+ processingPdf.processed = true;+ }+ }+ };++ // eslint-disable-next-line no-constant-condition+ while (true) {+ if (queue.pending > parallelLimit) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ continue;+ }++ processingPdfs = processingPdfs.filter((p) => !p.processed);++ const fileReferences = await ncMeta+ .knexConnection(temp_file_references_table)+ .whereNotIn(+ 'id',+ skipPdfs.concat(processingPdfs.map((p) => p.id)),+ )+ .andWhere('thumbnail_generated', false)+ .andWhere('referenced', true)+ .andWhere('mimetype', 'application/pdf')+ .limit(limit);++ if (fileReferences.length === 0) {+ break;+ }++ try {+ // check if thumbnails exist+ for (const fileReference of fileReferences) {+ let relativePath;++ const isUrl = /^https?:\/\//i.test(fileReference.file_path);+ if (isUrl) {+ relativePath = getPathFromUrl(fileReference.file_path).replace(+ /^\/+/,+ '',+ );+ } else {+ relativePath = fileReference.file_path;+ }++ const thumbnailRoot = relativePath.replace(+ /nc\/uploads/,+ 'nc/thumbnails',+ );++ try {+ const thumbnails = await storageAdapter.getDirectoryList(+ thumbnailRoot,+ );++ if (+ ['card_cover.jpg', 'small.jpg', 'tiny.jpg'].every((t) =>+ thumbnails.includes(t),+ )+ ) {+ await ncMeta+ .knexConnection(temp_file_references_table)+ .where('file_path', fileReference.file_path)+ .update({+ thumbnail_generated: true,+ });++ fileReference.thumbnail_generated = true;+ }+ } catch (e) {+ // ignore error+ }++ if (fileReference.thumbnail_generated) {+ continue;+ }++ processingPdfs.push({+ id: fileReference.id,+ processed: false,+ });++ queue.add(() => wrapper(fileReference, isUrl));+ }+ } catch (e) {+ this.log(`error while generating thumbnail:`, e);+ }+ }++ await queue.onIdle();+ } catch (e) {+ this.log(+ `There was an error while generating thumbnails for old attachments`,+ );+ this.log(e);+ return false;+ }++ this.log(`Thumbnail generation for old attachments completed successfully`);++ return true;+ }+}\ No newline at end of file