Integrate DuneChat with verified private channel membership
This commit is contained in:
parent
5986ca938f
commit
186022581a
11 changed files with 604 additions and 2 deletions
41
.forgejo/workflows/dunechat.yml
Normal file
41
.forgejo/workflows/dunechat.yml
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
name: DuneChat Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['feat/dunechat-*']
|
||||
|
||||
jobs:
|
||||
dunechat:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '9.2.1'
|
||||
- name: Build and test DuneChat and its GUI identity hook
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneChat test jar
|
||||
gradle --no-daemon -p DuneRealmsGUI test jar
|
||||
mkdir dunechat-artifacts
|
||||
cp DuneChat/build/libs/DuneChat.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar dunechat-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > dunechat-artifacts/SOURCE_COMMIT
|
||||
(cd dunechat-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-DuneChat
|
||||
path: dunechat-artifacts/
|
||||
if-no-files-found: error
|
||||
36
DuneChat/README.md
Normal file
36
DuneChat/README.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# DuneChat
|
||||
|
||||
Chat prefixes and private channels. Built on canonical main `5d727d7`. Not pushed. Not tested in game.
|
||||
|
||||
## What players see
|
||||
Public chat: `[STAFF]/[VIP] [Race] [CLAN TAG] [Company] Name: message`. Order is `prefix-order` in config.yml. Race colour follows the house colour used by the nameplates.
|
||||
|
||||
| Command | Does |
|
||||
|---|---|
|
||||
| `/cc <msg>` (`/clanchat`) | one message to your clan. `/cc` alone toggles clan chat mode |
|
||||
| `/coc <msg>` (`/companychat`) | same for your company |
|
||||
| `/sc <msg>` (`/staffchat`) | staff only, permission `dunechat.staff` |
|
||||
| `/g` (`/gc`) | back to public chat |
|
||||
| `/chatspy` | staff with `dunechat.spy` also see clan and company chat |
|
||||
|
||||
You can be in one clan and one company at the same time; each has its own private channel. Private chat is logged to the console (`log-private-chat`).
|
||||
|
||||
## Where the data comes from
|
||||
The same central briefing the nameplates use (`briefing.identity`: staff, vip, clans, companies), pushed in by a 5-line hook in DuneRealmsGUI (`DuneGUI.pushChatIdentity`, reflection, no hard dependency). Group membership keys on the central id when the briefing carries one, otherwise on the name, so please confirm the briefing includes ids.
|
||||
|
||||
## Safety
|
||||
- Names and tags are stripped of `& § % < >` and control characters before they reach a prefix; the message itself is never colour-parsed.
|
||||
- Never un-cancels chat: a mute or filter from another plugin still wins.
|
||||
- Leaving a clan or company while in its channel drops you back to public chat.
|
||||
|
||||
## Install
|
||||
1. Build: `gradle -p DuneChat build` -> `build/libs/DuneChat.jar`.
|
||||
2. Apply the DuneRealmsGUI change (DuneGUI.java, plugin.yml softdepend), rebuild DuneRealmsGUI.
|
||||
3. Grant `dunechat.staff` / `dunechat.spy` through LuckPerms.
|
||||
|
||||
## Verified / not verified
|
||||
CI: DuneChat compiles; 7 unit tests (parsing, prefix order, injection, group isolation, staff rules). The DuneRealmsGUI edit was not compiled in CI (that module needs another module missing from the cut-down CI tree; the errors seen were unrelated). Not tested: real chat events, other chat plugins (LuckPerms prefixes, DuneEss, DuneMenus chat prompts), Bedrock clients.
|
||||
|
||||
## Limits
|
||||
- Per server only: planets are separate servers, so clan/company/staff chat does not cross servers. A proxy relay would be a separate piece.
|
||||
- No mute, filter, cooldown or channel history.
|
||||
21
DuneChat/build.gradle.kts
Normal file
21
DuneChat/build.gradle.kts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
plugins { java }
|
||||
group = "com.example"
|
||||
version = "1.0.0"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://nexus.scarsz.me/content/groups/public/") {
|
||||
content { includeModule("com.discordsrv", "discordsrv") }
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
compileOnly("com.discordsrv:discordsrv:1.30.5") { isTransitive = false }
|
||||
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
|
||||
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
|
||||
tasks.test { useJUnitPlatform() }
|
||||
tasks.jar { archiveFileName.set("DuneChat.jar") }
|
||||
1
DuneChat/settings.gradle.kts
Normal file
1
DuneChat/settings.gradle.kts
Normal file
|
|
@ -0,0 +1 @@
|
|||
rootProject.name = "DuneChat"
|
||||
146
DuneChat/src/main/java/com/example/dunechat/ChatLogic.java
Normal file
146
DuneChat/src/main/java/com/example/dunechat/ChatLogic.java
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
package com.example.dunechat;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Pure chat rules: identity parsing, prefixes and who may read a channel. No Bukkit types. */
|
||||
final class ChatLogic {
|
||||
enum Channel { GLOBAL, CLAN, COMPANY, STAFF }
|
||||
|
||||
/** Group keys are exact central membership UUIDs. Blank means no authorized membership. */
|
||||
record Identity(String faction, String race, boolean staff, boolean vip,
|
||||
String clanKey, String clanTag, String companyKey, String companyName) {
|
||||
static final Identity NONE = new Identity("", "", false, false, "", "", "", "");
|
||||
}
|
||||
|
||||
static String clean(String value, int max) {
|
||||
String safe = value == null ? "" : value.replaceAll("[&§%<>\\p{Cntrl}]", "").strip();
|
||||
return safe.substring(0, Math.min(Math.max(0, max), safe.length()));
|
||||
}
|
||||
|
||||
static String color(String faction) {
|
||||
return switch (faction == null ? "" : faction) {
|
||||
case "atreides" -> "&a"; case "harkonnen" -> "&c"; case "corrino" -> "&6";
|
||||
case "ordos" -> "&e"; case "fremen" -> "&b"; default -> "&f";
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean flag(JsonObject o, String k) {
|
||||
return o != null && o.has(k) && o.get(k).isJsonPrimitive() && o.get(k).getAsJsonPrimitive().isBoolean() && o.get(k).getAsBoolean();
|
||||
}
|
||||
|
||||
private static String text(JsonObject o, String k) {
|
||||
JsonElement e = o == null ? null : o.get(k);
|
||||
return e != null && e.isJsonPrimitive() ? e.getAsString() : "";
|
||||
}
|
||||
|
||||
/** First object in an array field, or null. Only the first group counts: one clan and one company per player. */
|
||||
private static JsonObject first(JsonObject o, String k) {
|
||||
JsonElement e = o == null ? null : o.get(k);
|
||||
if (e == null || !e.isJsonArray()) return null;
|
||||
JsonArray a = e.getAsJsonArray();
|
||||
return a.isEmpty() || !a.get(0).isJsonObject() ? null : a.get(0).getAsJsonObject();
|
||||
}
|
||||
|
||||
/** Reads the same central briefing the nameplates use: briefing.identity.{staff,vip,clans[],companies[]}. */
|
||||
static Identity parse(JsonObject data, String faction, String race, int max) {
|
||||
JsonObject id = null;
|
||||
if (data != null && data.has("briefing") && data.get("briefing").isJsonObject()) {
|
||||
JsonObject b = data.getAsJsonObject("briefing");
|
||||
if (b.has("identity") && b.get("identity").isJsonObject()) id = b.getAsJsonObject("identity");
|
||||
}
|
||||
JsonObject clan = first(id, "clans"), company = first(id, "companies");
|
||||
String clanName = text(clan, "name"), clanTag = text(clan, "tag");
|
||||
String companyName = text(company, "name");
|
||||
return new Identity(faction == null ? "" : faction, clean(race, max), flag(id, "staff"), flag(id, "vip"),
|
||||
"", clean(clanTag.isBlank() ? clanName : clanTag, max), "", clean(companyName, max));
|
||||
}
|
||||
|
||||
record Membership(String clan, String company, long observedAt) {
|
||||
static final Membership NONE = new Membership("", "", 0);
|
||||
}
|
||||
|
||||
static Membership memberships(JsonObject data, UUID actor, long now) {
|
||||
if (data == null || !flag(data, "ok") || !"1".equals(text(data, "schema"))) return Membership.NONE;
|
||||
long observedAt = data.get("observedAt").getAsLong();
|
||||
if (observedAt < now - 45_000 || observedAt > now + 5_000) return Membership.NONE;
|
||||
return new Membership(memberId(data.getAsJsonArray("clans"), actor),
|
||||
memberId(data.getAsJsonArray("companies"), actor), observedAt);
|
||||
}
|
||||
|
||||
private static String memberId(JsonArray rows, UUID actor) {
|
||||
if (rows == null || rows.size() > 512) return "";
|
||||
String found = "";
|
||||
for (JsonElement element : rows) {
|
||||
JsonObject row = element.getAsJsonObject();
|
||||
if (!"active".equals(text(row, "lifecycle"))) continue;
|
||||
JsonArray members = row.getAsJsonArray("members");
|
||||
if (members == null || members.size() > 5_000) continue;
|
||||
for (JsonElement member : members) {
|
||||
if (!actor.toString().equals(text(member.getAsJsonObject(), "uuid"))) continue;
|
||||
String id = canonicalId(text(row, "id"));
|
||||
if (id.isEmpty() || !found.isEmpty() && !found.equals(id)) return "";
|
||||
found = id;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static String canonicalId(String id) {
|
||||
try {
|
||||
String canonical = UUID.fromString(id).toString();
|
||||
return canonical.equalsIgnoreCase(id) ? canonical : "";
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
static Identity withMembership(Identity identity, Membership membership, long now) {
|
||||
if (membership.observedAt() < now - 45_000) return identity;
|
||||
return new Identity(identity.faction(), identity.race(), identity.staff(), identity.vip(),
|
||||
membership.clan(), identity.clanTag(), membership.company(), identity.companyName());
|
||||
}
|
||||
|
||||
static boolean inGroup(Channel c, Identity i) {
|
||||
return switch (c) {
|
||||
case CLAN -> !i.clanKey().isBlank();
|
||||
case COMPANY -> !i.companyKey().isBlank();
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
static boolean canSend(Channel c, Identity sender, boolean staffPerm) {
|
||||
return switch (c) { case STAFF -> staffPerm; case CLAN, COMPANY -> inGroup(c, sender); case GLOBAL -> true; };
|
||||
}
|
||||
|
||||
/** Whether {@code viewer} sees a message sent in {@code c} by {@code sender}. */
|
||||
static boolean receives(Channel c, Identity sender, Identity viewer, boolean viewerStaff, boolean viewerSpy) {
|
||||
return switch (c) {
|
||||
case GLOBAL -> true;
|
||||
case STAFF -> viewerStaff;
|
||||
case CLAN -> inGroup(c, viewer) && viewer.clanKey().equals(sender.clanKey()) || viewerSpy;
|
||||
case COMPANY -> inGroup(c, viewer) && viewer.companyKey().equals(sender.companyKey()) || viewerSpy;
|
||||
};
|
||||
}
|
||||
|
||||
/** Public prefix as legacy ampersand text, in the configured order. Only cleaned values are inserted. */
|
||||
static String prefix(Identity i, List<String> order) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
String c = color(i.faction());
|
||||
for (String key : order) {
|
||||
switch (key) {
|
||||
case "staff" -> { if (i.staff()) parts.add("&c&l[STAFF]&r"); else if (i.vip()) parts.add("&6&l[VIP]&r"); }
|
||||
case "race" -> { if (!i.race().isBlank()) parts.add(c + "[" + i.race() + "]&r"); }
|
||||
case "clan" -> { if (!i.clanTag().isBlank()) parts.add("&6[" + i.clanTag() + "]&r"); }
|
||||
case "company" -> { if (!i.companyName().isBlank()) parts.add("&3[" + i.companyName() + "]&r"); }
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
return String.join(" ", parts);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package com.example.dunechat;
|
||||
|
||||
import github.scarsz.discordsrv.DiscordSRV;
|
||||
import github.scarsz.discordsrv.api.Subscribe;
|
||||
import github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent;
|
||||
|
||||
/** Leave the existing public relay in place and prevent it from processing private messages. */
|
||||
public final class DiscordPrivacy implements AutoCloseable {
|
||||
private final DuneChat chat;
|
||||
|
||||
DiscordPrivacy(DuneChat chat) {
|
||||
this.chat = chat;
|
||||
DiscordSRV.api.subscribe(this);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void beforeRelay(GameChatMessagePreProcessEvent event) {
|
||||
if (event.getPlayer() != null && chat.isPrivate(event.getPlayer())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
DiscordSRV.api.unsubscribe(this);
|
||||
}
|
||||
}
|
||||
196
DuneChat/src/main/java/com/example/dunechat/DuneChat.java
Normal file
196
DuneChat/src/main/java/com/example/dunechat/DuneChat.java
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
package com.example.dunechat;
|
||||
|
||||
import com.example.dunechat.ChatLogic.Channel;
|
||||
import com.example.dunechat.ChatLogic.Identity;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Chat prefixes (race, clan, company) and private clan, company and staff channels.
|
||||
* Identity comes from the central JARVIS briefing, pushed in by DuneRealmsGUI through {@link #identity}.
|
||||
* Chat is per server; there is no cross-server relay.
|
||||
*/
|
||||
public final class DuneChat extends JavaPlugin implements Listener, CommandExecutor {
|
||||
private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand();
|
||||
private final Map<UUID, Identity> identities = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, ChatLogic.Membership> memberships = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Channel> mode = new ConcurrentHashMap<>();
|
||||
private record CommandMessage(UUID sender, Channel channel) {}
|
||||
private final ThreadLocal<CommandMessage> commandMessage = new ThreadLocal<>();
|
||||
private DiscordPrivacy discordPrivacy;
|
||||
private final Set<UUID> spies = ConcurrentHashMap.newKeySet();
|
||||
private List<String> order = List.of("staff", "race", "clan", "company");
|
||||
private int max = 16;
|
||||
|
||||
@Override public void onEnable() {
|
||||
saveDefaultConfig();
|
||||
order = getConfig().getStringList("prefix-order");
|
||||
max = Math.max(4, getConfig().getInt("max-prefix-length", 16));
|
||||
if (getServer().getPluginManager().isPluginEnabled("DiscordSRV")) {
|
||||
try {
|
||||
discordPrivacy = new DiscordPrivacy(this);
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
getLogger().warning("DiscordSRV privacy hook failed; private channels are unavailable.");
|
||||
}
|
||||
}
|
||||
getServer().getPluginManager().registerEvents(this, this);
|
||||
for (String c : List.of("clanchat", "companychat", "staffchat", "globalchat", "chatspy")) {
|
||||
var cmd = getCommand(c);
|
||||
if (cmd != null) cmd.setExecutor(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
if (discordPrivacy != null) discordPrivacy.close();
|
||||
}
|
||||
|
||||
/** Called by DuneRealmsGUI (by reflection) whenever the central briefing for a player changes. */
|
||||
public void identity(UUID player, String briefingJson, String faction, String race) {
|
||||
Identity next = Identity.NONE;
|
||||
try {
|
||||
if (briefingJson != null) next = ChatLogic.parse(JsonParser.parseString(briefingJson).getAsJsonObject(), faction, race, max);
|
||||
} catch (RuntimeException malformed) { getLogger().warning("Ignored malformed identity for " + player); }
|
||||
identities.put(player, next);
|
||||
}
|
||||
|
||||
/** Called with an authenticated JARVIS organisation-list response for this player. */
|
||||
public void memberships(UUID player, String json) {
|
||||
ChatLogic.Membership membership = ChatLogic.Membership.NONE;
|
||||
try {
|
||||
if (json != null) membership = ChatLogic.memberships(
|
||||
JsonParser.parseString(json).getAsJsonObject(), player, System.currentTimeMillis());
|
||||
} catch (RuntimeException invalid) {
|
||||
getLogger().warning("Ignored malformed chat membership projection");
|
||||
}
|
||||
memberships.put(player, membership);
|
||||
}
|
||||
|
||||
private Identity of(Player p) {
|
||||
UUID id = p.getUniqueId();
|
||||
return ChatLogic.withMembership(identities.getOrDefault(id, Identity.NONE),
|
||||
memberships.getOrDefault(id, ChatLogic.Membership.NONE), System.currentTimeMillis());
|
||||
}
|
||||
private boolean staff(Player p) { return p.hasPermission("dunechat.staff"); }
|
||||
private Channel channel(Player player) {
|
||||
var command = commandMessage.get();
|
||||
return command != null && command.sender().equals(player.getUniqueId())
|
||||
? command.channel() : mode.getOrDefault(player.getUniqueId(), Channel.GLOBAL);
|
||||
}
|
||||
boolean isPrivate(Player player) { return channel(player) != Channel.GLOBAL; }
|
||||
|
||||
private boolean privateReady() {
|
||||
return discordPrivacy != null || !getServer().getPluginManager().isPluginEnabled("DiscordSRV");
|
||||
}
|
||||
|
||||
@EventHandler public void onQuit(PlayerQuitEvent e) {
|
||||
UUID id = e.getPlayer().getUniqueId(); identities.remove(id); memberships.remove(id); mode.remove(id); spies.remove(id);
|
||||
}
|
||||
|
||||
/** Never un-cancels: if another plugin cancelled the chat (mute, filter), we leave it alone. */
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onChat(AsyncChatEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
Channel c = channel(p);
|
||||
Identity me = of(p);
|
||||
if (c != Channel.GLOBAL) {
|
||||
if (!privateReady() || !ChatLogic.canSend(c, me, staff(p))) {
|
||||
e.setCancelled(true);
|
||||
p.sendMessage(Component.text("Your private channel is unavailable. Use /g to return to public chat.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
}
|
||||
final Channel channel = c;
|
||||
if (channel != Channel.GLOBAL) {
|
||||
e.viewers().removeIf(v -> !(v instanceof Player vp) || !ChatLogic.receives(channel, me, of(vp), staff(vp), spies.contains(vp.getUniqueId()) && vp.hasPermission("dunechat.spy")));
|
||||
}
|
||||
e.renderer((source, name, message, viewer) -> render(channel, me, name, message));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void logAcceptedPrivateChat(AsyncChatEvent event) {
|
||||
Channel channel = channel(event.getPlayer());
|
||||
if (channel != Channel.GLOBAL) logPrivate(channel, event.getPlayer(), event.message());
|
||||
}
|
||||
|
||||
private Component render(Channel c, Identity me, Component name, Component message) {
|
||||
Component sep = Component.text(": ", NamedTextColor.GRAY);
|
||||
if (c == Channel.GLOBAL) {
|
||||
String prefix = ChatLogic.prefix(me, order);
|
||||
Component head = prefix.isEmpty() ? Component.empty() : LEGACY.deserialize(prefix).append(Component.space());
|
||||
return head.append(name).append(sep).append(message);
|
||||
}
|
||||
String label = switch (c) {
|
||||
case CLAN -> getConfig().getString("clan-chat-label", "CLAN") + (me.clanTag().isBlank() ? "" : " " + me.clanTag());
|
||||
case COMPANY -> getConfig().getString("company-chat-label", "COMPANY") + (me.companyName().isBlank() ? "" : " " + me.companyName());
|
||||
default -> getConfig().getString("staff-chat-label", "STAFF");
|
||||
};
|
||||
NamedTextColor color = c == Channel.CLAN ? NamedTextColor.GOLD : c == Channel.COMPANY ? NamedTextColor.DARK_AQUA : NamedTextColor.RED;
|
||||
return Component.text("[" + ChatLogic.clean(label, 40) + "] ", color).append(name).append(sep).append(message.color(NamedTextColor.WHITE));
|
||||
}
|
||||
|
||||
private void logPrivate(Channel c, Player p, Component message) {
|
||||
if (getConfig().getBoolean("log-private-chat", false))
|
||||
getLogger().info("[" + c + "] " + p.getName() + ": " + net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(message));
|
||||
}
|
||||
|
||||
@Override public boolean onCommand(CommandSender s, Command cmd, String label, String[] a) {
|
||||
if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; }
|
||||
Channel c = switch (cmd.getName()) {
|
||||
case "clanchat" -> Channel.CLAN; case "companychat" -> Channel.COMPANY; case "staffchat" -> Channel.STAFF;
|
||||
case "globalchat" -> Channel.GLOBAL; default -> null;
|
||||
};
|
||||
if (cmd.getName().equals("chatspy")) {
|
||||
if (!p.hasPermission("dunechat.spy")) { p.sendMessage(Component.text("No permission.", NamedTextColor.RED)); return true; }
|
||||
boolean on = spies.add(p.getUniqueId()); if (!on) spies.remove(p.getUniqueId());
|
||||
p.sendMessage(Component.text("Chat spy " + (on ? "on" : "off") + ".", NamedTextColor.GOLD)); return true;
|
||||
}
|
||||
if (c == null) return false;
|
||||
Identity me = of(p);
|
||||
if (c == Channel.GLOBAL) { mode.remove(p.getUniqueId()); p.sendMessage(Component.text("Public chat.", NamedTextColor.GOLD)); return true; }
|
||||
if (!privateReady()) {
|
||||
p.sendMessage(Component.text("Private channels are unavailable.", NamedTextColor.RED));
|
||||
return true;
|
||||
}
|
||||
if (!ChatLogic.canSend(c, me, staff(p))) {
|
||||
p.sendMessage(Component.text(c == Channel.STAFF ? "No permission." : "You are not in a " + (c == Channel.CLAN ? "clan" : "company") + ".", NamedTextColor.RED)); return true;
|
||||
}
|
||||
if (a.length == 0) {
|
||||
boolean off = mode.get(p.getUniqueId()) == c;
|
||||
if (off) mode.remove(p.getUniqueId()); else mode.put(p.getUniqueId(), c);
|
||||
p.sendMessage(Component.text(off ? "Public chat." : c + " chat on. /g to leave.", NamedTextColor.GOLD)); return true;
|
||||
}
|
||||
String message = String.join(" ", a).strip();
|
||||
if (message.isEmpty() || message.length() > 256 || message.startsWith("/")
|
||||
|| message.chars().anyMatch(ch -> ch == '§' || Character.isISOControl(ch))) {
|
||||
p.sendMessage(Component.text("Enter ordinary chat text of up to 256 characters.", NamedTextColor.RED));
|
||||
return true;
|
||||
}
|
||||
commandMessage.set(new CommandMessage(p.getUniqueId(), c));
|
||||
try {
|
||||
p.chat(message);
|
||||
} finally {
|
||||
commandMessage.remove();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
8
DuneChat/src/main/resources/config.yml
Normal file
8
DuneChat/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# Prefix order in public chat. Remove an entry to hide it.
|
||||
prefix-order: [staff, race, clan, company]
|
||||
max-prefix-length: 16
|
||||
clan-chat-label: "CLAN"
|
||||
company-chat-label: "COMPANY"
|
||||
staff-chat-label: "STAFF"
|
||||
# Staff with dunechat.spy can opt in using /chatspy. Private messages stay out of the console by default.
|
||||
log-private-chat: false
|
||||
31
DuneChat/src/main/resources/plugin.yml
Normal file
31
DuneChat/src/main/resources/plugin.yml
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
name: DuneChat
|
||||
version: 1.0.0
|
||||
main: com.example.dunechat.DuneChat
|
||||
api-version: '1.21.8'
|
||||
softdepend: [DiscordSRV]
|
||||
description: Chat prefixes for race, clan and company, plus private clan, company and staff channels.
|
||||
commands:
|
||||
clanchat:
|
||||
aliases: [cc]
|
||||
description: Send to your private clan chat, or toggle it
|
||||
usage: /cc [message]
|
||||
companychat:
|
||||
aliases: [coc]
|
||||
description: Send to your private company chat, or toggle it
|
||||
usage: /coc [message]
|
||||
staffchat:
|
||||
aliases: [sc]
|
||||
description: Staff-only chat
|
||||
usage: /sc [message]
|
||||
globalchat:
|
||||
aliases: [gc, g]
|
||||
description: Return to public chat
|
||||
usage: /g
|
||||
chatspy:
|
||||
description: Staff - watch clan and company chats
|
||||
usage: /chatspy
|
||||
permissions:
|
||||
dunechat.staff:
|
||||
default: op
|
||||
dunechat.spy:
|
||||
default: op
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
package com.example.dunechat;
|
||||
|
||||
import com.example.dunechat.ChatLogic.Channel;
|
||||
import com.example.dunechat.ChatLogic.Identity;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ChatLogicTest {
|
||||
private static Identity parse(String briefing, String house, String race) {
|
||||
return ChatLogic.parse(JsonParser.parseString(briefing).getAsJsonObject(), house, race, 16);
|
||||
}
|
||||
private static final String CLAN = "aaaaaaaa-0000-0000-0000-000000000001";
|
||||
private static final String COMPANY = "bbbbbbbb-0000-0000-0000-000000000001";
|
||||
private static final String OTHER = "aaaaaaaa-0000-0000-0000-000000000002";
|
||||
private static final java.util.UUID ACTOR = java.util.UUID.fromString("cccccccc-0000-0000-0000-000000000001");
|
||||
|
||||
private static Identity proof(Identity display, String clan, String company) {
|
||||
return ChatLogic.withMembership(display, new ChatLogic.Membership(clan, company, 100000L), 100001L);
|
||||
}
|
||||
|
||||
private static final String DATA = "{\"briefing\":{\"identity\":{\"staff\":false,\"vip\":true,\"clans\":[{\"id\":\"c1\",\"name\":\"Sand Hawks\",\"tag\":\"HAWK\"},{\"name\":\"Second\"}],\"companies\":[{\"id\":\"k1\",\"name\":\"Spice Co\"}]}}}";
|
||||
|
||||
@Test void parsesClanCompanyAndUsesOnlyTheFirstOfEach() {
|
||||
Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY);
|
||||
assertEquals(CLAN, i.clanKey()); assertEquals("HAWK", i.clanTag());
|
||||
assertEquals(COMPANY, i.companyKey()); assertEquals("Spice Co", i.companyName());
|
||||
assertTrue(i.vip()); assertFalse(i.staff());
|
||||
}
|
||||
|
||||
@Test void prefixFollowsConfiguredOrderAndSkipsMissingParts() {
|
||||
Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY);
|
||||
assertEquals("&6&l[VIP]&r &b[Fremen]&r &6[HAWK]&r &3[Spice Co]&r", ChatLogic.prefix(i, List.of("staff", "race", "clan", "company")));
|
||||
assertEquals("&3[Spice Co]&r &b[Fremen]&r", ChatLogic.prefix(i, List.of("company", "race")));
|
||||
assertEquals("", ChatLogic.prefix(Identity.NONE, List.of("staff", "race", "clan", "company")));
|
||||
}
|
||||
|
||||
@Test void colourAndMarkupCannotBeInjectedThroughNames() {
|
||||
Identity i = parse("{\"briefing\":{\"identity\":{\"clans\":[{\"tag\":\"&4EVIL<red>§k\"}]}}}", "atreides", "&cRace%");
|
||||
assertFalse(ChatLogic.prefix(i, List.of("race", "clan")).contains("§"));
|
||||
assertEquals("4EVILredk", i.clanTag(), "markup characters are removed, nothing is interpreted");
|
||||
assertEquals("cRace", i.race());
|
||||
}
|
||||
|
||||
@Test void privateChannelsReachOnlyTheSameGroup() {
|
||||
Identity me = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY);
|
||||
Identity mate = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY);
|
||||
Identity otherClan = proof(Identity.NONE, OTHER, COMPANY);
|
||||
assertTrue(ChatLogic.receives(Channel.CLAN, me, mate, false, false));
|
||||
assertFalse(ChatLogic.receives(Channel.CLAN, me, otherClan, false, false));
|
||||
assertTrue(ChatLogic.receives(Channel.COMPANY, me, otherClan, false, false), "same company, different clan");
|
||||
assertFalse(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, false, false));
|
||||
assertTrue(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, true, true), "spy sees it");
|
||||
}
|
||||
|
||||
@Test void aClanAndACompanyAreIndependent() {
|
||||
Identity onlyCompany = proof(Identity.NONE, "", COMPANY);
|
||||
assertFalse(ChatLogic.canSend(Channel.CLAN, onlyCompany, false));
|
||||
assertTrue(ChatLogic.canSend(Channel.COMPANY, onlyCompany, false));
|
||||
}
|
||||
|
||||
@Test void staffChatNeedsThePermissionToSendAndToRead() {
|
||||
assertFalse(ChatLogic.canSend(Channel.STAFF, Identity.NONE, false));
|
||||
assertTrue(ChatLogic.canSend(Channel.STAFF, Identity.NONE, true));
|
||||
assertTrue(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, true, false));
|
||||
assertFalse(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, false, true), "spy alone is not staff chat");
|
||||
}
|
||||
|
||||
@Test void missingBriefingGivesNoPrefixAndNoGroups() {
|
||||
Identity i = ChatLogic.parse(null, null, null, 16);
|
||||
assertEquals("", ChatLogic.prefix(i, List.of("race", "clan", "company")));
|
||||
assertFalse(ChatLogic.inGroup(Channel.CLAN, i));
|
||||
}
|
||||
|
||||
@Test void onlyFreshExplicitMembershipAuthorizesPrivateChat() {
|
||||
var display = parse(DATA, "fremen", "Fremen");
|
||||
assertFalse(ChatLogic.canSend(Channel.CLAN, display, false), "public label alone grants nothing");
|
||||
var response = JsonParser.parseString("""
|
||||
{"ok":true,"schema":1,"observedAt":100000,"clans":[
|
||||
{"id":"%s","lifecycle":"active","canManage":true,"members":[]},
|
||||
{"id":"%s","lifecycle":"active","members":[{"uuid":"%s"}]}
|
||||
],"companies":[]}
|
||||
""".formatted(OTHER, CLAN, ACTOR)).getAsJsonObject();
|
||||
var membership = ChatLogic.memberships(response, ACTOR, 100001L);
|
||||
assertEquals(CLAN, membership.clan());
|
||||
assertTrue(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 100001L), false));
|
||||
assertFalse(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 145001L), false));
|
||||
}
|
||||
}
|
||||
|
|
@ -212,13 +212,19 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
|
|||
}
|
||||
private void refreshSidebar(Player p){
|
||||
UUID owner=p.getUniqueId();if(requests.containsKey(owner))return;UUID operation=UUID.randomUUID();requests.put(owner,operation);
|
||||
boolean chatEnabled=Bukkit.getPluginManager().isPluginEnabled("DuneChat");
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;try{result=bridge.request(owner,null,0,null);}catch(Exception unavailable){}JsonObject received=result;if(!isEnabled())return;
|
||||
JsonObject memberships=null;if(chatEnabled)try{memberships=bridge.organisations(owner);}catch(Exception unavailable){}
|
||||
JsonObject chatMemberships=memberships;
|
||||
Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline())return;
|
||||
if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);}
|
||||
if(chatEnabled)pushChatMemberships(owner,chatMemberships);
|
||||
if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);pushChatIdentity(p,null,null,null);}
|
||||
});
|
||||
});
|
||||
}
|
||||
private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);}
|
||||
private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);pushChatIdentity(p,data,house,label);}
|
||||
private void pushChatIdentity(Player p,JsonObject data,String house,String race){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("identity",UUID.class,String.class,String.class,String.class).invoke(chat,p.getUniqueId(),data==null?null:data.toString(),house,race);}catch(ReflectiveOperationException|RuntimeException unavailable){}}
|
||||
private void pushChatMemberships(UUID uuid,JsonObject data){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("memberships",UUID.class,String.class).invoke(chat,uuid,data==null?null:data.toString());}catch(ReflectiveOperationException|RuntimeException unavailable){}}
|
||||
private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void organisationContact(org.bukkit.event.player.PlayerInteractEntityEvent event){String marker=event.getRightClicked().getPersistentDataContainer().get(new NamespacedKey("dunerealms","organisation_home_npc"),PersistentDataType.STRING);if(marker==null)return;event.setCancelled(true);if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;String[] parts=marker.split(":",2);if(parts.length!=2||!Set.of("clan","company").contains(parts[0]))return;try{String id=UUID.fromString(parts[1]).toString();organisations.openHomeNpc(event.getPlayer(),parts[0].equals("clan")?"clans":"companies",id,event.getRightClicked().getUniqueId());}catch(IllegalArgumentException ignored){}}
|
||||
@EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff