repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
dcx.pyPython970 lines35.3 KiBraw download
#!/usr/bin/env python3
"""dcx — Discord chat export, themed and quiet.

A wrapper around DiscordChatExporter.Cli that does three things the raw tool
does not:

    1. Handles the auth token for you. First run walks you through getting one,
       reads it masked from the terminal, and saves it to ~/.config/dcx/token
       (0600). Every run after that is silent. It only asks again when YOU ask
       — `dcx login`, or --relogin on any command.

    2. Exports a server channel-by-channel behind a single live spinner. The
       tool's own progress bars are captured to a log, so the screen shows one
       moving line — what it is doing right now — and leaves behind one compact
       line per channel already done. The list grows; the screen does not fill.

    3. Wears the same Rose Pine coat as the rest of the ~/.local/bin tools, via
       the shared ricefx shimmer library sitting next to it.

    dcx guilds                       list the servers you can see
    dcx channels GUILD_ID            list a server's channels
    dcx guild   GUILD_ID             export every text channel in a server
    dcx channel CHAN_ID [CHAN_ID…]   export one or more channels
    dcx dm                           export every direct-message channel
    dcx login                        re-enter (and re-save) the token
    dcx guide                        how to obtain a token / server / channel ID

Where the token lives, and why there
    ~/.config/dcx/token, mode 0600, OUTSIDE any dotfiles repo. The backup repo
    (~/dotfiles) syncs ~/.local/bin but not ~/.config/dcx, and its sync.sh runs
    a secret scan before every commit — so this script can be published while
    the token it reads never is. The token is handed to the exporter through the
    DISCORD_TOKEN environment variable, never on the command line: argv is world
    -readable in `ps`, the environment of a single child is not.

    A user token is your whole Discord account in one string. Treat it like a
    password. This tool only ever reads chats YOUR account can already see.

Rose Pine UI via ricefx, which ships alongside in ~/.local/bin. Absent (a fresh
VM, a scp'd copy) the plain fallback below takes over — the tool never depends
on it.
"""
from __future__ import annotations

import argparse
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time

VERSION = "1.1.0"

# ── shimmer ─────────────────────────────────────────────────────────────────
# sys.path[0] is this script's own directory, so a sibling ricefx.py is found
# without any install step. A standalone copy on another box has no sibling —
# hence the fallback, a static Rose Pine base-dark palette with the animation
# stripped out.
try:
    import ricefx
except ImportError:
    ricefx = None

RESET = "\x1b[0m"
BOLD = "\x1b[1m"
HIDE, SHOW = "\x1b[?25l", "\x1b[?25h"
CLEAR = "\x1b[2K\r"
_ANSI = re.compile(r"\x1b\[[0-9;?]*[a-zA-Z]")

# Rose Pine base dark. Local copy so the standalone script is genuinely
# standalone. pine (#31748f) is deliberately absent from anything that draws
# text: at 3.3:1 on base it is a fill colour, never ink.
_PALETTE = {
    "overlay": (38, 35, 58),   "muted": (110, 106, 134),
    "subtle": (144, 140, 170), "text": (224, 222, 244),
    "love": (235, 111, 146),   "gold": (246, 193, 119),
    "rose": (235, 188, 186),   "foam": (156, 207, 216),
    "iris": (196, 167, 231),   "pine": (49, 116, 143),
}

# Nerd-font glyphs, not emoji — these sit inside status lines whose width is
# counted in cells, and emoji are two cells wide in some terminals and one in
# others. ☧ (Chi-Rho) is plain Unicode and always one cell.
ICON = {"mark": "☧", "ok": "", "bad": "", "warn": "", "key": "",
        "skip": "○", "arrow": "→", "dot": "·", "list": ""}

BAR_W = 22
FPS = 12
SPIN_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"


def color_ok(stream=sys.stderr) -> bool:
    if os.environ.get("NO_COLOR") is not None or os.environ.get("RICEFX_OFF"):
        return False
    try:
        return bool(stream.isatty())
    except (AttributeError, ValueError):
        return False


COLOR = color_ok()


def accent(name: str) -> tuple[int, int, int]:
    """A Rose Pine accent for the active theme. ricefx follows the terminal's
    dawn/dark; the fallback is base-dark only."""
    if ricefx is not None:
        try:
            return ricefx.accent(name)
        except (KeyError, Exception):  # noqa: BLE001 — never let colour crash
            pass
    return _PALETTE.get(name, _PALETTE["text"])


