This commit is contained in:
Allan Carr
2025-07-13 00:17:08 -07:00
parent 231130267f
commit 7f782d5a64
19 changed files with 2564 additions and 1416 deletions

View File

@@ -1,7 +1,8 @@
import { Job, Queue, QueueEvents, Worker } from "bullmq";
import { fileTypeFromFile } from "file-type";
import { FileTypeResult } from "file-type/core";
import fs from "fs-extra";
import { access } from "fs/promises";
import { access, FileHandle, open as fsOpen } from "fs/promises";
import gm from "gm";
import imageThumbnail from "image-thumbnail";
import path from "path";
@@ -9,75 +10,187 @@ import { logger } from "../server.js";
import { AssetPaths, FolderPaths } from "./serverInit.js";
//@ts-ignore
import simpleThumb from "simple-thumbnail";
//const ffmpeg = require("ffmpeg-static");
/** @returns {string} Returns the relative path from the file to the thumbnail on the server. This must be converted to a URL. */
export default async function GenerateThumbnail(file: string) {
// const type: core.FileTypeResult | undefined = await ft.fileTypeFromFile(file);
const type: FileTypeResult | undefined = await fileTypeFromFile(file);
let thumbPath: string = path.join(
path.dirname(file),
FolderPaths.ThumbsSubDir,
`${path.parse(path.basename(file)).name}.jpg`
);
const QUEUE_NAME = "thumbnailQueue";
const connectionOpts = {
host: "localhost",
port: 6379,
maxRetriesPerRequest: 3,
enableReadyCheck: true,
reconnectOnError: (err: Error) => err.message.includes("READONLY")
};
const thumbnailQueue = new Queue(QUEUE_NAME, {
connection: connectionOpts,
defaultJobOptions: {
removeOnComplete: true,
removeOnFail: true,
attempts: 3,
backoff: { type: "exponential", delay: 1000 }
}
});
const thumbnailQueueEvents = new QueueEvents(QUEUE_NAME, {
connection: connectionOpts
});
const thumbnailWorker = new Worker(
QUEUE_NAME,
async (job: Job<{ file: string }>) => {
const { file } = job.data;
logger.debug(`[ThumbnailWorker] Starting thumbnail generation for ${file}`);
try {
await job.updateProgress(10);
const result = await processThumbnail(file, job);
await job.updateProgress(100);
logger.debug(`[ThumbnailWorker] Completed thumbnail generation for ${file}`);
return result;
} catch (error) {
logger.error(`[ThumbnailWorker] Error generating thumbnail for ${file}:`, error);
throw error;
}
},
{
connection: connectionOpts,
concurrency: 1
}
);
// Worker event listeners for logging
thumbnailWorker.on("ready", () => {
logger.debug("[ThumbnailWorker] Worker is ready");
});
thumbnailWorker.on("active", (job, prev) => {
logger.debug(`[ThumbnailWorker] Job ${job.id} active (previous: ${prev})`);
});
thumbnailWorker.on("completed", async (job) => {
logger.debug(`[ThumbnailWorker] Job ${job.id} completed`);
await job.remove();
logger.debug(`[ThumbnailWorker] Job ${job.id} removed from Redis`);
});
thumbnailWorker.on("failed", (job, err) => {
logger.error(`[ThumbnailWorker] Job ${job?.id} failed:`, err);
});
thumbnailWorker.on("stalled", (jobId) => {
logger.error(`[ThumbnailWorker] Job stalled: ${jobId}`);
});
thumbnailWorker.on("error", (err) => {
logger.error("[ThumbnailWorker] Worker error:", err);
});
thumbnailWorker.on("ioredis:close", () => {
logger.error("[ThumbnailWorker] Redis connection closed");
});
// Queue event listeners
thumbnailQueue.on("waiting", (job) => {
logger.debug(`[ThumbnailQueue] Job waiting in queue: ${job.data.file}`);
});
thumbnailQueue.on("error", (err) => {
logger.error("[ThumbnailQueue] Queue error:", err);
});
async function processThumbnail(file: string, job?: Job): Promise<string> {
let fileHandle: FileHandle | null = null;
let thumbPath = "unknown";
try {
//Ensure the thumbs directory exists.
await access(file, fs.constants.R_OK);
// Wait for stable file size to avoid incomplete thumbnails
const size1 = (await fs.stat(file)).size;
await new Promise((r) => setTimeout(r, 100));
const size2 = (await fs.stat(file)).size;
if (size1 !== size2) {
throw new Error("File is still being written to, skipping thumbnail generation");
}
fileHandle = await fsOpen(file, "r");
const type: FileTypeResult | undefined = await fileTypeFromFile(file);
const baseName = path.parse(path.basename(file)).name;
thumbPath = path.join(path.dirname(file), FolderPaths.ThumbsSubDir, `${baseName}.jpg`);
await fs.ensureDir(path.dirname(thumbPath));
//Check for existing thumbnail
if (await fs.pathExists(thumbPath)) {
logger.debug("Using existing thumbnail:", thumbPath);
logger.debug(`[ThumbnailWorker] Using existing thumbnail: ${thumbPath}`);
return path.relative(path.dirname(file), thumbPath);
}
//Check to see if the file is an image, PDF, or video.
if (!type?.mime) {
throw new Error("Unknown file type");
}
if (!type?.mime) throw new Error("Unknown file type");
if (type?.mime === "application/pdf" || type?.mime === "image/heic" || type?.mime === "image/heif") {
await GeneratePdfThumbnail(file, thumbPath);
} else if (type?.mime.startsWith("video")) {
await simpleThumb(file, thumbPath, "250x?", {
// path: ffmpeg,
});
await fileHandle.close();
fileHandle = null;
if (["application/pdf", "image/heic", "image/heif"].includes(type.mime)) {
logger.debug(`[ThumbnailWorker] Generating PDF/HEIC thumbnail for: ${file}`);
await generatePdfThumbnail(file, thumbPath);
} else if (type.mime.startsWith("video")) {
logger.debug(`[ThumbnailWorker] Generating video thumbnail for: ${file}`);
await simpleThumb(file, thumbPath, "250x?");
} else {
logger.debug("Thumbnail being created for : " + thumbPath);
//Ignoring typescript as the interface is lacking a parameter.
// @ts-ignore
const thumbnail = await imageThumbnail(file, {
logger.debug(`[ThumbnailWorker] Generating image thumbnail for: ${file}`);
const thumbnailBuffer = await imageThumbnail(file, {
responseType: "buffer",
height: 250,
width: 250,
failOnError: false
width: 250
});
await fs.writeFile(thumbPath, thumbnail);
await fs.writeFile(thumbPath, thumbnailBuffer);
}
return path.relative(path.dirname(file), thumbPath);
} catch (err) {
logger.error("Error when genenerating thumbnail:", {
} catch (error) {
logger.error("[ThumbnailWorker] Error generating thumbnail:", {
thumbPath,
err,
message: (err as Error).message
error,
message: (error as Error).message
});
return path.relative(path.dirname(file), AssetPaths.File);
} finally {
if (fileHandle) {
try {
await fileHandle.close();
} catch (closeError) {
logger.error("[ThumbnailWorker] Error closing file handle:", closeError);
}
}
}
}
async function GeneratePdfThumbnail(file: string, thumbPath: string) {
const fileOnDisk: Buffer = await fs.readFile(file);
return new Promise<string>((resolve, reject) => {
gm(fileOnDisk)
.selectFrame(0)
async function generatePdfThumbnail(file: string, thumbPath: string): Promise<string> {
return new Promise((resolve, reject) => {
gm(file + "[0]") // first page only
.setFormat("jpg")
.resize(250, 250, "!")
.quality(75)
.write(thumbPath, (error) => {
if (error) {
reject(error);
} else {
resolve(thumbPath);
}
});
.write(thumbPath, (err) => (err ? reject(err) : resolve(thumbPath)));
});
}
/**
* Add a thumbnail generation job and wait for result.
* Returns the relative path to the thumbnail or default file icon on error.
*/
export default async function GenerateThumbnail(file: string): Promise<string> {
const baseName = path.parse(path.basename(file)).name;
const thumbPath = path.join(path.dirname(file), FolderPaths.ThumbsSubDir, `${baseName}.jpg`);
if (await fs.pathExists(thumbPath)) {
logger.debug(`[GenerateThumbnail] Returning existing thumbnail immediately for ${file}`);
return path.relative(path.dirname(file), thumbPath);
}
try {
logger.debug(`[GenerateThumbnail] Adding job to queue for ${file}`);
const job = await thumbnailQueue.add("generate", { file });
const result = await job.waitUntilFinished(thumbnailQueueEvents);
logger.debug(`[GenerateThumbnail] Job completed for ${file}`);
return result as string;
} catch (error) {
logger.error(`[GenerateThumbnail] Job failed for ${file}:`, error);
return path.relative(path.dirname(file), AssetPaths.File);
}
}