import { fileTypeFromFile } from "file-type"; import { FileTypeResult } from "file-type/core"; import fs from "fs-extra"; import { access } from "fs/promises"; import gm from "gm"; import imageThumbnail from "image-thumbnail"; import path from "path"; 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 //thumbPath: string ) { // const type: core.FileTypeResult | undefined = await ft.fileTypeFromFile(file); const type: FileTypeResult | undefined = await fileTypeFromFile(file); let thumbnailExtension: string = GetThumbnailExtension(type); let thumbPath: string = path.join( path.dirname(file), FolderPaths.ThumbsSubDir, path.parse(path.basename(file)).name + thumbnailExtension ); try { //Ensure the thumbs directory exists. await fs.ensureDir(path.dirname(thumbPath)); try { await access(thumbPath); logger.debug("Thumbnail already exists for : " + thumbPath); return path.relative(path.dirname(file), thumbPath); } catch {} //Check to see if the file is an image, PDF, or video. if (type?.mime === "application/pdf") { const fileOnDisk: Buffer = await fs.readFile(file); await GeneratePdfThumbnail(file, thumbPath); } else if (type?.mime.startsWith("video")) { await simpleThumb(file, thumbPath, "250x?", { // path: ffmpeg, }); } else { logger.debug("Thumbnail being created for : " + thumbPath); //Ignoring typescript as the interface is lacking a parameter. // @ts-ignore const thumbnail = await imageThumbnail(file, { responseType: "buffer", height: 250, width: 250, failOnError: false }); console.log("Image success."); await fs.writeFile(thumbPath, thumbnail); } return path.relative(path.dirname(file), thumbPath); } catch (err) { logger.error("Error when genenerating thumbnail:", { thumbPath, err, message: (err as Error).message }); return path.relative(path.dirname(file), AssetPaths.File); } } async function GeneratePdfThumbnail(file: string, thumbPath: string) { const fileOnDisk: Buffer = await fs.readFile(file); return new Promise((resolve, reject) => { gm(fileOnDisk) .selectFrame(0) .setFormat("png") .resize(200, 200, "!") .quality(75) .write(thumbPath, (error) => { if (error) { reject(error); } else { resolve(thumbPath); } }); }); } function GetThumbnailExtension(file: FileTypeResult | undefined) { if (file === undefined) return ".png"; return ".png"; }