def fg(rgb) -> str:
    return f"\x1b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m"


def c(name: str, s: str) -> str:
    return f"{fg(accent(name))}{s}{RESET}" if COLOR else s


def vlen(s: str) -> int:
    return len(_ANSI.sub("", s))


def sweep(s: str, t: float = 0.0) -> str:
    if not COLOR:
        return s
    if ricefx is not None:
        return ricefx.sweep(s, t)
    return c("iris", s)


def spin_glyph(t: float) -> str:
    if ricefx is not None and COLOR:
        return ricefx.spin(t, FPS)
    ch = SPIN_FRAMES[int(t * FPS) % len(SPIN_FRAMES)]
    return c("iris", ch) if COLOR else ch


def rule(width: int = 46) -> str:
    if ricefx is not None and COLOR:
        return ricefx.rule(width)
    return c("muted", "─" * width)


def banner() -> None:
    # DCX in the same half-block font tarx uses.
    art = ["█▀▄ █▀▀ ▀▄▀", "█▄▀ █▄▄ █░█"]
    if not COLOR:
        return
    if ricefx is not None:
        ricefx.banner_sweep([" " + a for a in art], stream=sys.stderr)
    else:
        for a in art:
            sys.stderr.write(f" {BOLD}{c('iris', a)}{RESET}\n")


# ── talking to the user ─────────────────────────────────────────────────────
def say(s: str = "") -> None:
    sys.stderr.write(s + "\n")


def info(s: str) -> None:
    say(f" {c('iris', ICON['dot'])} {c('subtle', s)}")


def warn(s: str) -> None:
    say(f" {c('gold', ICON['warn'])} {c('text', s)}")


def ok(s: str) -> None:
    say(f" {c('foam', ICON['ok'])} {c('text', s)}")


def die(s: str, code: int = 1) -> "NoReturn":  # noqa: F821
    say(f" {c('love', ICON['bad'])} {c('text', 'dcx: ' + s)}")
    sys.exit(code)


def human(n: float) -> str:
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024 or unit == "TB":
            return f"{n:.0f} {unit}" if unit == "B" else f"{n:,.1f} {unit}"
        n /= 1024
    return f"{n:.1f} TB"


def clock(sec: float) -> str:
    sec = int(max(0, sec))
    if sec < 60:
        return f"{sec}s"
    if sec < 3600:
        return f"{sec // 60}m{sec % 60:02d}s"
    return f"{sec // 3600}h{(sec % 3600) // 60:02d}m"


def commafy(n: int) -> str:
    return f"{n:,}"


def truncate(s: str, room: int) -> str:
    if room <= 1 or vlen(s) <= room:
        return s
    return s[: room - 1] + "…"


# ── config & token ──────────────────────────────────────────────────────────
def dcx_home() -> str:
    """Where DiscordChatExporter.Cli and its runtime live."""
    return os.environ.get("DCX_HOME", os.path.expanduser("~/tools/dce"))


def config_dir() -> str:
    base = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
    return os.path.join(base, "dcx")


def token_path() -> str:
    return os.path.join(config_dir(), "token")


def default_output() -> str:
    # NixOS: the exporter comes from the Nix store (home.packages), so there is
    # no ~/tools/dce to keep exports beside — they go under ~/Documents.
    return os.environ.get("DCX_OUTPUT",
                          os.path.expanduser("~/Documents/discord-exports"))


def dce_bin() -> str:
    exe = os.path.join(dcx_home(), "DiscordChatExporter.Cli")
    if not os.path.isfile(exe):
        found = shutil.which("DiscordChatExporter.Cli")
        if found:
            return found
        die(f"DiscordChatExporter.Cli not on PATH or in {dcx_home()} — it comes "
            f"from discordchatexporter-cli in NixDaemon's tools.nix")
    if not os.access(exe, os.X_OK):
        try:
            os.chmod(exe, 0o755)
        except OSError:
            die(f"{exe} is not executable and could not be chmod'd")
    return exe


# On NixDaemon the token file is a sops-nix symlink into $XDG_RUNTIME_DIR
# (modules/home/dcx.nix): decrypted at login, read-only, never in the store.
# It is edited with sops, not written by dcx. The encrypted file starts out
# holding this placeholder until the real token is pasted in.
SOPS_PLACEHOLDER = "REPLACE_WITH_DISCORD_TOKEN"
SOPS_EDIT = "TMPDIR=/dev/shm sops ~/NixDaemon/secrets/dcx/token"


