synchro du labo (0bf0da65) : app.blade.php, README.md

This commit is contained in:
cloudion
2026-11-03 22:41:10 +00:00
commit 6aabd2cc8e
2 changed files with 575 additions and 0 deletions

21
README.md Normal file
View File

@@ -0,0 +1,21 @@
# 💬 Chat
Ton flux : envoie des messages, des braindumps, des tsoins — tout. Persisté, auto-rafraîchi.
| | |
| --- | --- |
| id | `chat` |
| fournit | `chat` `capture` `tsoin` `braindump` |
| bions qu'il nomme | `jOSApps` `jOSGpg` `jOSPorts` `jOSZone` |
| fichiers | `app.blade.php` |
| dans le labo | `resources/views/ploxions/chat/` (dépôt `my_website2`) |
## Contribuer
- **Dans le xer** : https://labo.j0bot.ch/px/atelier?ploxion=chat — prends-le, modifie-le, vois-le tourner, « ⧗ envoyer le tsoin ».
- **Dans VS Code** : `xb prendre chat` (ou l'extension xerboxion › ⇩ Prendre), puis ⧗ Envoyer.
- Le chemin complet : https://labo.j0bot.ch/px/contribuer
Ce dépôt est un **miroir** du labo (synchronisé par `bin/ploxions-forge.mjs`, depuis le commit `0bf0da65`) : une modif se propose par un tsoin ou une branche du labo, pas directement ici.
© 2026 chill-tekk · ne pas nuire

554
app.blade.php Normal file
View File

@@ -0,0 +1,554 @@
{{-- PL0XI0N chat — le FLUX du xerboxion : RS-7 envoie TOUT (messages, braindumps,
tsoins). Persisté côté serveur (table chat_messages) → vrai flux, pas
localStorage. Lit GET /chat/feed.json (polling incrémental ?after=) et poste
POST /chat {kind,content}. Admin-only. window.jOSApps['chat']. mount->{unmount}.
LOT C social-v0 (24.09, D7) — LES SALONS : ?room=<salon> (ou ctx.room) ouvre un salon, dont post-<id> = le fil de
discussion d'une chose partagée (accès = visibilité du post, gaté serveur, 404 sinon) ; « ☰ salons » ouvre la liste
(GET /chat/salons.json À L'OUVERTURE, aucun polling de plus) : mes salons · les choses que je vois · mes zones (jOSZone,
room zone-<id>). Kill-switch : serveur SOCIAL_SALONS=false (liste vide), client localStorage xb:chat.salons = 'off'
(bouton caché, le chat d'avant). --}}
<style>
.ch { display:flex; flex-direction:column; height:100%; background:#06090d;
color:rgba(220,232,240,.92); font-family:ui-sans-serif,system-ui,sans-serif; font-size:.84rem; }
.ch__bar { flex:0 0 auto; display:flex; align-items:center; gap:8px; padding:8px 11px; border-bottom:1px solid rgba(120,160,230,.18); }
.ch__t { font-weight:700; letter-spacing:.04em; color:rgba(160,195,255,.95); }
.ch__cnt { margin-left:auto; font-size:.66rem; color:rgba(150,180,220,.55); font-family:ui-monospace,monospace; }
/* salons (rooms) : flux privé (RS-7) vs salons partagés (potes) */
.ch__rooms { display:flex; gap:5px; margin-left:10px; flex-wrap:wrap; }
.ch__room { cursor:pointer; font-size:.66rem; padding:2px 9px; border-radius:14px; border:1px solid rgba(120,160,230,.3); background:none; color:rgba(180,205,240,.78); }
.ch__room.on { background:rgba(120,160,230,.2); color:#fff; border-color:rgba(120,160,230,.6); }
.ch__room.priv.on { border-color:rgba(200,150,255,.6); background:rgba(120,70,180,.22); }
/* salons (lot C) : le panneau « ☰ salons » — mes salons, les choses partagées, mes zones */
.ch__salbtn { cursor:pointer; font-size:.66rem; padding:2px 10px; min-height:32px; border-radius:14px; border:1px solid rgba(120,200,255,.35); background:none; color:rgba(170,215,250,.9); }
.ch__salbtn.on { background:rgba(60,120,180,.3); color:#fff; }
.ch__sal { flex:0 0 auto; max-height:46%; overflow-y:auto; padding:6px 11px 8px; border-bottom:1px solid rgba(120,160,230,.18); background:rgba(10,16,26,.85); -webkit-overflow-scrolling:touch; }
.ch__sal h5 { margin:8px 0 4px; font-size:.6rem; letter-spacing:.07em; text-transform:uppercase; color:rgba(150,180,220,.6); }
.ch__si { display:flex; align-items:center; gap:8px; width:100%; min-height:40px; padding:5px 9px; margin:2px 0; border-radius:9px; border:1px solid rgba(120,160,230,.18);
background:none; color:rgba(220,232,240,.92); font:inherit; font-size:.78rem; text-align:left; cursor:pointer; }
.ch__si.on { border-color:rgba(120,200,255,.6); background:rgba(60,120,180,.18); }
.ch__si b { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-weight:600; }
.ch__si small { flex:0 0 auto; font-size:.62rem; color:rgba(150,180,220,.6); font-family:ui-monospace,monospace; }
.ch__svide { font-size:.72rem; color:rgba(190,212,228,.45); padding:4px 2px; }
.ch__about { flex:0 0 auto; font-size:.7rem; padding:5px 12px; color:rgba(170,210,250,.8); border-bottom:1px solid rgba(120,160,230,.12); }
.ch__about:empty { display:none; }
.ch__stream { flex:1; min-height:0; overflow-y:auto; padding:11px 12px; display:flex; flex-direction:column; gap:8px; }
.ch__m { max-width:88%; align-self:flex-end; border-radius:12px 12px 3px 12px; padding:7px 11px;
background:rgba(28,40,64,.65); border:1px solid rgba(120,160,230,.2); }
.ch__m.other { align-self:flex-start; border-radius:12px 12px 12px 3px; background:rgba(24,30,40,.6); border-color:rgba(150,170,200,.22); }
.ch__m.k-braindump { border-left:2px solid rgba(120,220,160,.7); border-color:rgba(120,220,160,.35); background:rgba(20,40,32,.5); }
.ch__m.k-tsoin { align-self:center; max-width:94%; text-align:center; border-color:rgba(200,150,255,.5);
background:radial-gradient(circle at 50% 0%, rgba(70,40,110,.5), rgba(22,16,34,.6));
box-shadow:0 0 18px rgba(160,90,255,.18); }
.ch__au { color:rgba(150,200,255,.92); font-weight:700; }
.ch__h { display:flex; align-items:center; gap:6px; font-size:.6rem; color:rgba(150,180,220,.55);
font-family:ui-monospace,monospace; margin-bottom:2px; }
.ch__k { text-transform:uppercase; letter-spacing:.05em; }
.ch__m.k-braindump .ch__k { color:rgba(120,220,160,.9); }
.ch__m.k-tsoin .ch__k { color:rgba(200,150,255,.95); }
.ch__c { white-space:pre-wrap; word-break:break-word; line-height:1.4; color:rgba(228,238,246,.96); }
.ch__c a { color:rgba(150,200,255,.9); }
.ch__empty { margin:auto; color:rgba(190,212,228,.45); }
.ch__kinds { flex:0 0 auto; display:flex; gap:6px; padding:7px 11px 0; }
.ch__kb { cursor:pointer; font-size:.72rem; padding:3px 11px; border-radius:20px; border:1px solid rgba(120,160,230,.28);
background:none; color:rgba(180,205,240,.8); }
.ch__kb.on { background:rgba(120,160,230,.18); color:#fff; border-color:rgba(120,160,230,.6); }
.ch__kb.on.tsoin { border-color:rgba(200,150,255,.7); background:rgba(120,70,180,.25); }
.ch__kb.on.braindump { border-color:rgba(120,220,160,.6); background:rgba(40,90,60,.3); }
.ch__in { flex:0 0 auto; display:flex; gap:8px; padding:8px 11px 10px; }
.ch__f { flex:1; resize:none; min-height:40px; max-height:160px; border-radius:10px; padding:9px 11px;
border:1px solid rgba(120,160,230,.28); background:rgba(18,26,42,.6); color:#fff; font-family:inherit; font-size:.84rem; outline:none; }
.ch__f:focus { border-color:rgba(120,160,230,.6); }
.ch__send { flex:0 0 auto; align-self:stretch; cursor:pointer; padding:0 16px; border-radius:10px;
border:1px solid rgba(120,160,230,.4); background:rgba(40,80,150,.4); color:#fff; font-size:.82rem; }
.ch__send:hover { background:rgba(50,100,190,.5); }
.ch__send[disabled] { opacity:.5; cursor:not-allowed; }
.ch__status { font-size:.64rem; color:rgba(255,150,150,.85); padding:0 12px 6px; min-height:11px; }
/* GPG : chiffrement de bout en bout (couche window.jOSGpg / ploxion trousseau) */
.ch__gpgbar { flex:0 0 auto; display:flex; align-items:center; gap:7px; padding:5px 11px 0; flex-wrap:wrap; }
.ch__lock { cursor:pointer; font-size:.72rem; padding:3px 11px; border-radius:20px; border:1px solid rgba(120,200,255,.3); background:none; color:rgba(170,210,250,.8); }
.ch__lock.on { background:rgba(60,120,180,.32); border-color:rgba(120,200,255,.7); color:#fff; }
.ch__rcpt { display:none; gap:6px; flex-wrap:wrap; }
.ch__rcpt.show { display:flex; }
.ch__rc { font-size:.66rem; padding:2px 9px; border-radius:14px; border:1px solid rgba(150,180,220,.3); background:none; color:rgba(190,215,240,.82); cursor:pointer; }
.ch__rc.on { background:rgba(60,120,180,.28); border-color:rgba(120,200,255,.6); color:#fff; }
.ch__rc.warn { color:rgba(255,180,120,.9); border-color:rgba(255,180,120,.4); cursor:default; }
.ch__m.k-enc { border-color:rgba(120,200,255,.45); }
.ch__lockbadge { color:rgba(120,200,255,.9); }
/* pièces jointes : bouton 📎, file en attente, images (chiffrées GPG) */
.ch__attach { flex:0 0 auto; align-self:stretch; cursor:pointer; padding:0 12px; border-radius:10px;
border:1px solid rgba(120,200,255,.4); background:rgba(40,80,150,.3); color:#cfe6ff; font-size:1rem; }
.ch__attach:hover { background:rgba(50,100,190,.45); }
.ch__pending { flex:0 0 auto; display:flex; gap:6px; flex-wrap:wrap; align-items:center; padding:0 12px; }
.ch__pending:empty { display:none; }
.ch__pending .ch__pn { font-size:.66rem; color:rgba(150,200,255,.85); }
.ch__pthumb { width:34px; height:34px; object-fit:cover; border-radius:5px; border:1px solid rgba(120,200,255,.4); }
.ch__pclear { cursor:pointer; background:none; border:0; color:rgba(255,150,150,.8); font-size:.8rem; }
.ch__atts { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; }
.ch__att { max-width:200px; max-height:200px; border-radius:8px; border:1px solid rgba(120,200,255,.3); cursor:pointer; background:rgba(0,0,0,.25); }
.ch__att--ph { display:flex; align-items:center; justify-content:center; width:120px; height:90px;
font-size:.66rem; color:rgba(150,200,255,.7); text-align:center; padding:6px; }
/* expéditeur : la xerion active reçue du bus (ploxion.chat.sender ← profil.identity) */
.ch__sender { display:none; align-items:center; gap:5px; font-size:.66rem; padding:2px 9px; border-radius:14px;
border:1px solid rgba(120,200,255,.3); color:rgba(170,210,250,.85); }
.ch__sender.on { display:inline-flex; }
.ch__sdot { width:8px; height:8px; border-radius:50%; background:var(--xr-accent,#3fe0d0); }
/* ── passe mobile (téléphone patate) ──────────────────────────────
la barre wrappe (titre + salons + expéditeur), les puces = cibles
tactiles ≥32px, le flux scrolle en inertie, champ à 16px (pas de zoom
iOS). En xs on densifie les puces sans rien retirer. */
.ch__bar { flex-wrap:wrap; }
.ch__stream { -webkit-overflow-scrolling:touch; }
.ch__kb { min-height:36px; }
.ch__room,.ch__lock,.ch__rc { min-height:32px; }
@media (hover:none){ .ch__f { font-size:16px; } }
[data-size="xs"] .ch__kinds { gap:4px; padding:6px 8px 0; }
[data-size="xs"] .ch__kb { padding:5px 9px; font-size:.7rem; }
[data-size="xs"] .ch__gpgbar { padding:5px 8px 0; }
[data-size="xs"] .ch__in { padding:6px 8px 8px; gap:6px; }
[data-size="xs"] .ch__m { max-width:94%; }
[data-size="xs"] .ch__send { padding:0 12px; }
</style>
<script>
(function () {
// relecture sécurité 25.09 : esc échappe AUSSI " et ' — l'ancien (jOSb.esc = textContent → innerHTML) les laissait passer, et un
// titre de chose (data-label du panneau ☰ salons), une URL de message (href) ou une signature GPG (title) avec « " » sortait de
// l'attribut → XSS stockée chez qui ouvre le salon. linkify découpe le texte BRUT (l'URL s'arrête aux blancs, guillemets et
// chevrons), échappe chaque morceau, et un href n'est jamais que http(s). Test : node bin/verify-social-securite.mjs
function esc(s) { return window.jOSb.esc(s); }
function linkify(s){ s=String(s==null?'':s); var out='', i=0, re=/https?:\/\/[^\s<>"']+/g, m;
while((m=re.exec(s))){ out+=esc(s.slice(i,m.index))+'<a href="'+esc(m[0])+'" target="_blank" rel="noopener noreferrer">'+esc(m[0])+'</a>'; i=m.index+m[0].length; }
return out+esc(s.slice(i)); }
function csrf(){return window.jOSb&&window.jOSb.csrf?window.jOSb.csrf():(function(){var m=document.querySelector('meta[name=csrf-token]');return m?(m.getAttribute('content')||m.content||''):'';})();}
function stamp(iso){ if(!iso) return ''; var d=new Date(iso); function p(n){return(n<10?'0':'')+n;} return p(d.getDate())+'/'+p(d.getMonth()+1)+' '+p(d.getHours())+':'+p(d.getMinutes()); }
var KINDS = [
{ k:'message', icon:'💬', label:'Message' },
{ k:'braindump', icon:'🧠', label:'Braindump' },
{ k:'tsoin', icon:'✦', label:'Tsoin' }
];
function kindMeta(k){ for(var i=0;i<KINDS.length;i++) if(KINDS[i].k===k) return KINDS[i]; return { k:k, icon:'•', label:k }; }
// XUI : getters live posés au mount (l'état-vérité reste dans le mount) ; null si pas monté
var LIVE = null;
function mount(container, ctx) {
var alive = true, timer = null, last = 0, kind = 'message', sending = false, atBottom = true;
var feedUrl = (ctx && ctx.config && ctx.config.feed) ? ctx.config.feed : '/chat/feed.json';
var postUrl = (ctx && ctx.config && ctx.config.post) ? ctx.config.post : '/chat';
// Salons : le flux privé (admin/RS-7) vs les salons partagés (potes).
// L'admin voit le privé en premier ; un connecté non-admin ne voit que
// les salons partagés (le backend renvoie 403 sur 'prive' de toute façon).
var isAdmin = (function () { var m = document.querySelector('meta[name="user-admin"]'); return !!(m && m.getAttribute('content') === '1'); })();
var ME = (function () { var m = document.querySelector('meta[name="user-name"]'); return m ? (m.getAttribute('content') || '') : ''; })();
var PRIV = (ctx && ctx.config && ctx.config.private_room) || 'prive';
var SHARED = (ctx && ctx.config && ctx.config.rooms) || ['labo'];
var ROOMS = (isAdmin ? [{ id: PRIV, label: '🔒 privé', priv: true }] : [])
.concat(SHARED.map(function (r) { return { id: r, label: '# ' + r }; }));
var room = ROOMS.length ? ROOMS[0].id : PRIV;
// salons (lot C) : ?room= / ctx.room ouvre directement un salon (post-<id> = la chose partagée)
var SALONS_ON = true; try { SALONS_ON = localStorage.getItem('xb:chat.salons') !== 'off'; } catch (e) {}
function okRoom(r) { return typeof r === 'string' && /^[a-z0-9_-]{1,48}$/.test(r); }
function addRoom(r, label) {
for (var i = 0; i < ROOMS.length; i++) if (ROOMS[i].id === r) { if (label) ROOMS[i].label = label; return; }
ROOMS.push({ id: r, label: label || ('# ' + r) });
}
var deepRoom = null;
try {
deepRoom = (ctx && ctx.room) || null;
// ?room= de l'URL : seulement sur la page du chat, ou pour un salon de chose (post-<id>) — la carte a son propre ?room
var qr = new URLSearchParams(location.search).get('room');
if (!deepRoom && qr && (/\/px\/chat(\/|$)/.test(location.pathname) || /^post-\d+$/.test(qr))) deepRoom = qr;
} catch (e) {}
if (SALONS_ON && okRoom(deepRoom) && deepRoom !== PRIV) { addRoom(deepRoom, /^post-\d+$/.test(deepRoom) ? '💡 chose' : null); room = deepRoom; }
var LABELS = {}; // room → libellé lisible (rempli par /chat/salons.json)
container.innerHTML =
'<div class="ch">'
+ ' <div class="ch__bar"><span class="ch__t">💬 Chat</span>' + (SALONS_ON ? '<button class="ch__salbtn" data-salons title="tous tes salons : les tiens, ceux des choses partagées, tes zones">☰ salons</button>' : '') + '<div class="ch__rooms"></div><span class="ch__sender" data-sender title="expéditeur : identité active (profil)"></span><span class="ch__cnt"></span></div>'
+ ' <div class="ch__sal" data-sal hidden></div>'
+ ' <div class="ch__about" data-about></div>'
+ ' <div class="ch__stream"><div class="ch__empty">le flux est vide — envoie ton premier message, braindump ou tsoin</div></div>'
+ ' <div class="ch__kinds">' + KINDS.map(function (x) {
return '<button class="ch__kb ' + x.k + (x.k === 'message' ? ' on' : '') + '" data-k="' + x.k + '">' + x.icon + ' ' + x.label + '</button>';
}).join('') + '</div>'
+ ' <div class="ch__gpgbar"><button class="ch__lock" data-lock title="chiffrer ce message (GPG)">🔓 clair</button><div class="ch__rcpt"></div></div>'
+ ' <div class="ch__status"></div>'
+ ' <div class="ch__pending" data-pending></div>'
+ ' <div class="ch__in"><button class="ch__attach" data-attach title="Joindre des photos (chiffrées GPG)">📎</button>'
+ ' <textarea class="ch__f" placeholder="écris… (Entrée = envoyer · Maj+Entrée = saut de ligne)"></textarea>'
+ ' <button class="ch__send" data-send>envoyer</button>'
+ ' <input type="file" data-file accept="image/*" multiple style="display:none"></div>'
+ '</div>';
var elStream = container.querySelector('.ch__stream'), elCnt = container.querySelector('.ch__cnt');
var elField = container.querySelector('.ch__f'), elSend = container.querySelector('[data-send]');
var elStatus = container.querySelector('.ch__status'), elKinds = container.querySelector('.ch__kinds');
var elLock = container.querySelector('[data-lock]'), elRcpt = container.querySelector('.ch__rcpt');
var elRooms = container.querySelector('.ch__rooms');
var elAttach = container.querySelector('[data-attach]'), elFile = container.querySelector('[data-file]');
var elPending = container.querySelector('[data-pending]');
var elSender = container.querySelector('[data-sender]');
var elSal = container.querySelector('[data-sal]'), elSalBtn = container.querySelector('[data-salons]'), elAbout = container.querySelector('[data-about]');
var count = 0, gpgOn = false, picked = {};
var pendingFiles = [], objUrls = []; // photos à envoyer + objectURLs à révoquer
var sender = null, offs = []; // xerion active (bus profil.identity) + désabonnements jOSPorts
function renderRooms() {
if (ROOMS.length < 2) { elRooms.innerHTML = ''; return; } // un seul salon -> pas de switch
elRooms.innerHTML = ROOMS.map(function (R) {
return '<button class="ch__room' + (R.priv ? ' priv' : '') + (R.id === room ? ' on' : '') + '" data-room="' + esc(R.id) + '">' + esc(R.label) + '</button>';
}).join('');
elRooms.querySelectorAll('[data-room]').forEach(function (b) {
b.addEventListener('click', function () { setRoom(b.getAttribute('data-room')); });
});
}
function setRoom(r) {
if (r === room) return;
room = r; last = 0; count = 0;
elStream.innerHTML = '<div class="ch__empty">salon « ' + esc(LABELS[room] || room) + ' » — ' + (room === PRIV ? 'ton flux privé' : 'dis bonjour 👋') + '</div>';
elCnt.textContent = ''; atBottom = true;
renderRooms(); renderAbout(); poll();
}
// la chose derrière un salon post-<id> : son titre + un lien vers elle (le fil) — texte échappé
function renderAbout() {
if (!elAbout) return;
var m = /^post-(\d+)$/.exec(room);
elAbout.innerHTML = m ? ('💡 le fil de la chose <b>' + esc(LABELS[room] || ('#' + m[1])) + '</b>') : '';
}
// ---- ☰ salons : chargé À L'OUVERTURE (pas de polling) ----
var salOpen = false, salData = null;
function salItem(r, label, meta) {
return '<button class="ch__si' + (r === room ? ' on' : '') + '" data-goroom="' + esc(r) + '" data-label="' + esc(label) + '"><b>' + esc(label) + '</b>' + (meta ? '<small>' + esc(meta) + '</small>' : '') + '</button>';
}
function zonesSalons() {
var Z = window.jOSZone, out = [];
try { if (Z && Z.all) Z.all().forEach(function (z) {
var id = String(z && z.id || '').toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 43);
if (id) out.push({ room: 'zone-' + id, label: (z.icone ? z.icone + ' ' : '🫧 ') + (z.nom || id) });
}); } catch (e) {}
return out;
}
function renderSal() {
if (!elSal) return;
if (!salData) { elSal.innerHTML = '<div class="ch__svide">… les salons arrivent</div>'; return; }
if (salData.off) { elSal.innerHTML = '<div class="ch__svide">les salons sont coupés sur ce boxion.</div>'; return; }
var h = '<h5>mes salons</h5>';
var mes = (salData.mes || []).filter(function (x) { return okRoom(x.room); });
h += mes.length ? mes.map(function (x) { return salItem(x.room, x.label || x.room, (x.n || 0) + ' msg'); }).join('') : '<div class="ch__svide">tu n\'as encore écrit nulle part — ouvre une chose ci-dessous.</div>';
h += '<h5>les choses partagées que tu vois</h5>';
var ch = (salData.choses || []).filter(function (x) { return okRoom(x.room); });
h += ch.length ? ch.map(function (x) {
var meta = (x.n ? x.n + ' msg' : 'personne encore') + (x.repo ? ' · repo' : '') + (x.by ? ' · ' + x.by : '');
return salItem(x.room, (x.kind === 'idee' ? '💡 ' : '') + (x.label || x.room), meta);
}).join('') : '<div class="ch__svide">rien de partagé avec toi pour l\'instant.</div>';
var zs = zonesSalons();
if (zs.length) h += '<h5>mes zones</h5>' + zs.map(function (z) { return salItem(z.room, z.label, 'zone'); }).join('');
elSal.innerHTML = h;
}
function loadSal() {
salData = null; renderSal();
fetch('/chat/salons.json', { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
.then(function (r) { return r.ok ? r.json() : { off: false, mes: [], choses: [] }; })
.then(function (d) {
if (!alive) return; salData = d || {};
(salData.mes || []).concat(salData.choses || []).forEach(function (x) { if (x && okRoom(x.room) && x.label) LABELS[x.room] = x.label; });
ROOMS.forEach(function (R) { var l = LABELS[R.id]; if (l && /^post-/.test(R.id)) R.label = '💡 ' + (l.length > 20 ? l.slice(0, 19) + '…' : l); });
renderSal(); renderAbout(); renderRooms();
}).catch(function () { if (alive) { salData = { mes: [], choses: [] }; renderSal(); } });
}
if (elSalBtn) elSalBtn.addEventListener('click', function () {
salOpen = !salOpen; elSal.hidden = !salOpen; elSalBtn.classList.toggle('on', salOpen);
if (salOpen) loadSal();
});
if (elSal) elSal.addEventListener('click', function (e) {
var b = e.target.closest('[data-goroom]'); if (!b) return;
var r = b.getAttribute('data-goroom'); if (!okRoom(r)) return;
var lab = b.getAttribute('data-label') || r; LABELS[r] = LABELS[r] || lab;
addRoom(r, lab.length > 22 ? lab.slice(0, 21) + '…' : lab);
salOpen = false; elSal.hidden = true; if (elSalBtn) elSalBtn.classList.remove('on');
setRoom(r);
});
elStream.addEventListener('scroll', function () {
atBottom = (elStream.scrollHeight - elStream.scrollTop - elStream.clientHeight) < 40;
});
function appendMsg(m) {
if (count === 0) elStream.innerHTML = '';
var meta = kindMeta(m.kind);
var el = document.createElement('div');
// self = mes propres messages (alignés à droite). Flux privé = tout est à moi (RS-7).
var isSelf = (room === PRIV) || (!!ME && (m.author || '') === ME);
var G = window.jOSGpg;
var enc = !!(G && G.isArmored(m.content)); // bloc PGP -> chiffré
el.className = 'ch__m k-' + m.kind + (isSelf ? '' : ' other') + (enc ? ' k-enc' : '');
el.innerHTML = '<div class="ch__h">' + (isSelf ? '' : '<span class="ch__au">' + esc(m.author) + '</span>')
+ '<span class="ch__k">' + esc(meta.icon + ' ' + meta.label) + '</span>'
+ (enc ? '<span class="ch__lockbadge">🔒</span>' : '')
+ '<span>' + esc(stamp(m.at)) + '</span></div>'
+ '<div class="ch__c">' + (enc ? '🔒 chiffré — déchiffrement…' : linkify(m.content)) + '</div>';
elStream.appendChild(el);
if (enc) {
var body = el.querySelector('.ch__c');
G.tryDecrypt(m.content).then(function (v) {
if (!alive || !body) return;
if (v.ok) {
body.innerHTML = linkify(v.text) + (v.by ? ' <span class="ch__lockbadge" title="signé par ' + esc(v.by) + '">✓</span>' : '');
} else {
var r = v.reason === 'verrouille' ? 'déverrouille ton 🔑 Trousseau'
: v.reason === 'pas-de-cle' ? 'crée ta clé (ploxion 🔑 Trousseau)'
: 'pas chiffré pour toi';
body.innerHTML = '<span style="color:rgba(150,180,220,.6)">🔒 chiffré — ' + esc(r) + '</span>';
}
if (atBottom) elStream.scrollTop = elStream.scrollHeight;
});
}
// pièces jointes (photos) : cipher servi par /chat/blob → déchiffré côté client → image
if (m.attachments && m.attachments.length && window.jOSGpg) {
var atts = document.createElement('div'); atts.className = 'ch__atts'; el.appendChild(atts);
m.attachments.forEach(function (a) {
var ph = document.createElement('div'); ph.className = 'ch__att ch__att--ph'; ph.textContent = '🔒 ' + (a.name || 'photo') + ' …'; atts.appendChild(ph);
fetch(a.url, { headers: { Accept: 'application/octet-stream' } })
.then(function (r) { return r.ok ? r.arrayBuffer() : Promise.reject(r.status); })
.then(function (buf) { return window.jOSGpg.decryptBytes(new Uint8Array(buf)); })
.then(function (v) {
if (!alive) return;
if (v.ok) {
// (relecture adverse 25.09) le type du blob déchiffré ne vient JAMAIS tel quel de l'expéditeur (a.mime est libre à
// l'upload) : un « text/html » ou un svg, ouvert d'un clic (window.open d'un blob:, même origine que la page),
// exécutait son script sur l'origine du labo. Une image matricielle garde son type, le reste est un octet-stream.
// Kill-switch localStorage xb:chat.blob=expediteur : le type déclaré, comme avant (un svg s'affiche à nouveau).
var declare = String(a.mime || 'image/jpeg'), libre = false;
try { libre = localStorage.getItem('xb:chat.blob') === 'expediteur'; } catch (e) {}
var sur = (libre || /^image\/(png|jpe?g|gif|webp|avif|bmp|heic|heif)$/i.test(declare)) ? declare : 'application/octet-stream';
var url = URL.createObjectURL(new Blob([v.bytes], { type: sur }));
objUrls.push(url);
var img = document.createElement('img'); img.className = 'ch__att'; img.src = url; img.alt = a.name || '';
img.title = a.name || ''; img.addEventListener('click', function () { window.open(url, '_blank'); });
ph.replaceWith(img);
} else {
ph.textContent = '🔒 ' + (a.name || 'photo') + ' — ' + (v.reason === 'verrouille' ? 'déverrouille le 🔑' : v.reason === 'pas-de-cle' ? 'crée ta clé 🔑' : 'pas pour toi');
}
if (atBottom) elStream.scrollTop = elStream.scrollHeight;
})
.catch(function () { if (alive) ph.textContent = '🔒 ' + (a.name || 'photo') + ' — illisible'; });
});
}
count++;
if (atBottom) elStream.scrollTop = elStream.scrollHeight;
elCnt.textContent = count + ' msg';
}
function poll() {
var polled = room;
fetch(feedUrl + '?room=' + encodeURIComponent(room) + (last ? '&after=' + last : ''), { headers: { Accept: 'application/json' } })
.then(function (r) {
if (r.status === 404 && /^post-/.test(polled) && alive && polled === room && !count) {
elStream.innerHTML = '<div class="ch__empty">cette chose n\'existe plus, ou elle n\'est pas partagée avec toi.</div>';
}
return r.ok ? r.json() : null;
})
.then(function (d) {
if (!alive || !d) return;
(d.messages || []).forEach(appendMsg);
if (d.last) last = d.last;
})
.catch(function () {});
}
function doPost(payloadContent, extraMeta) {
sending = true; elSend.setAttribute('disabled', ''); elStatus.textContent = '';
var body = { kind: kind, content: payloadContent, room: room };
if (extraMeta) body.meta = extraMeta;
// le message part au nom de la xerion active (reçue du bus profil.identity)
if (sender) { body.meta = body.meta || {}; body.meta.sender = { name: sender.name, slug: sender.slug, color: sender.color }; }
fetch(postUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), Accept: 'application/json' },
body: JSON.stringify(body)
}).then(function (r) { if (!r.ok) throw new Error('http ' + r.status); return r.json(); })
.then(function (m) {
if (!alive) return;
if (m.id && m.id > last) { atBottom = true; appendMsg(m); last = m.id; }
elField.value = '';
}).catch(function (e) {
if (alive) elStatus.textContent = 'échec de l\'envoi (' + (e && e.message ? e.message : '?') + ', admin requis ?)';
}).finally(function () {
sending = false; if (alive) { elSend.removeAttribute('disabled'); elField.focus(); }
});
}
function failSend(e) { if (alive) { elStatus.textContent = 'échec : ' + (e && e.message ? e.message : e); sending = false; elSend.removeAttribute('disabled'); } }
function clearPending() { pendingFiles = []; if (elFile) elFile.value = ''; renderPending(); }
function renderPending() {
if (!pendingFiles.length) { elPending.innerHTML = ''; return; }
var html = '<span class="ch__pn">🖼 ' + pendingFiles.length + ' photo' + (pendingFiles.length > 1 ? 's' : '') + ' (chiffrées à l\'envoi)</span>';
pendingFiles.slice(0, 8).forEach(function (f) { try { var u = URL.createObjectURL(f); objUrls.push(u); html += '<img class="ch__pthumb" src="' + u + '">'; } catch (e) {} });
if (pendingFiles.length > 8) html += '<span class="ch__pn">+' + (pendingFiles.length - 8) + '</span>';
html += '<button class="ch__pclear" data-pclear>✕ vider</button>';
elPending.innerHTML = html;
var c = elPending.querySelector('[data-pclear]'); if (c) c.addEventListener('click', clearPending);
}
// chiffre + upload chaque photo (séquentiel → borne mémoire même à >50), renvoie les ids.
function uploadFiles(fprs) {
var ids = [], total = pendingFiles.length, done = 0, files = pendingFiles.slice();
function one(file) {
return file.arrayBuffer()
.then(function (buf) { return window.jOSGpg.encryptBytes(new Uint8Array(buf), fprs); })
.then(function (cipher) {
var fd = new FormData();
fd.append('file', new Blob([cipher], { type: 'application/octet-stream' }), (file.name || 'photo') + '.gpg');
fd.append('room', room); fd.append('name', file.name || 'photo'); fd.append('mime', file.type || 'image/jpeg');
return fetch('/chat/upload', { method: 'POST', headers: { 'X-CSRF-TOKEN': csrf(), Accept: 'application/json' }, body: fd });
})
.then(function (r) { if (!r.ok) throw new Error('upload ' + r.status); return r.json(); })
.then(function (a) { ids.push(a.id); done++; if (alive) elStatus.textContent = 'photos chiffrées + envoyées ' + done + '/' + total + '…'; });
}
var p = Promise.resolve();
files.forEach(function (f) { p = p.then(function () { return one(f); }); });
return p.then(function () { return ids; });
}
function send() {
if (sending) return;
var content = elField.value.trim();
var hasFiles = pendingFiles.length > 0;
if (!content && !hasFiles) return;
var fprs = gpgOn ? Object.keys(picked).filter(function (f) { return picked[f]; }) : [];
// PHOTOS : toujours chiffrées (RS-7). On upload les blobs chiffrés, puis le message les référence.
if (hasFiles) {
if (!window.jOSGpg || !window.jOSGpg.state().unlocked) { elStatus.textContent = 'déverrouille ton 🔑 Trousseau pour chiffrer les photos'; return; }
sending = true; elSend.setAttribute('disabled', ''); elStatus.textContent = 'chiffrement des photos…';
uploadFiles(fprs).then(function (ids) {
if (!alive) return;
clearPending();
var txt = content || ('📷 ' + ids.length + ' photo' + (ids.length > 1 ? 's' : ''));
var finish = function (payload, gpgFlag) { doPost(payload, { gpg: gpgFlag, to: fprs, attachments: ids }); };
if (gpgOn) window.jOSGpg.encryptTo(txt, fprs).then(function (a) { finish(a, true); }).catch(failSend);
else finish(txt, false);
}).catch(failSend);
return;
}
// 🔒 GPG texte : chiffre AVANT d'envoyer ; le serveur ne voit que du cipher.
if (gpgOn && window.jOSGpg) {
elStatus.textContent = 'chiffrement…';
window.jOSGpg.encryptTo(content, fprs)
.then(function (armored) { doPost(armored, { gpg: true, to: fprs }); })
.catch(function (e) { if (alive) elStatus.textContent = 'GPG : ' + (e && e.message ? e.message : 'échec') + ' — déverrouille ton 🔑 Trousseau'; });
return;
}
doPost(content, null);
}
elKinds.addEventListener('click', function (e) {
var b = e.target.closest('[data-k]'); if (!b) return;
kind = b.getAttribute('data-k');
elKinds.querySelectorAll('.ch__kb').forEach(function (x) { x.classList.toggle('on', x.getAttribute('data-k') === kind); });
elField.focus();
});
elField.addEventListener('keydown', function (e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } });
elSend.addEventListener('click', send);
// 📎 photos : sélection multiple (cumulable → >50), chiffrées à l'envoi
elAttach.addEventListener('click', function () { elFile.click(); });
elFile.addEventListener('change', function () { pendingFiles = pendingFiles.concat([].slice.call(elFile.files || [])); renderPending(); });
// ---- GPG : toggle 🔒 + choix des destinataires (couche window.jOSGpg) ----
function renderRcpt() {
var G = window.jOSGpg;
if (!gpgOn) { elRcpt.className = 'ch__rcpt'; elRcpt.innerHTML = ''; return; }
elRcpt.className = 'ch__rcpt show';
var rcs = G ? G.recipients() : [];
if (!rcs.length) {
elRcpt.innerHTML = '<span class="ch__rc warn">crée ta clé : ploxion 🔑 Trousseau</span>';
return;
}
// 'moi' (self) toujours coché et verrouillé (pour relire ses envois)
elRcpt.innerHTML = rcs.map(function (r) {
if (r.self) { picked[r.fpr] = true; return '<span class="ch__rc on" title="toujours inclus">' + esc(r.name) + '</span>'; }
return '<button class="ch__rc' + (picked[r.fpr] ? ' on' : '') + '" data-rc="' + esc(r.fpr) + '">' + esc(r.name) + '</button>';
}).join('');
elRcpt.querySelectorAll('[data-rc]').forEach(function (b) {
b.addEventListener('click', function () {
var f = b.getAttribute('data-rc'); picked[f] = !picked[f];
b.classList.toggle('on', !!picked[f]);
});
});
}
elLock.addEventListener('click', function () {
gpgOn = !gpgOn;
elLock.classList.toggle('on', gpgOn);
elLock.textContent = gpgOn ? '🔒 chiffré' : '🔓 clair';
if (gpgOn && window.jOSGpg && window.jOSGpg.ensureLib) window.jOSGpg.ensureLib().catch(function () {});
renderRcpt();
});
// re-render la liste si le trousseau change (clé créée/déverrouillée/contact importé)
if (window.jOSGpg && window.jOSGpg.on) window.jOSGpg.on(function () { if (gpgOn) renderRcpt(); });
// ---- bus (jOSPorts) : in `sender` ← profil.identity — l'expéditeur suit la xerion active ----
function applySender(p) {
if (!p || typeof p !== 'object') return; // payload invalide -> ignore
var name = (typeof p.name === 'string' && p.name.trim()) ? p.name.trim() : '';
if (!name) return;
sender = { name: name,
slug: (typeof p.slug === 'string' ? p.slug : ''),
color: (typeof p.color === 'string' && /^[#0-9a-zA-Z(),.%\s-]*$/.test(p.color) ? p.color : ''),
fpr: (typeof p.fpr === 'string' ? p.fpr : '') };
ME = name; // ses messages s'alignent comme « moi »
if (elSender) {
elSender.innerHTML = '<span class="ch__sdot"' + (sender.color ? ' style="background:' + esc(sender.color) + '"' : '') + '></span>' + esc(name);
elSender.classList.add('on');
}
// bonne clé : pré-coche la clé GPG de la xerion active si le trousseau la connaît
if (sender.fpr && window.jOSGpg && window.jOSGpg.recipients) {
try {
(window.jOSGpg.recipients() || []).forEach(function (r) {
if (r && r.fpr === sender.fpr) { picked[r.fpr] = true; if (gpgOn) renderRcpt(); }
});
} catch (e) {}
}
}
if (window.jOSPorts && window.jOSPorts.on) {
try {
offs.push(window.jOSPorts.on('ploxion.chat.sender', function (p) { try { applySender(p); } catch (e) {} }));
} catch (e) {}
}
renderRooms();
renderAbout();
if (SALONS_ON && /^post-\d+$/.test(room)) loadSal(); // ouvert sur une chose : son titre (un seul appel)
poll();
timer = setInterval(function () { if (alive) poll(); }, 3500);
setTimeout(function () { elField.focus(); }, 30);
// XUI : expose l'état courant au describe() (lecture seule)
LIVE = { count: function () { return count; }, room: function () { return room; }, sender: function () { return sender; } };
return { unmount: function () { alive = false; LIVE = null; if (timer) clearInterval(timer); offs.forEach(function (off) { try { if (off) off(); } catch (e) {} }); offs = []; objUrls.forEach(function (u) { try { URL.revokeObjectURL(u); } catch (e) {} }); objUrls = []; container.innerHTML = ''; } };
}
// ===== XUI (contrat v0) : describe() PUR — flux serveur (pas de cache local), donc
// LIVE au mount, état honnête « hors ligne » sinon. Ne lève jamais. =====
function describe(){
try {
var items;
if (LIVE) {
var s = null; try { s = LIVE.sender(); } catch (e0) {}
items = [
{ p:1, kind:'stat', label:'💬 chat · ' + LIVE.room(), value: LIVE.count() + ' msg' },
{ p:2, kind:'stat', label:'expéditeur', value: s && s.name ? s.name : 'identité active' }
];
} else {
items = [
{ p:1, kind:'stat', label:'💬 chat', value: 'flux serveur — ouvre pour lire' },
{ p:2, kind:'text', label: 'messages · braindumps · tsoins, salons privé/labo, photos chiffrées GPG' }
];
}
return { v:1, id:'chat', title:'Chat', icon:'💬', items:items };
} catch (e) {
return { v:1, id:'chat', title:'Chat', icon:'💬', items:[{ p:1, kind:'text', label:'Chat' }] };
}
}
window.jOSApps = window.jOSApps || {};
window.jOSApps['chat'] = { manifest: { id: 'chat', name: 'Chat', icon: '💬' }, mount: mount, describe: describe };
})();
</script>