Files
bodyshop-media-server/jobs/jobsListMedia.ts
2022-06-02 09:58:34 -07:00

82 lines
2.5 KiB
TypeScript

import { Request, Response } from "express";
import fs from "fs-extra";
import path from "path";
import { logger } from "../server";
import GenerateThumbnail from "../util/generateThumbnail";
import MediaFile from "../util/interfaces/MediaFile";
import GenerateUrl from "../util/MediaUrlGen";
import { PathToRoFolder } from "../util/pathGenerators";
import { FolderPaths } from "../util/serverInit";
export async function JobsListMedia(req: Request, res: Response) {
const jobid: string = (req.body.jobid || "").trim();
await fs.ensureDir(PathToRoFolder(jobid));
logger.debug("Listing media for job: " + PathToRoFolder(jobid));
let ret: MediaFile[];
try {
if (req.files) {
//We just uploaded files, we're going to send only those back.
ret = await Promise.all(
(req.files as Express.Multer.File[]).map(async (file) => {
const relativeThumbPath: string = await GenerateThumbnail(
path.join(FolderPaths.Jobs, jobid, file.filename)
);
return {
src: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
file.filename,
]),
thumbnail: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
relativeThumbPath,
]),
thumbnailHeight: 250,
thumbnailWidth: 250,
filename: file.filename,
};
})
);
} else {
const filesList: fs.Dirent[] = (
await fs.readdir(PathToRoFolder(jobid), {
withFileTypes: true,
})
).filter((f) => f.isFile() && !/(^|\/)\.[^\/\.]/g.test(f.name));
ret = await Promise.all(
filesList.map(async (file) => {
const relativeThumbPath: string = await GenerateThumbnail(
path.join(FolderPaths.Jobs, jobid, file.name)
);
return {
src: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
file.name,
]),
thumbnail: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
relativeThumbPath,
]),
thumbnailHeight: 250,
thumbnailWidth: 250,
filename: file.name,
};
})
);
}
res.json(ret);
} catch (error) {
logger.error("Error listing job media.", { jobid, error });
res.status(500).json(error);
}
}