def sops_managed() -> bool:
    return os.path.islink(token_path())


def stored_token() -> str | None:
    if sops_managed():
        try:
            with open(token_path(), encoding="utf-8") as f:
                tok = f.read().strip()
        except OSError:
            die(f"{token_path()} is managed by sops but unreadable — is the "
                "sops-nix user service running? (systemctl --user status sops-nix)")
        if not tok or tok == SOPS_PLACEHOLDER:
            die(f"no Discord token in sops yet. Paste it with:  {SOPS_EDIT}  "
                "then run `nh os switch`.")
        return tok
    try:
        with open(token_path(), encoding="utf-8") as f:
            tok = f.read().strip()
        return tok or None
    except OSError:
        return None


def save_token(tok: str) -> None:
    if sops_managed():
        die(f"the token is managed by sops, not saved by dcx. Update it with:  "
            f"{SOPS_EDIT}  then `nh os switch`.")
    d = config_dir()
    os.makedirs(d, exist_ok=True)
    try:
        os.chmod(d, 0o700)
    except OSError:
        pass
    path = token_path()
    # Write via a private-mode fd so the secret is never briefly world-readable.
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(tok.strip() + "\n")
    os.chmod(path, 0o600)


MASK = "•"


def _prompt_tty(label: str, show: bool) -> str:
    """One secret, read from /dev/tty with a mask drawn as you type.

    getpass() would read it, but it shows nothing at all — no cursor movement,
    no length, no sign the keyboard is even connected, which is the single most
    common reason people think a tool "didn't ask". So this drives the terminal
    directly: ECHO off (the real characters never reach the screen or the
    scrollback) while a dot is painted per keystroke. /dev/tty, not stdin, so a
    paste works even when stdin is busy; never argv, never the environment.
    """
    try:
        tty_f = open("/dev/tty", "r+b", buffering=0)
    except OSError:
        import getpass
        return getpass.getpass(f" {label}: ")
    try:
        import termios
    except ImportError:
        tty_f.close()
        import getpass
        return getpass.getpass(f" {label}: ")

    fd = tty_f.fileno()
    old = termios.tcgetattr(fd)
    dot = (fg(accent("iris")) + MASK + RESET) if COLOR else MASK
    tty_f.write(f" {c('iris', ICON['key'])} {c('text', label)}{c('muted', ': ')}"
                .encode())
    chars: list[str] = []
    pending = bytearray()
    try:
        raw = termios.tcgetattr(fd)
        raw[3] &= ~(termios.ECHO | termios.ICANON)      # lflag
        termios.tcsetattr(fd, termios.TCSADRAIN, raw)
        while True:
            b = os.read(fd, 1)
            if not b or b in (b"\r", b"\n"):
                break
            if b == b"\x03":                            # Ctrl-C
                raise KeyboardInterrupt
            if b == b"\x04":                            # Ctrl-D
                if not chars:
                    raise KeyboardInterrupt
                continue
            if b in (b"\x7f", b"\x08"):                 # backspace
                if chars:
                    chars.pop()
                    tty_f.write(b"\b \b")
                continue
            if b == b"\x15":                            # Ctrl-U, clear the line
                tty_f.write(b"\b \b" * len(chars))
                chars.clear()
                continue
            if b < b" ":                                # any other control key
                continue
            pending += b
            try:
                ch = pending.decode()
            except UnicodeDecodeError:
                continue          # partial UTF-8 sequence, wait for the rest
            pending.clear()
            chars.append(ch)
            tty_f.write(ch.encode() if show else dot.encode())
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
        try:
            tty_f.write(b"\n")
            tty_f.close()
        except OSError:
            pass
    return "".join(chars)


def read_token(show: bool = False) -> str:
    try:
        tok = _prompt_tty("paste token", show)
    except (EOFError, KeyboardInterrupt):
        say()
        die("cancelled", 130)
    tok = tok.strip()
    if not tok:
        die("empty token")
    return tok


