Repository Public
1import QRCode from "qrcode"2import { useEffect, useState } from "react"3import { unb64 } from "../core/bytes"4import { safetyNumber } from "../core/crypto"5import type { Conv } from "../core/engine"6import * as mls from "../core/mls"7import type { FileRef } from "../core/types"8import { Avatar, errText, I, Sheet, Switch, t, toast, ttlLabel, useApp } from "./bits"9import { Viewer, Visual } from "./chat"1011const TTLS = [0, 300, 3600, 86400, 7 * 86400, 30 * 86400]1213export function Details({ conv, onClose, onOpen, onLeft }: { conv: Conv; onClose: () => void; onOpen: (id: string, msg?: string) => void; onLeft: () => void }) {14 const { engine } = useApp()15 const [verify, setVerify] = useState<string | null>(null)16 const [adding, setAdding] = useState(false)17 const [viewer, setViewer] = useState<FileRef | null>(null)18 const [task, setTask] = useState("")19 const [note, setNote] = useState(engine.notes[conv.id] ?? "")20 useEffect(() => setNote(engine.notes[conv.id] ?? ""), [conv.id])21 const peer = engine.peerOf(conv)22 const myRole = conv.serverMembers.find((m) => m.user_id === engine.me.id)?.role23 const devices = conv.state ? mls.members(conv.state) : []24 const media = conv.messages.flatMap((m) => (m.deleted ? [] : (m.files ?? []).filter((f) => f.thumb))).slice(-60).reverse()25 const docs = conv.messages.flatMap((m) => (m.deleted ? [] : (m.files ?? []).filter((f) => !f.thumb && !f.voice).map((f) => ({ f, m })))).slice(-30).reverse()26 const pinned = conv.messages.filter((m) => m.pinned && !m.deleted)27 const bookmarks = conv.messages.filter((m) => m.bookmarked && !m.deleted)28 const title = engine.convTitle(conv)2930 return (31 <aside className="side" aria-label={t("Conversation details", "Détails de la conversation")}>32 <div className="pane-head">33 <div className="row"><h2 className="h2 grow">{t("Details", "Détails")}</h2><button className="icon-btn" onClick={onClose} aria-label={t("Close", "Fermer")}>{I.x}</button></div>34 </div>35 <div className="pane-body" style={{ padding: "0 16px 24px" }}>36 <div className="col" style={{ alignItems: "center", textAlign: "center", gap: 6, padding: "8px 0 4px" }}>37 <Avatar id={peer ?? conv.id} name={title} size={84} />38 <b style={{ fontSize: 19 }}>{title}</b>39 {peer && <span className="dim small">@{engine.users.get(peer)?.handle}</span>}40 {conv.kind === "group" && myRole === "owner" && (41 <button className="btn sm ghost" onClick={() => {42 const n = prompt(t("Group name", "Nom du groupe"), conv.name ?? "")43 if (n !== null && n.trim()) void engine.send(conv.id, { t: "meta", name: n.trim() })44 }}>{I.edit}{t("Rename", "Renommer")}</button>45 )}46 </div>4748 <h3 className="h3">{t("Security", "Sécurité")}</h3>49 <div className="card col" style={{ gap: 12 }}>50 <div className="row small"><span style={{ color: "var(--ok)", width: 18, display: "inline-flex" }}>{I.lock}</span><span className="grow">{t("End-to-end encrypted with MLS (RFC 9420).", "Chiffré de bout en bout avec MLS (RFC 9420).")} {conv.state ? `${t("Epoch", "Époque")} ${mls.epochOf(conv.state)} · ${devices.length} ${t("devices", "appareils")}` : ""}</span></div>51 <div className="row">52 <span className="grow"><b className="small">{t("Disappearing messages", "Messages éphémères")}</b><br /><span className="dim tiny">{t("Applies to new messages, on every device and on the server.", "S’applique aux nouveaux messages, sur chaque appareil et sur le serveur.")}</span></span>53 <select className="input" style={{ width: 120, minHeight: 36, padding: "4px 8px" }} value={conv.ttl ?? 0} disabled={!conv.state} onChange={(e) => engine.send(conv.id, { t: "meta", ttl: Number(e.target.value) })} aria-label={t("Disappearing messages", "Messages éphémères")}>54 {TTLS.map((s) => <option key={s} value={s}>{ttlLabel(s)}</option>)}55 </select>56 </div>57 <div className="row"><span className="grow small"><b>{t("Mute notifications", "Couper les notifications")}</b></span><Switch checked={!!conv.muted} onChange={(v) => engine.setMuted(conv.id, v)} label={t("Mute notifications", "Couper les notifications")} /></div>58 </div>5960 <h3 className="h3">{conv.kind === "group" ? `${t("Members", "Membres")} · ${conv.serverMembers.length}` : t("Contact", "Contact")}</h3>61 <div className="col" style={{ gap: 2 }}>62 {conv.serverMembers.map((m) => {63 const pin = engine.pins.get(m.user_id)64 const self = m.user_id === engine.me.id65 const n = devices.filter((d) => d.userId === m.user_id).length66 return (67 <div key={m.user_id} className="list-row" style={{ padding: "8px 4px" }}>68 <Avatar id={m.user_id} name={engine.userName(m.user_id)} size={38} online={engine.users.get(m.user_id)?.online} />69 <span className="grow">70 <span className="ell" style={{ display: "block", fontWeight: 600 }}>{engine.userName(m.user_id)}{self ? ` (${t("you", "vous")})` : ""}</span>71 <span className="dim tiny">{m.role === "owner" && conv.kind === "group" ? `${t("owner", "propriétaire")} · ` : ""}{n} {t(n > 1 ? "devices" : "device", n > 1 ? "appareils" : "appareil")}</span>72 </span>73 {!self && (pin?.changed ? <span className="badge warn">{t("Key changed", "Clé changée")}</span> : pin?.verified ? <span className="badge ok">{t("Verified", "Vérifié")}</span> : null)}74 {!self && <button className="btn sm" onClick={() => setVerify(m.user_id)}>{I.shield}</button>}75 {!self && conv.kind === "group" && myRole === "owner" && (76 <button className="icon-btn" aria-label={t("Remove", "Retirer")} onClick={() => confirm(t(`Remove ${engine.userName(m.user_id)} from the group?`, `Retirer ${engine.userName(m.user_id)} du groupe ?`)) && engine.removeMember(conv.id, m.user_id).catch((e) => toast(errText(e)))}>{I.x}</button>77 )}78 </div>79 )80 })}81 {conv.kind === "group" && !conv.left && <button className="list-row" onClick={() => setAdding(true)}>{I.plus}<span>{t("Add people", "Ajouter des personnes")}</span></button>}82 </div>8384 {pinned.length > 0 && (<>85 <h3 className="h3">{t("Pinned", "Épinglés")}</h3>86 {pinned.map((m) => <button key={m.id} className="list-row small" onClick={() => onOpen(conv.id, m.id)}>{I.pin}<span className="ell grow">{m.body || m.files?.[0]?.name}</span></button>)}87 </>)}88 {bookmarks.length > 0 && (<>89 <h3 className="h3">{t("Your bookmarks", "Vos signets")}</h3>90 {bookmarks.map((m) => <button key={m.id} className="list-row small" onClick={() => onOpen(conv.id, m.id)}>{I.bookmark}<span className="ell grow">{m.body || m.files?.[0]?.name}</span></button>)}91 </>)}9293 <h3 className="h3">{t("Shared tasks", "Tâches partagées")}</h3>94 <div className="col" style={{ gap: 4 }}>95 {conv.tasks.map((k) => (96 <div key={k.id} className="row small">97 <input type="checkbox" checked={k.done} onChange={() => engine.send(conv.id, { t: "task", op: "toggle", task: k.id })} aria-label={k.title} />98 <span className="grow" style={{ textDecoration: k.done ? "line-through" : undefined, opacity: k.done ? 0.55 : 1 }}>{k.title}</span>99 <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => engine.send(conv.id, { t: "task", op: "del", task: k.id })} aria-label={t("Delete", "Supprimer")}>{I.x}</button>100 </div>101 ))}102 <form className="row" onSubmit={(e) => {103 e.preventDefault()104 if (task.trim()) void engine.send(conv.id, { t: "task", op: "add", task: crypto.randomUUID(), title: task.trim() })105 setTask("")106 }}>107 <input className="input" style={{ minHeight: 38 }} placeholder={t("Add a task for everyone", "Ajouter une tâche pour tous")} value={task} onChange={(e) => setTask(e.target.value)} disabled={!conv.state} aria-label={t("New task", "Nouvelle tâche")} />108 </form>109 </div>110111 <h3 className="h3">{t("Private note", "Note privée")}</h3>112 <textarea className="textarea" placeholder={t("Only you can read this. It is encrypted and shared between your own devices.", "Vous seul pouvez lire ceci. La note est chiffrée et partagée entre vos propres appareils.")} value={note} onChange={(e) => setNote(e.target.value)} onBlur={() => note !== (engine.notes[conv.id] ?? "") && engine.setNote(conv.id, note)} aria-label={t("Private note", "Note privée")} />113114 {media.length > 0 && (<>115 <h3 className="h3">{t("Photos and videos", "Photos et vidéos")}</h3>116 <div className="gallery">{media.map((f) => <Visual key={f.id} engine={engine} f={f} square onOpen={() => setViewer(f)} />)}</div>117 </>)}118 {docs.length > 0 && (<>119 <h3 className="h3">{t("Files", "Fichiers")}</h3>120 {docs.map(({ f, m }) => <button key={f.id} className="list-row small" onClick={() => onOpen(conv.id, m.id)}>{I.file}<span className="ell grow">{f.name}</span></button>)}121 </>)}122123 <div className="divider" />124 {conv.kind === "group" && !conv.left && (125 <button className="btn danger block ghost" onClick={async () => {126 if (!confirm(t("Leave this group? You will stop receiving its messages.", "Quitter ce groupe ? Vous ne recevrez plus ses messages."))) return127 await engine.leave(conv.id).catch((e) => toast(errText(e)))128 onLeft()129 }}>{I.logout}{t("Leave the group", "Quitter le groupe")}</button>130 )}131 <button className="btn danger block ghost" onClick={async () => {132 if (!confirm(t("Erase this conversation's history from this device? Other devices keep theirs.", "Effacer l’historique de cette conversation sur cet appareil ? Les autres appareils conservent le leur."))) return133 await engine.deleteLocal(conv.id)134 if (conv.left) onLeft()135 }}>{I.trash}{t("Erase history on this device", "Effacer l’historique sur cet appareil")}</button>136 </div>137 {verify && <Verify userId={verify} onClose={() => setVerify(null)} />}138 {adding && <AddPeople conv={conv} onClose={() => setAdding(false)} />}139 {viewer && <Viewer engine={engine} f={viewer} onClose={() => setViewer(null)} />}140 </aside>141 )142}143144/** Safety number and QR code: two people compare them in person or over another channel. */145export function Verify({ userId, onClose }: { userId: string; onClose: () => void }) {146 const { engine } = useApp()147 const pin = engine.pins.get(userId)148 const [num, setNum] = useState("")149 const [qr, setQr] = useState("")150 const [scanned, setScanned] = useState<"" | "match" | "mismatch">("")151 const [scanning, setScanning] = useState(false)152 useEffect(() => {153 if (!pin) return154 safetyNumber({ id: engine.me.id, key: engine.dev.identityKey }, { id: userId, key: unb64(pin.ik) }).then((n) => {155 setNum(n)156 void QRCode.toDataURL(`spm-verify:${n.replace(/ /g, "")}`, { margin: 0, width: 360, errorCorrectionLevel: "M" }).then(setQr)157 })158 }, [engine, userId, pin?.ik])159160 // Scanning uses the browser's built-in barcode detector where it exists (not in every browser).161 useEffect(() => {162 if (!scanning) return163 let stream: MediaStream | undefined, stop = false164 const video = document.getElementById("scan-video") as HTMLVideoElement165 ;(async () => {166 try {167 stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } })168 video.srcObject = stream169 await video.play()170 const det = new (window as any).BarcodeDetector({ formats: ["qr_code"] })171 while (!stop) {172 const codes = await det.detect(video).catch(() => [])173 if (codes[0]?.rawValue?.startsWith("spm-verify:")) {174 const ok = codes[0].rawValue.slice(11) === num.replace(/ /g, "")175 setScanned(ok ? "match" : "mismatch")176 if (ok) await engine.setVerified(userId, true)177 break178 }179 await new Promise((r) => setTimeout(r, 250))180 }181 } catch {182 toast(t("The camera could not be used for scanning.", "La caméra n’a pas pu être utilisée pour le balayage."))183 }184 setScanning(false)185 })()186 return () => {187 stop = true188 stream?.getTracks().forEach((x) => x.stop())189 }190 }, [scanning])191192 if (!pin) return <Sheet title={t("Verification", "Vérification")} onClose={onClose}><p className="muted">{t("This person has not set up encryption yet.", "Cette personne n’a pas encore configuré le chiffrement.")}</p></Sheet>193 const groups = num.split(" ")194 return (195 <Sheet title={`${t("Verify", "Vérifier")} ${engine.userName(userId)}`} onClose={onClose}>196 <div className="col" style={{ gap: 14 }}>197 <p className="muted small">{t("Compare this number with the one shown on their device, in person or over a call. If they are identical, nobody is impersonating either of you.", "Comparez ce numéro avec celui affiché sur son appareil, en personne ou lors d’un appel. S’ils sont identiques, personne n’usurpe l’identité de l’un de vous.")}</p>198 {pin.changed && <div className="banner warn">{I.warn}<span>{t("This person's key has changed since you last trusted it. The number below is for the key you trusted before.", "La clé de cette personne a changé depuis que vous l’avez approuvée. Le numéro ci-dessous correspond à l’ancienne clé.")}</span></div>}199 {scanning ? <video id="scan-video" playsInline muted style={{ width: "100%", borderRadius: 16, aspectRatio: "1", objectFit: "cover" }} /> : qr && <div className="qr"><img src={qr} alt={t("Verification QR code", "Code QR de vérification")} /></div>}200 <div className="safety" data-testid="safety-number">{groups.slice(0, 6).join(" ")}<br />{groups.slice(6).join(" ")}</div>201 {scanned === "match" && <div className="banner info">{I.shield}{t("The codes match.", "Les codes concordent.")}</div>}202 {scanned === "mismatch" && <div className="banner bad">{I.warn}{t("The scanned code does not match. Do not trust this conversation.", "Le code balayé ne concorde pas. Ne faites pas confiance à cette conversation.")}</div>}203 <div className="row">204 {"BarcodeDetector" in window && <button className="btn grow" onClick={() => setScanning((s) => !s)}>{I.camera}{scanning ? t("Stop", "Arrêter") : t("Scan their code", "Balayer son code")}</button>}205 <button className={`btn grow ${pin.verified ? "" : "primary"}`} onClick={() => engine.setVerified(userId, !pin.verified)}>{I.shield}{pin.verified ? t("Remove verification", "Retirer la vérification") : t("Mark as verified", "Marquer comme vérifié")}</button>206 </div>207 </div>208 </Sheet>209 )210}211212function AddPeople({ conv, onClose }: { conv: Conv; onClose: () => void }) {213 const { engine } = useApp()214 const [dir, setDir] = useState<{ id: string; handle: string; display_name: string }[]>([])215 const [sel, setSel] = useState<string[]>([])216 const [busy, setBusy] = useState(false)217 useEffect(() => {218 engine.t.request<typeof dir>("GET", "/api/directory").then((d) => setDir(d.filter((u) => !conv.serverMembers.some((m) => m.user_id === u.id)))).catch(() => {})219 }, [engine, conv])220 return (221 <Sheet title={t("Add people", "Ajouter des personnes")} onClose={onClose}>222 <div className="col">223 <div className="col" style={{ gap: 2, maxHeight: "46dvh", overflowY: "auto" }}>224 {dir.map((u) => {225 const on = sel.includes(u.id)226 return (227 <button key={u.id} className="list-row" role="checkbox" aria-checked={on} onClick={() => setSel((s) => (on ? s.filter((x) => x !== u.id) : [...s, u.id]))}>228 <Avatar id={u.id} name={u.display_name} size={38} />229 <span className="grow">{u.display_name}</span>230 <span className={`badge ${on ? "accent" : ""}`} style={{ width: 24, padding: 0, justifyContent: "center" }}>{on ? "✓" : ""}</span>231 </button>232 )233 })}234 {!dir.length && <p className="dim small">{t("Everyone is already in this group.", "Tout le monde fait déjà partie de ce groupe.")}</p>}235 </div>236 <p className="dim small">{t("New members cannot read messages sent before they joined.", "Les nouveaux membres ne peuvent pas lire les messages envoyés avant leur arrivée.")}</p>237 <button className="btn primary" disabled={!sel.length || busy} onClick={async () => {238 setBusy(true)239 try {240 await engine.addMembers(conv.id, sel)241 onClose()242 } catch (e) {243 toast(errText(e))244 setBusy(false)245 }246 }}>{busy && <span className="spinner" />}{t("Add", "Ajouter")}</button>247 </div>248 </Sheet>249 )250}251