feat: in Firefox, the print queue's files download by themselves
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 3m31s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m27s

Firefox cannot write into a folder a site chose, so the folder button was
hidden there. It now appears in every browser: in Firefox it switches on
automatic downloads, each file that enters Fila de impressão downloaded
once, named after its order, into Firefox's download folder, which the
dialog explains how to point at FlexiPRINT's. Firefox writes .part and
renames when whole, so FlexiPRINT never reads half a file either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-08 14:26:11 -03:00
parent 1216998914
commit 87cd7d77fb
2 changed files with 58 additions and 12 deletions

View File

@@ -451,4 +451,5 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.autofolder.warn{color:var(--warn);border-color:rgba(242,179,61,.5)}
.autofolder.busy svg{animation:pulse 1s ease-in-out infinite alternate}
@keyframes pulse{to{opacity:.35}}
.steps-list{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:6px;font-size:14px;color:var(--tx2)}

View File

@@ -190,18 +190,27 @@ function download(uid){return async()=>{
const link=node('a');link.href=result.url;link.referrerPolicy='no-referrer';link.download=result.name;link.click();
};}
// ---- Automatic folder ------------------------------------------------------
// The print queue's files, saved by this browser into a folder the operator
// chose (the FlexiPRINT folder, or the internal server's share), as orders
// enter Fila de impressão. Chrome and Edge only, while the Kanban is open.
// The folder is remembered; after the browser restarts it needs one click.
// The print queue's files, saved by this browser as orders enter Fila de
// impressão, while the Kanban is open. Chrome and Edge write into a folder the
// operator chose (FlexiPRINT's, or the internal server's share), remembered,
// with one click to release it after the browser restarts. Firefox cannot
// write into a chosen folder: there each file is downloaded, and Firefox's own
// download folder is set to FlexiPRINT's.
const kv=(()=>{let opened;const open=()=>opened||(opened=new Promise((ok,fail)=>{const r=indexedDB.open('dtf-kanban',1);
r.onupgradeneeded=()=>r.result.createObjectStore('kv');r.onsuccess=()=>ok(r.result);r.onerror=()=>fail(r.error);}));
const run=async(mode,fn)=>{const db=await open();return new Promise((ok,fail)=>{const t=db.transaction('kv',mode);const req=fn(t.objectStore('kv'));
t.oncomplete=()=>ok(req?.result);t.onerror=()=>fail(t.error);});};
return {get:k=>run('readonly',s=>s.get(k)),set:(k,v)=>run('readwrite',s=>s.put(v,k)),del:k=>run('readwrite',s=>s.delete(k))};})();
const FOLDER={supported:'showDirectoryPicker' in window,handle:null,granted:false,saved:new Set(),busy:false,status:'',lastSig:null};
const FOLDER={supported:'showDirectoryPicker' in window,handle:null,granted:false,downloads:false,
saved:new Set(),busy:false,status:'',lastSig:null};
// Switched on: a chosen folder released, or automatic downloads.
const folderActive=()=>FOLDER.supported?!!FOLDER.handle&&FOLDER.granted:FOLDER.downloads;
async function restoreFolder(){
if(!FOLDER.supported)return;
if(!FOLDER.supported){
try{FOLDER.downloads=localStorage.getItem('dtf-auto-downloads')==='1';}catch{}
if(FOLDER.downloads)FOLDER.saved=new Set(await kv.get('saved:downloads').catch(()=>null)||[]);
return;
}
try{FOLDER.handle=await kv.get('folder')||null;
if(FOLDER.handle){FOLDER.granted=(await FOLDER.handle.queryPermission({mode:'readwrite'}))==='granted';
FOLDER.saved=new Set(await kv.get('saved:'+FOLDER.handle.name)||[]);
@@ -215,13 +224,15 @@ function folderLine(){
}
function folderText(){
const h=FOLDER.handle;
if(!FOLDER.supported)return FOLDER.downloads?FOLDER.status||'Baixando sozinho os arquivos que entram na fila (pasta de downloads do Firefox)'
:'Download automático desligado: clique para baixar sozinho os arquivos que entram na fila';
return !h?'Pasta automática desligada: clique para escolher a pasta onde os arquivos da fila são salvos sozinhos'
:!FOLDER.granted?'Clique para liberar a pasta “'+h.name+'” e voltar a salvar os arquivos da fila'
:FOLDER.status||'Salvando os arquivos da fila em “'+h.name+'”';
}
function paintFolder(b=$('autofolder')){
if(!b)return;
const h=FOLDER.handle;b.classList.toggle('on',!!h&&FOLDER.granted);b.classList.toggle('warn',!!h&&!FOLDER.granted);
const h=FOLDER.handle;b.classList.toggle('on',folderActive());b.classList.toggle('warn',FOLDER.supported&&!!h&&!FOLDER.granted);
b.classList.toggle('busy',FOLDER.busy);b.title=folderText();b.setAttribute('aria-label',folderText());
}
async function chooseFolder(){
@@ -232,6 +243,7 @@ async function chooseFolder(){
paintFolder();say('Os arquivos da fila vão ser salvos em “'+handle.name+'”.');syncFolder();
}
async function folderClick(){
if(!FOLDER.supported)return downloadsDialog();
try{
if(FOLDER.handle&&!FOLDER.granted){
FOLDER.granted=(await FOLDER.handle.requestPermission({mode:'readwrite'}))==='granted';
@@ -250,19 +262,52 @@ async function folderClick(){
row.append(close,pick);box.append(row);back.append(box);back.onclick=e=>{if(e.target===back)back.remove();};document.body.append(back);
}catch(e){if(e.name!=='AbortError')say(e.message,true);}
}
// Firefox: the same, through ordinary downloads into Firefox's download folder.
function downloadsDialog(){
const back=node('div',undefined,'modal');const box=node('div',undefined,'modal-box');
box.append(node('h2','Download automático'),
node('p','Com o Kanban aberto, os arquivos finais dos pedidos que entram na Fila de impressão são baixados sozinhos, '+
'com o número do pedido no nome. Eles vão para a pasta de downloads do Firefox.','muted'));
const steps=node('ol',undefined,'steps-list');
for(const t of ['No Firefox, abra Configurações → Geral → Arquivos e aplicativos.',
'Em “Salvar arquivos em”, escolha a pasta que o FlexiPRINT lê (ou a pasta da rede do servidor).',
'Desmarque “Sempre perguntar onde salvar arquivos”.'])steps.append(node('li',t));
box.append(node('p','Para cair direto na pasta do FlexiPRINT:','muted'),steps,
node('p','Outros downloads deste Firefox também vão para essa pasta; por isso, use um perfil do Firefox só para o Kanban na sala de impressão.','faint'));
const row=node('div',undefined,'modal-actions');
const close=node('button','Fechar','btn ghost');close.type='button';close.onclick=()=>back.remove();
const toggle=button(FOLDER.downloads?'Desligar':'Ligar download automático',async()=>{
back.remove();FOLDER.downloads=!FOLDER.downloads;FOLDER.lastSig=null;
try{localStorage.setItem('dtf-auto-downloads',FOLDER.downloads?'1':'0');}catch{}
if(FOLDER.downloads){FOLDER.saved=new Set(await kv.get('saved:downloads').catch(()=>null)||[]);say('Download automático ligado.');syncFolder();}
else say('Download automático desligado.');
paintFolder();},FOLDER.downloads?'btn ghost':'btn primary');
row.append(close,toggle);box.append(row);back.append(box);back.onclick=e=>{if(e.target===back)back.remove();};document.body.append(back);
}
// Save what the queue has and this folder has not received yet. A file the
// FlexiPRINT moved away after importing is not downloaded again.
async function syncFolder(){
if(!FOLDER.handle||!FOLDER.granted||FOLDER.busy||!board||!may('produce'))return;
if(!folderActive()||FOLDER.busy||!board||!may('produce'))return;
const sig=board.orders.filter(o=>o.state==='fil'&&!o.cancelled_at).map(o=>o.id+':'+o.version).join(',');
if(sig===FOLDER.lastSig)return;
FOLDER.busy=true;
try{
const {files}=await api('/queue/finals?auto=1');
const pending=files.filter(f=>!FOLDER.saved.has(f.upload_id));
const where=FOLDER.supported?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
const memory=FOLDER.supported?'saved:'+FOLDER.handle.name:'saved:downloads';
for(const [i,file] of pending.entries()){
FOLDER.status='Salvando '+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
FOLDER.status=(FOLDER.supported?'Salvando ':'Baixando ')+(i+1)+' de '+pending.length+': '+file.name;paintFolder();
say(FOLDER.status,false,60000);
if(!FOLDER.supported){
// 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();
FOLDER.saved.add(file.upload_id);
await kv.set(memory,[...FOLDER.saved].slice(-3000)).catch(()=>{});
await new Promise(r=>setTimeout(r,900));
continue;
}
const temp=await FOLDER.handle.getFileHandle(file.name+'.baixando',{create:true});
const out=await temp.createWritable();
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
@@ -272,9 +317,9 @@ async function syncFolder(){
await FOLDER.handle.removeEntry(file.name).catch(()=>{});
if('move' in temp)await temp.move(file.name);
FOLDER.saved.add(file.upload_id);
await kv.set('saved:'+FOLDER.handle.name,[...FOLDER.saved].slice(-3000)).catch(()=>{});
await kv.set(memory,[...FOLDER.saved].slice(-3000)).catch(()=>{});
}
FOLDER.lastSig=sig;FOLDER.status=pending.length?'Salvos '+pending.length+' arquivo(s) em “'+FOLDER.handle.name+'”':'';
FOLDER.lastSig=sig;FOLDER.status=pending.length?(FOLDER.supported?'Salvos ':'Baixados ')+pending.length+' arquivo(s) em '+where:'';
if(pending.length)say(FOLDER.status+'.');
}catch(e){
if(e.name==='NotAllowedError'){FOLDER.granted=false;}
@@ -447,7 +492,7 @@ function renderBoard(){
if(tools){
const tools=node('div',undefined,'coltools');
if(orders.length){const all=downloadButton('Baixar',downloadQueue,'btn ghost small');all.title='Baixar os arquivos finais de todos os pedidos da fila';tools.append(all);}
if(FOLDER.supported)tools.append(folderLine());
tools.append(folderLine());
sub.append(tools);
}
head.append(line,sub);