import View from"./view.mjs";import Files from"../../files/files.mjs";import{hasFileExtension}from"../../../common/data/validators.mjs";import{fromUuid}from"../../core/utils.mjs";import{randomID}from"../../../common/utils/helpers.mjs";import fs from"node:fs";import path from"node:path";export default class FileUploadView extends View{route="/upload";_methods=["post"];async handlePost(e,o){const{game:a,config:s}=global;let t=null;if(!(e.session.admin||!a.ready&&!s.adminPassword)&&(a.ready&&(t=await db.User.get(e.user)),!t||!t.hasPermission("FILES_UPLOAD")))return o.json({error:`User [${t?.id??""}] does not have permission to upload files.`});let r=e.body.source;const i=e.files.upload,n={...e.body};if(n.uuid){if(!hasFileExtension(i.name,Object.keys(CONST.IMAGE_FILE_EXTENSIONS)))return o.json({error:"Not an image file."});r="data",n.target=await this.#e(n.uuid,i)}const m=await Files.upload(r,i,n).catch(e=>({error:e.message||e}));return o.json(m)}async#e(e,o){const a=await fromUuid(e),s=a.constructor.extractedAssetPath,t=o.name.split("."),r=t.pop();return o.name=`${t.join(".")}-${randomID()}.${r}`,o.name=a.parent?[a.parent.id,a.collectionName,a.id,o.name].join("-"):o.name,fs.mkdirSync(s,{recursive:!0}),Files.standardizePath(path.relative(global.paths.data,s))}}