import {parseMessages,decode} from './bpq.mjs'; async function killAsSysop(id,item,bpq){ const status=await bpq('/Mail/Status'),key=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];if(!key)throw Error('Sessione amministrativa BPQ non disponibile'); const html=await bpq('/Mail/MsgDetails?'+key,{method:'POST',body:String(id)}); if(!new RegExp('Message\\s+'+id+'(?!\\d)').test(html))throw Error('BPQ non ha confermato il messaggio da cancellare'); const fields={};for(const match of html.matchAll(/]*>/gi)){ const name=match[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=match[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i); if(name&&value)fields[name[1]??name[2]??name[3]]=decode(value[1]??value[2]??value[3]); } const names=['From','To','BID','EFROM','VIA','Title']; if(names.some(name=>!(name in fields)||/[|\r\n\0]/.test(fields[name])))throw Error('Metadati BPQ non verificabili: cancellazione interrotta'); const typeBlock=html.match(/]*name=["']?Type["']?[^>]*>([\s\S]*?)<\/select>/i)?.[1]; const selected=typeBlock&&[...typeBlock.matchAll(/]*)>/gi)].find(m=>/\bselected\b/i.test(m[1])); const type=selected?.[1].match(/\bvalue=["']?([BPT])/i)?.[1];if(type!==item.type)throw Error('Metadati BPQ non verificabili: cancellazione interrotta'); // MsgSave is the native sysop action. Preserve all editable fields and change // only Status to K; BPQ clears forwarding bits and saves its own database. await bpq('/Mail/MsgSave?'+key,{method:'POST',body:[...names.map(name=>fields[name]),type,'K',''].join('|')}); } export async function deleteNativeMessage(id,bpq,{sysop=false}={}){ if(!Number.isSafeInteger(id)||id<1)throw Error('Messaggio non valido'); // A cached WebMail key may survive a BPQ restart. With an expired key BPQ // returns a new session's message list instead of executing WMDel. const page=await bpq('/Webmail'),key=page.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile'); const read=async()=>{const html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw Error('Lista messaggi BPQ non disponibile');return parseMessages(html);}; const visible=message=>message.id===id&&message.status!=='K'; const item=(await read()).find(visible);if(!item)return {ok:true,alreadyDeleted:true}; const response=await bpq('/WebMail/WMDel/'+id+'?'+key); if(/Not your message|not allowed|permission denied/i.test(response)){ if(!sysop)throw Error('BPQ non autorizza la cancellazione: verifica i permessi sysop della BBS'); await killAsSysop(id,item,bpq); } if((await read()).some(visible))throw Error('BPQ non ha confermato la cancellazione'); return {ok:true}; }