diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java b/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java new file mode 100644 index 0000000..53f5af0 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java @@ -0,0 +1,35 @@ +package com.ts3client.net; + +import java.util.Map; + +/** + * A complaint one client filed about another; the server keeps at most one per pair. + * + * @param targetDbId the database id of the client complained about + * @param fromDbId the database id of the client who complained + */ +public record Complaint(int targetDbId, String targetName, int fromDbId, String fromName, + String message, long timestampEpochSeconds) { + + /** Reads a complaint off a {@code notifycomplainlist} event's fields. */ + static Complaint from(Map fields) { + return new Complaint((int) parseLong(fields.get("tcldbid")), + orEmpty(fields.get("tname")), + (int) parseLong(fields.get("fcldbid")), + orEmpty(fields.get("fname")), + orEmpty(fields.get("message")), + parseLong(fields.get("timestamp"))); + } + + private static String orEmpty(String s) { + return s == null || s.equals("null") ? "" : s; + } + + private static long parseLong(String s) { + try { + return s == null ? 0 : Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java new file mode 100644 index 0000000..6300828 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java @@ -0,0 +1,79 @@ +package com.ts3client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The server's complaints: filing, listing and removing them. + * + *

Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same + * way: {@code complainlist} replies with {@code notifycomplainlist} events ahead of the + * command's own completion. Every call here blocks and must run off the UI thread; the + * connection's public wrappers do that. + */ +final class ComplaintAdmin { + + /** What {@code complainlist} answers when there are no complaints at all. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + /** What {@code complainadd} answers when we already complained about that client. */ + private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502; + + private final TeamspeakConnection conn; + + /** The {@code complainlist} reply in progress; one request may be in flight at a time. */ + private volatile List listing; + + ComplaintAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + List list() throws Exception { + List complaints = Collections.synchronizedList(new ArrayList<>()); + listing = complaints; + try { + conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + listing = null; + } + return new ArrayList<>(complaints); + } + + void onListEntry(UnknownTeamspeakEvent e) { + List complaints = listing; + if (complaints != null) complaints.add(Complaint.from(e.getMap())); + } + + /** Files a complaint about a client; the server takes one per client from each of us. */ + void add(int targetDbId, String message) throws Exception { + try { + conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)), + new CommandSingleParameter("message", message))).complete(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e; + throw new IllegalStateException("Cannot add multiple complaints about the same client."); + } + } + + void delete(Complaint complaint) throws Exception { + conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())), + new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete(); + } + + /** Removes every complaint about one client. */ + void deleteAll(int targetDbId) throws Exception { + conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete(); + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java index c322850..536b178 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java @@ -670,6 +670,7 @@ final class ConnectionEventHandler implements TS3Listener { else if ("notifybanlist".equals(e.getCommand())) conn.bans.onListEntry(e); else if ("notifytokenlist".equals(e.getCommand())) conn.privilegeKeys.onListEntry(e); else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e); + else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e); } // ---- helpers ---- diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java index 2c882f6..c9d56a9 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java @@ -35,8 +35,8 @@ public final class ServerModel { private int nextPermissionId = FIRST_PERMISSION_ID; /** Permission id -> the local client's resolved value, from {@code notifyclientneededpermissions}. */ private final Map selfPermissionValues = new LinkedHashMap<>(); - /** The local client's {@link #SELF_POWERS}, which the needed permissions leave out; absent until known. */ - private final Map selfPowers = new HashMap<>(); + /** The local client's {@link #UNREPORTED_PERMISSIONS}, which the needed permissions leave out; absent until known. */ + private final Map unreportedValues = new HashMap<>(); private String serverName = "TeamSpeak Server"; /** The {@code virtualserver_*} properties from {@code initserver}, kept up to date by server edits. */ private final Map serverProperties = new HashMap<>(); @@ -52,7 +52,7 @@ public final class ServerModel { permissionIds.clear(); nextPermissionId = FIRST_PERMISSION_ID; selfPermissionValues.clear(); - selfPowers.clear(); + unreportedValues.clear(); serverProperties.clear(); defaultChannelGroupId = 0; } @@ -161,21 +161,22 @@ public final class ServerModel { } /** - * The powers {@code notifyclientneededpermissions} never carries, not even for an admin; + * The permissions {@code notifyclientneededpermissions} never carries, not even for an admin; * they have to be asked for with {@code permget}. */ - public static final List SELF_POWERS = List.of("i_client_move_power", - "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power"); + public static final List UNREPORTED_PERMISSIONS = List.of("i_client_move_power", + "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power", + "b_client_complain_delete", "b_client_complain_delete_own"); - /** Takes on the answer to asking for {@link #SELF_POWERS}; those it leaves out count as 0. */ - public synchronized void setSelfPowers(Map powers) { - selfPowers.clear(); - selfPowers.putAll(powers); + /** Takes on the answer to asking for {@link #UNREPORTED_PERMISSIONS}; those it leaves out count as 0. */ + public synchronized void setUnreportedPermissions(Map values) { + unreportedValues.clear(); + unreportedValues.putAll(values); } - /** One of {@link #SELF_POWERS}; 0 until known, or when the server would not tell. */ + /** One of {@link #UNREPORTED_PERMISSIONS}; 0 until known, or when the server would not tell. */ public synchronized int selfPower(String name) { - return selfPowers.getOrDefault(name, 0); + return unreportedValues.getOrDefault(name, 0); } // ---- what the local client may do ---- @@ -200,6 +201,16 @@ public final class ServerModel { return bans.stream().allMatch(b -> b.createdBy(selfUid)); } + /** + * Whether we may remove all of {@code complaints}: any with {@code b_client_complain_delete}, + * only those we filed with {@code b_client_complain_delete_own}. + */ + public synchronized boolean canDeleteComplaints(Collection complaints, int selfDbId) { + if (selfPower("b_client_complain_delete") > 0) return true; + if (selfPower("b_client_complain_delete_own") <= 0) return false; + return complaints.stream().allMatch(c -> c.fromDbId() == selfDbId); + } + /** Whether we may rewrite {@code ban}: that is deleting it and creating its replacement. */ public synchronized boolean canEditBan(BanEntry ban, String selfUid) { return permits("b_client_ban_create") && canDeleteBans(List.of(ban), selfUid); @@ -499,6 +510,15 @@ public final class ServerModel { return null; } + /** An online client by its database id, or {@code null} if none is visible. */ + public synchronized ClientEntry findClientByDatabaseId(int databaseId) { + if (databaseId <= 0) return null; + for (ClientEntry c : clients.values()) { + if (c.databaseId == databaseId) return c; + } + return null; + } + public synchronized ClientEntry findClientByName(String name) { for (ClientEntry c : clients.values()) { if (c.nickname != null && c.nickname.equals(name)) return c; diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java index 4718d6b..eda3f06 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java @@ -60,6 +60,8 @@ public final class TeamspeakConnection implements TS3Listener { /** The longest reason the protocol carries with a kick. */ public static final int KICK_REASON_LIMIT = 40; + /** The longest reason a complaint may carry. */ + public static final int COMPLAINT_REASON_LIMIT = 200; /** The protocol's reason ids for the two flavours of clientkick. */ private static final int REASON_KICK_CHANNEL = 4; @@ -95,9 +97,10 @@ public final class TeamspeakConnection implements TS3Listener { final ConnectionStatsCollector stats = new ConnectionStatsCollector(this); /** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */ final ChannelAdmin channels = new ChannelAdmin(this); - /** The server's ban list and privilege keys; also package-private for {@link ConnectionEventHandler}. */ + /** The server's ban list, privilege keys and complaints; also package-private for {@link ConnectionEventHandler}. */ final BanAdmin bans = new BanAdmin(this); final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); + final ComplaintAdmin complaints = new ComplaintAdmin(this); private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); /* @@ -735,13 +738,13 @@ public final class TeamspeakConnection implements TS3Listener { } /** - * Asks for our own {@link ServerModel#SELF_POWERS}, which {@code notifyclientneededpermissions} + * Asks for our own {@link ServerModel#UNREPORTED_PERMISSIONS}, which {@code notifyclientneededpermissions} * never carries. Asking needs {@code b_client_permissionoverview_own}; refused, we take them * as none, which is what the groups that lack the one usually have of the others. */ void requestSelfPowers() { List rows = new ArrayList<>(); - for (String name : ServerModel.SELF_POWERS) { + for (String name : ServerModel.UNREPORTED_PERMISSIONS) { rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name))); } submit(sock -> { @@ -752,8 +755,8 @@ public final class TeamspeakConnection implements TS3Listener { String value = fields.get("permvalue"); if (name != null && value != null) powers.put(name, Integer.parseInt(value)); } - model.setSelfPowers(powers); - }, e -> model.setSelfPowers(Map.of())); + model.setUnreportedPermissions(powers); + }, e -> model.setUnreportedPermissions(Map.of())); } /** Assigns or removes a server group for a client (by database id, as {@code servergroupaddclient} needs). */ @@ -1007,6 +1010,36 @@ public final class TeamspeakConnection implements TS3Listener { }); } + // ---- complaints ---- + + /** Complains about an online client to the server's admins. */ + public void complain(ClientEntry client, String reason) { + act("Failed to send complaint: ", sock -> { + complaints.add(client.databaseId, reason); + log("Complaint sent."); + }); + } + + /** Reads the server's complaints, delivering them (or a failure message) off the UI thread. */ + public void requestComplaints(BiConsumer, String> callback) { + run(callback, complaints::list); + } + + /** + * Removes every complaint about each of {@code targetDbIds}, then each of {@code single}, + * stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void deleteComplaints(Collection targetDbIds, Collection single, + Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (int target : targetDbIds) complaints.deleteAll(target); + for (Complaint complaint : single) complaints.delete(complaint); + return null; + }); + } + // ---- bans ---- /** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java index 5128851..78e55ad 100644 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java @@ -432,6 +432,11 @@ public final class ServerSession { return permits("b_client_ban_list"); } + /** Whether the server grants us {@code b_client_complain_list}; offered while unknown. */ + public boolean canViewComplaints() { + return permits("b_client_complain_list"); + } + /** Whether the server grants us {@code b_virtualserver_token_list}; offered while unknown. */ public boolean canListPrivilegeKeys() { return permits("b_virtualserver_token_list"); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java index d9e76fc..8183bcf 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java @@ -37,6 +37,9 @@ final class ClientMenu { JMenuItem poke = new JMenuItem("Poke", Icons.of("POKE")); poke.addActionListener(a -> actions.pokeClient(client)); menu.add(poke); + JMenuItem complain = new JMenuItem("Make a Complaint", Icons.of("SEND_COMPLAINT")); + complain.addActionListener(a -> actions.complainAboutClient(client)); + menu.add(complain); menu.addSeparator(); JMenuItem kickChannel = new JMenuItem("Kick Client from Channel", Icons.of("KICK_FROM_CHANNEL")); kickChannel.addActionListener(a -> actions.kickClientFromChannel(client)); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java new file mode 100644 index 0000000..b6f3acf --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java @@ -0,0 +1,511 @@ +package com.ts3client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import com.ts3client.net.ClientEntry; +import com.ts3client.net.Complaint; +import com.ts3client.net.ServerModel; +import com.ts3client.net.TeamspeakConnection; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * The server's complaints, as the official client's Tools > Complaints List window: one + * collapsible row per client complained about, with each complaint's date, author and + * reason beneath it. + * + *

