78 lines
2.4 KiB
TypeScript
78 lines
2.4 KiB
TypeScript
import { Request, Response } from "express";
|
|
import multer from "multer";
|
|
|
|
import GenerateThumbnail from "../util/generateThumbnail";
|
|
import generateUniqueFilename from "../util/generateUniqueFilename";
|
|
import { PathToRoFolder } from "../util/pathGenerators";
|
|
|
|
import fs from "fs-extra";
|
|
|
|
import { access } from "fs/promises";
|
|
import imageThumbnail from "image-thumbnail";
|
|
import path, { resolve } from "path";
|
|
import gm from "gm";
|
|
import ft from "file-type";
|
|
import core from "file-type/core";
|
|
import GenerateUrl from "./MediaUrlGen";
|
|
import { FolderPaths } from "./serverInit";
|
|
import { logger } from "../server";
|
|
import dotenv from "dotenv";
|
|
|
|
const heicConverter = require("heic-convert");
|
|
|
|
//gm.subClass();
|
|
dotenv.config({
|
|
path: resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`),
|
|
});
|
|
|
|
export async function ConvertHeicFiles(files: Express.Multer.File[]) {
|
|
for (const file of files) {
|
|
const type: core.FileTypeResult | undefined = await ft.fromFile(file.path);
|
|
if (type?.mime === "image/heic") {
|
|
logger.log(
|
|
"debug",
|
|
`Converting ${file.filename} image to JPEG from HEIC.`
|
|
);
|
|
const convertedFileName = `${
|
|
path.parse(path.basename(file.originalname)).name
|
|
}-${Math.floor(Date.now() / 1000)}.jpeg`;
|
|
|
|
await ConvertToJpeg(
|
|
file.path,
|
|
`${file.destination}/${convertedFileName}`
|
|
);
|
|
//Move the HEIC.
|
|
if (process.env.KEEP_CONVERTED_ORIGINALS) {
|
|
await fs.ensureDir(
|
|
path.join(file.destination, FolderPaths.ConvertedOriginalSubDir)
|
|
);
|
|
await fs.move(
|
|
file.path,
|
|
`${path.join(
|
|
file.destination,
|
|
FolderPaths.ConvertedOriginalSubDir
|
|
)}/${file.filename}`
|
|
);
|
|
} else {
|
|
await fs.unlink(file.destination);
|
|
}
|
|
//Update the multer file entry.
|
|
|
|
file.filename = convertedFileName;
|
|
file.mimetype = "image/jpeg";
|
|
file.path = `${file.destination}/${convertedFileName}`;
|
|
}
|
|
}
|
|
}
|
|
|
|
async function ConvertToJpeg(file: string, newPath: string) {
|
|
const fileOnDisk: Buffer = await fs.readFile(file);
|
|
|
|
const outputBuffer = await heicConverter({
|
|
buffer: fileOnDisk, // the HEIC file buffer
|
|
format: "JPEG", // output format
|
|
quality: process.env.CONVERT_QUALITY || 0.5, // the jpeg compression quality, between 0 and 1
|
|
});
|
|
return await fs.writeFile(newPath, outputBuffer);
|
|
}
|