Files
bpq_gui/public/attachments.js
T

8 lines
7.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let attachmentGeneration=0,attachmentPdf=null;
const attachmentDialog=document.createElement('dialog');attachmentDialog.className='attachment-dialog';attachmentDialog.innerHTML='<div class="dialog-heading"><h2 id="attachment-title">Allegato</h2><button id="attachment-close" class="icon-button" aria-label="Chiudi anteprima">×</button></div><div id="attachment-preview"></div><footer><a id="attachment-download" class="primary" download>Scarica file ↓</a></footer>';document.body.append(attachmentDialog);$('#attachment-close').onclick=()=>attachmentDialog.close();attachmentDialog.addEventListener('close',()=>{attachmentGeneration++;attachmentPdf?.destroy().catch(()=>{});attachmentPdf=null;$('#attachment-preview').replaceChildren();});
async function renderPdf(url,generation){const pdfjs=await import('/vendor/pdfjs/pdf.min.mjs');pdfjs.GlobalWorkerOptions.workerSrc='/vendor/pdfjs/pdf.worker.min.mjs';const documentPdf=await pdfjs.getDocument({url,withCredentials:true,isEvalSupported:false,enableXfa:false,disableFontFace:true,useSystemFonts:true,standardFontDataUrl:'/vendor/pdfjs/standard_fonts/',cMapUrl:'/vendor/pdfjs/cmaps/',cMapPacked:true}).promise;if(generation!==attachmentGeneration){await documentPdf.destroy();return;}attachmentPdf=documentPdf;const preview=$('#attachment-preview');preview.innerHTML='<div class="pdf-controls"><button id="pdf-previous" class="secondary">←</button><span id="pdf-page"></span><button id="pdf-next" class="secondary">→</button></div><canvas id="pdf-canvas" aria-label="Anteprima pagina PDF"></canvas>';let page=1,busy=false;async function draw(){if(busy||generation!==attachmentGeneration)return;busy=true;try{const p=await documentPdf.getPage(page);const v=p.getViewport({scale:1});const scale=Math.min(2,Math.max(1,(preview.clientWidth-30)/v.width));const viewport=p.getViewport({scale});const canvas=$('#pdf-canvas');if(!canvas||generation!==attachmentGeneration)return;canvas.width=viewport.width;canvas.height=viewport.height;await p.render({canvasContext:canvas.getContext('2d'),viewport}).promise;$('#pdf-page').textContent=page+' / '+documentPdf.numPages;$('#pdf-previous').disabled=page===1;$('#pdf-next').disabled=page===documentPdf.numPages;}finally{busy=false}}$('#pdf-previous').onclick=()=>{if(page>1&&!busy){page--;draw()}};$('#pdf-next').onclick=()=>{if(page<documentPdf.numPages&&!busy){page++;draw()}};await draw();}
async function openAttachment(id,file){const generation=++attachmentGeneration;$('#attachment-title').textContent=file.name;const url='/api/messages/'+id+'/attachments/'+file.index;$('#attachment-download').href=url;$('#attachment-preview').innerHTML='<p class="empty">Caricamento anteprima…</p>';attachmentDialog.showModal();if(file.mime.startsWith('image/')){const image=document.createElement('img');image.alt=file.name;image.src=url+'?preview=1';image.onerror=()=>$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile. Puoi scaricare il file.</p>';$('#attachment-preview').replaceChildren(image);}else if(file.mime==='application/pdf'){try{await renderPdf(url+'?preview=1',generation)}catch{if(generation===attachmentGeneration)$('#attachment-preview').innerHTML='<p class="empty">Anteprima PDF non disponibile. Puoi scaricare il file.</p>';}}else if(file.mime==='text/plain'){try{const data=await api('/messages/'+id+'/attachments/'+file.index+'?text=1');if(generation!==attachmentGeneration)return;const pre=document.createElement('pre');pre.textContent=data.text;$('#attachment-preview').replaceChildren(pre);if(data.truncated){const hint=document.createElement('p');hint.className='muted';hint.textContent='Anteprima limitata ai primi 128 KB. Il download contiene il file completo.';$('#attachment-preview').append(hint)}}catch(e){$('#attachment-preview').textContent=e.message}}else{$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile per questo formato. Puoi scaricare il file.</p>';}}
async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='<span class="muted">Controllo allegati…</span>';reader.querySelector('.reader-footer')?.before(section);try{const data=await api('/messages/'+id+'/attachments');if(!section.isConnected)return;if(!data.files.length&&!data.encoded){section.remove();return;}section.replaceChildren();if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`<span class="attachment-icon">${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}</span><div><b>${esc(file.name)}</b><small>${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}</small></div><button class="secondary attachment-open">Anteprima</button><a class="secondary" href="/api/messages/${id}/attachments/${file.index}" download>Scarica ↓</a>`;row.querySelector('button').onclick=()=>openAttachment(id,file);if(file.mime==='application/octet-stream')row.querySelector('button').hidden=true;section.append(row);}}if(data.encoded?.state==='complete'){const imageFile=data.files.find(f=>f.reconstructed&&f.mime.startsWith('image/')),body=reader.querySelector('.reader-body');if(imageFile&&body){const original=document.createElement('details');original.className='sevenplus-original';const summary=document.createElement('summary');summary.textContent='Mostra messaggio originale e dati 7plus';original.append(summary,...body.childNodes);const preview=document.createElement('div');preview.className='sevenplus-inline';const img=document.createElement('img');img.src='/api/messages/'+id+'/attachments/'+imageFile.index+'?preview=1';img.alt=imageFile.name;img.loading='lazy';img.onclick=()=>openAttachment(id,imageFile);const caption=document.createElement('p');caption.textContent=imageFile.name+' · '+imageFile.parts+' parti ricostruite · CRC verificati';preview.append(img,caption);body.replaceChildren(preview,original);}}if(data.encoded){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>${data.encoded.state==='complete'?'Ricostruzione completa · '+data.encoded.total+'/'+data.encoded.total+' parti verificate. Anteprima e download disponibili negli allegati.':data.encoded.state==='incomplete'?'Ricevute '+data.encoded.availableParts.length+'/'+data.encoded.total+' parti. Mancano: '+data.encoded.missingParts.join(', ')+'.'+(data.encoded.damagedParts.length?' Parti danneggiate: '+data.encoded.damagedParts.join(', ')+'.':''):data.encoded.state==='damaged'?'Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti '+data.encoded.damagedParts.join(', ')+'.':'Parte '+data.encoded.part+'/'+data.encoded.total+'. Nessun blocco 7plus riconoscibile nel messaggio.'}</p>${data.encoded.issues?.length?'<p>'+esc(data.encoded.issues.join(' · '))+'</p>':''}${data.encoded.messageIds?.length?'<div class="sevenplus-parts">'+data.encoded.messageIds.map(mid=>'<button class="text-button" data-seven-message="'+mid+'">#'+mid+'</button>').join('')+'</div>':''}<a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`<span class="muted">${esc(e.message)}</span>`;}}
const attachmentRead=readMessage;readMessage=async function(id){await attachmentRead(id);if(selected===id&&$('#reader .reader-footer'))showAttachments(id,$('#reader'));};
const attachmentWlRead=wlRead;wlRead=async function(id){await attachmentWlRead(id);if(wlSelected===id&&$('#wl-reader .reader-footer'))showAttachments(id,$('#wl-reader'));};