One per server tab and modeless, like the ban list; the tab closes it when the + * connection goes away. + */ +final class ComplaintsDialog extends JDialog { + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private enum Column { + TARGET("Target Nickname", 200), + FROM("From Nickname", 160), + REASON("Reason", 280); + + final String title; + final int width; + + Column(String title, int width) { + this.title = title; + this.width = width; + } + } + + /** A client complained about, with the complaints against them. */ + private record Target(int dbId, String name, List complaints) { + } + + /** A row of the table: a target, or one complaint under its expanded target. */ + private record Row(Target target, Complaint complaint) { + boolean isTarget() { + return complaint == null; + } + } + + private final TeamspeakConnection conn; + private final Consumer banClient; + + private final ComplaintTableModel tableModel = new ComplaintTableModel(); + private final JTable table = new JTable(tableModel) { + /** The popup acts on what was clicked, as a tree's would; Swing asks here before showing it. */ + @Override + public Point getPopupLocation(MouseEvent e) { + int row = e == null ? -1 : rowAtPoint(e.getPoint()); + if (row >= 0 && !isRowSelected(row)) setRowSelectionInterval(row, row); + return super.getPopupLocation(e); + } + }; + private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); + private final JLabel status = new JLabel(" "); + private final JMenuItem removeItem = item("Remove", "DELETE", this::removeSelected); + private final JMenuItem banItem = item("Ban Client", "BAN_CLIENT", this::banSelected); + + private List targets = List.of(); + /** Targets shown expanded, by database id; kept across reloads. */ + private final Set expanded = new HashSet<>(); + private boolean loading; + + /** @param banClient opens the ban dialog for an online client */ + ComplaintsDialog(Frame owner, TeamspeakConnection conn, Consumer banClient) { + super(owner, "Complaints List", false); + this.conn = conn; + this.banClient = banClient; + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(buildTable(), BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(680, 420))); + pack(); + setLocationRelativeTo(owner); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + removeButton.setToolTipText("Remove selected complaints
(Delete)"); + removeButton.addActionListener(e -> removeSelected()); + + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + bar.add(removeButton); + bar.add(Box.createHorizontalGlue()); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.setShowGrid(false); + table.getTableHeader().setReorderingAllowed(false); + table.getSelectionModel().addListSelectionListener(e -> updateButtons()); + table.setComponentPopupMenu(tablePopup()); + table.addMouseListener(new ToggleOnClick()); + ComplaintCellRenderer renderer = new ComplaintCellRenderer(); + for (Column c : Column.values()) { + table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); + table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); + } + + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setToolTipText("Reload complaints
(F5)"); + reload.addActionListener(e -> reload()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(reload, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private JPopupMenu tablePopup() { + JPopupMenu menu = new JPopupMenu(); + menu.add(item("Reload", "REFRESH", this::reload)); + menu.addSeparator(); + menu.add(removeItem); + menu.add(banItem); + menu.addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + removeItem.setEnabled(removeButton.isEnabled()); + banItem.setEnabled(banTarget() != null); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + return menu; + } + + private static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + private void bindKeys() { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + this::removeSelected); + bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), () -> setLeadExpanded(true)); + bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), () -> setLeadExpanded(false)); + Dialogs.closeOnEscape(this); + } + + private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { + String name = "ts3-complaints-" + key; + target.getInputMap(condition).put(key, name); + target.getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + /** Follows the server's name, as the ban list's title does. */ + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? "Complaints List" : "Complaints List - " + name); + } + + void connectionLost() { + dispose(); + } + + private void reload() { + if (loading) return; + loading = true; + status.setText("Loading…"); + conn.requestComplaints((complaints, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + setTargets(List.of()); + status.setText("Failed to request complaint list: " + error); + } else { + setTargets(groupByTarget(complaints)); + status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); + } + })); + } + + private static List groupByTarget(List complaints) { + Map byId = new LinkedHashMap<>(); + for (Complaint c : complaints) { + byId.computeIfAbsent(c.targetDbId(), id -> new Target(id, c.targetName(), new ArrayList<>())) + .complaints().add(c); + } + List out = new ArrayList<>(byId.values()); + out.sort(Comparator.comparing(Target::name, String.CASE_INSENSITIVE_ORDER)); + for (Target t : out) t.complaints().sort(Comparator.comparingLong(Complaint::timestampEpochSeconds)); + return out; + } + + private void setTargets(List targets) { + this.targets = targets; + rebuildRows(); + } + + /** Lays the rows out again after a reload or a target opening or closing, keeping the selection. */ + private void rebuildRows() { + Set selected = new HashSet<>(selectedRows()); + List rows = new ArrayList<>(); + for (Target t : targets) { + rows.add(new Row(t, null)); + if (expanded.contains(t.dbId())) { + for (Complaint c : t.complaints()) rows.add(new Row(t, c)); + } + } + tableModel.setRows(rows); + for (int i = 0; i < rows.size(); i++) { + if (selected.contains(rows.get(i))) table.addRowSelectionInterval(i, i); + } + updateButtons(); + } + + private void setExpanded(Target target, boolean open) { + if (open ? expanded.add(target.dbId()) : expanded.remove(target.dbId())) rebuildRows(); + } + + private void setLeadExpanded(boolean open) { + int lead = table.getSelectionModel().getLeadSelectionIndex(); + if (lead < 0 || lead >= tableModel.getRowCount()) return; + Row row = tableModel.get(lead); + if (row.isTarget()) { + setExpanded(row.target(), open); + } else if (!open) { + int parent = tableModel.indexOf(new Row(row.target(), null)); + setExpanded(row.target(), false); + table.setRowSelectionInterval(parent, parent); + } + } + + private List selectedRows() { + List rows = new ArrayList<>(); + for (int i : table.getSelectedRows()) rows.add(tableModel.get(i)); + return rows; + } + + /** Whole targets selected, and complaints selected on their own (not under a selected target). */ + private Selection selection() { + Set whole = new LinkedHashSet<>(); + List single = new ArrayList<>(); + List rows = selectedRows(); + for (Row r : rows) if (r.isTarget()) whole.add(r.target()); + for (Row r : rows) if (!r.isTarget() && !whole.contains(r.target())) single.add(r.complaint()); + return new Selection(whole, single); + } + + private record Selection(Set whole, List single) { + boolean isEmpty() { + return whole.isEmpty() && single.isEmpty(); + } + + List affected() { + List all = new ArrayList<>(single); + for (Target t : whole) all.addAll(t.complaints()); + return all; + } + } + + private int selfDbId() { + ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); + return self == null ? 0 : self.databaseId; + } + + private void updateButtons() { + Selection sel = selection(); + removeButton.setEnabled(!sel.isEmpty() && conn.getModel().canDeleteComplaints(sel.affected(), selfDbId())); + } + + /** + * Who Ban Client acts on: the target on a target row, the author on a complaint row, + * as in the official client. Only an online client can be banned this way. + */ + private ClientEntry banTarget() { + int[] rows = table.getSelectedRows(); + if (rows.length != 1) return null; + ServerModel model = conn.getModel(); + if (model.selfPower("i_client_ban_power") == 0) return null; + Row row = tableModel.get(rows[0]); + ClientEntry client = model.findClientByDatabaseId(row.isTarget() ? row.target().dbId() : row.complaint().fromDbId()); + return client == null || client.id == conn.getSelfClientId() ? null : client; + } + + // ---- actions ---- + + private void removeSelected() { + if (!removeButton.isEnabled()) return; + Selection sel = selection(); + String question = sel.single().isEmpty() && sel.whole().size() == 1 + ? "Do you really want to remove all complaints of this user?" + : "Do you really want to remove the selected complaint(s)?"; + int answer = JOptionPane.showConfirmDialog(this, question, "Remove Complaints", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + List whole = sel.whole().stream().map(Target::dbId).toList(); + conn.deleteComplaints(whole, sel.single(), error -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + error, getTitle(), + JOptionPane.ERROR_MESSAGE); + } + reload(); + })); + } + + private void banSelected() { + ClientEntry client = banTarget(); + if (client != null) banClient.accept(client); + } + + // ---- table ---- + + private final class ToggleOnClick extends MouseAdapter { + @Override + public void mousePressed(MouseEvent e) { + int row = table.rowAtPoint(e.getPoint()); + if (row < 0 || !SwingUtilities.isLeftMouseButton(e)) return; + Row clicked = tableModel.get(row); + if (!clicked.isTarget()) return; + boolean onHandle = table.columnAtPoint(e.getPoint()) == Column.TARGET.ordinal() + && e.getX() - table.getCellRect(row, 0, false).x < handleWidth(); + if (onHandle || e.getClickCount() == 2) { + setExpanded(clicked.target(), !expanded.contains(clicked.target().dbId())); + } + } + } + + private static Icon handleIcon(boolean open) { + return UIManager.getIcon(open ? "Tree.expandedIcon" : "Tree.collapsedIcon"); + } + + private static int handleWidth() { + Icon icon = handleIcon(false); + return (icon == null ? UIScale.scale(12) : icon.getIconWidth()) + UIScale.scale(6); + } + + private final class ComplaintTableModel extends AbstractTableModel { + + private List rows = List.of(); + + void setRows(List rows) { + this.rows = rows; + fireTableDataChanged(); + } + + Row get(int row) { + return rows.get(row); + } + + int indexOf(Row row) { + return rows.indexOf(row); + } + + @Override + public int getRowCount() { + return rows.size(); + } + + @Override + public int getColumnCount() { + return Column.values().length; + } + + @Override + public String getColumnName(int column) { + return Column.values()[column].title; + } + + @Override + public Object getValueAt(int row, int column) { + return text(rows.get(row), Column.values()[column]); + } + + String text(Row row, Column column) { + if (row.isTarget()) { + int n = row.target().complaints().size(); + return switch (column) { + case TARGET -> row.target().name(); + case FROM -> ""; + case REASON -> n == 1 ? "has 1 complaint" : "has " + n + " complaints"; + }; + } + Complaint c = row.complaint(); + return switch (column) { + case TARGET -> c.timestampEpochSeconds() <= 0 ? "" : DATE.format( + Instant.ofEpochSecond(c.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); + case FROM -> c.fromName(); + case REASON -> c.message(); + }; + } + } + + /** Draws the tree handle and indent in the first column, and a target's count greyed out. */ + private final class ComplaintCellRenderer extends DefaultTableCellRenderer { + @Override + public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focused, int row, int column) { + // setForeground sticks as the renderer's unselected colour; clear it so the + // table's own colour applies again after a greyed cell. + setForeground(null); + super.getTableCellRendererComponent(t, value, selected, focused, row, column); + Row r = tableModel.get(row); + Column c = Column.values()[column]; + setIcon(null); + setBorder(new ScaledEmptyBorder(0, 2, 0, 2)); + if (c == Column.TARGET) { + if (r.isTarget()) { + setIcon(handleIcon(expanded.contains(r.target().dbId()))); + setIconTextGap(UIScale.scale(6)); + } else { + setBorder(new ScaledEmptyBorder(0, 2 + UIScale.unscale(handleWidth()) + 6, 0, 2)); + } + } + setToolTipText(c == Column.REASON && !r.isTarget() && !r.complaint().message().isEmpty() + ? r.complaint().message() : null); + if (c == Column.REASON && r.isTarget() && !selected) setForeground(UIManager.getColor("Label.disabledForeground")); + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java index 29053b4..497b21b 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java @@ -308,6 +308,16 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { if (selected != null) selected.showBanList(banReasonPresets()); } + @Override + public boolean canViewComplaints() { + return selected != null && selected.session().canViewComplaints(); + } + + @Override + public void onShowComplaints() { + if (selected != null) selected.showComplaints(); + } + @Override public boolean canListPrivilegeKeys() { return selected != null && selected.session().canListPrivilegeKeys(); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java index a98fa09..53da11f 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java @@ -81,6 +81,11 @@ final class MainMenuBar extends JMenuBar { void onShowBanList(); + /** Whether the current server lets us read its complaints; asked as the Tools menu opens. */ + boolean canViewComplaints(); + + void onShowComplaints(); + /** Whether the current server lets us list its privilege keys; asked as the Permissions menu opens. */ boolean canListPrivilegeKeys(); @@ -116,6 +121,7 @@ final class MainMenuBar extends JMenuBar { private JMenuItem avatarItem; private JMenuItem deleteAvatarItem; private JMenuItem banListItem; + private JMenuItem complaintsItem; private JMenuItem privilegeKeysItem; private JMenuItem usePrivilegeKeyItem; @@ -265,24 +271,32 @@ final class MainMenuBar extends JMenuBar { banListItem.addActionListener(e -> { if (listener.canViewBanList()) listener.onShowBanList(); }); + complaintsItem = new JMenuItem("Complaints List", Icons.of("COMPLAINT_LIST")); + complaintsItem.setAccelerator(KeyStroke.getKeyStroke("control shift C")); + complaintsItem.addActionListener(e -> { + if (listener.canViewComplaints()) listener.onShowComplaints(); + }); JMenuItem options = new JMenuItem("Options…", Icons.of("SETTINGS")); options.setAccelerator(KeyStroke.getKeyStroke("alt P")); options.addActionListener(e -> listener.onShowSettings()); - JPopupMenu.Separator banListSeparator = new JPopupMenu.Separator(); + JPopupMenu.Separator adminSeparator = new JPopupMenu.Separator(); tools.add(identitiesItem); tools.add(contactsItem); tools.addSeparator(); tools.add(banListItem); - tools.add(banListSeparator); + tools.add(complaintsItem); + tools.add(adminSeparator); tools.add(options); // Permissions arrive after the connection does, so the item is judged as the menu opens // rather than on a fixed refresh. tools.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { - boolean shown = banListItem.isEnabled() && listener.canViewBanList(); - banListItem.setVisible(shown); - banListSeparator.setVisible(shown); + boolean bans = banListItem.isEnabled() && listener.canViewBanList(); + boolean complaints = complaintsItem.isEnabled() && listener.canViewComplaints(); + banListItem.setVisible(bans); + complaintsItem.setVisible(complaints); + adminSeparator.setVisible(bans || complaints); } @Override @@ -323,6 +337,7 @@ final class MainMenuBar extends JMenuBar { avatarItem.setEnabled(connected); deleteAvatarItem.setEnabled(connected); banListItem.setEnabled(connected); + complaintsItem.setEnabled(connected); privilegeKeysItem.setEnabled(connected); usePrivilegeKeyItem.setEnabled(connected); awayItem.setSelected(away); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java index f37ed55..21dbdf9 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java @@ -55,6 +55,7 @@ final class ServerTab { /** The one open ban list window for this server, if any. */ private BanListDialog banList; private PrivilegeKeysDialog privilegeKeys; + private ComplaintsDialog complaints; ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio, SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) { @@ -190,6 +191,16 @@ final class ServerTab { banList.toFront(); } + /** Opens the server's complaints, or brings the already open window forward. */ + void showComplaints() { + if (!session.isConnected()) return; + if (complaints == null || !complaints.isDisplayable()) { + complaints = new ComplaintsDialog(host, conn, treeActions::banClient); + } + complaints.setVisible(true); + complaints.toFront(); + } + /** Asks for a privilege key and redeems it on this server. */ void usePrivilegeKey() { if (!session.isConnected()) return; @@ -213,12 +224,16 @@ final class ServerTab { privilegeKeys.toFront(); } - /** The server's name changed or the connection went; the ban list and privilege keys windows follow. */ + /** The server's name changed or the connection went; the ban list, complaints and privilege keys windows follow. */ void serverWindowsChanged(boolean connected) { if (banList != null) { if (connected) banList.serverNameChanged(); else banList.connectionLost(); } + if (complaints != null) { + if (connected) complaints.serverNameChanged(); + else complaints.connectionLost(); + } if (privilegeKeys != null) { if (connected) privilegeKeys.serverNameChanged(); else privilegeKeys.connectionLost(); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java index 82be55e..342abf6 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java @@ -140,6 +140,14 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { if (msg != null) conn.poke(client.id, msg); } + @Override + public void complainAboutClient(ClientEntry client) { + if (!conn.isConnected()) return; + String reason = ReasonDialog.prompt(host, "Make a Complaint", "Enter the reason for your complaint:", + TeamspeakConnection.COMPLAINT_REASON_LIMIT); + if (reason != null) conn.complain(client, reason); + } + @Override public void kickClientFromChannel(ClientEntry client) { String reason = kickReason("Kick Client from Channel", client); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java index 3260667..cca1c30 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java @@ -47,6 +47,8 @@ public final class ServerTreePanel extends JPanel { void pokeClient(ClientEntry client); + void complainAboutClient(ClientEntry client); + void kickClientFromChannel(ClientEntry client); void kickClientFromServer(ClientEntry client);