/* Shared direct multipart transport for customer originals/corrections and operator finals. */ // A big cart would otherwise open dozens of server reservations at once and // meet the pending-upload cap. Four at a time, the rest queued here. const DTF_UPLOAD_SLOTS=4; let uploadSlotsUsed=0; const uploadSlotsWaiting=[]; function uploadSlot(){ if(uploadSlotsUseduploadSlotsWaiting.push(resolve)); } function releaseUploadSlot(){ const next=uploadSlotsWaiting.shift(); if(next)next();else uploadSlotsUsed--; } async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true, signal=null}) { const cancelled=()=>new DOMException('Envio cancelado.','AbortError'); const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]); const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join(''); const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]); // A busy server asks for a wait: retry this file alone, quietly, before the // customer sees the failure (Marcus, 2026-11-11). Only a 429 that carries // Retry-After; the quota refusal has none and is shown at once. const retryWait=error=>{ const seconds=Number(error?.retryAfter); return error?.status===429&&Number.isFinite(seconds)?Math.min(60,Math.max(1,Math.ceil(seconds))):null; }; const withRetry=async call=>{ for(let attempt=0;;attempt++){ try{return await call();} catch(error){ const wait=retryWait(error); if(wait===null||attempt>=3)throw error; await new Promise(resolve=>setTimeout(resolve,wait*1000)); } } }; let id=resume?localStorage.getItem(key):null,state; if(id){ try{state=await api(prefix+'/'+id);} catch(error){ // The id was started under another session (a sign-in changes the scope): // the new session does not own it, so this file starts again as a new // upload. A 403/404/410 must never keep the retry on the old id. if(![403,404,410].includes(error.status))throw error; id=null; if(resume)localStorage.removeItem(key); } } if(!id){state=await withRetry(()=>api(startPath,{name:file.name,size:file.size}));id=state.id;if(resume)localStorage.setItem(key,id);} async function waitForScan(){ onBytes(file.size); // The antivirus streams the whole file: about a second per 2 MB, and at // least two and a half minutes. const attempts=Math.max(150,Math.ceil(file.size/2e6)); for(let attempt=0;attemptsetTimeout(resolve,1000)); } throw new Error('Verificação de segurança pendente. Tente novamente para consultar o resultado.'); } if(state.complete)return waitForScan(); const done=new Set(state.parts||[]),size=state.part_bytes; const length=part=>Math.min(size,file.size-(part-1)*size); let sent=[...done].reduce((t,part)=>t+length(part),0); onBytes(sent); // Each part through XMLHttpRequest, which reports the bytes as they go: the // bar moves while a part is on its way, not once per part (Dropstar, 2026-10-29). const put=(url,body)=>new Promise((resolve,reject)=>{ if(signal?.aborted)return reject(cancelled()); const xhr=new XMLHttpRequest();xhr.open('PUT',url); xhr.upload.onprogress=e=>onBytes(Math.min(file.size,sent+e.loaded)); const lost=()=>reject(new Error('Upload interrompido. Tente novamente para retomar.')); xhr.onload=()=>xhr.status>=200&&xhr.status<300?resolve():lost(); xhr.onerror=lost;xhr.ontimeout=lost;xhr.onabort=()=>reject(cancelled()); signal?.addEventListener('abort',()=>xhr.abort(),{once:true}); xhr.send(body); }); for(let offset=0,part=1;offsetapi(prefix+'/'+id+'/parts/'+part,{})); await put(signed.url,file.slice(offset,offset+size)); done.add(part);sent+=length(part); onBytes(sent); } await api(prefix+'/'+id+'/complete',{}); return waitForScan(); } window.dtfUpload = async (file, options) => { if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError'); await uploadSlot(); try{return await sendUpload(file, options);} finally{releaseUploadSlot();} };