Files
2026-12-02 21:10:42 -05:00

28 lines
15 KiB
JavaScript

import {ID,lookup,safeName,PACKS} from './core.mjs';
import {own,snapshot,cleanImport,walk,replaceRefs,makeArchive,readArchive,IMAGE} from './portable.mjs';
const dialog=()=>foundry.applications.api.DialogV2;
const picker=()=>foundry.applications.apps.FilePicker;
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const random=()=>foundry.utils.randomID();
const root=()=>`worlds/${game.world.id}/PlayerAssets/${safeName(game.user.name)}`;
const types=['Portraits','Tokens','Homebrew'];
const folders=(kind)=>kind==='Actor'?['Player Workshop',game.user.name,'Test Characters']:['Player Homebrew Drafts',game.user.name];
function owned(){return [...game.actors,...game.items].filter(d=>own(d,game.user));}
function getDoc(uuid){const [kind,id]=String(uuid).split('.');const d=(kind==='Actor'?game.actors:kind==='Item'?game.items:null)?.get(id);if(!own(d,game.user))throw Error('You must explicitly own this world document.');return d;}
function options(arr){return arr.map(([v,label])=>`<option value="${esc(v)}">${esc(label)}</option>`).join('');}
const field=(label,name,opts)=>`<div class="form-group"><label>${esc(label)}</label><select name="${name}">${options(opts)}</select></div>`;
async function ask(title,html,read,label='Continue'){return dialog().prompt({window:{title},position:{width:560},content:html,ok:{label,callback:(_event,_button,d)=>read(d.element)},rejectClose:false});}
const select=(el,n)=>el.querySelector(`[name="${n}"]`)?.value;
function download(blob,name){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),30000);}
function localPath(s){try{const p=decodeURI(s);return !/[:?#\\]/.test(p)&&!p.startsWith('/')&&!p.split('/').some(x=>x==='.'||x==='..')?p:null;}catch{return null;}}
async function listArt(){const out=[];for(const sub of types){try{const r=await picker().browse('data',`${root()}/${sub}`);for(const p of r.files??[])if(IMAGE.test(p)&&localPath(p)?.startsWith(`${root()}/${sub}/`))out.push(p);}catch(e){console.warn(ID,'Art directory not available',sub,e);}}return out;}
async function upload(file,sub){if(!types.includes(sub)||!IMAGE.test(file.name)||!file.size||file.size>16*1024*1024)throw Error('Use an image (PNG/JPG/WebP/GIF/AVIF), maximum 16 MiB.');const ext=file.name.match(IMAGE)[1].toLowerCase(),name=`${random()}.${ext}`;const result=await picker().upload('data',`${root()}/${sub}`,new File([file],name,{type:file.type}),{}, {notify:false});if(result?.error||!result?.path)throw Error(result?.error??'File upload did not return a path. Ask the GM to run Workshop setup.');return result.path;}
async function artwork(){const files=await listArt();const docs=owned();const rows=files.map(p=>`<option value="${esc(p)}">${esc(p.split('/').at(-2)+' / '+p.split('/').at(-1))}</option>`).join('');const data=await ask('My Artwork',`<p>Upload new images or assign an existing personal image. Files stay on the server when unassigned. Tokenizer can still be opened from the normal actor sheet.</p><div class="form-group"><label>Image file</label><input type="file" name="upload" accept="image/png,image/jpeg,image/webp,image/gif,image/avif"></div>${field('Folder','sub',types.map(t=>[t,t]))}<div class="form-group"><label>Existing image</label><select name="existing"><option value="">None</option>${rows}</select></div>${field('Action','action',[['upload','Upload only'],['portrait','Assign portrait / item image'],['token','Assign prototype token'],['download','Download existing image']])}${field('My document','doc',[['','None'],...docs.map(d=>[d.uuid,d.name])])}`,el=>({file:el.querySelector('input[type=file]').files[0],sub:select(el,'sub'),existing:select(el,'existing'),action:select(el,'action'),doc:select(el,'doc')}));if(!data)return;const d=['portrait','token'].includes(data.action)?getDoc(data.doc):null;if(data.action==='token'&&d.documentName!=='Actor')throw Error('Token artwork requires an actor.');const path=data.file?await upload(data.file,data.sub):data.existing;if(!path)throw Error('Choose an image.');if(data.action==='download'){const r=await fetch(path,{credentials:'same-origin'});if(!r.ok)throw Error('Image could not be downloaded.');download(await r.blob(),path.split('/').at(-1));}else if(d){await d.update(data.action==='token'?{'prototypeToken.texture.src':path,'prototypeToken.randomImg':false}:{img:path});}ui.notifications.info('Artwork action complete.');}
async function exportVault(all){const docs=owned();const selection=all?await ask('Export entire vault','<p>Export all explicitly owned world actors, items and personal artwork. External licensed assets are not bundled.</p><label><input type="checkbox" name="other"> Include other referenced local images that I have rights to transfer (not system/module assets).</label>',el=>({docs,allArt:true,other:el.querySelector('[name=other]').checked}),'Export ZIP'):await ask('Export personal content',`${field('Document','doc',docs.map(d=>[d.uuid,`${d.documentName}: ${d.name}`]))}<label><input type="checkbox" name="other"> Include other local image files referenced by this document that I have rights to transfer (not system/module assets).</label><p>Embedded spells, inventory and features are included. External sources and linked documents may still require the original compendiums.</p>`,el=>({docs:[getDoc(select(el,'doc'))],allArt:false,other:el.querySelector('[name=other]').checked}),'Export ZIP');if(!selection)return;const selected=selection.docs;if(!selected.length&&!selection.allArt)throw Error('No documents selected');const {blob,warnings}=await makeArchive({docs:selected,assets:selection.allArt?await listArt():[],canBundle:s=>{const p=localPath(s);return !!p&&(p.startsWith(root()+'/')||(selection.other&&!/^(modules|systems|icons|ui|fonts)\//i.test(p)));},readAsset:async s=>{const r=await fetch(s,{credentials:'same-origin',redirect:'error'});if(!r.ok)throw Error(`HTTP ${r.status}`);if(Number(r.headers.get('content-length'))>16*1024*1024)throw Error('Image too large');const b=await r.arrayBuffer();if(b.byteLength>16*1024*1024)throw Error('Image too large');return b;},metadata:{system:game.system.id,systemVersion:game.system.version,foundry:game.version,exported:new Date().toISOString(),requiredModules:[...game.modules.values()].filter(m=>m.active&&m.id!==ID).map(m=>({id:m.id,version:m.version}))}});download(blob,`${safeName(all?game.user.name+'-vault':selected[0].name)}.zip`);ui.notifications.info(`Export complete. ${warnings.length} image references not bundled; see manifest.`);}
async function nativeExport(){const docs=owned();if(!docs.length)throw Error('No personal documents to export.');const id=await ask('Export Foundry JSON',field('Document','doc',docs.map(d=>[d.uuid,`${d.documentName}: ${d.name}`]))+'<p>Standard Foundry JSON can be imported in another world without Player Workshop. Artwork and external dependencies are not bundled.</p>',el=>select(el,'doc'),'Export JSON');if(id){const d=getDoc(id);await d.exportToJSON();}}
async function importVault(){const file=await ask('Import personal vault',`<p>Import a ZIP previously created by Player Workshop. New copies will be created; nothing is overwritten. Import only archives you trust. Embedded effects and module data may execute in the destination system. GM must allow document creation and uploads.</p><input type="file" accept=".zip,application/zip" name="archive">`,el=>el.querySelector('input[type=file]').files[0],'Inspect archive');if(!file)return;if(file.size>65*1024*1024)throw Error('Archive too large');const {manifest:m,files}=readArchive(await file.arrayBuffer());const missing=(m.requiredModules??[]).filter(x=>!game.modules.get(x.id)?.active).map(x=>x.id);const versionMismatch=m.systemVersion!==game.system.version;const warnings=Array.isArray(m.warnings)?m.warnings:[];if(!await dialog().confirm({window:{title:'Confirm import'},content:`<p>${m.records.length} new documents; ${m.assets.length} images. Original system: ${esc(m.systemVersion)}; current: ${esc(game.system.version)}.</p>${versionMismatch?'<p><strong>System version differs; compatibility is not guaranteed.</strong></p>':''}<p>Source-world modules not active here (informational, not required): ${esc(missing.join(', ')||'None')}</p><p>${warnings.length} original image warnings. External compendium and unselected document references may remain unresolved. Imports go to your personal workshop or the world root if no workshop exists.</p>`,rejectClose:false}))return;const map=new Map();for(const r of m.records)map.set(r.uuid,`${r.kind}.${random()}`);for(const a of m.assets){const ext=a.name.split('.').at(-1);const b=files.get(a.name);const p=await upload(new File([b],`import.${ext}`,{type:`image/${ext==='jpg'?'jpeg':ext}`}), 'Homebrew');map.set(a.path,p);}const created=[];try{for(const r of [...m.records].sort((a,b)=>Number(a.kind==='Actor')-Number(b.kind==='Actor'))){const id=map.get(r.uuid).split('.')[1];const data=walk(cleanImport(r.data,game.user.id,id),s=>replaceRefs(s,map));data.folder=lookup(game,r.kind,folders(r.kind))?.id??null;const d=await CONFIG[r.kind].documentClass.create(data,{keepId:true,keepEmbeddedIds:true});if(!d||d.id!==id||!own(d,game.user))throw Error(`Could not verify ownership/ID for ${r.data.name}`);created.push(d.name);}}catch(e){throw Error(`Import stopped after ${created.length} document(s). Uploaded files and completed copies remain. ${e.message}`);}ui.notifications.info(`Imported ${created.length} document(s). Review character sheets and source references.`);}
async function publish(){const docs=owned().filter(d=>d.documentName==='Item'||d.type==='npc');if(!docs.length)throw Error('Create a world Item or NPC first.');const choice=await ask('Publish homebrew',`${field('Original','doc',docs.map(d=>[d.uuid,d.name]))}<div class="form-group"><label>Version</label><input name="version" value="1.0" maxlength="40"></div><p>Creates a new community copy. Your original stays private and editable. Community packs are collaborative; the DM can approve a separate snapshot. Only publish content you may share.</p>`,el=>({doc:select(el,'doc'),version:el.querySelector('[name=version]').value}),'Publish copy');if(!choice)return;const d=getDoc(choice.doc),pack=game.packs.get(`world.player-homebrew-${d.documentName==='Item'?'items':'creatures'}`);if(!pack||pack.locked)throw Error('Community pack is missing or locked. Ask GM to run setup.');const data=cleanImport(snapshot(d).data,game.user.id,random());data.ownership={default:2,[game.user.id]:3};data.flags??={};data.flags[ID]={homebrew:true,author:game.user.name,authorId:game.user.id,version:choice.version||'1.0',status:'published',original:d.uuid};if(data.system?.source&&typeof data.system.source==='object')data.system.source.book='Homebrew';const out=await CONFIG[d.documentName].documentClass.create(data,{pack:pack.collection,keepId:true,keepEmbeddedIds:true});if(!out)throw Error('Publication failed.');ui.notifications.info(`Published ${out.name}; your original is unchanged.`);}
async function approve(){if(game.user.role!==CONST.USER_ROLES.GAMEMASTER)throw Error('Gamemaster only');const packs=PACKS.filter(p=>p[3]).map(p=>game.packs.get(`world.${p[1]}`)).filter(Boolean);const entries=[];for(const p of packs)for(const d of await p.getDocuments())entries.push(d);if(!entries.length)throw Error('No published homebrew found.');const uuid=await ask('Approve homebrew',field('Community creation','doc',entries.map(d=>[d.uuid,`${d.name} (${d.documentName})`]))+'<p>Creates a locked approved copy; community content stays available to all characters.</p>',el=>select(el,'doc'),'Approve copy');if(!uuid)return;const source=entries.find(d=>d.uuid===uuid);const pack=game.packs.get(`world.dm-approved-homebrew-${source.documentName==='Item'?'items':'creatures'}`);if(!pack)throw Error('Approved pack missing');const data=cleanImport(source.toObject(),game.user.id,random());data.ownership={default:2};data.flags??={};data.flags[ID]={...(source.getFlag(ID,'homebrew')?source.flags[ID]:{}),homebrew:true,status:'approved',approvedBy:game.user.name,communitySource:source.uuid};const was=pack.locked;try{if(was)await pack.configure({locked:false});const out=await CONFIG[source.documentName].documentClass.create(data,{pack:pack.collection,keepId:true,keepEmbeddedIds:true});if(!out)throw Error('Approval failed');}finally{if(was)await pack.configure({locked:true});}ui.notifications.info('Approved homebrew copy created.');}
async function move(){const docs=owned().filter(d=>d.documentName==='Actor');const v=await ask('Organize my characters',field('Character','doc',docs.map(d=>[d.uuid,d.name]))+field('Destination','dest',['Test Characters','Backup Characters','Retired & Deceased'].map(x=>[x,x])),el=>({doc:select(el,'doc'),dest:select(el,'dest')}),'Move');if(!v)return;const d=getDoc(v.doc);if(!['Test Characters','Backup Characters','Retired & Deceased'].includes(v.dest))throw Error('Invalid folder');const f=lookup(game,'Actor',['Player Workshop',game.user.name,v.dest]);if(!f)throw Error('Ask GM to provision your workshop.');await d.update({folder:f.id});}
export async function openVault(){const docs=owned();const list=docs.map(d=>`<li>${esc(d.name)} — ${esc(d.documentName)} (${esc(d.folder?.name??'root')})</li>`).join('');const action=await dialog().wait({window:{title:'Player Vault — '+game.user.name},position:{width:660},content:`<p>Personal ownership: ${docs.filter(d=>d.documentName==='Actor').length} actors, ${docs.filter(d=>d.documentName==='Item').length} items.</p><details><summary>My documents</summary><ul>${list}</ul></details><p>Homebrew is available to all characters. DM approval is a campaign convention, not a sheet lock. Shared copies may be edited by the community.</p>`,buttons:[['open','Open my document'],['move','Organize characters'],['art','My artwork'],['publish','Publish homebrew'],['json','Export Foundry JSON'],['one','Export one ZIP'],['all','Export vault ZIP'],['import','Import vault'],...(game.user.role===CONST.USER_ROLES.GAMEMASTER?[['approve','Approve homebrew']]:[]),['close','Close']].map(([action,label])=>({action,label,callback:()=>action})),rejectClose:false});try{switch(action){case 'open':{if(!docs.length)throw Error('Create a character or item first.');const id=await ask('Open personal document',field('Document','doc',docs.map(d=>[d.uuid,d.name])),el=>select(el,'doc'),'Open');if(id)getDoc(id).sheet.render(true);break;}case 'move':await move();break;case 'art':await artwork();break;case 'publish':await publish();break;case 'json':await nativeExport();break;case 'one':await exportVault(false);break;case 'all':await exportVault(true);break;case 'import':await importVault();break;case 'approve':await approve();break;}}catch(e){console.error(ID,e);ui.notifications.error(`Player Workshop: ${e.message}`);}}