Files
bodyshop-media-server/jobs/jobsDeleteMedia.ts
2024-08-27 13:45:12 -07:00

65 lines
2.3 KiB
TypeScript

import { Request, Response } from "express";
import fs from "fs-extra";
import path from "path";
import { logger } from "../server.js";
import MediaFile from "../util/interfaces/MediaFile.js";
import ListableChecker from "../util/listableChecker.js";
import { PathToRoBillsFolder, PathToRoFolder } from "../util/pathGenerators.js";
import { BillsRelativeFilePath, FolderPaths, JobRelativeFilePath } from "../util/serverInit.js";
export async function JobsDeleteMedia(req: Request, res: Response) {
const jobid: string = (req.body.jobid || "").trim();
const files: string[] = req.body.files || [];
await fs.ensureDir(PathToRoFolder(jobid));
logger.debug("Deleteing media for job: " + PathToRoFolder(jobid));
let ret: MediaFile[];
try {
// Setup lists for both file locations
const jobFileList: fs.Dirent[] = (
await fs.readdir(PathToRoFolder(jobid), {
withFileTypes: true
})
).filter((f) => f.isFile() && ListableChecker(f));
const billFileList: fs.Dirent[] = (
await fs.readdir(PathToRoBillsFolder(jobid), {
withFileTypes: true
})
).filter((f) => f.isFile() && ListableChecker(f));
// Check both list for the files that need to be deleted
await Promise.all(
jobFileList.map(async (file) => {
if (files.includes(path.parse(path.basename(file.name)).base)) {
// File is in the set of requested files.
await fs.remove(JobRelativeFilePath(jobid, file.name));
await fs.remove(
path.join(FolderPaths.Jobs, jobid, FolderPaths.ThumbsSubDir, file.name.replace(/\.[^/.]+$/, ".png"))
);
}
})
);
await Promise.all(
billFileList.map(async (file) => {
if (files.includes(path.parse(path.basename(file.name)).base)) {
// File is in the set of requested files.
await fs.remove(BillsRelativeFilePath(jobid, file.name));
await fs.remove(
path.join(
FolderPaths.Jobs,
jobid,
FolderPaths.BillsSubDir,
FolderPaths.ThumbsSubDir,
file.name.replace(/\.[^/.]+$/, ".png")
)
);
}
})
);
if (!res.headersSent) res.sendStatus(200);
} catch (error) {
logger.error("Error deleting job media.", { jobid, error });
if (!res.headersSent) res.status(500).json(error);
}
}