const path = require("path"); const sharp = require("sharp"); const configService = require("./configService"); const _configService = configService; class MediaOptimizerService { constructor() { if (!MediaOptimizerService.instance) { MediaOptimizerService.instance = this; } return MediaOptimizerService.instance; } // todo rename this function to prepareAndGeneratePreview doGeneratePreview( fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80, ) { const dataPath = _configService.getSettings().userDataPath; const mediaPath = path.join(dataPath, "images", fileCategory, fileType); const originalPath = path.join(mediaPath, originalFileName); const fileNameWithoutExt = originalFileName.split(".")[0]; const previewFileName = fileNameWithoutExt + "_preview.jpg"; const previewPath = path.join(mediaPath, previewFileName); if (previewWidth == 0) { previewWidth = 342; // ? poster if (fileType == "backdrops") previewWidth = 780; if (fileType == "logos") previewWidth = 300; } if (fileType == "logos") { return this.generatePreview( originalPath, previewPath.replace(".jpg", ".png"), previewWidth, ); // return sharp(originalPath) // .resize({ width: previewWidth }) // .toFile(previewPath.replace('.jpg', '.png')); } else { return this.generatePreview( originalPath, previewPath, previewWidth, previewQuality, ); // return sharp(originalPath) // .resize({ width: previewWidth }) // .jpeg({ quality: previewQuality }) // .toFile(previewPath); } } generatePreview( originalPath, previewPath, previewWidth, previewQuality = 80, ) { return sharp(originalPath) .resize({ width: previewWidth }) .jpeg({ quality: previewQuality }) .toFile(previewPath); } } module.exports = new MediaOptimizerService();