75 lines
2.9 KiB
TypeScript
75 lines
2.9 KiB
TypeScript
import { Request, Response } from "express";
|
|
import ft from "file-type";
|
|
import core from "file-type/core";
|
|
import fs from "fs-extra";
|
|
import { logger } from "../server";
|
|
import GenerateUrl from "../util/MediaUrlGen";
|
|
import GenerateThumbnail from "../util/generateThumbnail";
|
|
import MediaFile from "../util/interfaces/MediaFile";
|
|
import ListableChecker from "../util/listableChecker";
|
|
import { PathToRoFolder } from "../util/pathGenerators";
|
|
import { FolderPaths, JobRelativeFilePath } 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 relativeFilePath: string = JobRelativeFilePath(jobid, file.filename);
|
|
|
|
const relativeThumbPath: string = await GenerateThumbnail(relativeFilePath);
|
|
|
|
const type: core.FileTypeResult | undefined = await ft.fileTypeFromFile(relativeFilePath);
|
|
|
|
return {
|
|
type,
|
|
size: file.size,
|
|
src: GenerateUrl([FolderPaths.StaticPath, FolderPaths.JobsFolder, jobid, file.filename]),
|
|
thumbnail: GenerateUrl([FolderPaths.StaticPath, FolderPaths.JobsFolder, jobid, relativeThumbPath]),
|
|
thumbnailHeight: 250,
|
|
thumbnailWidth: 250,
|
|
filename: file.filename,
|
|
relativeFilePath
|
|
};
|
|
})
|
|
);
|
|
} else {
|
|
const filesList: fs.Dirent[] = (
|
|
await fs.readdir(PathToRoFolder(jobid), {
|
|
withFileTypes: true
|
|
})
|
|
).filter((f) => f.isFile() && ListableChecker(f));
|
|
|
|
ret = await Promise.all(
|
|
filesList.map(async (file) => {
|
|
const relativeFilePath: string = JobRelativeFilePath(jobid, file.name);
|
|
|
|
const relativeThumbPath: string = await GenerateThumbnail(relativeFilePath);
|
|
const type: core.FileTypeResult | undefined = await ft.fileTypeFromFile(relativeFilePath);
|
|
const fileSize = await fs.stat(relativeFilePath);
|
|
return {
|
|
type,
|
|
size: fileSize.size,
|
|
src: GenerateUrl([FolderPaths.StaticPath, FolderPaths.JobsFolder, jobid, file.name]),
|
|
thumbnail: GenerateUrl([FolderPaths.StaticPath, FolderPaths.JobsFolder, jobid, relativeThumbPath]),
|
|
thumbnailHeight: 250,
|
|
thumbnailWidth: 250,
|
|
filename: file.name,
|
|
relativeFilePath
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
if (!res.headersSent) res.json(ret);
|
|
} catch (error) {
|
|
logger.error("Error listing job media.", { jobid, error });
|
|
if (!res.headersSent) res.status(500).json(error);
|
|
}
|
|
}
|