diff --git a/web/kanban.js b/web/kanban.js index 892ad54..d3d497e 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -412,8 +412,19 @@ async function writeWhole(dir,name,source){ await dir.removeEntry(name).catch(()=>{}); // A browser that cannot rename a file outside its own storage copies it. try{await temp.move(name);} - catch{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable(); - await whole.write(await temp.getFile());await whole.close();await dir.removeEntry(temp.name);} + catch{ + try{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable(); + await whole.write(await temp.getFile());await whole.close();} + catch(e){await dir.removeEntry(temp.name).catch(()=>{});throw e;} + await dir.removeEntry(temp.name);} +} +// A file another program holds open (FlexiPRINT reading it, an editor): the +// browser refuses to write, move or delete it. The pass goes on without it and +// the next one, 30 s later, tries again. +const LOCKED=new Set(['NoModificationAllowedError','InvalidModificationError','NotReadableError']); +function fileStep(locked){ + return async(name,fn)=>{try{await fn();return true;} + catch(e){if(!LOCKED.has(e.name))throw e;locked.push(name);return false;}}; } const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true}); // The flow's folders exist from the moment the main one is chosen, empty or not. @@ -445,16 +456,16 @@ async function fetchInto(dir,file){ // by FlexiPRINT, and is never written again; a withdrawn one, from a card that // left Imprimindo, is deleted if Flexi has not taken it. Returns how many // parts it wrote. -async function syncHot(){ +async function syncHot(step){ const hot=await api('/queue/hot',{}); if(!hot.write.length&&!hot.watch.length&&!hot.withdraw.length)return 0; const root=await stageDir(hot.folder); const dirOf=async path=>{let dir=root;for(const part of path.split('/'))dir=await dir.getDirectoryHandle(part,{create:true});return dir;}; const missing=e=>e.name==='NotFoundError'; - for(const p of hot.withdraw){ + for(const p of hot.withdraw)await step(p.name,async()=>{ await (await dirOf(p.folder)).removeEntry(p.name).catch(e=>{if(!missing(e))throw e;}); await api('/queue/hot/'+p.id,{state:'gone'}); - } + }); for(const p of hot.watch){ try{await (await dirOf(p.folder)).getFileHandle(p.name);} catch(e){if(!missing(e))throw e;await api('/queue/hot/'+p.id,{state:'consumed'});} @@ -462,9 +473,11 @@ async function syncHot(){ let written=0; for(const p of hot.write){ FOLDER.status='Gravando na hot folder '+p.folder+': '+p.name;paintFolder(); - try{await fetchInto(await dirOf(p.folder),p);} - catch(e){await api('/queue/hot/'+p.id,{state:'released'}).catch(()=>{});throw e;} - await api('/queue/hot/'+p.id,{state:'written'});written++; + const ok=await step(p.name,async()=>{ + try{await fetchInto(await dirOf(p.folder),p);} + catch(e){await api('/queue/hot/'+p.id,{state:'released'}).catch(()=>{});throw e;} + }); + if(ok){await api('/queue/hot/'+p.id,{state:'written'});written++;} } return written; } @@ -478,6 +491,11 @@ async function syncHot(){ // own timer always asks, since another computer may have moved the order. async function syncFolder(force=false){ if(!folderActive()||FOLDER.busy||!board||!may('print'))return; + // One tab per computer writes the folders: two tabs writing the same file + // lock each other out. The other tabs skip the pass. + if(navigator.locks&&!force?.held)return navigator.locks.request('dtf-folders',{ifAvailable:true}, + lock=>lock?syncFolder({held:true,force:force===true}):undefined); + if(force?.held)force=force.force; const stages=FOLDER.mode==='folder'; const follows=stages?['rec','tra','imp','rev','fin','cor']:['tra']; const sig=board.orders.filter(o=>follows.includes(o.state)||o.cancelled_at) @@ -492,24 +510,25 @@ async function syncFolder(force=false){ const wanted=new Map(files.map(f=>[f.upload_id,f])); const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads'; let removed=0, moved=0, saved=0; + const locked=[], step=fileStep(locked); const record=async(uid,file,folder)=>{ FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder, ...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})}); FOLDER.last=new Date();await keepSaved();}; - if(stages)for(const [uid,rec] of [...FOLDER.saved]){ - if(!rec.order||!rec.folder)continue; + if(stages)for(const [uid,rec] of [...FOLDER.saved])await step(rec.name,async()=>{ + if(!rec.order||!rec.folder)return; const state=states[rec.order], target=STAGE_FOLDERS[state]; const now=wanted.get(uid); const replaced=(state==='rec'||state==='tra')&&(!now||now.order!==rec.order); const kept=rec.folder===STAGE_FOLDERS.fin&&Date.now()-(rec.at||0)>KEEP_FINISHED_DAYS*86400000; - if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();continue;} - if(rec.folder===target)continue; - if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;continue;} + if(!target||replaced||kept){await removeSaved(rec);FOLDER.saved.delete(uid);removed++;await keepSaved();return;} + if(rec.folder===target)return; + if(await moveSaved(rec,target)){await record(uid,{...rec},target);moved++;return;} // Not where it was: downloaded again into its new folder while storage has it. if(now&&now.upload_id===uid){await fetchInto(await stageDir(target),now);await record(uid,now,target);moved++;} else{FOLDER.saved.delete(uid);await keepSaved();} - } - const hot=stages?await syncHot():0; + }); + const hot=stages?await syncHot(step):0; if(stages)for(const old of OLD_FOLDERS) if(![...FOLDER.saved.values()].some(r=>r.folder===old))await FOLDER.handle.removeEntry(old).catch(()=>{}); // New files, each into its stage's folder: the server sends those in Arte @@ -521,8 +540,10 @@ async function syncFolder(force=false){ FOLDER.status=(stages?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder(); say(FOLDER.status,false,60000); if(stages){ - await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file); - await record(file.upload_id,file,STAGE_FOLDERS[file.state]); + if(!await step(file.name,async()=>{ + await fetchInto(await stageDir(STAGE_FOLDERS[file.state]),file); + await record(file.upload_id,file,STAGE_FOLDERS[file.state]); + }))continue; }else{ // Firefox writes it as .part and renames it when whole. const link=node('a');link.href=file.url;link.referrerPolicy='no-referrer';link.download=file.name;link.click(); @@ -538,11 +559,11 @@ async function syncFolder(force=false){ let printed=0; for(const r of receipts){ try{await api('/orders/'+r.order+'/receipt/claim',{});}catch(e){if(e.status===409)continue;throw e;} - try{ + await step(r.name,async()=>{try{ const res=await fetch('/api/operator/orders/'+r.order+'/receipt'); if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').'); await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++; - }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;} + }catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}}); } // The review photos and videos, once each, into Revisões/. They are never // removed from there: the folder is the room's evidence of the check. @@ -551,10 +572,12 @@ async function syncFolder(force=false){ const key='review:'+review.upload_id; if(FOLDER.saved.has(key))continue; FOLDER.status='Salvando revisão: '+review.name;paintFolder(); - const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view'); - const res=await fetch(view.url,{referrerPolicy:'no-referrer'}); - if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').'); - await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res.body); + if(!await step(review.name,async()=>{ + const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view'); + const res=await fetch(view.url,{referrerPolicy:'no-referrer'}); + if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').'); + await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res.body); + }))continue; FOLDER.saved.set(key,{order:review.order,name:review.name,review:true}); FOLDER.last=new Date();await keepSaved();reviewSaved++; } @@ -566,6 +589,13 @@ async function syncFolder(force=false){ if(reviewSaved)say(reviewSaved+' foto(s)/vídeo(s) de revisão salvos em '+REVIEWS_FOLDER+'.'); if(moved)say(moved+' arquivo(s) mudaram de pasta com o pedido.'); if(removed)say(removed+' arquivo(s) de pedidos cancelados, excluídos, em correção, trocados ou finalizados há mais de '+KEEP_FINISHED_DAYS+' dias saíram das pastas.'); + // What another program held open waits for the next pass; the rest is done. + if(locked.length){ + FOLDER.lastSig=null; + FOLDER.error='O arquivo '+locked[0]+(locked.length>1?' e mais '+(locked.length-1):'')+ + ' está aberto em outro programa (o FlexiPRINT, por exemplo). Os outros foram gravados; o Kanban tenta este de novo em 30 s.'; + say('Pastas automáticas: '+FOLDER.error,true); + } }catch(e){ if(e.name==='NotAllowedError')FOLDER.granted=false; else if(e.name==='NotFoundError')FOLDER.error='A pasta “'+FOLDER.handle?.name+'” não foi encontrada. Ela foi apagada ou a rede caiu? Escolha a pasta de novo.';