61 lines
14 KiB
JavaScript
61 lines
14 KiB
JavaScript
import {incoming} from '/notifications.js';
|
||
let soundOn=localStorage.getItem('alnode-sound')!=='no',audio=null,chatLastId=0,chatState='offline',chatPollBusy=false;
|
||
const soundButton=document.createElement('button');soundButton.id='sound-toggle';soundButton.className='icon-button sound-toggle';soundButton.setAttribute('aria-label','Attiva o disattiva suoni');$('#refresh').before(soundButton);
|
||
function soundLabel(){soundButton.textContent=soundOn?'♪':'♩';soundButton.classList.toggle('enabled',soundOn);soundButton.title=soundOn?'Suono attivo':'Attiva suono notifiche';soundButton.setAttribute('aria-pressed',String(soundOn))}soundLabel();
|
||
function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();audio.resume();}catch{}}
|
||
function chime(){if(!soundOn||!audio||audio.state!=='running')return;const t=audio.currentTime;for(const [offset,freq]of [[0,659.25],[.17,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='sine';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.045,t+offset+.025);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.65);o.connect(g);g.connect(audio.destination);o.start(t+offset);o.stop(t+offset+.7)}}
|
||
soundButton.onclick=()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');if(soundOn){prepareAudio();setTimeout(chime,60)}soundLabel()};document.addEventListener('pointerdown',()=>{if(soundOn)prepareAudio()},{once:true});
|
||
const stack=document.createElement('div');stack.className='notification-stack';stack.setAttribute('aria-live','polite');document.body.append(stack);
|
||
function arrival(kind,title,detail,ids=[]){const item=document.createElement('div');item.className='arrival-toast '+kind;item.innerHTML=`<span>${kind==='mail'?'✉':'▤'}</span><div><strong>${esc(title)}</strong><small>${esc(detail)}</small></div><button aria-label="Chiudi notifica">×</button>`;item.querySelector('button').onclick=e=>{e.stopPropagation();item.remove()};item.onclick=()=>{navigate('bbs');if(ids.length===1)readMessage(ids[0]);item.remove()};stack.append(item);while(stack.children.length>4)stack.firstChild.remove();setTimeout(()=>item.remove(),12000)}
|
||
let knownStation=null,knownIds;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}
|
||
const oldLoadMessages=loadMessages;
|
||
loadMessages=async function(){await oldLoadMessages();if(!csrf||!allMessages.length)return;if(knownStation!==station.call){knownStation=station.call;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}}const arrivals=incoming(allMessages,knownIds,station.call);const fresh=[...arrivals.bulletins,...arrivals.mail];knownIds=new Set(allMessages.map(m=>m.id));localStorage.setItem('alnode-message-ids',JSON.stringify([...knownIds]));if(fresh.length){const bulls=fresh.filter(m=>m.type==='B'),mail=fresh.filter(m=>m.type==='P'||m.type==='T');if(bulls.length)arrival('bulletin',bulls.length===1?'Nuovo bollettino scaricato':`${bulls.length} nuovi bollettini scaricati`,bulls.length===1?bulls[0].subject:'Disponibili nella BBS',bulls.map(m=>m.id));if(mail.length)arrival('mail',mail.length===1?'Nuova mail ricevuta':`${mail.length} nuove mail ricevute`,mail.length===1?'Da '+mail[0].from+' · '+mail[0].subject:'Disponibili nella posta personale',mail.map(m=>m.id));chime();}};
|
||
setInterval(()=>{if(csrf)loadMessages()},15000);
|
||
const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='<span>◇</span> Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav);
|
||
const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`<div class="chat-heading"><h1>Chat</h1><div class="chat-actions"><span id="chat-state" class="chat-status">Disconnesso</span><button id="chat-connect" class="primary">Connetti</button><button id="chat-disconnect" class="secondary" hidden>Esci</button></div></div><div class="chat-layout"><aside class="chat-rooms"><div class="chat-label">STANZE<button id="new-topic" aria-label="Crea stanza">+</button></div><div id="chat-topics"><button class="room-button active"># General</button></div><div class="chat-links"><div class="chat-label">COLLEGAMENTI</div><div id="chat-links"></div></div></aside><div class="chat-main"><header class="chat-room-header"><b id="chat-room-name"># General</b><small id="chat-presence-count">— presenti</small></header><div id="chat-messages" class="chat-messages"><div class="chat-empty"><span>◇</span><h2>Chat BPQ</h2><p>Connettiti con il tuo account per partecipare alla chat.</p></div></div><form id="chat-form" class="chat-compose"><div class="chat-recipient"><label for="chat-recipient">Destinatario</label><select id="chat-recipient"><option value="">Tutta la stanza</option></select></div><div class="chat-input-row"><input id="chat-input" aria-label="Messaggio chat" placeholder="Scrivi un messaggio…" maxlength="500" autocomplete="off" disabled><button id="chat-send" class="primary" disabled>Invia ↗</button></div></form></div><aside class="chat-users"><div class="chat-label">PRESENTI <span id="chat-user-count">0</span></div><div id="chat-users"><p class="empty">Non connesso</p></div></aside></div>`;$('main').append(chatPage);
|
||
const topicDialog=document.createElement('dialog');topicDialog.innerHTML='<form id="topic-form"><h2>Crea o apri una stanza</h2><input id="topic-name" aria-label="Nome stanza" placeholder="Nome stanza" required pattern="[A-Za-z0-9_-]{1,24}" maxlength="24"><footer><button type="button" id="topic-cancel" class="secondary">Annulla</button><button class="primary">Entra</button></footer></form>';document.body.append(topicDialog);
|
||
const oldNavigate=navigate;navigate=function(next){oldNavigate(next);$('#breadcrumb').textContent='Stazione / '+({home:'Panoramica',bbs:'BBS',network:'Rete',chat:'Chat',winlink:'Winlink'}[next]);if(next==='chat')pollChat();window.scrollTo({top:0,behavior:'instant'})};
|
||
let chatFollowing=true,chatUnread=0,chatScrolling=false;
|
||
const chatArea=$('#chat-messages');chatArea.tabIndex=0;chatArea.setAttribute('aria-label','Conversazione chat');
|
||
const chatJump=document.createElement('button');chatJump.id='chat-jump';chatJump.className='chat-jump';chatJump.hidden=true;chatJump.type='button';chatJump.setAttribute('aria-label','Vai agli ultimi messaggi');$('.chat-main').insertBefore(chatJump,$('#chat-form'));
|
||
function updateChatJump(){chatJump.hidden=chatFollowing;chatJump.textContent=chatUnread?`${chatUnread} ${chatUnread===1?'nuovo messaggio':'nuovi messaggi'} ↓`:'Ultimi messaggi ↓';}
|
||
function chatToBottom(){if(page!=='chat')return;chatFollowing=true;chatUnread=0;chatScrolling=true;updateChatJump();requestAnimationFrame(()=>{chatArea.scrollTop=chatArea.scrollHeight;requestAnimationFrame(()=>{chatScrolling=false;});});}
|
||
chatJump.onclick=chatToBottom;
|
||
chatArea.addEventListener('scroll',()=>{if(chatScrolling||page!=='chat')return;chatFollowing=chatArea.scrollHeight-chatArea.scrollTop-chatArea.clientHeight<64;if(chatFollowing)chatUnread=0;updateChatJump();},{passive:true});
|
||
new ResizeObserver(()=>{if(chatFollowing&&page==='chat')chatToBottom();}).observe(chatArea);
|
||
const navigateWithChat=navigate;navigate=function(next){navigateWithChat(next);if(next==='chat'){if(chatFollowing)chatToBottom();else updateChatJump();}};
|
||
function renderChat(data){
|
||
chatState=data.state;const online=data.state==='online';
|
||
$('#chat-state').className='chat-status '+data.state;$('#chat-state').textContent=({offline:'Disconnesso',connecting:'Connessione…',online:'● Connesso · '+station.call,error:'Connessione interrotta'}[data.state]);$('#chat-connect').hidden=online;$('#chat-connect').disabled=data.state==='connecting';$('#chat-disconnect').hidden=!online;$('#chat-input').disabled=!online;$('#chat-send').disabled=!online;$('#chat-input').placeholder=online?'Scrivi alla stanza…':'Connettiti per scrivere…';
|
||
$('#chat-room-name').textContent='# '+data.topic;$('#chat-presence-count').textContent=online?data.users.filter(u=>u.topic.toLowerCase()===data.topic.toLowerCase()).length+' nella stanza':'Non connesso';$('#chat-user-count').textContent=online?data.users.length:'—';
|
||
$('#chat-users').innerHTML=online?data.users.map(u=>`<button class="chat-user" data-call="${esc(u.call)}" title="${esc(u.qth)}" aria-label="Messaggio privato a ${esc(u.call)}"><span class="chat-avatar">${esc(u.call.slice(0,2))}</span><div><b>${esc(u.call)}</b><div class="chat-user-name">${esc(u.name)}</div><small>${esc(u.node)} · ${esc(u.topic)}</small></div><span class="presence-dot ${u.idle>300?'idle':''}" title="${u.idle>300?'Inattivo':'Attivo'}"></span></button>`).join('')||'<p class="empty">Nessun utente rilevato</p>':'<p class="chat-offline-note">Connettiti per vedere chi è presente.</p>';
|
||
const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML='<option value="">Tutta la stanza</option>'+data.users.filter(u=>u.call!==station.call).map(u=>`<option value="${esc(u.call)}">Privato · ${esc(u.call)}</option>`).join('');$('#chat-recipient').value=recipient;if(!$('#chat-recipient').value)$('#chat-recipient').value='';$('#chat-recipient').disabled=!online;if(online&&$('#chat-recipient').value)$('#chat-input').placeholder='Messaggio privato a '+$('#chat-recipient').value+'…';
|
||
$$('.chat-user').forEach(b=>b.onclick=()=>{$('#chat-recipient').value=b.dataset.call===station.call?'':b.dataset.call;$('#chat-input').placeholder=b.dataset.call===station.call?'Scrivi alla stanza…':'Messaggio privato a '+b.dataset.call+'…';$('#chat-input').focus();});
|
||
$('#chat-topics').innerHTML=[...new Set(['General',...data.topics,data.topic])].map(t=>`<button class="room-button ${t.toLowerCase()===data.topic.toLowerCase()?'active':''}" data-topic="${esc(t)}"># ${esc(t)}</button>`).join('');
|
||
$$('[data-topic]').forEach(b=>b.onclick=async()=>{try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:b.dataset.topic})});chatFollowing=true;chatUnread=0;pollChat();}catch(e){toast(e.message);}});
|
||
$('#chat-links').innerHTML=online?data.links.map(l=>`<div class="chat-link"><span>${esc(l.call)}</span><span class="${l.state==='Open'?'open':'closed'}">${l.state==='Open'?'Attivo':'Non attivo'}</span></div>`).join('')||'<div class="chat-link">—</div>':'<div class="chat-link">Non connesso</div>';
|
||
const events=data.events.filter(e=>e.id>chatLastId),initial=chatLastId===0;
|
||
if(events.length){if(chatArea.querySelector('.chat-empty'))chatArea.replaceChildren();const fragment=document.createDocumentFragment();let added=0;
|
||
for(const event of events){chatLastId=Math.max(chatLastId,event.id);if(event.type==='system'&&/^[A-Z0-9]{3,6}(?:\s+[A-Z0-9]{3,6})*$/.test(event.text))continue;
|
||
const element=document.createElement('div');if(event.type==='message'&&!/\*\*\* (?:Joined|Left)/i.test(event.text)){element.className='chat-event '+(event.sender===station.call?'own':'')+(event.to?' private':'');element.innerHTML=`<div class="chat-avatar">${esc(event.sender?.slice(0,2)||'?')}</div><div class="chat-message-content"><div class="chat-message-meta"><strong>${esc(event.sender)}${event.to?` <span class="chat-private-label">→ ${esc(event.to)} · privato</span>`:''}</strong><time datetime="${esc(event.at)}" title="${esc(new Date(event.at).toLocaleString('it-IT',{}))}">${new Date(event.at).toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})}</time></div><p>${esc(event.text)}</p></div>`;added++;}else{element.className='chat-system';element.textContent=(event.sender?event.sender+' · ':'')+event.text;}fragment.append(element);}
|
||
chatArea.append(fragment);while(chatArea.children.length>300)chatArea.firstChild.remove();
|
||
if(initial||chatFollowing||events.some(e=>e.sender===station.call&&e.type==='message')){chatFollowing=true;if(page==='chat')chatToBottom();}else{chatUnread+=added;updateChatJump();}
|
||
}
|
||
}
|
||
|
||
async function pollChat(){if(!csrf||chatPollBusy)return;chatPollBusy=true;try{renderChat(await api('/chat'))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
|
||
$('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}};
|
||
$('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}};
|
||
$('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}};
|
||
setInterval(()=>{if(csrf&&(page==='chat'||chatState==='online'||chatState==='connecting'))pollChat()},2000);
|
||
|
||
const presenceButton=document.createElement('button');presenceButton.className='secondary mobile-presence';presenceButton.textContent='Utenti';presenceButton.setAttribute('aria-expanded','false');presenceButton.onclick=()=>{const open=$('.chat-layout').classList.toggle('users-open');presenceButton.setAttribute('aria-expanded',String(open))};$('.chat-actions').prepend(presenceButton);
|
||
|
||
$('#chat-recipient').addEventListener('change',()=>{$('#chat-input').placeholder=$('#chat-recipient').value?'Messaggio privato a '+$('#chat-recipient').value+'…':'Scrivi alla stanza…';});
|
||
if(location.hash==='#chat')navigate('chat');
|
||
|
||
window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}});
|
||
|
||
function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);}
|
||
window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);
|