def token_guide() -> None:
    """How to get a Discord user token. Styled, but the facts are the tool's."""
    say()
    say(f" {c('iris', ICON['key'])} {c('text', BOLD + 'getting your Discord token' + RESET)}")
    say(" " + rule(52))
    steps = [
        ("1", "Open Discord in a WEB BROWSER (not the desktop app) and log in."),
        ("2", "Open developer tools:  Ctrl+Shift+I  (F12 also works)."),
        ("3", "Click the  Network  tab, then click any channel so requests appear."),
        ("4", "In the filter box type   /api   and click any request in the list."),
        ("5", "Open  Headers → Request Headers  and find   authorization ."),
        ("6", "Copy that value — that whole string is your token."),
    ]
    for n, txt in steps:
        say(f"   {c('gold', n)}  {c('text', txt)}")
    say()
    say(f"   {c('subtle', 'A user token is your entire account in one string. Treat it like a')}")
    say(f"   {c('subtle', 'password: never share it, never paste it into a website. dcx stores it')}")
    say(f"   {c('subtle', 'at ' + token_path() + ' (0600) and sends it only to Discord.')}")
    say()
    say(f"   {c('muted', 'Full walkthrough with pictures:')}")
    say(f"   {c('foam', 'https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md')}")
    say(" " + rule(52))


def token_is_valid(tok: str) -> bool:
    """A cheap round-trip: can this token list guilds? Keeps a fat-fingered
    paste from being saved and then failing on every future run."""
    exe = dce_bin()
    env = dce_env(tok)
    try:
        p = subprocess.run([exe, "guilds"], env=env, capture_output=True,
                           text=True, timeout=45)
    except (OSError, subprocess.SubprocessError):
        return False
    blob = (p.stdout + p.stderr).lower()
    if p.returncode != 0:
        return False
    if "token is invalid" in blob or "unauthorized" in blob or "401" in blob:
        return False
    return True


def first_run_setup(show: bool) -> str:
    banner()
    say(f" {c('subtle', ICON['mark'] + ' dcx')}  {c('muted', '│')}  "
        f"{c('text', 'first run — no token saved yet')}")
    token_guide()
    tok = read_token(show)
    info("checking the token with Discord…")
    if not token_is_valid(tok):
        die("Discord rejected that token. Re-check the copied value and run "
            "`dcx login` to try again.")
    save_token(tok)
    ok(f"token saved to {token_path()}")
    say()
    return tok


def do_login(args) -> str:
    """Explicit re-entry. This is the ONLY path (besides first run and
    --relogin) that prompts — a normal command never re-asks."""
    banner()
    token_guide()
    tok = read_token(args.show_token)
    info("checking the token with Discord…")
    if not token_is_valid(tok):
        die("Discord rejected that token — not saved.")
    save_token(tok)
    ok(f"token saved to {token_path()}")
    return tok


def resolve_token(args, *, need: bool = True) -> str | None:
    """Priority: --token, then $DISCORD_TOKEN, then the saved file. If none and
    a token is needed, run the first-run setup. --relogin forces a re-prompt."""
    if getattr(args, "relogin", False):
        return do_login(args)
    if getattr(args, "token", None):
        return args.token
    env = os.environ.get("DISCORD_TOKEN")
    if env:
        return env.strip()
    tok = stored_token()
    if tok:
        return tok
    if not need:
        return None
    return first_run_setup(args.show_token)


# ── driving DiscordChatExporter.Cli ─────────────────────────────────────────
def dce_env(tok: str) -> dict:
    env = os.environ.copy()
    env["DISCORD_TOKEN"] = tok            # env, never argv (out of `ps`)
    env["FUCK_RUSSIA"] = "true"           # the tool's own flag to mute its banner
    return env


FORMATS = {
    "json": "Json", "html": "HtmlDark", "htmldark": "HtmlDark", "dark": "HtmlDark",
    "htmllight": "HtmlLight", "light": "HtmlLight",
    "csv": "Csv", "txt": "PlainText", "text": "PlainText", "plaintext": "PlainText",
}
FMT_EXT = {"Json": ".json", "HtmlDark": ".html", "HtmlLight": ".html",
           "Csv": ".csv", "PlainText": ".txt"}


def parse_list(out: str) -> list[tuple[str, str]]:
    """Both `guilds` and `channels` print `<id> | <name>` (channels prefix the
    name with `Category / `). Anything without a leading numeric id is chatter."""
    rows = []
    for line in out.splitlines():
        if "|" not in line:
            continue
        left, _, right = line.partition("|")
        left, right = left.strip(), right.strip()
        if not re.fullmatch(r"\d+", left):
            continue
        rows.append((left, right))
    return rows


