""" `meshbay-cli chat` with no group: the groups, then one group's chat, IRC-style. The list shows every group of the account; Enter opens one whose node is up and whose chat is on (`enabled_apps` in the sealed ack, empty meaning all). The room shows the last messages, then the ones that arrive (`chat_msg` pushed by the node), and a line at the bottom to write in. Esc, or `/part`, goes back to the list; Ctrl+Q, or `/quit`, quits. A right-click copies — the text selected with the mouse, else the line under the pointer — and pastes into the line written in. `/put FILE` sends one local file (relative to the current directory, or absolute) into the chat's folder and names it in the conversation, as the application's paperclip does; `/get NAME` saves a file of that folder, named from it, into the current directory. Messages are read and posted exactly as the `chat` action reads and posts them — signature, epoch key, content, then the roster's verdict on the signing device — and drawn as text, never markup. """ import asyncio import contextlib import os import time from pathlib import Path from meshbay_common.paths import long_path from rich.segment import Segment from rich.text import Text from textual import events from textual.app import ComposeResult from textual.binding import Binding from textual.screen import Screen from textual.selection import Selection from textual.strip import Strip from textual.widgets import DataTable, Footer, Input, RichLog, Static from ..client.account import Account from ..client.chat import ( Message, attachment_text, chat_folder, chat_keys, history, open_row, post, ) from ..client.groups import my_groups from ..client.paths import handle from ..client.pool import Pool from ..client.roster import RosterCheck from ..client.transfers import PART_SUFFIX, download, upload from ..client.tree import Tree from ..client.upload_plan import refused_names from ..errors import CliError from ..output import human_size, safe from . import clipboard # How much of the conversation a room opens on. BACKLOG = 50 HELP = ("/put FILE: send a file /get NAME: save one here /part or Esc: back " "/quit or Ctrl+Q: quit right-click: copy, paste /help: this") # Under a message's first line, its next ones and what is said about it. INDENT = " " * 6 KEY_CHANGED = ("! This account is using a key you have not seen before: a new device " "added elsewhere, or the node naming the wrong person.") def chat_enabled(ack: dict) -> bool: apps = ack.get("enabled_apps") or [] return not apps or "chat" in apps class ChatGroupsScreen(Screen): BINDINGS = [ Binding("r", "refresh", "Refresh"), Binding("q", "app.quit", "Quit"), ] DEFAULT_CSS = """ ChatGroupsScreen > .title { height: 1; padding: 0 1; background: $panel; } ChatGroupsScreen > DataTable { height: 1fr; } """ def __init__(self, account: Account): super().__init__() self.account = account self.pool = Pool(account) self.groups: list[dict] = [] def compose(self) -> ComposeResult: yield Static(Text("Chat — choose a group, Enter to join"), classes="title") table = DataTable(cursor_type="row") table.add_column("Group", key="group") table.add_column("Node", key="node") yield table yield Footer() def on_mount(self) -> None: self.query_one(DataTable).focus() self.action_refresh() def action_refresh(self) -> None: self.run_worker(self._load(), exclusive=True, group="groups") async def _load(self) -> None: try: self.groups = sorted(await my_groups(self.account), key=lambda g: (g["name"].lower(), g.get("owner_username"))) except CliError as e: self.app.notify(e.message, severity="error", markup=False) return table = self.query_one(DataTable) table.clear() for g in self.groups: up = g.get("node_online") table.add_row(Text(safe(handle(g)), style="" if up else "dim", no_wrap=True, overflow="ellipsis"), Text("up" if up else "down", style="" if up else "dim"), key=g["id"]) def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None: group = next((g for g in self.groups if g["id"] == event.row_key.value), None) if group is not None: self.run_worker(self._join(group), exclusive=True, group="join") async def _join(self, group: dict) -> None: self.app.notify(f"Joining {safe(handle(group))}…", timeout=3, markup=False) try: session = await self.pool.session(group) except CliError as e: self.app.notify(e.message, severity="error", markup=False, timeout=8) return if not chat_enabled(session.ack): self.app.notify(f"{safe(handle(group))} has its chat turned off.", severity="warning", markup=False) return await self.app.push_screen(ChatRoomScreen(self.account, group, session)) async def on_unmount(self) -> None: with contextlib.suppress(Exception): await self.pool.close() class ChatLog(RichLog): """The conversation, selectable with the mouse — RichLog alone is not.""" def __init__(self, **kwargs): super().__init__(**kwargs) # (first line, line after the last, its text) for each thing written. self._blocks: list[tuple[int, int, str]] = [] def write(self, content, *args, **kwargs): # Writes before the size is known come back through here once it is. first = len(self.lines) result = super().write(content, *args, **kwargs) if len(self.lines) > first and isinstance(content, Text): self._blocks.append((first, len(self.lines), content.plain.replace("\n" + INDENT, "\n"))) return result def text_at(self, y: int) -> str | None: return next((text for first, end, text in self._blocks if first <= y < end), None) def get_selection(self, selection: Selection) -> tuple[str, str] | None: text = "\n".join(line.text.rstrip() for line in self.lines) return selection.extract(text), "\n" def selection_updated(self, selection: Selection | None) -> None: self._line_cache.clear() self.refresh() def _render_line(self, y: int, scroll_x: int, width: int) -> Strip: line = super()._render_line(y, scroll_x, width) if y >= len(self.lines): return line selection = self.text_selection span = selection.get_span(y) if selection is not None else None if span is not None: start, end = span end = self.lines[y].cell_length if end == -1 else end start, end = max(start - scroll_x, 0), max(end - scroll_x, 0) style = self.screen.get_component_rich_style("screen--selection") line = Strip.join([ line.crop(0, start), Strip(Segment.apply_style(list(line.crop(start, end)), post_style=style)), line.crop(end)]) # Where each cell sits in the text: what the screen's selection reads. return line.apply_offsets(scroll_x, y) async def right_click(self, event: events.MouseDown) -> None: selection = self.text_selection text = self.get_selection(selection)[0] if selection is not None else "" if not text: y = event.screen_y - self.content_region.y + self.scroll_offset.y text = self.text_at(y) or "" if text: self.app.copy_to_clipboard(text) self.app.notify("Copied.", timeout=2) self.run_worker(clipboard.write_text(text), group="clipboard") class ChatInput(Input): async def right_click(self, event: events.MouseDown) -> None: self.focus() self.run_worker(self._paste(), exclusive=True, group="clipboard") async def _paste(self) -> None: text = await clipboard.read_text() if text is None: text = self.app.clipboard # One line to write in: the lines of what is pasted, side by side. text = " ".join(part for part in text.splitlines() if part.strip()) if not text: self.app.notify("Nothing to paste.", timeout=2) return self.replace(text, *self.selection) class ChatRoomScreen(Screen): BINDINGS = [Binding("escape", "part", "Back to the groups")] DEFAULT_CSS = """ ChatRoomScreen > .title { height: 1; padding: 0 1; background: $panel; } ChatRoomScreen > ChatLog { height: 1fr; padding: 0 1; } ChatRoomScreen > .transfer { height: 1; padding: 0 1; display: none; } ChatRoomScreen > ChatInput { dock: bottom; } """ def __init__(self, account: Account, group: dict, session): super().__init__() self.account = account self.group = group self.session = session self.keys = None self.check = RosterCheck(account, session) self._day = "" self._ready = asyncio.Event() self._transferring = False def compose(self) -> ComposeResult: yield Static(Text(f"#{safe(handle(self.group))} — {HELP}", no_wrap=True, overflow="ellipsis"), classes="title") yield ChatLog(wrap=True, markup=False, highlight=False, auto_scroll=True) yield Static("", classes="transfer", markup=False) yield ChatInput(placeholder=f"Message to {safe(handle(self.group))}", select_on_focus=False) yield Footer() @property def log_view(self) -> ChatLog: return self.query_one(ChatLog) def on_mount(self) -> None: self.query_one(Input).focus() self.session.ch.on_push("chat_msg", self._pushed) self.session.ch.on_push("chat_epoch_ack", self._epoch_moved) self.session.ch.on_push("chat_directory_ack", self._folder_moved) self.run_worker(self._open(), group="room") def on_unmount(self) -> None: self.session.ch.off_push("chat_msg", self._pushed) self.session.ch.off_push("chat_epoch_ack", self._epoch_moved) self.session.ch.off_push("chat_directory_ack", self._folder_moved) async def _open(self) -> None: try: self.keys = await chat_keys(self.session) rows = await history(self.session, BACKLOG) for row in rows: self.show(await open_row(row, self.keys, self.group["id"], self.check)) except CliError as e: self.note(f"! {e.message}") return finally: self._ready.set() if not rows: self.note("No message yet. Say something.") # ── Drawing ────────────────────────────────────────────────────────────── def note(self, text: str, style: str = "italic dim") -> None: self.log_view.write(Text(text, style=style)) def show(self, m: Message) -> None: day = time.strftime("%Y-%m-%d", time.localtime(m.timestamp)) if day != self._day: self._day = day self.note(f"— {day} —") line = Text(time.strftime("%H:%M ", time.localtime(m.timestamp)), style="dim") line.append(f"<{safe(m.sender)}> ", style="bold") if m.unreadable: line.append(f"[this message cannot be read: {m.unreadable}]", style="italic") else: if m.attachment: line.append(f"[file: {safe(m.attachment['filename'])}, " f"{human_size(m.attachment['size'])}]", style="cyan") if m.text: line.append("\n" + INDENT) line.append(("\n" + INDENT).join(safe(part) for part in m.text.split("\n"))) self.log_view.write(line) if m.trust == "changed": self.note(INDENT + KEY_CHANGED, style="bold yellow") # ── What the node pushes ───────────────────────────────────────────────── def _pushed(self, msg: dict) -> None: self.run_worker(self._arrived(msg), group="arrivals") async def _arrived(self, msg: dict) -> None: await self._ready.wait() if self.keys is None: return # A message sealed under an epoch opened since the keys were fetched. if int(msg.get("epoch") or 0) not in self.keys.by_epoch: with contextlib.suppress(CliError): self.keys = await chat_keys(self.session) msg = {**msg, "timestamp": msg.get("timestamp") or time.time()} self.show(await open_row(msg, self.keys, self.group["id"], self.check)) def _epoch_moved(self, msg: dict) -> None: """Somebody was removed: a new epoch, and the key to post under with it.""" self.session.ack["chat_epoch"] = int(msg.get("epoch") or 0) self.run_worker(self._refetch_keys(), group="keys") async def _refetch_keys(self) -> None: with contextlib.suppress(CliError): self.keys = await chat_keys(self.session) def _folder_moved(self, msg: dict) -> None: """The operator chose another folder for the chat's files.""" self.session.ack["chat_directory"] = str(msg.get("path") or "") # ── Writing ────────────────────────────────────────────────────────────── async def on_input_submitted(self, event: Input.Submitted) -> None: text = event.value.rstrip() event.input.value = "" if not text.strip(): return command = text.strip().lower() if command in ("/part", "/leave"): self.action_part() return if command in ("/quit", "/exit"): self.app.exit() return if command == "/help": self.note(HELP) return verb, _, arg = text.strip().partition(" ") if verb.lower() in ("/put", "/get"): arg = _unquote(arg.strip()) if not arg: self.note(f"{verb.lower()} FILE: " + ("the local file to send." if verb.lower() == "/put" else "the file to save, named from " "the chat's folder.")) elif self._transferring: self.note("! A file is on its way already; wait for it.", style="bold red") else: self.run_worker(self._put(arg) if verb.lower() == "/put" else self._get(arg), group="transfer") return if command.startswith("/") and not command.startswith("//"): self.note(f"Unknown command {safe(text.split()[0])}. {HELP}") return if command.startswith("//"): text = text.lstrip()[1:] # "//x" posts "/x" await self._ready.wait() try: await post(self.session, self.keys, text, self.account.username) except CliError as e: self.note(f"! Not sent: {e.message}", style="bold red") return # The node relays to everybody else; this side shows its own at once. self.show(Message(0, time.time(), self.account.username, text, trust="pinned")) def action_part(self) -> None: self.app.pop_screen() # ── Files ──────────────────────────────────────────────────────────────── async def _folder(self) -> tuple[Tree, str] | None: tree = Tree.from_index(await self.session.index()) folder = chat_folder(self.session.ack, tree.roots) if not folder: self.note("! This group has no folder for the chat's files: every one is " "read-only or unavailable.", style="bold red") return None return tree, folder def _progress(self, arrow: str, name: str, size: int): bar = self.query_one(".transfer", Static) done = [0] started = time.monotonic() def advance(n: int) -> None: done[0] += n rate = done[0] / max(time.monotonic() - started, 0.001) pct = 100 * done[0] // size if size else 100 bar.update(Text(f"{arrow} {safe(name)} {pct}% {human_size(int(rate))}/s", no_wrap=True, overflow="ellipsis")) def queued(n: int) -> None: bar.update(Text(f"{arrow} {safe(name)} waiting for a free slot on the node" + (f" ({n} ahead)" if n else ""), no_wrap=True)) bar.update(Text(f"{arrow} {safe(name)}", no_wrap=True)) bar.display = True return advance, queued def _transfer_ended(self) -> None: self._transferring = False bar = self.query_one(".transfer", Static) bar.display = False bar.update("") async def _put(self, arg: str) -> None: path = Path(os.path.abspath(os.path.expanduser(arg))) if not os.path.isfile(long_path(path)): self.note(f"! {safe(arg)}: " + ("a folder; /put sends one file." if os.path.isdir(long_path(path)) else "no such file."), style="bold red") return name = path.name if problems := refused_names([name], []): self.note(f"! Not sent: {safe(problems[0])}", style="bold red") return self._transferring = True try: await self._ready.wait() if self.keys is None: self.note("! Not sent: the chat could not be opened.", style="bold red") return found = await self._folder() if found is None: return _, folder = found size = os.stat(long_path(path)).st_size advance, queued = self._progress("↑", name, size) with open(long_path(path), "rb") as fh: def read(offset: int, length: int) -> bytes: fh.seek(offset) return fh.read(length) stored = await upload(self.session, read, size, name, folder, progress=advance, on_queued=queued) try: await post(self.session, self.keys, attachment_text(stored, size), self.account.username) except CliError as e: self.note(f"! {safe(stored)} is in {safe(folder)}, but the message naming " f"it was not sent: {safe(e.message)}", style="bold red") return except OSError as e: self.note(f"! Not sent: {safe(arg)}: {e.strerror}", style="bold red") return except CliError as e: self.note(f"! Not sent: {safe(e.message)}", style="bold red") return finally: self._transfer_ended() self.show(Message(0, time.time(), self.account.username, "", trust="pinned", attachment={"filename": stored, "size": size, "type": "file"})) if stored != name: self.note(f"{INDENT}stored as {safe(stored)}: {safe(name)} was taken.") async def _get(self, arg: str) -> None: name = arg.replace("\\", "/").strip("/") if not name or any(p in ("", ".", "..") for p in name.split("/")): self.note(f"! {safe(arg)}: name a file of the chat's folder.", style="bold red") return self._transferring = True try: found = await self._folder() if found is None: return tree, folder = found entry = tree.file(f"{folder}/{name}") if entry is None: self.note(f"! No file {safe(name)} in the chat's folder ({safe(folder)}).", style="bold red") return target = Path.cwd() / name.rsplit("/", 1)[-1] if os.path.exists(long_path(target)) and not os.path.exists( long_path(target.with_name(target.name + PART_SUFFIX))): self.note(f"! {safe(str(target))} is here already; nothing was downloaded.", style="bold red") return size = int(entry["size"]) advance, queued = self._progress("↓", name, size) await download(self.session, entry, target, progress=advance, on_queued=queued) except OSError as e: self.note(f"! Not saved: {e.strerror}", style="bold red") return except CliError as e: self.note(f"! Not saved: {safe(e.message)}", style="bold red") return finally: self._transfer_ended() self.note(f"Saved {safe(str(target))} ({human_size(size)}).") def _unquote(text: str) -> str: """A path pasted with its quotes, as a file manager or a shell gives it.""" if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'": return text[1:-1] return text