Users: totals, a card per person, bridge groups, search, sign out
The Users screen gets a strip of totals (people, active in 30 days, admins, new, rooms, media, bridged accounts) and a list with an activity dot and how long ago each person was seen. The selected person opens into a card: last seen, joined, sessions, rooms, media, email, picture, flags (admin, deactivated, locked, shadow-banned) and their actions as chips. On a wide terminal the card sits beside the list. The admin script now counts rooms and devices for each person (up to 300), reads per-user media statistics and the server's room total, and matches accounts against the appservice registrations in homeserver.yaml, so bridge puppets and bots fold into a group per bridge. New keys: / search, f filter (admins, active, inactive, deactivated), o sort (last seen, name, joined, media), s sign out everywhere (MAS: kill-sessions; otherwise every device but interzone's own is removed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
86eceb964a
commit
bbf37a50d3
18 files changed
+1395
-362
No files matched your search
@@ -180,9 +180,16 @@ Need help, found a bug, or just like the project? Join the Matrix space
|
||||
- **Scheduled backups:** a systemd timer on the server dumps the database
|
||||
by itself (`/matrix/interzone-backups`, keeping the newest N);
|
||||
download them for Restore.
|
||||
- **Users** (Synapse): list accounts, reset passwords, grant or remove
|
||||
admin rights, deactivate and reactivate, through the admin API from
|
||||
inside the Synapse container. Nothing needs to be exposed publicly.
|
||||
- **Users** (Synapse): totals at the top (people, active in the last
|
||||
30 days, admins, new, rooms, media), then everyone with how recently
|
||||
they were seen; the one selected opens into a card with when they
|
||||
joined, their sessions, rooms, uploaded media, email and picture.
|
||||
Bridges' puppets and bots are folded into a group per bridge. `/`
|
||||
searches, `f` filters (admins, active, inactive, deactivated) and `o`
|
||||
sorts (last seen, name, joined, media). Reset passwords, grant or
|
||||
remove admin rights, sign someone out everywhere, deactivate and
|
||||
reactivate, through the admin API from inside the Synapse container.
|
||||
Nothing needs to be exposed publicly.
|
||||
With MAS (Matrix Authentication Service), accounts are changed with
|
||||
`mas-cli` in its container instead, and signing in needs only the
|
||||
admin's username: MAS issues the session.
|
||||
|
||||
+144
-13
@@ -23,6 +23,30 @@ type MatrixUser struct {
|
||||
Deactivated bool
|
||||
Created time.Time
|
||||
LastSeen time.Time
|
||||
|
||||
// Bridge is the appservice the account belongs to (a bridge's puppet
|
||||
// or bot), "" for a person. Bot marks the appservice's own account.
|
||||
Bridge string
|
||||
Bot bool
|
||||
// Rooms and Devices are -1 when they weren't counted (an appservice
|
||||
// account, or more people than are worth asking about).
|
||||
Rooms, Devices int
|
||||
MediaCount int
|
||||
MediaBytes int64
|
||||
Emails []string // and phone numbers
|
||||
Type string // Synapse's user_type: "", "bot" or "support"
|
||||
Locked bool
|
||||
ShadowBanned bool
|
||||
Avatar bool
|
||||
}
|
||||
|
||||
// Person reports whether the account is someone's, not a bridge's.
|
||||
func (u MatrixUser) Person() bool { return u.Bridge == "" }
|
||||
|
||||
// UserList is everyone on the server, with a few totals.
|
||||
type UserList struct {
|
||||
Users []MatrixUser
|
||||
Rooms int // rooms the server knows of, -1 if it didn't say
|
||||
}
|
||||
|
||||
// AdminLogin is the account interzone signs in as to administer users.
|
||||
@@ -63,6 +87,27 @@ def login():
|
||||
if req.get("mas"):
|
||||
raise Failed({"error": "the session was refused", "errcode": "M_UNKNOWN_TOKEN", "path": "/token"})
|
||||
return call("POST", "/_matrix/client/v3/login", {"type": "m.login.password", "identifier": {"type": "m.id.user", "user": req["admin"]}, "password": req["password"], "initial_device_display_name": "interzone"})["access_token"]
|
||||
def total(path, user, tok):
|
||||
try:
|
||||
return call("GET", path % urllib.parse.quote(user), token=tok).get("total", -1)
|
||||
except Failed:
|
||||
return -1
|
||||
def appservices():
|
||||
# The bridges' registrations name the accounts they own.
|
||||
out = []
|
||||
try:
|
||||
import re, yaml
|
||||
cfg = yaml.safe_load(open("/data/homeserver.yaml"))
|
||||
for path in cfg.get("app_service_config_files") or []:
|
||||
try:
|
||||
reg = yaml.safe_load(open(path))
|
||||
regexes = [re.compile(n["regex"]) for n in (reg.get("namespaces") or {}).get("users") or [] if n.get("regex")]
|
||||
out.append((str(reg.get("id", path)), str(reg.get("sender_localpart", "")), regexes))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
def run(tok):
|
||||
if req["op"] == "logout":
|
||||
call("POST", "/_matrix/client/v3/logout", {}, token=tok)
|
||||
@@ -73,7 +118,49 @@ def run(tok):
|
||||
page = call("GET", "/_synapse/admin/v2/users?guests=false&deactivated=true&limit=500&from=" + urllib.parse.quote(str(frm)), token=tok)
|
||||
users += page.get("users", [])
|
||||
frm = page.get("next_token")
|
||||
return {"users": users}
|
||||
services = appservices()
|
||||
people = 0
|
||||
for u in users:
|
||||
u["appservice"], u["bot"] = "", False
|
||||
local = u["name"][1:].split(":", 1)[0]
|
||||
for sid, sender, regexes in services:
|
||||
if local == sender or any(r.match(u["name"]) for r in regexes):
|
||||
u["appservice"], u["bot"] = sid, local == sender
|
||||
break
|
||||
if u["appservice"] or people >= 300:
|
||||
continue
|
||||
people += 1
|
||||
u["rooms"] = total("/_synapse/admin/v1/users/%s/joined_rooms", u["name"], tok)
|
||||
u["devices"] = total("/_synapse/admin/v2/users/%s/devices", u["name"], tok)
|
||||
try:
|
||||
d = call("GET", "/_synapse/admin/v2/users/" + urllib.parse.quote(u["name"]), token=tok)
|
||||
u["threepids"] = [t.get("address", "") for t in d.get("threepids") or []]
|
||||
except Failed:
|
||||
pass
|
||||
media, frm = {}, "0"
|
||||
try:
|
||||
while frm is not None:
|
||||
page = call("GET", "/_synapse/admin/v1/statistics/users/media?limit=500&from=" + urllib.parse.quote(str(frm)), token=tok)
|
||||
for m in page.get("users", []):
|
||||
media[m["user_id"]] = [m.get("media_count", 0), m.get("media_length", 0)]
|
||||
frm = page.get("next_token")
|
||||
except Failed:
|
||||
pass
|
||||
for u in users:
|
||||
u["media"] = media.get(u["name"], [0, 0])
|
||||
rooms = -1
|
||||
try:
|
||||
rooms = call("GET", "/_synapse/admin/v1/rooms?limit=1", token=tok).get("total_rooms", -1)
|
||||
except Failed:
|
||||
pass
|
||||
return {"users": users, "rooms": rooms}
|
||||
if req["op"] == "logout_all":
|
||||
me = call("GET", "/_matrix/client/v3/account/whoami", token=tok).get("device_id")
|
||||
path = "/_synapse/admin/v2/users/" + urllib.parse.quote(req["user"])
|
||||
devices = [d["device_id"] for d in call("GET", path + "/devices", token=tok).get("devices", []) if d["device_id"] != me]
|
||||
if devices:
|
||||
call("POST", path + "/delete_devices", {"devices": devices}, token=tok)
|
||||
return {"ok": True, "count": len(devices)}
|
||||
call("PUT", "/_synapse/admin/v2/users/" + urllib.parse.quote(req["user"]), req["body"], token=tok)
|
||||
return {"ok": True}
|
||||
try:
|
||||
@@ -173,8 +260,9 @@ func adminRun(ctx context.Context, c *config.Config, login *AdminLogin, req map[
|
||||
return json.RawMessage(out), e, nil
|
||||
}
|
||||
|
||||
// ListUsers returns every account on the server, deactivated ones included.
|
||||
func ListUsers(ctx context.Context, c *config.Config, login *AdminLogin) ([]MatrixUser, error) {
|
||||
// ListUsers returns every account on the server, deactivated ones
|
||||
// included, with what they use: rooms, sessions and media.
|
||||
func ListUsers(ctx context.Context, c *config.Config, login *AdminLogin) (*UserList, error) {
|
||||
out, err := adminCall(ctx, c, login, map[string]any{"op": "list"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -186,29 +274,72 @@ func ListUsers(ctx context.Context, c *config.Config, login *AdminLogin) ([]Matr
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return parseUsers(out, admins)
|
||||
}
|
||||
|
||||
// parseUsers reads the admin script's list; admins, if set, overrides who
|
||||
// is an admin.
|
||||
func parseUsers(out []byte, admins map[string]bool) (*UserList, error) {
|
||||
var v struct {
|
||||
Users []struct {
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"displayname"`
|
||||
Admin any `json:"admin"`
|
||||
Deactivated any `json:"deactivated"`
|
||||
Created int64 `json:"creation_ts"`
|
||||
LastSeen int64 `json:"last_seen_ts"`
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"displayname"`
|
||||
Admin any `json:"admin"`
|
||||
Deactivated any `json:"deactivated"`
|
||||
Created int64 `json:"creation_ts"`
|
||||
LastSeen int64 `json:"last_seen_ts"`
|
||||
Appservice string `json:"appservice"`
|
||||
Bot bool `json:"bot"`
|
||||
Rooms *int `json:"rooms"`
|
||||
Devices *int `json:"devices"`
|
||||
Media []int64 `json:"media"`
|
||||
Threepids []string `json:"threepids"`
|
||||
UserType string `json:"user_type"`
|
||||
Locked any `json:"locked"`
|
||||
ShadowBanned any `json:"shadow_banned"`
|
||||
Avatar string `json:"avatar_url"`
|
||||
} `json:"users"`
|
||||
Rooms *int `json:"rooms"`
|
||||
}
|
||||
if err := json.Unmarshal(out, &v); err != nil {
|
||||
return nil, fmt.Errorf("couldn't read the user list: %w", err)
|
||||
}
|
||||
users := make([]MatrixUser, 0, len(v.Users))
|
||||
list := &UserList{Users: make([]MatrixUser, 0, len(v.Users)), Rooms: -1}
|
||||
if v.Rooms != nil {
|
||||
list.Rooms = *v.Rooms
|
||||
}
|
||||
count := func(n *int) int {
|
||||
if n == nil {
|
||||
return -1
|
||||
}
|
||||
return *n
|
||||
}
|
||||
for _, u := range v.Users {
|
||||
admin := truthy(u.Admin)
|
||||
if admins != nil {
|
||||
admin = admins[localpart(u.Name)]
|
||||
}
|
||||
users = append(users, MatrixUser{ID: u.Name, DisplayName: u.DisplayName, Admin: admin,
|
||||
Deactivated: truthy(u.Deactivated), Created: msTime(u.Created), LastSeen: msTime(u.LastSeen)})
|
||||
mu := MatrixUser{ID: u.Name, DisplayName: u.DisplayName, Admin: admin,
|
||||
Deactivated: truthy(u.Deactivated), Created: msTime(u.Created), LastSeen: msTime(u.LastSeen),
|
||||
Bridge: u.Appservice, Bot: u.Bot, Rooms: count(u.Rooms), Devices: count(u.Devices),
|
||||
Emails: u.Threepids, Type: u.UserType, Locked: truthy(u.Locked), ShadowBanned: truthy(u.ShadowBanned), Avatar: u.Avatar != ""}
|
||||
if len(u.Media) == 2 {
|
||||
mu.MediaCount, mu.MediaBytes = int(u.Media[0]), u.Media[1]
|
||||
}
|
||||
list.Users = append(list.Users, mu)
|
||||
}
|
||||
return users, nil
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// SignOutEverywhere ends all of a user's sessions, leaving the password
|
||||
// alone. interzone's own session stays when it's the admin's.
|
||||
func SignOutEverywhere(ctx context.Context, c *config.Config, login *AdminLogin, userID string) error {
|
||||
if UsesMAS(c) {
|
||||
_, err := masRun(ctx, c, false, "kill-sessions", localpart(userID))
|
||||
return err
|
||||
}
|
||||
_, err := adminCall(ctx, c, login, map[string]any{"op": "logout_all", "user": userID})
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateUser changes an account: {"admin": true}, {"deactivated": true},
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package deploy
|
||||
|
||||
import "testing"
|
||||
|
||||
// The admin script's list: people with what they use, a bridge's bot and
|
||||
// puppet without, and the server's room count.
|
||||
func TestParseUsers(t *testing.T) {
|
||||
out := `{"users": [
|
||||
{"name": "@alice:example.org", "admin": 1, "displayname": "Alice", "creation_ts": 1700000000000, "last_seen_ts": 1761400000000,
|
||||
"avatar_url": "mxc://x", "appservice": "", "bot": false, "rooms": 27, "devices": 2, "threepids": ["alice@example.org"], "media": [142, 398458880]},
|
||||
{"name": "@bob:example.org", "admin": false, "deactivated": true, "locked": true, "appservice": "", "rooms": 0, "devices": 0, "media": [0, 0]},
|
||||
{"name": "@telegrambot:example.org", "appservice": "telegram", "bot": true, "media": [0, 0]},
|
||||
{"name": "@telegram_123:example.org", "appservice": "telegram", "user_type": "bot", "media": [3, 1024]}
|
||||
], "rooms": 31, "token": "t"}`
|
||||
list, err := parseUsers([]byte(out), map[string]bool{"bob": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Rooms != 31 || len(list.Users) != 4 {
|
||||
t.Fatalf("got %d rooms, %d users", list.Rooms, len(list.Users))
|
||||
}
|
||||
a, b, bot, puppet := list.Users[0], list.Users[1], list.Users[2], list.Users[3]
|
||||
if a.Admin || !b.Admin {
|
||||
t.Error("MAS's admins should override Synapse's flag")
|
||||
}
|
||||
if a.Rooms != 27 || a.Devices != 2 || a.MediaCount != 142 || a.MediaBytes != 398458880 || !a.Avatar || len(a.Emails) != 1 || !a.Person() {
|
||||
t.Errorf("alice: %+v", a)
|
||||
}
|
||||
if !b.Deactivated || !b.Locked {
|
||||
t.Errorf("bob: %+v", b)
|
||||
}
|
||||
if bot.Person() || !bot.Bot || bot.Rooms != -1 || bot.Devices != -1 {
|
||||
t.Errorf("the bridge bot: %+v", bot)
|
||||
}
|
||||
if puppet.Bridge != "telegram" || puppet.Bot || puppet.MediaCount != 3 || puppet.Type != "bot" {
|
||||
t.Errorf("the puppet: %+v", puppet)
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -49,8 +49,12 @@ func saveCache[T any](name string, data T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ago says how long ago t was, roughly: "just now", "5m ago", "3h ago".
|
||||
// ago says how long ago t was, roughly: "just now", "5m ago", "3h ago",
|
||||
// "4d ago", "3mo ago".
|
||||
func ago(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "never"
|
||||
}
|
||||
d := time.Since(t)
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
@@ -59,6 +63,10 @@ func ago(t time.Time) string {
|
||||
return fmt.Sprintf("%dm ago", int(d/time.Minute))
|
||||
case d < 48*time.Hour:
|
||||
return fmt.Sprintf("%dh ago", int(d/time.Hour))
|
||||
case d < 60*24*time.Hour:
|
||||
return fmt.Sprintf("%dd ago", int(d/(24*time.Hour)))
|
||||
case d < 365*24*time.Hour:
|
||||
return fmt.Sprintf("%dmo ago", int(d/(30*24*time.Hour)))
|
||||
}
|
||||
return fmt.Sprintf("%dd ago", int(d/(24*time.Hour)))
|
||||
return fmt.Sprintf("%dy ago", int(d/(365*24*time.Hour)))
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
var update = flag.Bool("update", false, "rewrite the layout golden files")
|
||||
|
||||
// stamp is vars.yml's generation time, zeroed before comparing.
|
||||
var stamp = regexp.MustCompile(`Generated by interzone on [0-9: -]*`)
|
||||
var stamp = regexp.MustCompile(`Generated by interzone on [0-9: -]*|\b[0-9]{4}-[0-9]{2}-[0-9]{2}( [0-9]{2}:[0-9]{2})?`)
|
||||
|
||||
var sizes = []struct{ w, h int }{{46, 40}, {120, 36}}
|
||||
|
||||
@@ -99,6 +99,13 @@ func TestLayout(t *testing.T) {
|
||||
}},
|
||||
{"dashboard", openDashboard},
|
||||
{"mirrors", openMirrors},
|
||||
{"users", openUsers},
|
||||
{"users-bridge", func(a *App) {
|
||||
openUsers(a)
|
||||
us := a.cur().(*usersScreen)
|
||||
us.open["telegram"] = true
|
||||
us.cursor = 5 // the Telegram heading
|
||||
}},
|
||||
}
|
||||
shootAll(t, sizes, shots)
|
||||
// A phone with its keyboard up.
|
||||
@@ -110,7 +117,7 @@ func TestLayoutWide(t *testing.T) {
|
||||
shootAll(t, []struct{ w, h int }{{180, 50}}, []struct {
|
||||
name string
|
||||
open func(a *App)
|
||||
}{{"dashboard", openDashboard}, {"mirrors", openMirrors}})
|
||||
}{{"dashboard", openDashboard}, {"mirrors", openMirrors}, {"users", openUsers}})
|
||||
}
|
||||
|
||||
func openDashboard(a *App) {
|
||||
@@ -138,6 +145,38 @@ func openDashboard(a *App) {
|
||||
ds.st, ds.loading = st, false
|
||||
}
|
||||
|
||||
func openUsers(a *App) {
|
||||
a.jump(a.index("Users"))
|
||||
us := a.cur().(*usersScreen)
|
||||
day := 24 * time.Hour
|
||||
at := func(d time.Duration) time.Time { return time.Now().Add(-d - time.Minute) }
|
||||
person := func(id, name string, seen, made time.Duration, rooms, devices, files int, mb int64) deploy.MatrixUser {
|
||||
u := deploy.MatrixUser{ID: id, DisplayName: name, Created: at(made), Rooms: rooms, Devices: devices, MediaCount: files, MediaBytes: mb << 20}
|
||||
if seen > 0 {
|
||||
u.LastSeen = at(seen)
|
||||
}
|
||||
return u
|
||||
}
|
||||
alice := person("@alice:example.org", "Alice Liddell", 2*time.Hour, 400*day, 27, 3, 142, 380)
|
||||
alice.Admin, alice.Avatar, alice.Emails = true, true, []string{"alice@example.org"}
|
||||
dave := person("@dave:example.org", "", 90*day, 300*day, 0, 0, 0, 0)
|
||||
dave.Deactivated = true
|
||||
bot := deploy.MatrixUser{ID: "@telegrambot:example.org", DisplayName: "Telegram bridge bot", Bridge: "telegram", Bot: true, Rooms: -1, Devices: -1, LastSeen: at(time.Hour)}
|
||||
puppet := func(id, name string) deploy.MatrixUser {
|
||||
return deploy.MatrixUser{ID: id, DisplayName: name, Bridge: "telegram", Rooms: -1, Devices: -1, MediaCount: 4, MediaBytes: 2 << 20}
|
||||
}
|
||||
us.list = &deploy.UserList{Rooms: 31, Users: []deploy.MatrixUser{
|
||||
alice,
|
||||
person("@bob:example.org", "Bob", 3*day, 200*day, 11, 1, 6, 12),
|
||||
person("@carol:example.org", "Carol", 45*day, 120*day, 4, 1, 0, 0),
|
||||
person("@eve:example.org", "", 0, 5*day, 0, 0, 0, 0),
|
||||
dave,
|
||||
bot, puppet("@telegram_1001:example.org", "Nikolai (Telegram)"), puppet("@telegram_1002:example.org", "Pavel (Telegram)"),
|
||||
{ID: "@whatsappbot:example.org", Bridge: "whatsapp", Bot: true, Rooms: -1, Devices: -1},
|
||||
}}
|
||||
us.busy = false
|
||||
}
|
||||
|
||||
func openMirrors(a *App) {
|
||||
a.jump(a.index("Mirrors"))
|
||||
ms := a.cur().(*mirrorsScreen)
|
||||
|
||||
@@ -150,7 +150,7 @@ func (s *usersScreen) click(id string) (tea.Cmd, bool) {
|
||||
if s.mode != usersList || s.busy {
|
||||
return nil, false
|
||||
}
|
||||
return listClick(id, &s.cursor, len(s.users), s.update)
|
||||
return listClick(id, &s.cursor, len(s.rows()), s.update)
|
||||
}
|
||||
|
||||
func (s *serversScreen) click(id string) (tea.Cmd, bool) {
|
||||
|
||||
@@ -462,342 +462,6 @@ func (s *backupsScreen) view(w, h int) string {
|
||||
return out
|
||||
}
|
||||
|
||||
// ── Users ──────────────────────────────────────────────────────────
|
||||
|
||||
type usersMsg struct {
|
||||
server string
|
||||
users []deploy.MatrixUser
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type userOpMsg struct {
|
||||
info string
|
||||
password string // shown once after a reset or a new account
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type userMode int
|
||||
|
||||
const (
|
||||
usersList userMode = iota
|
||||
usersLogin
|
||||
usersConfirm
|
||||
usersNew
|
||||
)
|
||||
|
||||
type userOp struct {
|
||||
desc string
|
||||
user string
|
||||
body map[string]any
|
||||
password string
|
||||
}
|
||||
|
||||
type usersScreen struct {
|
||||
cfg *config.Config
|
||||
server string // whose users are listed
|
||||
login deploy.AdminLogin
|
||||
users []deploy.MatrixUser
|
||||
cursor int
|
||||
mode userMode
|
||||
form *form
|
||||
op *userOp
|
||||
|
||||
busy bool
|
||||
err error
|
||||
info string
|
||||
password string
|
||||
spin spinner.Model
|
||||
}
|
||||
|
||||
func newUsersScreen() *usersScreen { return &usersScreen{spin: newSpinner()} }
|
||||
|
||||
func (s *usersScreen) tool() {}
|
||||
func (s *usersScreen) name() string { return "Users" }
|
||||
func (s *usersScreen) title() string { return "Users on " + s.cfg.Domain }
|
||||
func (s *usersScreen) typing() bool {
|
||||
return s.form != nil && (s.mode == usersLogin || s.mode == usersNew) && s.form.typing()
|
||||
}
|
||||
func (s *usersScreen) handlesEsc() bool { return s.mode != usersList }
|
||||
func (s *usersScreen) leave(*config.Config) {}
|
||||
func (s *usersScreen) keys() [][2]string {
|
||||
switch s.mode {
|
||||
case usersLogin:
|
||||
return [][2]string{{"tab/↑↓", "move"}, {"ctrl+r", "reveal"}, {"enter", "sign in"}, {"esc", "cancel"}}
|
||||
case usersNew:
|
||||
return [][2]string{{"tab/↑↓", "move"}, {"space", "toggle"}, {"ctrl+r", "reveal"}, {"enter", "create"}, {"esc", "cancel"}}
|
||||
case usersConfirm:
|
||||
return [][2]string{{"enter", "do it"}, {"esc", "cancel"}}
|
||||
}
|
||||
return [][2]string{{"↑↓", "select"}, {"n", "new"}, {"p", "reset password"}, {"a", "admin on/off"}, {"d", "deactivate"}, {"r", "reload"}}
|
||||
}
|
||||
|
||||
func (s *usersScreen) enter(c *config.Config) tea.Cmd {
|
||||
s.cfg = c
|
||||
s.login = deploy.AdminLogin{User: c.AdminUser, Password: c.AdminPassword, Token: c.AdminToken}
|
||||
s.mode, s.info, s.password, s.err = usersList, "", "", nil
|
||||
if srv := config.Active(); srv != s.server {
|
||||
s.server, s.users, s.cursor, s.busy = srv, nil, 0, false
|
||||
if users, _, ok := loadCache[[]deploy.MatrixUser]("users"); ok {
|
||||
s.users = users // shown while the fresh list loads
|
||||
}
|
||||
}
|
||||
return s.reload()
|
||||
}
|
||||
|
||||
func (s *usersScreen) reload() tea.Cmd {
|
||||
s.busy, s.err = true, nil
|
||||
cfg, login, srv := *s.cfg, s.login, s.server
|
||||
return tea.Batch(s.spin.Tick, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
users, err := deploy.ListUsers(ctx, &cfg, &login)
|
||||
return usersMsg{srv, users, login.Token, err}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *usersScreen) saveToken(t string) {
|
||||
s.login.Token = t
|
||||
if s.cfg.AdminToken != t {
|
||||
s.cfg.AdminToken = t
|
||||
_ = s.cfg.Save()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *usersScreen) loginForm() {
|
||||
if deploy.UsesMAS(s.cfg) {
|
||||
u := textField("user", "Admin username", s.login.User, "admin",
|
||||
"Your account on "+s.cfg.Domain+". Accounts live in MAS here, so no password is needed: interzone gets an admin session from MAS on the server.")
|
||||
s.form, s.mode = newForm(u), usersLogin
|
||||
return
|
||||
}
|
||||
u := textField("user", "Admin username", s.login.User, "admin", "An account with server-admin rights on "+s.cfg.Domain+".")
|
||||
pw := secretField("pass", "Password", "", "Only kept until interzone exits; the session it opens is saved.")
|
||||
s.form, s.mode = newForm(u, pw), usersLogin
|
||||
}
|
||||
|
||||
func (s *usersScreen) run(op *userOp) tea.Cmd {
|
||||
s.busy, s.info, s.password, s.err = true, "", "", nil
|
||||
cfg, login := *s.cfg, s.login
|
||||
return tea.Batch(s.spin.Tick, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
err := deploy.UpdateUser(ctx, &cfg, &login, op.user, op.body)
|
||||
return userOpMsg{info: op.desc, password: op.password, token: login.Token, err: err}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *usersScreen) update(msg tea.Msg) tea.Cmd {
|
||||
switch m := msg.(type) {
|
||||
case usersMsg:
|
||||
if m.server != s.server {
|
||||
return nil // from before switching servers
|
||||
}
|
||||
s.busy = false
|
||||
s.saveToken(m.token)
|
||||
if _, bad := m.err.(deploy.ErrAdminLogin); bad {
|
||||
s.err = m.err
|
||||
s.loginForm()
|
||||
return nil
|
||||
}
|
||||
s.err = m.err
|
||||
if m.err == nil {
|
||||
saveCache("users", m.users)
|
||||
s.users = m.users
|
||||
s.cursor = min(s.cursor, max(0, len(s.users)-1))
|
||||
}
|
||||
return nil
|
||||
case userOpMsg:
|
||||
s.busy = false
|
||||
s.saveToken(m.token)
|
||||
if _, bad := m.err.(deploy.ErrAdminLogin); bad {
|
||||
s.err = m.err
|
||||
s.loginForm()
|
||||
return nil
|
||||
}
|
||||
if m.err != nil {
|
||||
s.err = m.err
|
||||
return nil
|
||||
}
|
||||
s.info, s.password = "✓ "+m.info, m.password
|
||||
return s.reload()
|
||||
case spinner.TickMsg:
|
||||
return spinning(s.busy, &s.spin, m)
|
||||
case formDoneMsg:
|
||||
switch s.mode {
|
||||
case usersLogin:
|
||||
s.login.User, s.login.Password, s.login.Token = s.form.value("user"), s.form.value("pass"), ""
|
||||
if s.cfg.AdminUser == "" && s.login.User != "" {
|
||||
s.cfg.AdminUser = s.login.User // offered next time
|
||||
_ = s.cfg.Save()
|
||||
}
|
||||
s.mode = usersList
|
||||
return s.reload()
|
||||
case usersNew:
|
||||
return s.create()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
k, ok := msg.(tea.KeyMsg)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if k.String() == "esc" && s.mode != usersList {
|
||||
s.mode, s.op = usersList, nil
|
||||
return nil
|
||||
}
|
||||
switch s.mode {
|
||||
case usersLogin, usersNew:
|
||||
return s.form.Update(msg)
|
||||
case usersConfirm:
|
||||
switch {
|
||||
case (k.String() == "y" || k.String() == "enter") && s.op != nil:
|
||||
op := s.op
|
||||
s.mode, s.op = usersList, nil
|
||||
return s.run(op)
|
||||
case k.String() == "n":
|
||||
s.mode, s.op = usersList, nil
|
||||
case cursorKey(k.String(), s.cursor, len(s.users)) != s.cursor: // moving away cancels
|
||||
s.mode, s.op = usersList, nil
|
||||
s.cursor = cursorKey(k.String(), s.cursor, len(s.users))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
s.cursor = cursorKey(k.String(), s.cursor, len(s.users))
|
||||
if s.busy {
|
||||
return nil
|
||||
}
|
||||
var u deploy.MatrixUser
|
||||
if s.cursor < len(s.users) {
|
||||
u = s.users[s.cursor]
|
||||
}
|
||||
ask := func(op *userOp) tea.Cmd {
|
||||
s.op, s.mode = op, usersConfirm
|
||||
return nil
|
||||
}
|
||||
switch k.String() {
|
||||
case "r":
|
||||
return s.reload()
|
||||
case "n":
|
||||
name := textField("name", "Username", "", "alice", "Just the name, not @alice:"+s.cfg.Domain+".")
|
||||
name.required = true
|
||||
pw := secretField("pass", "Password", config.RandomPassword(16), "Generated for you; shown once the account exists.")
|
||||
pw.required = true
|
||||
s.form, s.mode = newForm(name, pw, toggleField("admin", "Make this user a server administrator", false, "")), usersNew
|
||||
case "p":
|
||||
if u.ID != "" {
|
||||
pw := config.RandomPassword(16)
|
||||
return ask(&userOp{desc: "new password set for " + u.ID + "; their devices were signed out", user: u.ID,
|
||||
body: map[string]any{"password": pw, "logout_devices": true}, password: pw})
|
||||
}
|
||||
case "a":
|
||||
if u.ID != "" && !u.Deactivated {
|
||||
verb := "Make " + u.ID + " a server administrator"
|
||||
if u.Admin {
|
||||
verb = "Remove " + u.ID + "'s administrator rights"
|
||||
}
|
||||
return ask(&userOp{desc: strings.ToLower(verb[:1]) + verb[1:] + ": done", user: u.ID, body: map[string]any{"admin": !u.Admin}})
|
||||
}
|
||||
case "d":
|
||||
if u.ID == "" {
|
||||
break
|
||||
}
|
||||
if u.Deactivated && deploy.UsesMAS(s.cfg) {
|
||||
return ask(&userOp{desc: u.ID + " reactivated with their old password", user: u.ID, body: map[string]any{"deactivated": false}})
|
||||
}
|
||||
if u.Deactivated {
|
||||
pw := config.RandomPassword(16)
|
||||
return ask(&userOp{desc: u.ID + " reactivated", user: u.ID, body: map[string]any{"deactivated": false, "password": pw}, password: pw})
|
||||
}
|
||||
return ask(&userOp{desc: u.ID + " deactivated", user: u.ID, body: map[string]any{"deactivated": true}})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *usersScreen) create() tea.Cmd {
|
||||
name := strings.ToLower(strings.TrimPrefix(strings.SplitN(s.form.value("name"), ":", 2)[0], "@"))
|
||||
pw := s.form.value("pass")
|
||||
if name == "" || pw == "" {
|
||||
return nil
|
||||
}
|
||||
id := "@" + name + ":" + s.cfg.Domain
|
||||
for _, u := range s.users {
|
||||
if u.ID == id {
|
||||
s.err, s.mode = fmt.Errorf("%s already exists", id), usersList
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.mode = usersList
|
||||
return s.run(&userOp{desc: id + " created", user: id,
|
||||
body: map[string]any{"password": pw, "admin": s.form.get("admin").on}, password: pw})
|
||||
}
|
||||
|
||||
func (s *usersScreen) view(w, h int) string {
|
||||
switch s.mode {
|
||||
case usersLogin:
|
||||
head := sWarn.Render("Signing in as "+s.login.User+" didn't work") + "\n" + sMuted.Render(errString(s.err)) + "\n\n"
|
||||
if s.login.User == "" {
|
||||
head = sSub.Render("Which account should interzone act as?") + "\n\n"
|
||||
}
|
||||
return head + s.form.View(w, h-4)
|
||||
case usersNew:
|
||||
return s.form.View(w, h)
|
||||
}
|
||||
var status []string
|
||||
switch {
|
||||
case s.busy:
|
||||
status = append(status, s.spin.View()+sMuted.Render(" talking to Synapse on the server…"))
|
||||
case s.err != nil:
|
||||
status = append(status, sBad.Render("✗ "+s.err.Error()))
|
||||
case s.info != "":
|
||||
status = append(status, sGood.Render(s.info))
|
||||
}
|
||||
if s.password != "" {
|
||||
status = append(status, sMuted.Render("Password ")+sTitle.Render(s.password)+sMuted.Render(" (shown once; it isn't saved)"))
|
||||
}
|
||||
foot := strings.Join(status, "\n")
|
||||
if s.mode == usersConfirm && s.op != nil {
|
||||
foot = confirmView(w, sWarn.Render(strings.ToUpper(s.op.desc[:1])+s.op.desc[1:]+"?"), "",
|
||||
keyLink("enter")+sMuted.Render(" yes ")+keyLink("esc")+sMuted.Render(" cancel"))
|
||||
if s.op.body["deactivated"] == true {
|
||||
foot = confirmView(w, sWarn.Render("Deactivate "+s.op.user+"?"),
|
||||
sSub.Render("They are signed out everywhere and can't sign in again until reactivated."), "",
|
||||
keyLink("enter")+sMuted.Render(" deactivate ")+keyLink("esc")+sMuted.Render(" cancel"))
|
||||
}
|
||||
}
|
||||
if len(s.users) == 0 {
|
||||
return foot
|
||||
}
|
||||
idW := 18
|
||||
for _, u := range s.users {
|
||||
idW = max(idW, min(48, len(u.ID)+2))
|
||||
}
|
||||
var rows []string
|
||||
for _, u := range s.users {
|
||||
badge := ""
|
||||
if u.Admin {
|
||||
badge += sPink.Render(" admin")
|
||||
}
|
||||
if u.Deactivated {
|
||||
badge += sBad.Render(" deactivated")
|
||||
}
|
||||
seen := "never seen"
|
||||
if !u.LastSeen.IsZero() {
|
||||
seen = "seen " + u.LastSeen.Local().Format("2006-01-02")
|
||||
}
|
||||
idStyle := sTitle
|
||||
if u.Deactivated {
|
||||
idStyle = sFaint
|
||||
}
|
||||
rows = append(rows, lipgloss.NewStyle().Width(idW).Render(idStyle.Render(u.ID))+
|
||||
lipgloss.NewStyle().Width(26).Render(sMuted.Render(truncate(u.DisplayName, 24)))+
|
||||
lipgloss.NewStyle().Width(22).Render(sFaint.Render(seen))+badge)
|
||||
}
|
||||
head := sMuted.Render(fmt.Sprintf("%d accounts", len(s.users)))
|
||||
return head + "\n\n" + listRows(rows, s.cursor, max(3, h-lipgloss.Height(foot)-4), w) + "\n\n" + foot
|
||||
}
|
||||
|
||||
func errString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
│ ││ │ Memory ███████████████░░░░░░░░░ 5.0 GB / 8.0 GB │ │
|
||||
│ ││ │ Swap ████████████░░░░░░░░░░░░ 1.0 GB / 2.0 GB │ │
|
||||
│ ││ │ Disk / ███████████████████░░░░░ 18.0 GB free / 80.0 GB │ │
|
||||
│ ││ │ Next backup Tue 2026-10-27 03:00:00 UTC │ │
|
||||
│ ││ │ Next backup Tue 0000-00-00 00:00:00 UTC │ │
|
||||
│ ││ ╰────────────────────────────────────────────────────────────────────────────────────╯ │
|
||||
│ ││ ╭────────────────────────────────────────────────────────────────────────────────────╮ │
|
||||
│ ││ │ Heaviest containers use 5% of 4 cores │ │
|
||||
|
||||
+3
-3
@@ -16,12 +16,12 @@
|
||||
│ ││ │ Memory ███████████████░░░░░░░░░ 5.0 GB / 8.0 GB │ │ synapse ██████████████ 7.6% 4.10% │ │
|
||||
│ ▸ Mirrors ││ │ Swap ████████████░░░░░░░░░░░░ 1.0 GB / 2.0 GB │ │ postgres █████░░░░░░░░░ 2.7% 0.80% │ │
|
||||
│ ││ │ Disk / ███████████████████░░░░░ 18.0 GB free / 80.0 GB │ │ traefik █░░░░░░░░░░░░░ 0.7% 0.20% │ │
|
||||
│ ▾ Servers ││ │ Next backup Tue 2026-10-27 03:00:00 UTC │ │ │ │
|
||||
│ ▾ Servers ││ │ Next backup Tue 0000-00-00 00:00:00 UTC │ │ │ │
|
||||
│ ● example.org ││ ╰──────────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────────╯ │
|
||||
│ ││ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
|
||||
│ ││ │ Certificates │ │
|
||||
│ ││ │ ✓ Synapse matrix.example.org 60 days until 2026-12-25 · R11 │ │
|
||||
│ ││ │ ! Element Web element.example.org 12 days until 2026-11-07 · R11 │ │
|
||||
│ ││ │ ✓ Synapse matrix.example.org 60 days until 0000-00-00 · R11 │ │
|
||||
│ ││ │ ! Element Web element.example.org 12 days until 0000-00-00 · R11 │ │
|
||||
│ ││ │ ✗ Cinny chat.other.net connection refused │ │
|
||||
│ ││ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
|
||||
│ ││ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
│ Memory ████░░ 5.0 GB / 8.0 GB │
|
||||
│ Swap ███░░░ 1.0 GB / 2.0 GB │
|
||||
│ Disk / █████░ 18.0 GB free / 80.0 │
|
||||
│ Next backup Tue 2026-10-27 03:00:00 UTC │
|
||||
│ Next backup Tue 0000-00-00 00:00:00 UTC │
|
||||
╰──────────────────────────────────────────╯
|
||||
╭──────────────────────────────────────────╮
|
||||
│ Heaviest containers use 5% of 4 cores │
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
◢◤ interzone matrix, deployed anywhere ONLINE
|
||||
╭────────────────────────╮╭────────────────────────────────────────────────────────────────────────────────────────────╮
|
||||
│ ▸ Setup ││ │
|
||||
│ ││ Users on example.org │
|
||||
│ ▾ Manage example.org ││ │
|
||||
│ ⌂ Overview ││ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭────────────╮ │
|
||||
│ ▌ @ Users ││ │ 4 │ │ 2 │ │ 1 │ │ 1 │ │ 31 │ │ 396 MB │ │ 4 │ │
|
||||
│ ▦ Dashboard ││ │ people │ │ active │ │ admin │ │ new │ │ rooms │ │ media │ │ bridged │ │
|
||||
│ ↻ Updates ││ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰────────────╯ │
|
||||
│ ◷ Backups ││ / search f everyone o by last seen │
|
||||
│ ↺ Restore ││ │
|
||||
│ ↶ Rollback ││ ▌ ● Alice Liddell admin 2h ago ╭────────────────────────────────────────────╮ │
|
||||
│ ✎ Fine-tune ││ ● Bob 3d ago │ ● Alice Liddell admin │ │
|
||||
│ ⇢ Move server ││ ● Carol 45d ago │ @alice:example.org │ │
|
||||
│ ▤ Servers ││ ○ eve never │ │ │
|
||||
│ ││ ⊘ dave deactivated │ Last seen 2h ago 0000-00-00 00:00 │ │
|
||||
│ ▸ Mirrors ││ ⇄ Telegram 3 accounts ▸ │ Joined 0000-00-00 1y ago │ │
|
||||
│ ││ ⇄ Whatsapp 1 account ▸ │ Sessions 3 devices │ │
|
||||
│ ▾ Servers ││ │ Rooms 27 │ │
|
||||
│ ● example.org ││ │ Media 380 MB 142 files │ │
|
||||
│ ││ │ Email alice@example.org │ │
|
||||
│ ││ │ Picture set │ │
|
||||
│ ││ │ │ │
|
||||
│ ││ │ p new password a remove admin │ │
|
||||
│ ││ │ s sign out everywhere d deactivate │ │
|
||||
│ ││ ╰────────────────────────────────────────────╯ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ◫ auto (wide) ctrl+l ││ │
|
||||
│ ◐ interzone ctrl+y ││ │
|
||||
│ ◂ fold ctrl+b ││ │
|
||||
╰────────────────────────╯╰────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
↑↓ select · / search · f filter · o sort · n new · p password · a admin · d deactivate · s sign out · r reload · esc ba
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
◢◤ interzone matrix, deployed anywhere ONLINE
|
||||
╭────────────────────────╮╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
|
||||
│ ▸ Setup ││ │
|
||||
│ ││ Users on example.org │
|
||||
│ ▾ Manage example.org ││ │
|
||||
│ ⌂ Overview ││ ╭──────────────────╮ ╭──────────────────╮ ╭──────────────────╮ ╭──────────────────╮ ╭──────────────────╮ ╭──────────────────╮ ╭──────────────────╮ │
|
||||
│ ▌ @ Users ││ │ 4 │ │ 2 │ │ 1 │ │ 1 │ │ 31 │ │ 396 MB │ │ 4 │ │
|
||||
│ ▦ Dashboard ││ │ people │ │ active (30 days) │ │ admin │ │ new (30 days) │ │ rooms │ │ media │ │ bridged │ │
|
||||
│ ↻ Updates ││ ╰──────────────────╯ ╰──────────────────╯ ╰──────────────────╯ ╰──────────────────╯ ╰──────────────────╯ ╰──────────────────╯ ╰──────────────────╯ │
|
||||
│ ◷ Backups ││ / search f everyone o by last seen │
|
||||
│ ↺ Restore ││ │
|
||||
│ ↶ Rollback ││ ▌ ● Alice Liddell admin 2h ago ╭──────────────────────────────────────────────────────────────────────────────────────╮ │
|
||||
│ ✎ Fine-tune ││ ● Bob 3d ago │ ● Alice Liddell admin │ │
|
||||
│ ⇢ Move server ││ ● Carol 45d ago │ @alice:example.org │ │
|
||||
│ ▤ Servers ││ ○ eve never │ │ │
|
||||
│ ││ ⊘ dave deactivated │ Last seen 2h ago 0000-00-00 00:00 │ │
|
||||
│ ▸ Mirrors ││ ⇄ Telegram 3 accounts ▸ │ Joined 0000-00-00 1y ago │ │
|
||||
│ ││ ⇄ Whatsapp 1 account ▸ │ Sessions 3 devices │ │
|
||||
│ ▾ Servers ││ │ Rooms 27 │ │
|
||||
│ ● example.org ││ │ Media 380 MB 142 files │ │
|
||||
│ ││ │ Email alice@example.org │ │
|
||||
│ ││ │ Picture set │ │
|
||||
│ ││ │ │ │
|
||||
│ ││ │ p new password a remove admin s sign out everywhere d deactivate │ │
|
||||
│ ││ ╰──────────────────────────────────────────────────────────────────────────────────────╯ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ◫ auto (wide) ctrl+l ││ │
|
||||
│ ◐ interzone ctrl+y ││ │
|
||||
│ ◂ fold ctrl+b ││ │
|
||||
╰────────────────────────╯╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
↑↓ select · / search · f filter · o sort · n new · p password · a admin · d deactivate · s sign out · r reload · esc back · ctrl+c quit
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
◢◤ ◆ Manage › Users
|
||||
Users on example.org
|
||||
|
||||
4 people 2 active 1 admin 1 new
|
||||
31 rooms 396 MB media 4 bridged
|
||||
/ search f everyone o by last seen
|
||||
|
||||
╭──────────────────────────────────────────╮
|
||||
│ ● Alice Liddell admin │
|
||||
│ @alice:example.org │
|
||||
│ │
|
||||
│ Last seen 2h ago 0000-00-00 00:00 │
|
||||
│ Joined 0000-00-00 1y ago │
|
||||
│ Sessions 3 devices │
|
||||
│ Rooms 27 │
|
||||
│ Media 380 MB 142 files │
|
||||
│ Email alice@example.org │
|
||||
│ Picture set │
|
||||
│ │
|
||||
│ p new password a remove admin │
|
||||
│ s sign out everywhere d deactivate │
|
||||
╰──────────────────────────────────────────╯
|
||||
● Bob 3d ago
|
||||
● Carol 45d ago
|
||||
○ eve never
|
||||
⊘ dave deactivated
|
||||
⇄ Telegram 3 accounts ▸
|
||||
⇄ Whatsapp 1 account ▸
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
‹ back ≡ menu ⋯
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
◢◤ ◆ Manage › Users
|
||||
Users on example.org
|
||||
4 people 2 active 1 admin 1 new
|
||||
/ search f everyone o by last seen
|
||||
▌ ● Alice Liddell admin 2h ago
|
||||
● Bob 3d ago
|
||||
● Carol 45d ago
|
||||
○ eve never
|
||||
⊘ dave deactivated
|
||||
⇄ Telegram 3 accounts ▸
|
||||
⇄ Whatsapp 1 account ▸
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
‹ back ≡ menu ⋯
|
||||
@@ -0,0 +1,36 @@
|
||||
◢◤ interzone matrix, deployed anywhere ONLINE
|
||||
╭────────────────────────╮╭────────────────────────────────────────────────────────────────────────────────────────────╮
|
||||
│ ▸ Setup ││ │
|
||||
│ ││ Users on example.org │
|
||||
│ ▾ Manage example.org ││ │
|
||||
│ ⌂ Overview ││ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭────────────╮ │
|
||||
│ ▌ @ Users ││ │ 4 │ │ 2 │ │ 1 │ │ 1 │ │ 31 │ │ 396 MB │ │ 4 │ │
|
||||
│ ▦ Dashboard ││ │ people │ │ active │ │ admin │ │ new │ │ rooms │ │ media │ │ bridged │ │
|
||||
│ ↻ Updates ││ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰────────────╯ │
|
||||
│ ◷ Backups ││ / search f everyone o by last seen │
|
||||
│ ↺ Restore ││ │
|
||||
│ ↶ Rollback ││ ● Alice Liddell admin 2h ago ╭────────────────────────────────────────────╮ │
|
||||
│ ✎ Fine-tune ││ ● Bob 3d ago │ ⇄ Telegram bridge │ │
|
||||
│ ⇢ Move server ││ ● Carol 45d ago │ │ │
|
||||
│ ▤ Servers ││ ○ eve never │ Accounts 3 1 active this month │ │
|
||||
│ ││ ⊘ dave deactivated │ Bot @telegrambot:example.org │ │
|
||||
│ ▸ Mirrors ││ ▌ ⇄ Telegram 3 accounts ▾ │ Media 4.0 MB │ │
|
||||
│ ││ ● Telegram bridge… bot 1h ago │ │ │
|
||||
│ ▾ Servers ││ ○ Nikolai (Telegram) never │ Puppets stand in for people on the other n │ │
|
||||
│ ● example.org ││ ○ Pavel (Telegram) never │ the bridge creates and manages them. │ │
|
||||
│ ││ ⇄ Whatsapp 1 account ▸ ╰────────────────────────────────────────────╯ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ◫ auto (wide) ctrl+l ││ │
|
||||
│ ◐ interzone ctrl+y ││ │
|
||||
│ ◂ fold ctrl+b ││ │
|
||||
╰────────────────────────╯╰────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
↑↓ select · enter hide · / search · f filter · o sort · n new · r reload · esc back · ctrl+c quit
|
||||
@@ -0,0 +1,40 @@
|
||||
◢◤ ◆ Manage › Users
|
||||
Users on example.org
|
||||
|
||||
4 people 2 active 1 admin 1 new
|
||||
31 rooms 396 MB media 4 bridged
|
||||
/ search f everyone o by last seen
|
||||
|
||||
● Alice Liddell admin 2h ago
|
||||
● Bob 3d ago
|
||||
● Carol 45d ago
|
||||
○ eve never
|
||||
⊘ dave deactivated
|
||||
▌ ⇄ Telegram 3 accounts ▾
|
||||
● Telegram bridge bot bot 1h ago
|
||||
○ Nikolai (Telegram) never
|
||||
○ Pavel (Telegram) never
|
||||
⇄ Whatsapp 1 account ▸
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
‹ back ≡ menu hide › ⋯
|
||||
@@ -0,0 +1,20 @@
|
||||
◢◤ ◆ Manage › Users
|
||||
Users on example.org
|
||||
4 people 2 active 1 admin 1 new
|
||||
/ search f everyone o by last seen
|
||||
● Alice Liddell admin 2h ago
|
||||
● Bob 3d ago
|
||||
● Carol 45d ago
|
||||
○ eve never
|
||||
⊘ dave deactivated
|
||||
▌ ⇄ Telegram 3 accounts ▾
|
||||
● Telegram bridge bot bot 1h ago
|
||||
○ Nikolai (Telegram) never
|
||||
○ Pavel (Telegram) never
|
||||
⇄ Whatsapp 1 account ▸
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
‹ back ≡ menu hide › ⋯
|
||||
@@ -0,0 +1,904 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/spinner"
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"interzone/internal/config"
|
||||
"interzone/internal/deploy"
|
||||
)
|
||||
|
||||
// ── Users ──────────────────────────────────────────────────────────
|
||||
//
|
||||
// Everyone on the server: a strip of totals, the people with what they
|
||||
// use, and the bridges' accounts folded into one group per bridge. The
|
||||
// person under the cursor opens into a card with their details and what
|
||||
// can be done to their account; beside the list on a wide terminal, in
|
||||
// its place on a phone.
|
||||
|
||||
type usersMsg struct {
|
||||
server string
|
||||
list *deploy.UserList
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type userOpMsg struct {
|
||||
info string
|
||||
password string // shown once after a reset or a new account
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type userMode int
|
||||
|
||||
const (
|
||||
usersList userMode = iota
|
||||
usersLogin
|
||||
usersConfirm
|
||||
usersNew
|
||||
)
|
||||
|
||||
type userOp struct {
|
||||
desc string
|
||||
user string
|
||||
body map[string]any
|
||||
password string
|
||||
signOut bool // end every session instead of changing the account
|
||||
}
|
||||
|
||||
// userFilters and userSorts are what f and o step through.
|
||||
var (
|
||||
userFilters = []string{"everyone", "admins", "active", "inactive", "deactivated"}
|
||||
userSorts = []string{"last seen", "name", "joined", "media"}
|
||||
)
|
||||
|
||||
// activeFor is how recently someone must have been seen to count as active.
|
||||
const activeFor = 30 * 24 * time.Hour
|
||||
|
||||
type usersScreen struct {
|
||||
cfg *config.Config
|
||||
server string // whose users are listed
|
||||
login deploy.AdminLogin
|
||||
list *deploy.UserList
|
||||
cursor int
|
||||
mode userMode
|
||||
form *form
|
||||
op *userOp
|
||||
|
||||
search textinput.Model
|
||||
searching bool
|
||||
filter int
|
||||
sortBy int
|
||||
open map[string]bool // bridges whose accounts are shown
|
||||
narrow bool
|
||||
|
||||
busy bool
|
||||
err error
|
||||
info string
|
||||
password string
|
||||
spin spinner.Model
|
||||
}
|
||||
|
||||
func newUsersScreen() *usersScreen {
|
||||
in := textinput.New()
|
||||
in.Prompt = "/ "
|
||||
in.PromptStyle = sAccent
|
||||
in.Placeholder = "name or @id…"
|
||||
in.PlaceholderStyle = sFaint
|
||||
return &usersScreen{spin: newSpinner(), search: in, open: map[string]bool{}}
|
||||
}
|
||||
|
||||
func (s *usersScreen) tool() {}
|
||||
func (s *usersScreen) name() string { return "Users" }
|
||||
func (s *usersScreen) title() string { return "Users on " + s.cfg.Domain }
|
||||
func (s *usersScreen) typing() bool {
|
||||
return s.searching || s.form != nil && (s.mode == usersLogin || s.mode == usersNew) && s.form.typing()
|
||||
}
|
||||
func (s *usersScreen) handlesEsc() bool {
|
||||
return s.mode != usersList || s.searching || s.search.Value() != ""
|
||||
}
|
||||
func (s *usersScreen) leave(*config.Config) {}
|
||||
func (s *usersScreen) setCompact(on bool) { s.narrow = on }
|
||||
func (s *usersScreen) keys() [][2]string {
|
||||
switch {
|
||||
case s.mode == usersLogin:
|
||||
return [][2]string{{"tab/↑↓", "move"}, {"ctrl+r", "reveal"}, {"enter", "sign in"}, {"esc", "cancel"}}
|
||||
case s.mode == usersNew:
|
||||
return [][2]string{{"tab/↑↓", "move"}, {"space", "toggle"}, {"ctrl+r", "reveal"}, {"enter", "create"}, {"esc", "cancel"}}
|
||||
case s.mode == usersConfirm:
|
||||
return [][2]string{{"enter", "do it"}, {"esc", "cancel"}}
|
||||
case s.searching:
|
||||
return [][2]string{{"enter", "done"}, {"esc", "clear"}}
|
||||
}
|
||||
keys := [][2]string{{"↑↓", "select"}}
|
||||
if r, ok := s.current(); ok && r.u == nil {
|
||||
keys = append(keys, [2]string{"enter", map[bool]string{true: "hide", false: "show"}[s.open[r.bridge]]})
|
||||
}
|
||||
keys = append(keys, [2]string{"/", "search"}, [2]string{"f", "filter"}, [2]string{"o", "sort"}, [2]string{"n", "new"})
|
||||
if r, ok := s.current(); ok && r.u != nil && r.u.Person() {
|
||||
keys = append(keys, [2]string{"p", "password"}, [2]string{"a", "admin"},
|
||||
[2]string{"d", map[bool]string{true: "reactivate", false: "deactivate"}[r.u.Deactivated]}, [2]string{"s", "sign out"})
|
||||
}
|
||||
if s.search.Value() != "" {
|
||||
keys = append(keys, [2]string{"esc", "clear search"})
|
||||
}
|
||||
return append(keys, [2]string{"r", "reload"})
|
||||
}
|
||||
|
||||
func (s *usersScreen) enter(c *config.Config) tea.Cmd {
|
||||
s.cfg = c
|
||||
s.login = deploy.AdminLogin{User: c.AdminUser, Password: c.AdminPassword, Token: c.AdminToken}
|
||||
s.mode, s.info, s.password, s.err = usersList, "", "", nil
|
||||
if srv := config.Active(); srv != s.server {
|
||||
s.server, s.list, s.cursor, s.busy = srv, nil, 0, false
|
||||
s.open = map[string]bool{}
|
||||
if list, _, ok := loadCache[deploy.UserList]("userlist"); ok {
|
||||
s.list = &list // shown while the fresh list loads
|
||||
}
|
||||
}
|
||||
return s.reload()
|
||||
}
|
||||
|
||||
func (s *usersScreen) reload() tea.Cmd {
|
||||
s.busy, s.err = true, nil
|
||||
cfg, login, srv := *s.cfg, s.login, s.server
|
||||
return tea.Batch(s.spin.Tick, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
list, err := deploy.ListUsers(ctx, &cfg, &login)
|
||||
return usersMsg{srv, list, login.Token, err}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *usersScreen) saveToken(t string) {
|
||||
s.login.Token = t
|
||||
if s.cfg.AdminToken != t {
|
||||
s.cfg.AdminToken = t
|
||||
_ = s.cfg.Save()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *usersScreen) loginForm() {
|
||||
if deploy.UsesMAS(s.cfg) {
|
||||
u := textField("user", "Admin username", s.login.User, "admin",
|
||||
"Your account on "+s.cfg.Domain+". Accounts live in MAS here, so no password is needed: interzone gets an admin session from MAS on the server.")
|
||||
s.form, s.mode = newForm(u), usersLogin
|
||||
return
|
||||
}
|
||||
u := textField("user", "Admin username", s.login.User, "admin", "An account with server-admin rights on "+s.cfg.Domain+".")
|
||||
pw := secretField("pass", "Password", "", "Only kept until interzone exits; the session it opens is saved.")
|
||||
s.form, s.mode = newForm(u, pw), usersLogin
|
||||
}
|
||||
|
||||
func (s *usersScreen) run(op *userOp) tea.Cmd {
|
||||
s.busy, s.info, s.password, s.err = true, "", "", nil
|
||||
cfg, login := *s.cfg, s.login
|
||||
return tea.Batch(s.spin.Tick, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
var err error
|
||||
if op.signOut {
|
||||
err = deploy.SignOutEverywhere(ctx, &cfg, &login, op.user)
|
||||
} else {
|
||||
err = deploy.UpdateUser(ctx, &cfg, &login, op.user, op.body)
|
||||
}
|
||||
return userOpMsg{info: op.desc, password: op.password, token: login.Token, err: err}
|
||||
})
|
||||
}
|
||||
|
||||
// userRow is a line of the list: a person or a bridge's account, or the
|
||||
// heading of a bridge's group (u is nil, n is how many it has).
|
||||
type userRow struct {
|
||||
u *deploy.MatrixUser
|
||||
bridge string
|
||||
n int
|
||||
}
|
||||
|
||||
// rows is the list as shown: the people matching the search and filter,
|
||||
// sorted, then a group per bridge, open when asked or while searching.
|
||||
func (s *usersScreen) rows() []userRow {
|
||||
if s.list == nil {
|
||||
return nil
|
||||
}
|
||||
q := strings.ToLower(strings.TrimSpace(s.search.Value()))
|
||||
var people []*deploy.MatrixUser
|
||||
bridges := map[string][]*deploy.MatrixUser{}
|
||||
for i := range s.list.Users {
|
||||
u := &s.list.Users[i]
|
||||
if q != "" && !strings.Contains(strings.ToLower(u.ID+" "+u.DisplayName), q) || !s.keep(u) {
|
||||
continue
|
||||
}
|
||||
if u.Person() {
|
||||
people = append(people, u)
|
||||
} else {
|
||||
bridges[u.Bridge] = append(bridges[u.Bridge], u)
|
||||
}
|
||||
}
|
||||
s.sortUsers(people)
|
||||
var rows []userRow
|
||||
for _, u := range people {
|
||||
rows = append(rows, userRow{u: u})
|
||||
}
|
||||
names := make([]string, 0, len(bridges))
|
||||
for b := range bridges {
|
||||
names = append(names, b)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, b := range names {
|
||||
rows = append(rows, userRow{bridge: b, n: len(bridges[b])})
|
||||
if s.open[b] || q != "" {
|
||||
s.sortUsers(bridges[b])
|
||||
for _, u := range bridges[b] {
|
||||
rows = append(rows, userRow{u: u, bridge: b})
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// keep reports whether u passes the filter.
|
||||
func (s *usersScreen) keep(u *deploy.MatrixUser) bool {
|
||||
recent := !u.LastSeen.IsZero() && time.Since(u.LastSeen) < activeFor
|
||||
switch userFilters[s.filter] {
|
||||
case "admins":
|
||||
return u.Admin
|
||||
case "active":
|
||||
return !u.Deactivated && recent
|
||||
case "inactive":
|
||||
return !u.Deactivated && !recent
|
||||
case "deactivated":
|
||||
return u.Deactivated
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *usersScreen) sortUsers(us []*deploy.MatrixUser) {
|
||||
sort.SliceStable(us, func(i, j int) bool {
|
||||
a, b := us[i], us[j]
|
||||
switch userSorts[s.sortBy] {
|
||||
case "name":
|
||||
return strings.ToLower(userName(a)) < strings.ToLower(userName(b))
|
||||
case "joined":
|
||||
return a.Created.After(b.Created)
|
||||
case "media":
|
||||
return a.MediaBytes > b.MediaBytes
|
||||
}
|
||||
if a.Deactivated != b.Deactivated { // last seen: the deactivated go last
|
||||
return b.Deactivated
|
||||
}
|
||||
return a.LastSeen.After(b.LastSeen)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *usersScreen) current() (userRow, bool) {
|
||||
rows := s.rows()
|
||||
if s.cursor < 0 || s.cursor >= len(rows) {
|
||||
return userRow{}, false
|
||||
}
|
||||
return rows[s.cursor], true
|
||||
}
|
||||
|
||||
func (s *usersScreen) update(msg tea.Msg) tea.Cmd {
|
||||
switch m := msg.(type) {
|
||||
case usersMsg:
|
||||
if m.server != s.server {
|
||||
return nil // from before switching servers
|
||||
}
|
||||
s.busy = false
|
||||
s.saveToken(m.token)
|
||||
if _, bad := m.err.(deploy.ErrAdminLogin); bad {
|
||||
s.err = m.err
|
||||
s.loginForm()
|
||||
return nil
|
||||
}
|
||||
s.err = m.err
|
||||
if m.err == nil {
|
||||
saveCache("userlist", *m.list)
|
||||
s.list = m.list
|
||||
s.cursor = min(s.cursor, max(0, len(s.rows())-1))
|
||||
}
|
||||
return nil
|
||||
case userOpMsg:
|
||||
s.busy = false
|
||||
s.saveToken(m.token)
|
||||
if _, bad := m.err.(deploy.ErrAdminLogin); bad {
|
||||
s.err = m.err
|
||||
s.loginForm()
|
||||
return nil
|
||||
}
|
||||
if m.err != nil {
|
||||
s.err = m.err
|
||||
return nil
|
||||
}
|
||||
s.info, s.password = "✓ "+m.info, m.password
|
||||
return s.reload()
|
||||
case spinner.TickMsg:
|
||||
return spinning(s.busy, &s.spin, m)
|
||||
case formDoneMsg:
|
||||
switch s.mode {
|
||||
case usersLogin:
|
||||
s.login.User, s.login.Password, s.login.Token = s.form.value("user"), s.form.value("pass"), ""
|
||||
if s.cfg.AdminUser == "" && s.login.User != "" {
|
||||
s.cfg.AdminUser = s.login.User // offered next time
|
||||
_ = s.cfg.Save()
|
||||
}
|
||||
s.mode = usersList
|
||||
return s.reload()
|
||||
case usersNew:
|
||||
return s.create()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
k, ok := msg.(tea.KeyMsg)
|
||||
if !ok {
|
||||
if s.searching {
|
||||
var cmd tea.Cmd
|
||||
s.search, cmd = s.search.Update(msg)
|
||||
return cmd
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if k.String() == "esc" && s.mode != usersList {
|
||||
s.mode, s.op = usersList, nil
|
||||
return nil
|
||||
}
|
||||
rows := s.rows()
|
||||
switch s.mode {
|
||||
case usersLogin, usersNew:
|
||||
return s.form.Update(msg)
|
||||
case usersConfirm:
|
||||
switch {
|
||||
case (k.String() == "y" || k.String() == "enter") && s.op != nil:
|
||||
op := s.op
|
||||
s.mode, s.op = usersList, nil
|
||||
return s.run(op)
|
||||
case k.String() == "n":
|
||||
s.mode, s.op = usersList, nil
|
||||
case cursorKey(k.String(), s.cursor, len(rows)) != s.cursor: // moving away cancels
|
||||
s.mode, s.op = usersList, nil
|
||||
s.cursor = cursorKey(k.String(), s.cursor, len(rows))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if s.searching {
|
||||
switch k.String() {
|
||||
case "enter", "esc", "up", "down":
|
||||
s.searching = false
|
||||
s.search.Blur()
|
||||
if k.String() == "esc" {
|
||||
s.search.SetValue("")
|
||||
}
|
||||
s.cursor = 0
|
||||
return nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
s.search, cmd = s.search.Update(msg)
|
||||
s.cursor = 0
|
||||
return cmd
|
||||
}
|
||||
s.cursor = cursorKey(k.String(), s.cursor, len(rows))
|
||||
var r userRow
|
||||
if s.cursor < len(rows) {
|
||||
r = rows[s.cursor]
|
||||
}
|
||||
switch k.String() {
|
||||
case "esc":
|
||||
s.search.SetValue("")
|
||||
s.cursor = 0
|
||||
return nil
|
||||
case "/":
|
||||
s.searching = true
|
||||
return s.search.Focus()
|
||||
case "f":
|
||||
s.filter = (s.filter + 1) % len(userFilters)
|
||||
s.cursor = 0
|
||||
return nil
|
||||
case "o":
|
||||
s.sortBy = (s.sortBy + 1) % len(userSorts)
|
||||
s.cursor = 0
|
||||
return nil
|
||||
case "enter", " ":
|
||||
if r.u == nil && r.bridge != "" {
|
||||
s.open[r.bridge] = !s.open[r.bridge]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if s.busy {
|
||||
return nil
|
||||
}
|
||||
var u deploy.MatrixUser
|
||||
if r.u != nil && r.u.Person() {
|
||||
u = *r.u // a bridge's accounts are the bridge's to change
|
||||
}
|
||||
ask := func(op *userOp) tea.Cmd {
|
||||
s.op, s.mode = op, usersConfirm
|
||||
return nil
|
||||
}
|
||||
switch k.String() {
|
||||
case "r":
|
||||
return s.reload()
|
||||
case "n":
|
||||
name := textField("name", "Username", "", "alice", "Just the name, not @alice:"+s.cfg.Domain+".")
|
||||
name.required = true
|
||||
pw := secretField("pass", "Password", config.RandomPassword(16), "Generated for you; shown once the account exists.")
|
||||
pw.required = true
|
||||
s.form, s.mode = newForm(name, pw, toggleField("admin", "Make this user a server administrator", false, "")), usersNew
|
||||
case "p":
|
||||
if u.ID != "" {
|
||||
pw := config.RandomPassword(16)
|
||||
return ask(&userOp{desc: "new password set for " + u.ID + "; their devices were signed out", user: u.ID,
|
||||
body: map[string]any{"password": pw, "logout_devices": true}, password: pw})
|
||||
}
|
||||
case "s":
|
||||
if u.ID != "" && !u.Deactivated {
|
||||
return ask(&userOp{desc: u.ID + " signed out everywhere", user: u.ID, signOut: true})
|
||||
}
|
||||
case "a":
|
||||
if u.ID != "" && !u.Deactivated {
|
||||
verb := "Make " + u.ID + " a server administrator"
|
||||
if u.Admin {
|
||||
verb = "Remove " + u.ID + "'s administrator rights"
|
||||
}
|
||||
return ask(&userOp{desc: strings.ToLower(verb[:1]) + verb[1:] + ": done", user: u.ID, body: map[string]any{"admin": !u.Admin}})
|
||||
}
|
||||
case "d":
|
||||
if u.ID == "" {
|
||||
break
|
||||
}
|
||||
if u.Deactivated && deploy.UsesMAS(s.cfg) {
|
||||
return ask(&userOp{desc: u.ID + " reactivated with their old password", user: u.ID, body: map[string]any{"deactivated": false}})
|
||||
}
|
||||
if u.Deactivated {
|
||||
pw := config.RandomPassword(16)
|
||||
return ask(&userOp{desc: u.ID + " reactivated", user: u.ID, body: map[string]any{"deactivated": false, "password": pw}, password: pw})
|
||||
}
|
||||
return ask(&userOp{desc: u.ID + " deactivated", user: u.ID, body: map[string]any{"deactivated": true}})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *usersScreen) create() tea.Cmd {
|
||||
name := strings.ToLower(strings.TrimPrefix(strings.SplitN(s.form.value("name"), ":", 2)[0], "@"))
|
||||
pw := s.form.value("pass")
|
||||
if name == "" || pw == "" {
|
||||
return nil
|
||||
}
|
||||
id := "@" + name + ":" + s.cfg.Domain
|
||||
if s.list != nil {
|
||||
for _, u := range s.list.Users {
|
||||
if u.ID == id {
|
||||
s.err, s.mode = fmt.Errorf("%s already exists", id), usersList
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mode = usersList
|
||||
return s.run(&userOp{desc: id + " created", user: id,
|
||||
body: map[string]any{"password": pw, "admin": s.form.get("admin").on}, password: pw})
|
||||
}
|
||||
|
||||
func (s *usersScreen) view(w, h int) string {
|
||||
switch s.mode {
|
||||
case usersLogin:
|
||||
head := sWarn.Render("Signing in as "+s.login.User+" didn't work") + "\n" + sMuted.Render(errString(s.err)) + "\n\n"
|
||||
if s.login.User == "" {
|
||||
head = sSub.Render("Which account should interzone act as?") + "\n\n"
|
||||
}
|
||||
return head + s.form.View(w, h-4)
|
||||
case usersNew:
|
||||
return s.form.View(w, h)
|
||||
}
|
||||
foot := s.footer(w)
|
||||
if s.list == nil {
|
||||
return foot
|
||||
}
|
||||
top := s.stats(w) + "\n" + s.toolbar(w)
|
||||
gap := "\n\n"
|
||||
if tight {
|
||||
gap = "\n"
|
||||
}
|
||||
listH := max(3, h-lipgloss.Height(top)-lipgloss.Height(foot)-2*len(gap)+2)
|
||||
if foot == "" {
|
||||
listH += len(gap) - 1
|
||||
}
|
||||
rows := s.rows()
|
||||
s.cursor = min(s.cursor, max(0, len(rows)-1))
|
||||
var body string
|
||||
switch {
|
||||
case len(rows) == 0:
|
||||
body = sMuted.Render("Nobody matches.")
|
||||
case w >= 84 && !s.narrow: // the list, and the card beside it
|
||||
lw := min(56, w*9/20)
|
||||
card := ""
|
||||
if r, ok := s.current(); ok {
|
||||
card = s.card(r, w-lw-2)
|
||||
}
|
||||
body = lipgloss.JoinHorizontal(lipgloss.Top, lipgloss.NewStyle().Width(lw+2).Render(s.listView(rows, lw, listH, false)), card)
|
||||
default:
|
||||
body = s.listView(rows, w, listH, true)
|
||||
}
|
||||
out := top + gap + body
|
||||
if foot != "" {
|
||||
out += gap + foot
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// footer is the result of the last change, a password to pass on, or the
|
||||
// question before a change.
|
||||
func (s *usersScreen) footer(w int) string {
|
||||
var status []string
|
||||
switch {
|
||||
case s.busy:
|
||||
status = append(status, s.spin.View()+sMuted.Render(" talking to Synapse on the server…"))
|
||||
case s.err != nil:
|
||||
status = append(status, sBad.Render("✗ "+s.err.Error()))
|
||||
case s.info != "":
|
||||
status = append(status, sGood.Render(s.info))
|
||||
}
|
||||
if s.password != "" {
|
||||
status = append(status, sMuted.Render("Password ")+sTitle.Render(s.password)+sMuted.Render(" (shown once; it isn't saved)"))
|
||||
}
|
||||
if s.mode != usersConfirm || s.op == nil {
|
||||
return strings.Join(status, "\n")
|
||||
}
|
||||
yes := func(verb string) string {
|
||||
return mark("key:enter", keyChip("enter")+sMuted.Render(" "+verb)) + " " + mark("key:esc", keyChip("esc")+sMuted.Render(" cancel"))
|
||||
}
|
||||
switch {
|
||||
case s.op.body["deactivated"] == true:
|
||||
return confirmView(w, sWarn.Render("Deactivate "+s.op.user+"?"),
|
||||
sSub.Render("They are signed out everywhere and can't sign in again until reactivated."), "", yes("deactivate"))
|
||||
case s.op.signOut:
|
||||
return confirmView(w, sWarn.Render("Sign "+s.op.user+" out everywhere?"),
|
||||
sSub.Render("Every phone, browser and app they use is signed out; their password stays the same."), "", yes("sign out"))
|
||||
}
|
||||
return confirmView(w, sWarn.Render(strings.ToUpper(s.op.desc[:1])+s.op.desc[1:]+"?"), "", yes("yes"))
|
||||
}
|
||||
|
||||
// stats is the strip of totals: tiles on a wide terminal, a line on a
|
||||
// phone.
|
||||
func (s *usersScreen) stats(w int) string {
|
||||
var people, active, admins, fresh, bridged int
|
||||
var media int64
|
||||
for _, u := range s.list.Users {
|
||||
media += u.MediaBytes
|
||||
if !u.Person() {
|
||||
bridged++
|
||||
continue
|
||||
}
|
||||
if u.Deactivated {
|
||||
continue
|
||||
}
|
||||
people++
|
||||
if u.Admin {
|
||||
admins++
|
||||
}
|
||||
if !u.LastSeen.IsZero() && time.Since(u.LastSeen) < activeFor {
|
||||
active++
|
||||
}
|
||||
if time.Since(u.Created) < activeFor {
|
||||
fresh++
|
||||
}
|
||||
}
|
||||
type stat struct{ value, label, short string }
|
||||
stats := []stat{{fmt.Sprint(people), noun(people, "person", "people"), noun(people, "person", "people")},
|
||||
{fmt.Sprint(active), "active (30 days)", "active"},
|
||||
{fmt.Sprint(admins), noun(admins, "admin", "admins"), noun(admins, "admin", "admins")},
|
||||
{fmt.Sprint(fresh), "new (30 days)", "new"}}
|
||||
if s.list.Rooms >= 0 {
|
||||
stats = append(stats, stat{fmt.Sprint(s.list.Rooms), noun(s.list.Rooms, "room", "rooms"), noun(s.list.Rooms, "room", "rooms")})
|
||||
}
|
||||
stats = append(stats, stat{humanBytes(media), "media", "media"})
|
||||
if bridged > 0 {
|
||||
stats = append(stats, stat{fmt.Sprint(bridged), "bridged", "bridged"})
|
||||
}
|
||||
if w >= 84 && !s.narrow && !tight {
|
||||
var tiles []func(w, h int) string
|
||||
for i, st := range stats {
|
||||
value := sTitle.Render(st.value)
|
||||
if i == 1 && active > 0 {
|
||||
value = sGood.Render(st.value)
|
||||
}
|
||||
tiles = append(tiles, func(w, h int) string {
|
||||
label := st.label
|
||||
if lipgloss.Width(label) > w-4 {
|
||||
label = st.short
|
||||
}
|
||||
return card("", []string{value, sMuted.Render(label)}, w, h, cFaint)
|
||||
})
|
||||
}
|
||||
return columns(w, tiles...)
|
||||
}
|
||||
var parts []string
|
||||
for _, st := range stats {
|
||||
parts = append(parts, sTitle.Render(st.value)+" "+sMuted.Render(st.short))
|
||||
}
|
||||
lines := flow(parts, w)
|
||||
if tight {
|
||||
return lines[0]
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// toolbar is the search box and what f and o switch.
|
||||
func (s *usersScreen) toolbar(w int) string {
|
||||
search := mark("key:/", keyChip("/")+sMuted.Render(" search"))
|
||||
if s.searching || s.search.Value() != "" {
|
||||
s.search.Width = max(8, min(30, w/3))
|
||||
search = s.search.View()
|
||||
}
|
||||
filter := mark("key:f", keyChip("f")+sMuted.Render(" ")+sAccent.Render(userFilters[s.filter]))
|
||||
order := mark("key:o", keyChip("o")+sMuted.Render(" by ")+sAccent.Render(userSorts[s.sortBy]))
|
||||
return truncateANSI(search+" "+filter+" "+order, w)
|
||||
}
|
||||
|
||||
// listView draws rows w wide in h lines. inline puts the card of the row
|
||||
// under the cursor in the list itself, as on a phone.
|
||||
func (s *usersScreen) listView(rows []userRow, w, h int, inline bool) string {
|
||||
var lines []string
|
||||
cur := 0
|
||||
for i, r := range rows {
|
||||
id := "row:" + fmt.Sprint(i)
|
||||
if i == s.cursor {
|
||||
cur = len(lines)
|
||||
if inline && r.u != nil && !tight {
|
||||
lines = append(lines, markLines(id, s.card(r, min(w, maxFormWidth))))
|
||||
continue
|
||||
}
|
||||
lines = append(lines, markRow(id, sAccent.Render("▌")+" "+s.rowLine(r, w-2, true), w))
|
||||
continue
|
||||
}
|
||||
lines = append(lines, markRow(id, " "+s.rowLine(r, w-2, false), w))
|
||||
}
|
||||
return windowAround(strings.Join(lines, "\n"), cur, h)
|
||||
}
|
||||
|
||||
// rowLine is one row of the list, w wide.
|
||||
func (s *usersScreen) rowLine(r userRow, w int, on bool) string {
|
||||
if r.u == nil {
|
||||
arrow := "▸"
|
||||
if s.open[r.bridge] || s.search.Value() != "" {
|
||||
arrow = "▾"
|
||||
}
|
||||
left := sPink.Render("⇄") + " " + sTitle.Render(bridgeName(r.bridge)) + sMuted.Render(fmt.Sprintf(" %d %s", r.n, noun(r.n, "account", "accounts")))
|
||||
return left + strings.Repeat(" ", max(1, w-lipgloss.Width(left)-2)) + sFaint.Render(arrow)
|
||||
}
|
||||
u := r.u
|
||||
indent := ""
|
||||
if !u.Person() {
|
||||
indent = " "
|
||||
}
|
||||
nameStyle := lipgloss.NewStyle().Foreground(cText)
|
||||
if on {
|
||||
nameStyle = sTitle
|
||||
}
|
||||
if u.Deactivated {
|
||||
nameStyle = sFaint
|
||||
}
|
||||
right := sMuted.Render(ago(u.LastSeen))
|
||||
if u.Deactivated {
|
||||
right = sFaint.Render("deactivated")
|
||||
}
|
||||
var tags string
|
||||
if u.Admin {
|
||||
tags += " " + tagChip("admin", cPink)
|
||||
}
|
||||
if u.Bot {
|
||||
tags += " " + tagChip("bot", cMuted)
|
||||
}
|
||||
room := w - lipgloss.Width(indent) - 3 - lipgloss.Width(tags) - lipgloss.Width(right) - 2
|
||||
left := indent + activity(*u) + " " + nameStyle.Render(truncate(userName(u), max(6, room))) + tags
|
||||
return left + strings.Repeat(" ", max(1, w-lipgloss.Width(left)-lipgloss.Width(right))) + right
|
||||
}
|
||||
|
||||
// card is everything about the row under the cursor, w wide.
|
||||
func (s *usersScreen) card(r userRow, w int) string {
|
||||
inner := w - 4
|
||||
if r.u == nil {
|
||||
return s.bridgeCard(r, w)
|
||||
}
|
||||
u := r.u
|
||||
name := gradient(truncate(userName(u), inner-4))
|
||||
if u.Deactivated {
|
||||
name = sFaint.Render(truncate(userName(u), inner-4))
|
||||
}
|
||||
var tags []string
|
||||
if u.Admin {
|
||||
tags = append(tags, tagChip("admin", cPink))
|
||||
}
|
||||
if u.Deactivated {
|
||||
tags = append(tags, tagChip("deactivated", cRed))
|
||||
}
|
||||
if u.Locked {
|
||||
tags = append(tags, tagChip("locked", cAmber))
|
||||
}
|
||||
if u.ShadowBanned {
|
||||
tags = append(tags, tagChip("shadow-banned", cAmber))
|
||||
}
|
||||
if u.Bot {
|
||||
tags = append(tags, tagChip("bot", cMuted))
|
||||
}
|
||||
lines := []string{activity(*u) + " " + name}
|
||||
if t := strings.Join(tags, " "); t != "" {
|
||||
if lipgloss.Width(lines[0])+2+lipgloss.Width(t) <= inner {
|
||||
lines[0] += " " + t
|
||||
} else {
|
||||
lines = append(lines, " "+t)
|
||||
}
|
||||
}
|
||||
lines = append(lines, " "+sMuted.Render(truncate(u.ID, inner-3)), "")
|
||||
kv := func(k, v string) {
|
||||
lines = append(lines, sMuted.Render(fmt.Sprintf("%-11s", k))+v)
|
||||
}
|
||||
seen := sFaint.Render("never")
|
||||
if !u.LastSeen.IsZero() {
|
||||
seen = sTitle.Render(ago(u.LastSeen)) + sFaint.Render(" "+u.LastSeen.Local().Format("2006-01-02 15:04"))
|
||||
}
|
||||
kv("Last seen", seen)
|
||||
if !u.Created.IsZero() {
|
||||
kv("Joined", sTitle.Render(u.Created.Local().Format("2006-01-02"))+sFaint.Render(" "+ago(u.Created)))
|
||||
}
|
||||
if u.Devices >= 0 {
|
||||
kv("Sessions", sTitle.Render(fmt.Sprint(u.Devices))+sMuted.Render(" "+noun(u.Devices, "device", "devices")))
|
||||
}
|
||||
if u.Rooms >= 0 {
|
||||
kv("Rooms", sTitle.Render(fmt.Sprint(u.Rooms)))
|
||||
}
|
||||
media := sFaint.Render("none")
|
||||
if u.MediaCount > 0 {
|
||||
media = sTitle.Render(humanBytes(u.MediaBytes)) + sMuted.Render(fmt.Sprintf(" %d %s", u.MediaCount, noun(u.MediaCount, "file", "files")))
|
||||
}
|
||||
kv("Media", media)
|
||||
if len(u.Emails) > 0 {
|
||||
kv("Email", sTitle.Render(truncate(strings.Join(u.Emails, ", "), inner-11)))
|
||||
}
|
||||
if u.Type != "" {
|
||||
kv("Type", sTitle.Render(u.Type))
|
||||
}
|
||||
if !u.Person() {
|
||||
kv("Bridge", sTitle.Render(bridgeName(u.Bridge)))
|
||||
}
|
||||
kv("Picture", map[bool]string{true: sTitle.Render("set"), false: sFaint.Render("none")}[u.Avatar])
|
||||
|
||||
if u.Person() {
|
||||
lines = append(lines, "")
|
||||
var acts []string
|
||||
act := func(k, label string) { acts = append(acts, mark("key:"+k, keyChip(k)+" "+sMuted.Render(label))) }
|
||||
if u.Deactivated {
|
||||
act("d", "reactivate")
|
||||
} else {
|
||||
act("p", "new password")
|
||||
act("a", map[bool]string{true: "remove admin", false: "make admin"}[u.Admin])
|
||||
act("s", "sign out everywhere")
|
||||
act("d", "deactivate")
|
||||
}
|
||||
lines = append(lines, flow(acts, inner)...)
|
||||
} else {
|
||||
lines = append(lines, "", sFaint.Render("Managed by the "+bridgeName(u.Bridge)+" bridge."))
|
||||
}
|
||||
return picked(lines, w)
|
||||
}
|
||||
|
||||
// bridgeCard sums up a bridge's accounts.
|
||||
func (s *usersScreen) bridgeCard(r userRow, w int) string {
|
||||
var bot string
|
||||
var active, total int
|
||||
var media int64
|
||||
for _, u := range s.list.Users {
|
||||
if u.Bridge != r.bridge {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
media += u.MediaBytes
|
||||
if u.Bot {
|
||||
bot = u.ID
|
||||
}
|
||||
if !u.LastSeen.IsZero() && time.Since(u.LastSeen) < activeFor {
|
||||
active++
|
||||
}
|
||||
}
|
||||
kv := func(k, v string) string { return sMuted.Render(fmt.Sprintf("%-11s", k)) + v }
|
||||
lines := []string{sPink.Render("⇄") + " " + gradient(bridgeName(r.bridge)) + sMuted.Render(" bridge"), "",
|
||||
kv("Accounts", sTitle.Render(fmt.Sprint(total))+sMuted.Render(fmt.Sprintf(" %d active this month", active)))}
|
||||
if bot != "" {
|
||||
lines = append(lines, kv("Bot", sTitle.Render(truncate(bot, w-15))))
|
||||
}
|
||||
lines = append(lines, kv("Media", sTitle.Render(humanBytes(media))), "",
|
||||
sFaint.Render("Puppets stand in for people on the other network;"), sFaint.Render("the bridge creates and manages them."))
|
||||
return picked(lines, w)
|
||||
}
|
||||
|
||||
// flow lays chips out in lines of w columns.
|
||||
func flow(chips []string, w int) []string {
|
||||
var lines []string
|
||||
line := ""
|
||||
for _, c := range chips {
|
||||
switch {
|
||||
case line == "":
|
||||
line = c
|
||||
case lipgloss.Width(line)+3+lipgloss.Width(c) <= w:
|
||||
line += " " + c
|
||||
default:
|
||||
lines = append(lines, line)
|
||||
line = c
|
||||
}
|
||||
}
|
||||
if line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// activity is a dot for how recently someone was around.
|
||||
func activity(u deploy.MatrixUser) string {
|
||||
switch {
|
||||
case u.Deactivated:
|
||||
return sFaint.Render("⊘")
|
||||
case u.LastSeen.IsZero():
|
||||
return sFaint.Render("○")
|
||||
case time.Since(u.LastSeen) < 7*24*time.Hour:
|
||||
return sGood.Render("●")
|
||||
case time.Since(u.LastSeen) < activeFor:
|
||||
return sWarn.Render("●")
|
||||
}
|
||||
return sFaint.Render("●")
|
||||
}
|
||||
|
||||
// userName is the display name, or the name in the ID without one.
|
||||
func userName(u *deploy.MatrixUser) string {
|
||||
if strings.TrimSpace(u.DisplayName) != "" {
|
||||
return u.DisplayName
|
||||
}
|
||||
return strings.SplitN(strings.TrimPrefix(u.ID, "@"), ":", 2)[0]
|
||||
}
|
||||
|
||||
// bridgeName turns an appservice ID such as "mautrix-telegram" into
|
||||
// "Telegram".
|
||||
func bridgeName(id string) string {
|
||||
n := id
|
||||
for _, p := range []string{"mautrix-", "matrix-", "mx-puppet-", "appservice-"} {
|
||||
n = strings.TrimPrefix(n, p)
|
||||
}
|
||||
n = strings.TrimSuffix(strings.TrimSuffix(n, "-bridge"), "bridge")
|
||||
n = strings.Trim(strings.ReplaceAll(n, "_", " "), " -")
|
||||
if n == "" {
|
||||
return id
|
||||
}
|
||||
return strings.ToUpper(n[:1]) + n[1:]
|
||||
}
|
||||
|
||||
// humanBytes is a size in the largest unit that keeps it above 1.
|
||||
func humanBytes(n int64) string {
|
||||
const unit = 1024
|
||||
if n < unit {
|
||||
return fmt.Sprintf("%d B", n)
|
||||
}
|
||||
v, units := float64(n)/unit, "KMGTP"
|
||||
i := 0
|
||||
for v >= unit && i < len(units)-1 {
|
||||
v /= unit
|
||||
i++
|
||||
}
|
||||
if v >= 100 {
|
||||
return fmt.Sprintf("%.0f %cB", v, units[i])
|
||||
}
|
||||
return fmt.Sprintf("%.1f %cB", v, units[i])
|
||||
}
|
||||
|
||||
// noun is one or many, for n.
|
||||
func noun(n int, one, many string) string {
|
||||
if n == 1 {
|
||||
return one
|
||||
}
|
||||
return many
|
||||
}
|
||||
Reference in new issue
Block a user