def list_guilds(tok: str) -> list[tuple[str, str]]:
    p = subprocess.run([dce_bin(), "guilds"], env=dce_env(tok),
                       capture_output=True, text=True)
    if p.returncode != 0:
        die("could not list servers — token expired? try `dcx login`\n"
            + "   " + (p.stderr.strip().splitlines() or [""])[-1])
    return parse_list(p.stdout)


def list_channels(tok: str, guild: str, include_vc: bool,
                  threads: str) -> list[tuple[str, str]]:
    cmd = [dce_bin(), "channels", "-g", guild,
           "--include-vc", "true" if include_vc else "false"]
    if threads != "None":
        cmd += ["--include-threads", threads]
    p = subprocess.run(cmd, env=dce_env(tok), capture_output=True, text=True)
    if p.returncode != 0:
        die("could not list channels for that server\n"
            + "   " + (p.stderr.strip().splitlines() or [""])[-1])
    return parse_list(p.stdout)


def list_dms(tok: str) -> list[tuple[str, str]]:
    p = subprocess.run([dce_bin(), "dm"], env=dce_env(tok),
                       capture_output=True, text=True)
    if p.returncode != 0:
        die("could not list DM channels\n"
            + "   " + (p.stderr.strip().splitlines() or [""])[-1])
    return parse_list(p.stdout)


# ── the live spinner ────────────────────────────────────────────────────────
class Spinner:
    """One self-redrawing line: a shimmering glyph, a label, an elapsed clock.

    It owns exactly one screen line and never scrolls. Persistent output (the
    per-channel result lines) is printed by the caller BETWEEN spinners, so the
    finished list grows above while a single live line sits at the bottom.
    """

    def __init__(self, label: str, enabled: bool):
        self.label = label
        self.enabled = enabled and COLOR
        self.start = time.monotonic()
        self._stop = threading.Event()
        self._thread: threading.Thread | None = None

    def start_ui(self) -> None:
        if not self.enabled:
            say(f" {c('iris', ICON['dot'])} {c('subtle', self.label)}")
            return
        sys.stderr.write(HIDE)
        self._thread = threading.Thread(target=self._loop, daemon=True)
        self._thread.start()

    def stop_ui(self) -> None:
        self._stop.set()
        if self._thread:
            self._thread.join(timeout=1.0)
        if self.enabled:
            sys.stderr.write(CLEAR + SHOW)
            sys.stderr.flush()

    def _loop(self) -> None:
        frame = 0
        while not self._stop.is_set():
            self._draw(frame / FPS)
            frame += 1
            self._stop.wait(1 / FPS)

    def _draw(self, t: float) -> None:
        width = shutil.get_terminal_size((80, 20)).columns
        elapsed = clock(time.monotonic() - self.start)
        tag = spin_glyph(t)
        right = c("muted", elapsed)
        note = c("gold", "exporting")
        fixed = 3 + vlen(note) + vlen(right) + 6
        label = truncate(self.label, max(6, width - fixed))
        line = f" {tag} {c('text', label)}  {note} {c('muted', ICON['dot'])} {right}"
        sys.stderr.write(CLEAR + line)
        sys.stderr.flush()


# ── one export ──────────────────────────────────────────────────────────────
def _json_msgcount(path: str) -> int | None:
    """DCE's JSON puts `messageCount` at the very end, so a small tail read
    gets it without loading a multi-gigabyte file."""
    try:
        with open(path, "rb") as f:
            f.seek(0, os.SEEK_END)
            size = f.tell()
            f.seek(max(0, size - 4096))
            tail = f.read().decode("utf-8", "replace")
    except OSError:
        return None
    m = re.search(r'"messageCount":\s*(\d+)', tail)
    return int(m.group(1)) if m else None


def _last_meaningful(log: str) -> str:
    for line in reversed(log.strip().splitlines()):
        s = _ANSI.sub("", line).strip()
        if s and not s.startswith("DiscordChatExporter"):
            return s[:80]
    return "no output"


