Add native Winlink attachment upload, reader indicators and verified storage

This commit is contained in:
alberto committed 2026-10-17 14:33:34 +02:00
1 parent 2b00b1cbbd
commit 5fde09823b
13 files changed
+223 -20

No files matched your search

+4 -4
View File
@@ -2,7 +2,7 @@ const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
let station={call:'',alias:'',features:{},apps:[]};
let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0;
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{'Content-Type':'application/json',...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}
async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{...(options.body instanceof FormData?{}:{'Content-Type':'application/json'}),...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function showLogin(){document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();document.dispatchEvent(new Event('station-ready'));}
@@ -20,13 +20,13 @@ async function loadMessages(){if(!station.features.bbs)return;try{allMessages=aw
function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');}
function mailTimeMeta(m){const zone=mailTimezone();const stamp=kind=>{const value=kind==='sent'?m.createdAt:m.receivedAt;return value?new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit'}):null;};return [stamp('sent')?'Inviato <b>'+esc(stamp('sent'))+'</b>':'',stamp('received')?'Ricevuto <b>'+esc(stamp('received'))+'</b>':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>'<span>'+x+'</span>').join('');}
function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}${m.attachmentCount?'<span class="mail-paperclip" aria-label="Allegati" title="'+m.attachmentCount+' '+BPQI18n.t('Allegati')+'">📎 '+m.attachmentCount+'</span>':''}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from.replace(/-\d+$/,'')===station.call.replace(/-\d+$/,''))&&(!cat||m.to===cat)&&(!q||`${m.subject} ${m.from} ${m.to} ${m.id}`.toLowerCase().includes(q)));$('#list-count').textContent=list.length+' messaggi';$('#message-list').innerHTML=list.map(m=>mailRow(m,selected,'data-id',{category:categoryLabel(m),status:m.status==='F'?'Inoltrato':m.status==='N'?'Nuovo':m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'<p class="empty">Nessun messaggio corrisponde ai filtri.</p>';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));}
async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><button class="secondary" id="reply">↩ Rispondi</button></footer>`;$('#reply').onclick=()=>openCompose({to:m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80),text:'\n\n--- '+m.from+' ---\n'+m.text.split('\n').map(l=>'> '+l).join('\n')});}catch(err){$('#reader').innerHTML=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
$$('[data-filter]').forEach(b=>b.onclick=()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));renderMessages()});$('#search').oninput=renderMessages;$('#category').onchange=renderMessages;
function openCompose(data={}){const f=$('#compose-form');f.reset();for(const [key,value]of Object.entries(data))f.elements[key].value=value;$('#compose-error').textContent='';$('#compose').showModal();f.elements.to.focus()}
$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value)&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()});
$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const created=await api('/messages',{method:'POST',body:JSON.stringify(data)});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{b.disabled=false;b.textContent='Salva e metti in coda →'}});
$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value||window.bpqComposeAttachments?.count())&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()});
$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';window.bpqComposeAttachments?.busy(true);$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const payload=winlinkMode&&window.bpqComposeAttachments?.count()?window.bpqComposeAttachments.form(data):JSON.stringify(data);const created=await api('/messages',{method:'POST',body:payload});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{window.bpqComposeAttachments?.busy(false);b.disabled=false;b.textContent='Salva e metti in coda →'}});
$('#refresh').onclick=async()=>{const b=$('#refresh');b.disabled=true;await Promise.all([loadDashboard(),loadMessages()]);b.disabled=false};
setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000);
function restoreSession(){api('/session').then(showShell).catch(()=>showLogin());}
+1 -1
View File
@@ -2,6 +2,6 @@ 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>`;}}
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();reader.querySelector('.reader-attachment-count')?.remove();if(data.files.length){const count=document.createElement('span');count.className='reader-attachment-count';count.textContent='📎 '+data.files.length;count.title='Allegati';reader.querySelector('.reader-header .tag')?.after(count);}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'));};
+32
View File
@@ -0,0 +1,32 @@
#compose{max-height:94dvh;overflow:hidden;padding:0}
#compose-form{display:flex;flex-direction:column;max-height:calc(94dvh - 2px)}
#compose .dialog-heading{flex:none;margin:0;padding:22px 30px 16px;border-bottom:1px solid #2b3a4d}
#compose .compose-scroll-body{min-height:0;overflow:auto;padding:20px 30px;overscroll-behavior:contain}
#compose footer{flex:none;margin:0;padding:15px 30px;border-top:1px solid #2b3a4d;background:#151d28}
.compose-attachments{border:1px dashed #3d5268;border-radius:10px;padding:14px 16px;margin:18px 0;background:#101b29;transition:border-color .15s,background .15s}
.compose-attachments[hidden]{display:none}
.compose-attachments.dragging{border-color:#a6c8ea;background:#1a3045}
.compose-attachments-heading{display:flex;justify-content:space-between;align-items:center;gap:12px}
.compose-attachments-heading>div{display:flex;gap:12px;align-items:center;font-size:12px}
.compose-attachments-heading small{color:#8ca2b6;font-size:10px;font-weight:400}
.compose-attachments-heading button{min-height:34px;padding:7px 12px;font-size:11px}
.compose-file-list{display:grid;gap:7px;margin-top:10px;max-height:170px;overflow:auto}
.compose-file-list:empty{display:none}
.compose-file{display:flex;align-items:center;gap:11px;padding:8px 10px;background:#172638;border:1px solid #2b4157;border-radius:7px;min-width:0}
.compose-file-icon{display:grid;place-items:center;width:36px;height:36px;flex:none;font-size:20px;color:#9fbdd9}
.compose-file-icon img{max-width:36px;max-height:36px;border-radius:4px;object-fit:contain}
.compose-file>div{min-width:0;flex:1}.compose-file b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:#e0eaf4}
.compose-file small{display:block;font-size:10px;color:#8ca2b6;margin-top:4px}
.compose-file-remove{border:0;background:transparent;color:#b2c4d4;width:32px;height:32px;border-radius:6px;font-size:20px;cursor:pointer}
.compose-file-remove:hover{background:#48313b;color:#ffb7bd}.compose-file-remove:focus-visible{outline:2px solid #a6c8ea}
#compose .compose-file-help{font-size:10px;line-height:1.5;color:#8ca2b6;margin:10px 0 0}
.mail-paperclip{display:inline-flex;gap:3px;align-items:center;margin-left:9px;color:#9ebfdf;font-size:10px;vertical-align:middle;white-space:nowrap}
.reader-attachment-count{display:inline-flex;align-items:center;gap:4px;border-radius:5px;background:#263b50;color:#c3d8ec;padding:4px 8px;font-size:10px;margin-left:8px}
@media(max-width:600px){.compose-attachments{padding:12px}.compose-attachments-heading>div{gap:6px;flex-wrap:wrap}.compose-file-list{max-height:130px}}
#compose:has(.compose-attachments:not([hidden])) textarea{height:120px;min-height:90px}
#compose:has(.compose-attachments:not([hidden])) .compose-row{grid-template-columns:1fr}
@media(max-width:600px){#compose .dialog-heading{padding:18px 20px 14px}#compose .compose-scroll-body{padding:16px 20px}#compose footer{padding:12px 20px}}
+28
View File
@@ -0,0 +1,28 @@
(() => {
const form=document.querySelector('#compose-form'),panel=document.createElement('section');panel.className='compose-attachments';panel.hidden=true;
panel.innerHTML='<div class="compose-attachments-heading"><div><b>Allegati</b><small id="compose-file-total">0 / 64 KB</small></div><button type="button" class="secondary" id="compose-file-add">+ Allega file</button></div><input id="compose-files" type="file" multiple hidden aria-label="Seleziona allegati"><div id="compose-file-list" class="compose-file-list"></div><p class="compose-file-help">Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.</p><p id="compose-file-error" class="error" role="alert"></p>';
form.querySelector('.compose-help').before(panel);
const scrollBody=document.createElement('div');scrollBody.className='compose-scroll-body';const heading=form.querySelector('.dialog-heading'),footer=form.querySelector('footer');
while(heading.nextSibling&&heading.nextSibling!==footer)scrollBody.append(heading.nextSibling);heading.after(scrollBody);
const input=panel.querySelector('input'),list=panel.querySelector('#compose-file-list');let files=[],sending=false;
const total=()=>files.reduce((sum,item)=>sum+item.file.size,0);
function render(){
panel.hidden=!wlCompose;panel.querySelector('#compose-file-total').textContent=files.length+' / 10 · '+size(total())+' / 64 KB';panel.querySelector('#compose-file-add').disabled=sending||files.length>=10;input.disabled=sending;
list.innerHTML=files.map((item,i)=>'<div class="compose-file"><span class="compose-file-icon">'+(item.url?'<img src="'+item.url+'" alt="">':'📎')+'</span><div><b data-no-i18n>'+esc(item.file.name)+'</b><small>'+size(item.file.size)+'</small></div><button type="button" class="compose-file-remove" data-remove-file="'+i+'" aria-label="Rimuovi allegato" '+(sending?'disabled':'')+'>×</button></div>').join('');
}
function add(incoming){
if(sending)return;const candidate=[...incoming],error=panel.querySelector('#compose-file-error');error.textContent='';
if(files.length+candidate.length>10){error.textContent='Massimo 10 allegati per messaggio';return;}
if(total()+candidate.reduce((sum,file)=>sum+file.size,0)>64*1024){error.textContent='Allegati troppo grandi: massimo 64 KB complessivi';return;}
const names=new Set(files.map(item=>item.file.name.toLowerCase()));
for(const file of candidate){if(names.has(file.name.toLowerCase())){error.textContent='Nomi allegati duplicati: rinomina i file';return;}names.add(file.name.toLowerCase());}
files.push(...candidate.map(file=>({file,url:/^image\/(png|jpeg|gif|webp)$/.test(file.type)?URL.createObjectURL(file):null})));render();
}
panel.querySelector('#compose-file-add').onclick=()=>input.click();input.onchange=()=>{add(input.files);input.value='';};
list.onclick=e=>{const button=e.target.closest('[data-remove-file]');if(!button||sending)return;const [removed]=files.splice(Number(button.dataset.removeFile),1);if(removed.url)URL.revokeObjectURL(removed.url);panel.querySelector('#compose-file-error').textContent='';render();};
for(const name of ['dragenter','dragover'])panel.addEventListener(name,e=>{e.preventDefault();if(!sending)panel.classList.add('dragging');});
panel.addEventListener('dragleave',e=>{if(!panel.contains(e.relatedTarget))panel.classList.remove('dragging');});panel.addEventListener('drop',e=>{e.preventDefault();panel.classList.remove('dragging');add(e.dataTransfer.files);});
window.bpqComposeAttachments={count:()=>files.length,reset(){files.forEach(item=>{if(item.url)URL.revokeObjectURL(item.url);});files=[];sending=false;input.value='';panel.querySelector('#compose-file-error').textContent='';render();},form(data){const textBytes=new TextEncoder().encode(String(data.text||'').replace(/\r?\n/g,'\r\n')).length;if(textBytes+total()>80*1024)throw new Error(BPQI18n.t('Testo e allegati superano 80 KB complessivi'));const payload=new FormData();for(const [key,value]of Object.entries(data))payload.set(key,value);for(const item of files)payload.append('files',item.file,item.file.name);return payload;},busy(value){sending=value;render();}};
document.querySelector('#compose').addEventListener('cancel',e=>{if((form.elements.text.value||form.elements.subject.value||files.length)&&!bpqConfirm('Chiudere e scartare questa bozza?'))e.preventDefault();});
document.addEventListener('bpq-languagechange',render);
})();
+15 -1
View File
@@ -609,7 +609,21 @@ Accesso rifiutato|Access denied
Collega prima il terminale|Connect the terminal first
Invia un solo comando, massimo 1000 caratteri|Send one command, up to 1000 characters
`;
const dictionary=new Map(entries.trim().split('\n').map(line=>line.split('|')));
const uploadCopy=`Allegati|Attachments
Allega file|Attach files
Seleziona allegati|Choose attachments
Rimuovi allegato|Remove attachment
Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.|Drop files here or select them. Up to 10 files and 64 KB total. Small files reduce radio connection time.
Massimo 10 allegati per messaggio|Up to 10 attachments per message
Allegati troppo grandi: massimo 64 KB complessivi|Attachments too large: maximum 64 KB total
Nomi allegati duplicati: rinomina i file|Duplicate attachment names: rename the files
Usa il caricamento file per gli allegati|Use file upload for attachments
Campi del messaggio non validi|Invalid message fields
Campo allegato non valido|Invalid attachment field
Gli allegati in uscita sono disponibili per le email Winlink|Outgoing attachments are available for Winlink emails
BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.|BPQ saved the message but the attachments do not match. Check the queue before retrying.`;
const sizeCopy='Testo e allegati superano 80 KB complessivi|Message text and attachments exceed 80 KB total\nMessaggio troppo grande per il server HTTP BPQ|Message too large for the BPQ HTTP server';
const dictionary=new Map((entries.trim()+'\n'+uploadCopy+'\n'+sizeCopy).split('\n').map(line=>line.split('|')));
function resolveLanguage(preference=null,languages=[]){
if(preference==='it'||preference==='en')return preference;
// The first browser language is the user's preferred UI language; English is the fallback.
+1 -1
View File
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css"><script defer src="/terminal.js"></script><link rel="stylesheet" href="/radio-control.css"><script defer src="/radio-control.js"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/compose-attachments.css"><script defer src="/compose-attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css"><script defer src="/terminal.js"></script><link rel="stylesheet" href="/radio-control.css"><script defer src="/radio-control.js"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<body>
<section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div></form></section>
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
+2 -1
View File
@@ -7,7 +7,8 @@ function wlRender(){if(!wlData)return;const q=$('#wl-search').value.toLowerCase(
async function wlRead(id){wlSelected=id;const generation=++wlGeneration;wlRender();$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Caricamento…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==wlGeneration)return;const meta=wlData?.messages.find(x=>x.id===id);$('#wl-reader').innerHTML=`<div class="reader-header"><span class="tag">EMAIL · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(meta?.fromAddress||m.from)}</b></span><span>A <b>${esc(meta?.address||m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><button id="wl-reply" class="secondary">↩ Rispondi</button><button id="wl-delete" class="danger">Elimina</button></footer>`;$('#wl-reply').onclick=()=>wlNew({to:meta?.fromAddress||m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80)});$('#wl-delete').onclick=()=>askDelete(id,m.subject);}catch(e){$('#wl-reader').innerHTML=`<p class="empty">${esc(e.message)}</p>`}}
$$('[data-wlfolder]').forEach(b=>b.onclick=()=>{wlFolder=b.dataset.wlfolder;$$('[data-wlfolder]').forEach(x=>x.classList.toggle('active',x===b));wlRender()});$('#wl-search').oninput=wlRender;
function wlNew(data={}){wlCompose=true;openCompose(data);$('#compose-form').elements.type.value='P';$('#compose-form').elements.type.closest('label').hidden=true;$('#compose-form').elements.to.placeholder='Nominativo Winlink oppure [email protected]';$('#compose .dialog-heading h2').textContent='Nuova email';}
$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='Nominativo oppure indirizzo email';});
const baseOpenCompose=openCompose;openCompose=function(data={}){window.bpqComposeAttachments?.reset();baseOpenCompose(data);};
$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;window.bpqComposeAttachments?.reset();$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='Nominativo oppure indirizzo email';});
$('#compose-form').addEventListener('submit',e=>{if(!wlCompose)return;const field=e.target.elements.to;let address=field.value.trim().replace(/^RMS[/:]/i,'');if(!address.includes('@'))address+='@WINLINK.ORG';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)){e.preventDefault();e.stopImmediatePropagation();$('#compose-error').textContent='Inserisci un nominativo Winlink o un indirizzo email valido';return;}field.value='RMS/'+address;e.target.elements.type.value='P';},true);
$('#wl-sync').onclick=async()=>{const b=$('#wl-sync');b.disabled=true;try{await window.bpqSync.start({kind:'winlink-internet'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';setTimeout(wlLoad,1500);setTimeout(async()=>{await wlLoad();await loadMessages()},5000);}catch(e){toast(e.message)}finally{setTimeout(()=>b.disabled=false,10000)}};
setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000);