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

+6
View File
@@ -8,6 +8,12 @@ Use the Italian / UK flag switch in the login screen or dashboard header to sele
Interface copy is maintained in `public/i18n.js`; add new UI phrases and parameterised status patterns there. Mark custom data widgets with `data-no-i18n` so their content is preserved.
## Winlink attachments
Incoming and queued Winlink messages show an attachment indicator in the list and file cards in the reader. Download original files or preview images, PDFs and plain text; HTML/SVG attachments are shown as text. Binary attachments use BPQ’s native B2 format.
In **New email**, use **Attach files** or drop files into the attachment panel. Review filenames, sizes and image thumbnails; remove files before saving. The Console accepts up to 10 files and 64 KiB total per outgoing email, with a combined message text/file limit of 80 KiB and the existing 32 KB body limit. These Console upload limits leave room for multipart headers within the native BPQ HTTP input buffer; BPQ, the receiving gateway and radio conditions may impose further limits. Small files are preferable over radio. Files stay in the browser until the message is saved and then use BPQ’s native WebMail attachment upload and normal Winlink queue, over Internet or radio. The Console verifies that BPQ stored the same filenames and file bytes before confirming success. If it reports a saved message with mismatched attachments, check the queue before retrying.
## Telnet login compatibility
Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port in `BPQ32.cfg`. Standard `Username:`, `Login:`, `User:` and `Password:` prompts also work. `PASSWORD` is not the prompt setting. Custom CTEXT banners do not need the word Welcome or a node prompt; both `ALIAS:CALL>` and `ALIAS:CALL}` work. After the password, the clients wait for 400 ms of quiet after non-empty banner text; a repeated login/password prompt or explicit denial rejects the login. Password echoes are removed before displaying the terminal banner, and Chat discards the Telnet banner before sending `CHAT`. A server that sends no text at all after the password times out instead of reporting an unconfirmed login as successful. Restart BPQ Console after changing prompt settings.
+1
View File
@@ -1,4 +1,5 @@
import path from 'node:path';
export function attachmentSummary(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return {attachmentCount:0,attachmentBytes:0};const header=bytes.subarray(0,end).toString('utf8');if(!/^MID:/mi.test(header)||!/^Body:\s*\d+\s*$/mi.test(header))return {attachmentCount:0,attachmentBytes:0};const files=[...header.matchAll(/^File:\s*(\d+)\s+[^\r\n]+\r?$/gmi)];return {attachmentCount:files.length,attachmentBytes:files.reduce((sum,f)=>sum+Number(f[1]),0)};}
export function safeName(name){return path.win32.basename(String(name).replaceAll('/','\\')).replace(/[\x00-\x1f\x7f]/g,'').slice(0,200)||'allegato.bin';}
export function mimeOf(bytes,name){if(bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return 'image/png';if(bytes[0]===255&&bytes[1]===216&&bytes[2]===255)return 'image/jpeg';if(/^GIF8[79]a$/.test(bytes.subarray(0,6).toString('ascii')))return 'image/gif';if(bytes.subarray(0,4).toString()==='RIFF'&&bytes.subarray(8,12).toString()==='WEBP')return 'image/webp';if(bytes.subarray(0,5).toString()==='%PDF-')return 'application/pdf';if(/\.(txt|csv|log|json|xml|html?|svg|md|7pl)$/i.test(name)&&!bytes.subarray(0,4096).includes(0))return 'text/plain';return 'application/octet-stream';}
export function b2Body(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return null;const header=bytes.subarray(0,end).toString('utf8'),body=header.match(/^Body:\s*(\d+)\s*$/m);if(!body||!/^Mid:/mi.test(header))return null;const length=Number(body[1]);if(end+4+length>bytes.length)throw new Error('Corpo B2 incompleto');const data=bytes.subarray(end+4,end+4+length);try{return new TextDecoder('utf8',{fatal:true}).decode(data);}catch{return data.toString('latin1');}}
+49
View File
@@ -0,0 +1,49 @@
import test from 'node:test';import assert from 'node:assert/strict';
import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import http from 'node:http';import net from 'node:net';import {spawn} from 'node:child_process';import {once} from 'node:events';
import {parseAttachments,b2Body} from './attachments.mjs';
const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
test('Winlink API uploads to native WebMail, verifies storage, lists and downloads received attachments',async()=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-upload-')),root=path.join(dir,'station');let child,stored=null,nativePosts=0,nextId=0;
const mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true});
const server=http.createServer(async(req,res)=>{try{
if(req.url==='/Webmail'){res.end('<a href=/WebMail/WMB?fixture>Mail</a>');return;}
if(req.url.startsWith('/WebMail/NewMsg')){res.end('Compose');return;}
if(req.url.startsWith('/WebMail/EMSave')){
nativePosts++;const chunks=[];for await(const chunk of req)chunks.push(chunk);
const form=await new Request('http://localhost/',{method:'POST',headers:{'Content-Type':req.headers['content-type']},body:Buffer.concat(chunks)}).formData();
assert.equal(form.get('To'),'RMS/[email protected]');const files=await Promise.all(form.getAll('myFile[]').map(async f=>({name:f.name,data:Buffer.from(await f.arrayBuffer())})));assert.equal(files.length,2);
const body=Buffer.from(form.get('Msg'));stored=Buffer.concat([Buffer.from('MID: local-fixture\r\nBody: '+body.length+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'),body,Buffer.from('\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);
nextId=1;await fs.writeFile(path.join(mail,'m_000001.mes'),stored);res.end('Message Saved');return;
}
if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?'<a href=/WebMail/WM?fixture&1> 1</a> 17-Oct PN 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;}
if(req.url==='/Mail/Status'){res.end('<a href=/Mail/Msgs?fixture>Messages</a>');return;}
if(req.url.startsWith('/Mail/MsgDetails')){res.end(Object.entries({From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'[email protected]',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'<input name="'+k+'" value="'+v+'">').join(''));return;}
if(req.url.startsWith('/WebMail/WM?')){res.end('<textarea>From: N0TEST\r\nTo: RMS\r\nTitle: Attachment fixture\r\nType/Status: PN\r\n\r\nNative body with binary attachments stripped by Console</textarea>');return;}
res.end('BPQ Ports');
}catch(e){res.statusCode=500;res.end(e.message);}});
try{
await listen(server);const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve));
await fs.writeFile(path.join(root,'BPQ32.cfg'),'NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+server.address().port+'\nCMS=1\nUSER=admin,fixture-secret,N0TEST,sysop\nENDPORT\nAPPLICATION 1,BBS,,N0TEST-11,MAIL\n');
await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {}\nBBSUsers : {}');
await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} ');await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port}));
for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.includes('.test.')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name));
child=spawn(process.execPath,[path.join(dir,'server.mjs')],{cwd:dir,env:{...process.env,BPQ_ROOT:root,BPQ_CONSOLE_CONFIG:path.join(dir,'console.config.json'),BPQ_CONSOLE_PORT:String(port)},windowsHide:true,stdio:['ignore','pipe','pipe']});
await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('Fixture timeout')),8000);timer.unref();})]);
const base='http://127.0.0.1:'+port,headers={origin:base,'content-type':'application/json'};
const login=await fetch(base+'/api/login',{method:'POST',headers,body:JSON.stringify({user:'admin',password:'fixture-secret'})});const auth=await login.json();headers.cookie=login.headers.get('set-cookie').split(';')[0];headers['x-csrf-token']=auth.csrf;
const bytes=[Buffer.from([255,216,255,0,13,10,255]),Buffer.from('Città 📻')],form=new FormData();
for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Attachment fixture',text:'Hello à',type:'P'}))form.set(key,value);
form.append('files',new Blob([bytes[0]]),'image.jpg');form.append('files',new Blob([bytes[1]]),'note.txt');delete headers['content-type'];
const created=await fetch(base+'/api/messages',{method:'POST',headers,body:form});assert.equal(created.status,201,await created.clone().text());assert.deepEqual(await created.json(),{id:1,attachmentCount:2});assert.equal(nativePosts,1);
assert.equal(b2Body(stored),'Hello à');assert.deepEqual(parseAttachments(stored).map(f=>f.data),bytes);
const files=await (await fetch(base+'/api/messages/1/attachments',{headers})).json();assert.equal(files.files.length,2);assert.equal(files.files[0].mime,'image/jpeg');assert.ok(!('data' in files.files[0]));
const download=await fetch(base+'/api/messages/1/attachments/0',{headers});assert.match(download.headers.get('content-disposition'),/^attachment/);assert.deepEqual(Buffer.from(await download.arrayBuffer()),bytes[0]);
const preview=await fetch(base+'/api/messages/1/attachments/0?preview=1',{headers});assert.equal(preview.headers.get('content-type'),'image/jpeg');
const text=await (await fetch(base+'/api/messages/1/attachments/1?text=1',{headers})).json();assert.equal(text.text,'Città 📻');
const reader=await (await fetch(base+'/api/messages/1',{headers})).json();assert.equal(reader.text,'Hello à');
const inbox=await (await fetch(base+'/api/winlink',{headers})).json();assert.equal(inbox.messages[0].attachmentCount,2);assert.equal(inbox.messages[0].folder,'queue');
const denied=await fetch(base+'/api/messages/1/attachments/0');assert.equal(denied.status,401);
const oversized=new FormData();for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Too big',text:'x'.repeat(30000),type:'P'}))oversized.set(key,value);oversized.append('files',new Blob([Buffer.alloc(60000)]),'large.bin');const rejected=await fetch(base+'/api/messages',{method:'POST',headers,body:oversized});assert.match((await rejected.json()).error,/80 KB/);assert.equal(nativePosts,1);
const badHeaders={...headers,'x-csrf-token':'wrong'};assert.equal((await fetch(base+'/api/messages',{method:'POST',headers:badHeaders,body:form})).status,403);assert.equal(nativePosts,1);
}finally{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});}
});
+33
View File
@@ -0,0 +1,33 @@
import {safeName,mimeOf,parseAttachments} from './attachments.mjs';
export const uploadLimits={files:10,bytes:64*1024,messageBytes:80*1024,requestBytes:96000};
export async function readSubmission(req){
const chunks=[];let length=0;
for await(const chunk of req){length+=chunk.length;if(length>uploadLimits.requestBytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');chunks.push(chunk);}
const bytes=Buffer.concat(chunks),contentType=req.headers['content-type']||'';
if(!/^multipart\/form-data\s*;/i.test(contentType)){
if(bytes.length>70000)throw Error('Messaggio troppo grande');
const data=JSON.parse(bytes.toString()||'{}');if(data.files||data.attachments)throw Error('Usa il caricamento file per gli allegati');return {...data,files:[]};
}
const form=await new Request('http://localhost/upload',{method:'POST',headers:{'Content-Type':contentType},body:bytes}).formData();
const data={},files=[];let total=0;
for(const [key,value]of form){
if(typeof value==='string'){if(!['to','subject','text','type'].includes(key)||key in data)throw Error('Campi del messaggio non validi');data[key]=value;continue;}
if(key!=='files')throw Error('Campo allegato non valido');
if(files.length>=uploadLimits.files)throw Error('Massimo 10 allegati per messaggio');
total+=value.size;if(total>uploadLimits.bytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');
const name=safeName(value.name).replace(/[";]/g,'_'),buffer=Buffer.from(await value.arrayBuffer());
if(files.some(f=>f.name.toLowerCase()===name.toLowerCase()))throw Error('Nomi allegati duplicati: rinomina i file');
files.push({name,size:buffer.length,data:buffer,mime:mimeOf(buffer,name)});
}
return {...data,files};
}
export function outgoingForm({to,subject,text,type,files=[]}){
const form=new FormData();for(const [key,value]of Object.entries({To:to,Subj:subject,Type:type,BID:'',Msg:text.replace(/\r?\n/g,'\r\n'),Send:'Send'}))form.set(key,value);
for(const file of files)form.append('myFile[]',new Blob([file.data],{type:'application/octet-stream'}),file.name);
return form;
}
export function verifySavedAttachments(bytes,expected){
const actual=parseAttachments(bytes);
if(actual.length!==expected.length||expected.some((file,i)=>file.name!==actual[i].name||!file.data.equals(actual[i].data)))throw Error('BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.');
return actual.map(({data,...file})=>file);
}
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {Readable} from 'node:stream';
import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
import {parseAttachments,b2Body,attachmentSummary} from './attachments.mjs';
async function request(form){const r=new Request('http://localhost/messages',{method:'POST',body:form}),stream=Readable.from([Buffer.from(await r.arrayBuffer())]);stream.headers={'content-type':r.headers.get('content-type')};return stream;}
function b2(body,files){return Buffer.concat([Buffer.from('MID: fixture\r\nBody: '+Buffer.byteLength(body)+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'+body+'\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);}
test('multipart upload reaches native BPQ fields with byte-exact binary and UTF8 files',async()=>{
const files=[{name:'image.jpg',data:Buffer.from([255,216,255,0,13,10,255])},{name:'note.txt',data:Buffer.from('Città e radio 📻')}];
const form=new FormData();for(const [k,v]of Object.entries({to:'RMS/[email protected]',subject:'Attachments',text:'Hello à',type:'P'}))form.set(k,v);for(const f of files)form.append('files',new Blob([f.data]),f.name);
const data=await readSubmission(await request(form));assert.equal(data.files.length,2);for(let i=0;i<files.length;i++)assert.deepEqual(data.files[i].data,files[i].data);
const native=outgoingForm(data);assert.equal(native.get('To'),data.to);assert.equal(native.get('Msg'),'Hello à');const nativeFiles=native.getAll('myFile[]');assert.equal(nativeFiles.length,2);for(let i=0;i<files.length;i++)assert.deepEqual(Buffer.from(await nativeFiles[i].arrayBuffer()),files[i].data);
const bytes=b2('Hello à',data.files);assert.equal(b2Body(bytes),'Hello à');assert.equal(verifySavedAttachments(bytes,data.files).length,2);assert.deepEqual(attachmentSummary(bytes),{attachmentCount:2,attachmentBytes:files.reduce((n,f)=>n+f.data.length,0)});
});
test('attachment count ignores plain text and requires a B2 header',()=>{assert.equal(attachmentSummary(Buffer.from('Body: 4\r\nFile: 3 test\r\n\r\ntext')).attachmentCount,0);});
test('upload rejects oversize files, too many files, duplicates and unsafe fields before contacting BPQ',async()=>{
const make=files=>{const f=new FormData();for(const [name,data]of files)f.append('files',new Blob([data]),name);return f;};
await assert.rejects(readSubmission(await request(make([['large.bin',Buffer.alloc(uploadLimits.bytes+1)]]))),/64 KB/);
await assert.rejects(readSubmission(await request(make(Array.from({length:11},(_,i)=>[i+'.txt','x'])))),/10 allegati/);
await assert.rejects(readSubmission(await request(make([['same.txt','a'],['SAME.txt','b']]))),/duplicati/);
const f=new FormData();f.set('to','a');f.append('to','b');await assert.rejects(readSubmission(await request(f)),/Campi/);
const req=Readable.from([Buffer.from(JSON.stringify({files:[{name:'bypass'}]}))]);req.headers={'content-type':'application/json'};await assert.rejects(readSubmission(req),/caricamento/);
});
test('filenames cannot inject headers, preserve paths, or silently collide after sanitisation',async()=>{
const form=new FormData();form.append('files',new Blob(['x']),'../../unsafe;name.txt');const data=await readSubmission(await request(form));assert.equal(data.files[0].name,'unsafe_name.txt');
const both=new FormData();both.append('files',new Blob(['x']),'one;two.txt');both.append('files',new Blob(['y']),'one_two.txt');await assert.rejects(readSubmission(await request(both)),/duplicati/);
});
test('saved message is rejected if BPQ drops, truncates or substitutes an attachment',()=>{
const files=[{name:'test.bin',data:Buffer.from([0,255,1])}];const bytes=b2('test',files);assert.deepEqual(parseAttachments(bytes)[0].data,files[0].data);assert.throws(()=>verifySavedAttachments(b2('test',[]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(b2('test',[{...files[0],data:Buffer.from([0,255,2])}]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(bytes.subarray(0,bytes.length-4),files),/incompleto/);
});
+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);
+20 -12
View File
@@ -1,3 +1,4 @@
import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
import {SyncOperations} from './sync-operations.mjs';
import {RadioControl} from './radio-control.mjs';
import {Terminal} from './terminal.mjs';
@@ -12,7 +13,7 @@ import {forwardingHistory} from './forwarding.mjs';
import {Forwarding} from './forwarding.mjs';
import {SevenPlus} from './sevenplus.mjs';
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
import {readFile, stat} from 'node:fs/promises';
import {readFile, stat,open} from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {randomBytes,timingSafeEqual} from 'node:crypto';
@@ -23,7 +24,7 @@ import {VaraRate} from './vara-rate.mjs';
import {mailDirection,mailFolder,cmsStatus} from './model.mjs';
import os from 'node:os';
import {execFile} from 'node:child_process';
import {parseAttachments,safeName,b2Body} from './attachments.mjs';
import {parseAttachments,safeName,b2Body,attachmentSummary} from './attachments.mjs';
const dir=path.dirname(fileURLToPath(import.meta.url));
const config=await loadConfig();
@@ -51,7 +52,7 @@ async function bpqRequest(url, options={}) {
// BPQ's legacy HTTP server is compatible with plain HTTP requests; modern
// fetch headers can make its local-auth detection fall back to the signon page.
let payload=options.body,headers={Connection:'close'};
if(payload instanceof FormData){const encoded=new Request(upstream+url,{method:'POST',body:payload});headers['Content-Type']=encoded.headers.get('content-type');payload=Buffer.from(await encoded.arrayBuffer());}
if(payload instanceof FormData){const encoded=new Request(upstream+url,{method:'POST',body:payload});headers['Content-Type']=encoded.headers.get('content-type');payload=Buffer.from(await encoded.arrayBuffer());if(payload.length>96000)throw Error('Messaggio troppo grande per il server HTTP BPQ');}
if(payload){payload=Buffer.from(payload);headers['Content-Length']=payload.length;}
return new Promise((resolve,reject)=>{const request=http.request(upstream+url,{method:options.method||'GET',headers,agent:false},response=>{let chunks=[];response.on('data',c=>chunks.push(c));response.on('end',()=>{if(response.statusCode!==200)return reject(new Error('BPQ non risponde ('+response.statusCode+')'));resolve(Buffer.concat(chunks).toString('utf8'))});response.on('error',reject)});request.setTimeout(10000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',reject);if(payload)request.write(payload);request.end()});
}
@@ -91,29 +92,36 @@ async function messageTimes(id){if(timestampCache.has(id))return timestampCache.
const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0;
function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));}
async function readMessageFields(id,retry=true){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/<input\b[^>]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}if(!('From' in fields)||!('Title' in fields)){metadataKey=null;metadataKeyAt=0;if(retry)return readMessageFields(id,false);throw Error('Metadati BBS non ancora disponibili');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
async function messageAttachmentSummary(id){let file;try{file=await open(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'),'r');const header=Buffer.alloc(65540);const {bytesRead}=await file.read(header,0,header.length,0);return attachmentSummary(header.subarray(0,bytesRead));}catch{return {attachmentCount:0,attachmentBytes:0};}finally{await file?.close();}}
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,...await messageAttachmentSummary(m.id),direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&(modemFamily(config.radio.driver)||packetPort(config))&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};}
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);timestampCache.delete(id);messageMetadata.invalidate(id);metadataReads.invalidate(id);mailReads.clear();if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};}
async function sendMessage(data){
let messageWriteQueue=Promise.resolve();
function sendMessage(data){const write=messageWriteQueue.then(()=>writeMessage(data));messageWriteQueue=write.catch(()=>{});return write;}
async function writeMessage(data){
const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P');
if(!/^[A-Z0-9][A-Z0-9@.\/#_-]{1,79}$/.test(to)||!subject||subject.length>80||!text||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)');
if(!/^[A-Z0-9][A-Z0-9@.\/#_-]{1,79}$/.test(to)||!subject||subject.length>80||/[\x00-\x1f\x7f]/.test(subject)||!text||text.includes('\0')||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)');
const files=data.files||[];if(files.length&&(type!=='P'||!/^RMS[/:]/i.test(to)))throw Error('Gli allegati in uscita sono disponibili per le email Winlink');
if(Buffer.byteLength(text.replace(/\r?\n/g,'\r\n'))+files.reduce((n,f)=>n+f.size,0)>uploadLimits.messageBytes)throw Error('Testo e allegati superano 80 KB complessivi');
const previous=new Set((await messages()).map(m=>m.id));
const {key}=await mailContext();await bpq('/WebMail/NewMsg?'+key);
const form=new FormData();for(const [k,v]of Object.entries({To:to,Subj:subject,Type:type,BID:'',Msg:text.replace(/\r?\n/g,'\r\n'),Send:'Send'}))form.set(k,v);
// A separate native compose session prevents a reader from replacing its attachments.
const composePage=await bpq('/Webmail'),key=composePage.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile');await bpq('/WebMail/NewMsg?'+key);
const form=outgoingForm({to,subject,text,type,files});
const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form});
if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio'));
// A successful write must be visible in BPQ's message list, not inferred from HTTP 200.
mailReads.clear();const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0]));
if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.');
return {id:created.id};
if(files.length){const saved=await readFile(path.join(root,'BPQMailChat','Mail','m_'+String(created.id).padStart(6,'0')+'.mes'));verifySavedAttachments(saved,files);}
return {id:created.id,attachmentCount:files.length};
}
setInterval(()=>{for(const [token,s] of sessions)if(s.expires<Date.now()){s.terminal?.close();sessions.delete(token);}},30000).unref();
const server=http.createServer(async(req,res)=>{
try{
const host=req.headers.host||'';
if(!/^(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/.test(host.split(':')[0])||host.split(':')[1]!==String(port)){json(res,403,{error:'Host non autorizzato'});return;}
res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
const url=new URL(req.url,'http://'+host);
if(url.pathname==='/ui-config.js'&&req.method==='GET'){res.writeHead(200,{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-cache'});res.end('globalThis.BPQ_DEFAULT_LANGUAGE='+JSON.stringify(config.language||null)+';');return;}
if(url.pathname==='/health'&&req.method==='GET'){json(res,200,{service:'bpq-console',pid:process.pid});return;}
@@ -174,13 +182,13 @@ const server=http.createServer(async(req,res)=>{
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow(config.cmsPeer||'RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}json(res,200,{id:Number(id),...msg,...await messageTimes(Number(id))});return;}
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await body(req)));return;}
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await readSubmission(req)));return;}
if(url.pathname==='/api/sync'&&req.method==='POST'){await syncNow();json(res,200,{ok:true});return;}
json(res,404,{error:'Operazione non disponibile'});return;
}
if(req.method!=='GET'){json(res,405,{error:'Metodo non disponibile'});return;}
const vendor=url.pathname.match(/^\/vendor\/pdfjs\/(pdf\.min\.mjs|pdf\.worker\.min\.mjs|(?:standard_fonts|cmaps)\/[A-Za-z0-9_.-]+)$/);if(vendor&&!vendor[1].includes('..')){const bytes=await readFile(path.join(dir,'public','vendor','pdfjs',vendor[1]));res.writeHead(200,{'Content-Type':vendor[1].endsWith('.mjs')?'text/javascript':'application/octet-stream','Cache-Control':'public, max-age=86400'});res.end(bytes);return;}
const files={'/i18n.js':'i18n.js','/i18n.css':'i18n.css','/sync-state.js':'sync-state.js','/sync-progress.js':'sync-progress.js','/sync-progress.css':'sync-progress.css','/radio-control.js':'radio-control.js','/radio-control.css':'radio-control.css','/terminal.js':'terminal.js','/terminal.css':'terminal.css','/winlink-radio.js':'winlink-radio.js','/winlink-radio.css':'winlink-radio.css','/forwarding.js':'forwarding.js','/forwarding.css':'forwarding.css','/journal.js':'journal.js','/journal.css':'journal.css','/world-land.json':'world-land.json','/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.json')?'application/json':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
const files={'/compose-attachments.js':'compose-attachments.js','/compose-attachments.css':'compose-attachments.css','/i18n.js':'i18n.js','/i18n.css':'i18n.css','/sync-state.js':'sync-state.js','/sync-progress.js':'sync-progress.js','/sync-progress.css':'sync-progress.css','/radio-control.js':'radio-control.js','/radio-control.css':'radio-control.css','/terminal.js':'terminal.js','/terminal.css':'terminal.css','/winlink-radio.js':'winlink-radio.js','/winlink-radio.css':'winlink-radio.css','/forwarding.js':'forwarding.js','/forwarding.css':'forwarding.css','/journal.js':'journal.js','/journal.css':'journal.css','/world-land.json':'world-land.json','/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.json')?'application/json':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
});
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));