def export_one(tok: str, chan_id: str, label: str, outdir: str,
               fmt: str, opts) -> dict:
    """Export a single channel behind a spinner, then leave one result line.

    Returns a dict with keys: status (ok|empty|fail), msgs, bytes, secs, file.
    """
    os.makedirs(outdir, exist_ok=True)
    disp = re.sub(r"\s+", " ", label).strip()
    cmd = [dce_bin(), "export", "-c", chan_id, "-f", fmt,
           "-o", outdir + os.sep]
    if opts.after:
        cmd += ["--after", opts.after]
    if opts.before:
        cmd += ["--before", opts.before]
    if opts.threads != "None":
        cmd += ["--include-threads", opts.threads]
    if opts.media:
        cmd += ["--media", "--reuse-media"]
    if opts.partition:
        cmd += ["-p", opts.partition]

    if opts.dry_run:
        say("   " + c("muted", " ".join(cmd)))
        return {"status": "dry", "msgs": 0, "bytes": 0, "secs": 0, "file": ""}

    start_wall = time.time()
    sp = Spinner(disp, not (opts.raw or opts.dry_run))
    sp.start_ui()
    try:
        p = subprocess.run(cmd, env=dce_env(tok), capture_output=True, text=True)
    finally:
        sp.stop_ui()
    log = p.stdout + "\n" + p.stderr
    took = time.time() - start_wall

    # Which files did this export write? New OR freshly-modified, so a re-export
    # that overwrites the same name is still detected.
    outputs = []
    try:
        for name in os.listdir(outdir):
            fp = os.path.join(outdir, name)
            if os.path.isfile(fp) and os.path.getmtime(fp) >= start_wall - 1:
                outputs.append(fp)
    except OSError:
        pass

    room = 26
    name_col = truncate(disp, room).ljust(room)

    if not outputs:
        # No file written. DCE says as much for an empty channel; anything else
        # is a genuine failure worth surfacing.
        low = log.lower()
        if p.returncode == 0 or "does not contain any messages" in low:
            say(f" {c('muted', ICON['skip'])} {c('subtle', name_col)}"
                f"{c('muted', 'empty')}")
            return {"status": "empty", "msgs": 0, "bytes": 0, "secs": took,
                    "file": ""}
        say(f" {c('love', ICON['bad'])} {c('text', name_col)}"
            f"{c('love', _last_meaningful(log))}")
        return {"status": "fail", "msgs": 0, "bytes": 0, "secs": took,
                "file": ""}

    main = max(outputs, key=os.path.getsize)
    total_bytes = sum(os.path.getsize(f) for f in outputs)
    msgs = _json_msgcount(main) if main.endswith(".json") else None
    fname = os.path.basename(main)

    msg_part = (c("text", commafy(msgs) + " msgs") if msgs is not None
                else c("subtle", "done"))
    meta = c("muted", f"{human(total_bytes)} {ICON['dot']} {clock(took)}")
    media_note = ""
    if opts.media:
        media_dir = main.rsplit(".", 1)[0] + "_Files"
        if os.path.isdir(os.path.join(outdir, os.path.basename(media_dir))):
            media_note = c("muted", " +media")
    say(f" {c('foam', ICON['ok'])} {c('text', name_col)}{msg_part}  {meta}"
        f"  {c('subtle', ICON['arrow'] + ' ' + truncate(fname, 30))}{media_note}")
    return {"status": "ok", "msgs": msgs or 0, "bytes": total_bytes,
            "secs": took, "file": main}


def sanitize(name: str) -> str:
    name = re.sub(r"[^\w.\- ]", "_", name).strip()
    name = re.sub(r"\s+", " ", name)
    # A server or channel name is chosen by whoever owns it: "." or ".."
    # would put the export beside or above its own folder.
    if not name.strip("."):
        return "export"
    return name


def head(guild_label: str, fmt: str, outdir: str) -> None:
    if not COLOR:
        return
    banner()
    say(f" {c('subtle', ICON['mark'] + ' dcx')}  {c('muted', '│')}  "
        f"{c('foam', fmt)}  {c('muted', '│')}  "
        f"{c('text', truncate(guild_label, 26))}  {c('muted', ICON['arrow'])}  "
        f"{c('subtle', truncate(outdir, 30))}")
    say(" " + rule(52))


def run_exports(tok: str, targets: list[tuple[str, str]], outdir: str,
                fmt: str, opts) -> int:
    """targets = [(channel_id, label)]. Sequential, one spinner at a time."""
    if not targets:
        warn("nothing to export")
        return 0
    tally = {"ok": 0, "empty": 0, "fail": 0}
    total_msgs = total_bytes = 0
    started = time.monotonic()
    for cid, label in targets:
        r = export_one(tok, cid, label, outdir, fmt, opts)
        st = r["status"]
        if st == "dry":
            continue
        tally[st] = tally.get(st, 0) + 1
        total_msgs += r["msgs"]
        total_bytes += r["bytes"]

    if opts.dry_run:
        return 0

    say(" " + rule(52))
    took = clock(time.monotonic() - started)
    parts = [c("foam", f"{tally['ok']} exported")]
    if tally["empty"]:
        parts.append(c("muted", f"{tally['empty']} empty"))
    if tally["fail"]:
        parts.append(c("love", f"{tally['fail']} failed"))
    summary = c("muted", f"  {ICON['dot']}  ").join(parts)
    ok(f"{summary}  {c('muted', ICON['dot'])}  "
       f"{c('text', commafy(total_msgs) + ' msgs')}  {c('muted', ICON['dot'])}  "
       f"{c('text', human(total_bytes))}  {c('muted', ICON['dot'])}  "
       f"{c('muted', took)}")
    info(f"{ICON['arrow']} {outdir}")
    return 1 if tally["fail"] else 0


# ── modes ───────────────────────────────────────────────────────────────────
def do_guilds(args) -> int:
    tok = resolve_token(args)
    rows = list_guilds(tok)
    if COLOR and not args.raw:
        say(f" {c('iris', ICON['list'])} {c('text', 'servers')}  "
            f"{c('muted', str(len(rows)) + ' visible')}")
        say(" " + rule(52))
    for cid, name in rows:
        if COLOR and not args.raw:
            say(f"  {c('gold', cid)}  {c('text', name)}")
        else:
            print(f"{cid} | {name}")
    return 0


def do_channels(args) -> int:
    tok = resolve_token(args)
    if not args.guild:
        die("which server? usage: dcx channels GUILD_ID")
    rows = list_channels(tok, args.guild, not args.no_voice, args.threads)
    if COLOR and not args.raw:
        say(f" {c('iris', ICON['list'])} {c('text', 'channels')}  "
            f"{c('muted', str(len(rows)) + ' in server ' + args.guild)}")
        say(" " + rule(52))
    for cid, name in rows:
        if COLOR and not args.raw:
            say(f"  {c('gold', cid)}  {c('text', name)}")
        else:
            print(f"{cid} | {name}")
    return 0


def _guild_name(tok: str, guild: str) -> str:
    for gid, name in list_guilds(tok):
        if gid == guild:
            return name
    return guild


def do_guild(args) -> int:
    tok = resolve_token(args)
    if not args.guild:
        die("which server? usage: dcx guild GUILD_ID")
    fmt = FORMATS[args.format]
    gname = _guild_name(tok, args.guild)
    rows = list_channels(tok, args.guild, not args.no_voice, args.threads)
    if args.only:
        needle = args.only.lower()
        rows = [(i, n) for i, n in rows if needle in n.lower()]
    outdir = args.output or os.path.join(default_output(), sanitize(gname))
    head(gname, fmt, outdir)
    info(f"{len(rows)} channel(s) to export")
    say(" " + rule(52))
    return run_exports(tok, rows, outdir, fmt, args)


def do_channel(args) -> int:
    tok = resolve_token(args)
    if not args.ids:
        die("which channel? usage: dcx channel CHANNEL_ID [CHANNEL_ID…]")
    fmt = FORMATS[args.format]
    outdir = args.output or default_output()
    head(f"{len(args.ids)} channel(s)", fmt, outdir)
    say(" " + rule(52))
    targets = [(cid, cid) for cid in args.ids]
    return run_exports(tok, targets, outdir, fmt, args)


def do_dm(args) -> int:
    tok = resolve_token(args)
    fmt = FORMATS[args.format]
    rows = list_dms(tok)
    outdir = args.output or os.path.join(default_output(), "Direct Messages")
    head("Direct Messages", fmt, outdir)
    info(f"{len(rows)} DM channel(s) to export")
    say(" " + rule(52))
    return run_exports(tok, rows, outdir, fmt, args)


def do_guide(args) -> int:
    banner()
    token_guide()
    say()
    info("the exporter also has its own: DiscordChatExporter.Cli guide")
    return 0


def do_login_cmd(args) -> int:
    do_login(args)
    return 0


# ── argument grammar ────────────────────────────────────────────────────────
EPILOG = f"""\
commands
  guilds                     list the servers your account can see
  channels GUILD_ID          list a server's channels (id | category / name)
  guild    GUILD_ID          export every text channel in a server
  channel  CHAN_ID [CHAN_ID…]  export one or more channels by id
  dm                         export every direct-message channel
  login                      re-enter and re-save the token
  guide                      how to obtain a token / server / channel ID

formats (-f)
  json (default)  best for archiving and analysis; message counts shown live
  html            HtmlDark   ·   light  HtmlLight   ·   csv   ·   txt

the token
  Read once on first use, saved to {token_path()} (0600), then never asked
  again. Force a fresh one with `dcx login` or --relogin on any command. It is
  handed to the exporter through $DISCORD_TOKEN, never on the command line.

examples
  dcx guilds                                 which servers can I see?
  dcx channels 000000000000000000            list that server's channels
  dcx guild 000000000000000000               archive the whole server (json)
  dcx guild 000000000000000000 -f html --media   readable, with attachments
  dcx channel 111 222 -o ~/chats/            two channels into a chosen dir
  dcx dm                                      back up every DM
  dcx guild 000 --only general -n            preview which channels would run
"""


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="dcx", allow_abbrev=False,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="Discord chat export — themed, quiet, and it remembers your token.",
        epilog=EPILOG)
    p.add_argument("command", nargs="?", help="guilds | channels | guild | "
                   "channel | dm | login | guide")
    p.add_argument("args", nargs="*", help="ids for the command")

    p.add_argument("-f", "--format", default="json",
                   type=lambda s: s.lower(),
                   choices=sorted(FORMATS.keys()),
                   help="export format (default: json)")
    p.add_argument("-o", "--output", metavar="DIR", help="output directory")
    p.add_argument("--after", metavar="DATE|ID", help="only messages after this")
    p.add_argument("--before", metavar="DATE|ID", help="only messages before this")
    p.add_argument("--media", action="store_true",
                   help="also download attachments/avatars (reused when present)")
    p.add_argument("-p", "--partition", metavar="N|SIZE",
                   help="split output every N messages or SIZE (e.g. 100 / 10mb)")
    p.add_argument("--threads", default="none",
                   type=lambda s: {"none": "None", "active": "Active",
                                   "all": "All"}.get(s.lower(), s),
                   choices=["None", "Active", "All"],
                   help="include threads: none (default) | active | all")
    p.add_argument("--no-voice", action="store_true",
                   help="skip voice channels when exporting a whole server")
    p.add_argument("--only", metavar="SUBSTR",
                   help="server export: only channels whose name contains SUBSTR")

    p.add_argument("-t", "--token", metavar="TOKEN",
                   help="use this token for one run (not saved). It is visible to "
                        "every local user in `ps` while dcx runs; prefer "
                        "DISCORD_TOKEN=… or the saved/sops token")
    p.add_argument("--relogin", action="store_true",
                   help="re-prompt for a token and save it before running")
    p.add_argument("--show-token", action="store_true",
                   help="echo the token as you type instead of masking it")

    p.add_argument("-n", "--dry-run", action="store_true",
                   help="print the exporter commands, run nothing")
    p.add_argument("--raw", action="store_true", help="no banner, no animation")
    p.add_argument("--version", action="version", version=f"dcx {VERSION}")
    return p


DISPATCH = {
    "guilds": do_guilds, "channels": do_channels, "guild": do_guild,
    "channel": do_channel, "dm": do_dm, "login": do_login_cmd, "guide": do_guide,
}


def main(argv: list[str]) -> int:
    global COLOR
    parser = build_parser()
    args = parser.parse_args(argv)
    COLOR = color_ok() and not args.raw

    cmd = args.command
    if cmd is None:
        banner()
        say()
        parser.print_help()
        return 0

    # `channels`/`guild` take one id in `command`'s slot only if the user typed
    # it as a positional; wire the first positional to the right field.
    args.guild = None
    args.ids = list(args.args)
    if cmd in ("channels", "guild") and args.ids:
        args.guild = args.ids[0]

    handler = DISPATCH.get(cmd)
    if handler is None:
        die(f"unknown command {cmd!r} — try: {', '.join(DISPATCH)}")
    return handler(args)


if __name__ == "__main__":
    if hasattr(signal, "SIGPIPE"):
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    try:
        sys.exit(main(sys.argv[1:]))
    except KeyboardInterrupt:
        sys.stderr.write(SHOW + RESET + "\n")
        say(f" {c('love', ICON['bad'])} interrupted")
        sys.exit(130)
    except BrokenPipeError:
        sys.exit(0)