Anzeigen: Beitritt/Verlassen als Text und Signalton, Discord-Status, TS-Thema, Sprecher in der Actionbar (abschaltbar)
This commit is contained in:
1 parent
3c0e3ed17a
commit
b335933678
19 files changed
+583
-37
No files matched your search
@@ -0,0 +1,155 @@
|
||||
package eu.mhsl.voicebridge.bridge;
|
||||
|
||||
import eu.mhsl.voicebridge.bridge.Room.Side;
|
||||
import eu.mhsl.voicebridge.bridge.audio.Mixer;
|
||||
import eu.mhsl.voicebridge.bridge.audio.Opus;
|
||||
import eu.mhsl.voicebridge.bridge.audio.Tones;
|
||||
import eu.mhsl.voicebridge.bridge.discord.DiscordRoomBot;
|
||||
import eu.mhsl.voicebridge.bridge.teamspeak.TeamspeakSide;
|
||||
import io.github.jaredmdobson.concentus.OpusEncoder;
|
||||
import io.github.jaredmdobson.concentus.OpusException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* Macht sichtbar, wer auf den anderen Plattformen ist: Beitritt/Verlassen als Text und Signalton,
|
||||
* Zusammenfassung wenn ein Bot dazukommt, Discord-Voice-Status und TS-Channel-Thema.
|
||||
* Hinweise gehen immer nur an die anderen Plattformen, die eigene zeigt das ja selbst an.
|
||||
*/
|
||||
final class Announcer {
|
||||
/** Discord und TeamSpeak drosseln Änderungen, öfter als alle 5 s wird Status/Thema nicht gesetzt. */
|
||||
private static final long STATUS_INTERVAL_MILLIS = 5000;
|
||||
|
||||
private final PluginLink plugin;
|
||||
private final TeamspeakSide teamspeak;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final Map<String, State> states = new HashMap<>();
|
||||
private final AtomicLong toneCounter = new AtomicLong();
|
||||
|
||||
private static final class State {
|
||||
final Map<Side, Map<String, String>> roster = new EnumMap<>(Side.class);
|
||||
boolean teamspeakConnected, discordInVoice;
|
||||
String discordStatus = "", teamspeakTopic = "";
|
||||
long lastStatus;
|
||||
}
|
||||
|
||||
Announcer(PluginLink plugin, TeamspeakSide teamspeak, ScheduledExecutorService scheduler) {
|
||||
this.plugin = plugin;
|
||||
this.teamspeak = teamspeak;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Takt für einen Raum.
|
||||
*
|
||||
* @param roster wer auf welcher Seite ist (ID → Name); fehlt eine Seite, ist sie gerade nicht verbunden
|
||||
* und wird nicht verglichen (sonst gäbe es nach jedem Reconnect eine Flut von Meldungen)
|
||||
*/
|
||||
void update(Room room, DiscordRoomBot bot, Map<Side, Map<String, String>> roster, boolean active) {
|
||||
State state = states.computeIfAbsent(room.key(), k -> new State());
|
||||
|
||||
if (active) {
|
||||
for (Side side : Side.values()) {
|
||||
Map<String, String> before = state.roster.get(side);
|
||||
Map<String, String> now = roster.get(side);
|
||||
if (before == null || now == null) continue;
|
||||
now.forEach((id, name) -> { if (!before.containsKey(id)) announce(room, bot, roster, side, name, true); });
|
||||
before.forEach((id, name) -> { if (!now.containsKey(id)) announce(room, bot, roster, side, name, false); });
|
||||
}
|
||||
}
|
||||
state.roster.clear();
|
||||
state.roster.putAll(roster);
|
||||
|
||||
// Zusammenfassung, sobald ein Bot im Channel ist
|
||||
boolean tsConnected = teamspeak != null && teamspeak.roomConnected(room);
|
||||
if (tsConnected && !state.teamspeakConnected) {
|
||||
String others = others(roster, Side.TEAMSPEAK, " | ");
|
||||
if (!others.isEmpty()) teamspeak.sendRoomMessage(room, "Verbunden mit " + others);
|
||||
}
|
||||
state.teamspeakConnected = tsConnected;
|
||||
|
||||
boolean dcInVoice = bot != null && bot.inVoice();
|
||||
if (dcInVoice && !state.discordInVoice) {
|
||||
String others = others(roster, Side.DISCORD, " | ");
|
||||
if (!others.isEmpty()) bot.sendText("Verbunden mit " + others);
|
||||
state.discordStatus = ""; // nach dem Beitritt neu setzen
|
||||
}
|
||||
state.discordInVoice = dcInVoice;
|
||||
|
||||
// Wer ist da: Discord-Status und TS-Thema
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - state.lastStatus < STATUS_INTERVAL_MILLIS) return;
|
||||
String dcStatus = active ? others(roster, Side.DISCORD, " · ") : "";
|
||||
String tsTopic = active ? others(roster, Side.TEAMSPEAK, " · ") : "";
|
||||
if (dcInVoice && !dcStatus.equals(state.discordStatus)) {
|
||||
bot.setStatus(dcStatus);
|
||||
state.discordStatus = dcStatus;
|
||||
state.lastStatus = now;
|
||||
}
|
||||
if (teamspeak != null && teamspeak.ready() && !tsTopic.equals(state.teamspeakTopic)) {
|
||||
teamspeak.setRoomTopic(room, tsTopic);
|
||||
state.teamspeakTopic = tsTopic;
|
||||
state.lastStatus = now;
|
||||
}
|
||||
}
|
||||
|
||||
private void announce(Room room, DiscordRoomBot bot, Map<Side, Map<String, String>> roster,
|
||||
Side side, String name, boolean joined) {
|
||||
String text = name + " (" + Room.label(side) + ") ist " + (joined ? "dazugekommen." : "gegangen.");
|
||||
List<short[]> tone = joined ? Tones.JOIN : Tones.LEAVE;
|
||||
|
||||
if (side != Side.MINECRAFT && !roster.getOrDefault(Side.MINECRAFT, Map.of()).isEmpty()) {
|
||||
plugin.sendNotice(room.key(), text);
|
||||
playToMinecraft(room, tone);
|
||||
}
|
||||
if (side != Side.TEAMSPEAK && teamspeak != null && teamspeak.roomConnected(room)) {
|
||||
teamspeak.sendRoomMessage(room, text);
|
||||
push(room.toTeamspeak(), tone);
|
||||
}
|
||||
if (side != Side.DISCORD && bot != null && !roster.getOrDefault(Side.DISCORD, Map.of()).isEmpty()) {
|
||||
bot.sendText(text);
|
||||
if (bot.inVoice()) push(room.toDiscord(), tone);
|
||||
}
|
||||
}
|
||||
|
||||
/** "Minecraft: Steve, Alex | Discord: Anna" ohne die Seite {@code except}. */
|
||||
static String others(Map<Side, Map<String, String>> roster, Side except, String separator) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
for (Side side : Side.values()) {
|
||||
Map<String, String> people = roster.get(side);
|
||||
if (side == except || people == null || people.isEmpty()) continue;
|
||||
parts.add(Room.label(side) + ": " + String.join(", ", people.values()));
|
||||
}
|
||||
return String.join(separator, parts);
|
||||
}
|
||||
|
||||
private void push(Mixer mixer, List<short[]> tone) {
|
||||
String source = "tone:" + toneCounter.incrementAndGet();
|
||||
for (short[] frame : tone) mixer.push(source, frame);
|
||||
}
|
||||
|
||||
/** Zum Plugin im 20-ms-Takt, wie echte Sprache, sonst verschluckt der Voicechat-Client die Frames. */
|
||||
private void playToMinecraft(Room room, List<short[]> tone) {
|
||||
UUID source = UUID.nameUUIDFromBytes(("voicebridge-tone:" + room.key()).getBytes(StandardCharsets.UTF_8));
|
||||
OpusEncoder encoder = Opus.encoder(1, 48000);
|
||||
for (int i = 0; i < tone.size(); i++) {
|
||||
short[] frame = tone.get(i);
|
||||
scheduler.schedule(() -> {
|
||||
try {
|
||||
plugin.sendAudio(room.key(), source, Opus.encodeMono(encoder, frame));
|
||||
} catch (OpusException ignored) {
|
||||
// ein fehlender Ton-Frame ist egal
|
||||
}
|
||||
}, i * 20L, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import eu.mhsl.voicebridge.bridge.Room.Side;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -33,6 +36,9 @@ public final class Bridge {
|
||||
private final TeamspeakSide teamspeak;
|
||||
private final ScheduledExecutorService ticker = Executors.newSingleThreadScheduledExecutor(
|
||||
Thread.ofPlatform().name("bridge-tick").factory());
|
||||
private final Announcer announcer;
|
||||
/** Wie lange nach dem letzten Paket jemand noch als "spricht" gilt. */
|
||||
private static final long SPEAKING_MILLIS = 400;
|
||||
|
||||
private volatile List<Message.RoomInfo> roomInfos = List.of();
|
||||
|
||||
@@ -57,6 +63,15 @@ public final class Bridge {
|
||||
this.teamspeak = config.teamspeak().enabled()
|
||||
? new TeamspeakSide(config.teamspeak(), config.dataDir(), List.copyOf(rooms.values()), updater)
|
||||
: null;
|
||||
for (Room room : rooms.values()) {
|
||||
DiscordRoomBot bot = discordBots.get(room.key());
|
||||
room.setNameResolver((side, id) -> switch (side) {
|
||||
case TEAMSPEAK -> teamspeak != null ? teamspeak.nickname(Integer.parseInt(id)) : id;
|
||||
case DISCORD -> bot != null ? bot.name(Long.parseLong(id)) : id;
|
||||
case MINECRAFT -> id;
|
||||
});
|
||||
}
|
||||
this.announcer = new Announcer(plugin, teamspeak, ticker);
|
||||
roomInfos = buildInfos();
|
||||
}
|
||||
|
||||
@@ -67,6 +82,7 @@ public final class Bridge {
|
||||
if (teamspeak != null) teamspeak.start();
|
||||
discordBots.values().forEach(DiscordRoomBot::start);
|
||||
ticker.scheduleAtFixedRate(this::safeTick, 1, 1, TimeUnit.SECONDS);
|
||||
ticker.scheduleAtFixedRate(this::sendSpeakers, 500, 500, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void safeTick() {
|
||||
@@ -84,9 +100,10 @@ public final class Bridge {
|
||||
for (Room room : rooms.values()) {
|
||||
Presence p = presence.get(room.key());
|
||||
DiscordRoomBot bot = discordBots.get(room.key());
|
||||
int mc = plugin.minecraftMembers(room.key());
|
||||
int ts = teamspeak != null ? teamspeak.humansIn(room) : 0;
|
||||
int dc = bot != null ? bot.humans() : 0;
|
||||
Map<Side, Map<String, String>> roster = roster(room, bot);
|
||||
int mc = roster.getOrDefault(Side.MINECRAFT, Map.of()).size();
|
||||
int ts = roster.getOrDefault(Side.TEAMSPEAK, Map.of()).size();
|
||||
int dc = roster.getOrDefault(Side.DISCORD, Map.of()).size();
|
||||
String counts = "Minecraft " + mc + ", TeamSpeak " + ts + ", Discord " + dc;
|
||||
if (!counts.equals(p.lastCounts)) {
|
||||
LOG.info("{}: {}", room.name(), counts);
|
||||
@@ -118,18 +135,45 @@ public final class Bridge {
|
||||
p.lastStats = 0;
|
||||
}
|
||||
|
||||
try {
|
||||
announcer.update(room, bot, roster, active);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warn("{}: Anzeige fehlgeschlagen", room.name(), e);
|
||||
}
|
||||
room.dropIdleSources();
|
||||
}
|
||||
roomInfos = buildInfos();
|
||||
}
|
||||
|
||||
/** Wer auf welcher Seite ist; Seiten, die gerade nicht verbunden sind, fehlen in der Map. */
|
||||
private Map<Side, Map<String, String>> roster(Room room, DiscordRoomBot bot) {
|
||||
Map<Side, Map<String, String>> roster = new EnumMap<>(Side.class);
|
||||
if (plugin.alive()) roster.put(Side.MINECRAFT, plugin.minecraftMembers(room.key()));
|
||||
if (teamspeak != null && teamspeak.ready()) roster.put(Side.TEAMSPEAK, teamspeak.participants(room));
|
||||
if (bot != null && bot.ready()) roster.put(Side.DISCORD, bot.participants());
|
||||
return roster;
|
||||
}
|
||||
|
||||
/** Actionbar im Spiel: wer aus Discord/TeamSpeak gerade spricht. */
|
||||
private void sendSpeakers() {
|
||||
try {
|
||||
for (Room room : rooms.values()) {
|
||||
if (!room.active()) continue;
|
||||
List<String> speakers = room.externalSpeakers(SPEAKING_MILLIS);
|
||||
if (!speakers.isEmpty()) plugin.sendSpeakers(room.key(), speakers);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warn("Sprecher-Anzeige fehlgeschlagen", e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Message.RoomInfo> buildInfos() {
|
||||
List<Message.RoomInfo> infos = new ArrayList<>(rooms.size());
|
||||
for (Room room : rooms.values()) {
|
||||
DiscordRoomBot bot = discordBots.get(room.key());
|
||||
infos.add(new Message.RoomInfo(room.key(), room.name(), room.groupId(),
|
||||
teamspeak != null ? teamspeak.humansIn(room) : 0,
|
||||
bot != null ? bot.humans() : 0,
|
||||
teamspeak != null ? teamspeak.participants(room).size() : 0,
|
||||
bot != null ? bot.participants().size() : 0,
|
||||
room.active()));
|
||||
}
|
||||
return infos;
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.net.SocketAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
@@ -25,7 +26,7 @@ final class PluginLink {
|
||||
private final DatagramSocket socket;
|
||||
private final Map<String, Room> rooms;
|
||||
private final Supplier<List<Message.RoomInfo>> roomInfos;
|
||||
private final Map<String, Integer> minecraftMembers = new ConcurrentHashMap<>();
|
||||
private final Map<String, List<Message.Member>> minecraftMembers = new ConcurrentHashMap<>();
|
||||
|
||||
private volatile SocketAddress plugin;
|
||||
private volatile long lastHello;
|
||||
@@ -47,8 +48,22 @@ final class PluginLink {
|
||||
return System.currentTimeMillis() - lastHello < ALIVE_MILLIS;
|
||||
}
|
||||
|
||||
int minecraftMembers(String room) {
|
||||
return alive() ? minecraftMembers.getOrDefault(room, 0) : 0;
|
||||
/** Spieler in der Gruppe (UUID → Name), leer solange das Plugin sich nicht meldet. */
|
||||
Map<String, String> minecraftMembers(String room) {
|
||||
if (!alive()) return Map.of();
|
||||
Map<String, String> result = new TreeMap<>();
|
||||
for (Message.Member member : minecraftMembers.getOrDefault(room, List.of())) result.put(member.id().toString(), member.name());
|
||||
return result;
|
||||
}
|
||||
|
||||
void sendNotice(String room, String text) {
|
||||
SocketAddress target = plugin;
|
||||
if (target != null && alive()) send(new Message.Notice(room, text), target);
|
||||
}
|
||||
|
||||
void sendSpeakers(String room, List<String> names) {
|
||||
SocketAddress target = plugin;
|
||||
if (target != null && alive()) send(new Message.Speakers(room, names), target);
|
||||
}
|
||||
|
||||
void sendAudio(String room, UUID source, byte[] opus) {
|
||||
@@ -105,6 +120,8 @@ final class PluginLink {
|
||||
if (room != null) room.fromMinecraft(audio.source(), audio.opus());
|
||||
}
|
||||
case Message.Rooms ignored -> {}
|
||||
case Message.Notice ignored -> {}
|
||||
case Message.Speakers ignored -> {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@@ -35,6 +36,9 @@ public final class Room {
|
||||
private final Mixer toDiscord = new Mixer();
|
||||
private final Map<String, Source> sources = new ConcurrentHashMap<>();
|
||||
|
||||
/** Anzeigename eines Sprechers (Seite, ID ohne Präfix), für die Actionbar. */
|
||||
private volatile BiFunction<Side, String, String> names = (side, id) -> id;
|
||||
|
||||
/** Wohin Frames für Minecraft gehen (Plugin-Verbindung). */
|
||||
private volatile MinecraftSink minecraft = (room, source, opus) -> {};
|
||||
|
||||
@@ -55,6 +59,7 @@ public final class Room {
|
||||
final FrameSplitter splitter = new FrameSplitter();
|
||||
OpusEncoder minecraftEncoder;
|
||||
volatile long lastSeen;
|
||||
volatile String name;
|
||||
int lastSequence = -1;
|
||||
|
||||
Source(Side side, String key) {
|
||||
@@ -78,6 +83,24 @@ public final class Room {
|
||||
public Mixer toDiscord() { return toDiscord; }
|
||||
|
||||
public void setMinecraftSink(MinecraftSink sink) { this.minecraft = sink; }
|
||||
public void setNameResolver(BiFunction<Side, String, String> names) { this.names = names; }
|
||||
|
||||
/** Wer aus Discord/TeamSpeak in den letzten {@code millis} Audio geschickt hat, als "Name (Plattform)". */
|
||||
public List<String> externalSpeakers(long millis) {
|
||||
long since = System.currentTimeMillis() - millis;
|
||||
return sources.values().stream()
|
||||
.filter(s -> s.side != Side.MINECRAFT && s.lastSeen >= since)
|
||||
.map(s -> s.name + " (" + label(s.side) + ")")
|
||||
.sorted().toList();
|
||||
}
|
||||
|
||||
public static String label(Side side) {
|
||||
return switch (side) {
|
||||
case MINECRAFT -> "Minecraft";
|
||||
case TEAMSPEAK -> "TeamSpeak";
|
||||
case DISCORD -> "Discord";
|
||||
};
|
||||
}
|
||||
|
||||
void setActive(boolean active) {
|
||||
if (this.active == active) return;
|
||||
@@ -109,6 +132,7 @@ public final class Room {
|
||||
if (!active || opus.length == 0) return;
|
||||
Source source = sources.computeIfAbsent(key, k -> new Source(side, k));
|
||||
source.lastSeen = System.currentTimeMillis();
|
||||
if (source.name == null) source.name = names.apply(side, key.substring(3));
|
||||
|
||||
List<short[]> frames = new ArrayList<>(2);
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package eu.mhsl.voicebridge.bridge.audio;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Kurze Signaltöne für Beitritt (aufsteigend) und Verlassen (absteigend), als 20-ms-Frames. */
|
||||
public final class Tones {
|
||||
private static final int AMPLITUDE = 3500;
|
||||
private static final int NOTE_MILLIS = 80;
|
||||
private static final int GAP_MILLIS = 20;
|
||||
|
||||
public static final List<short[]> JOIN = frames(660, 990);
|
||||
public static final List<short[]> LEAVE = frames(990, 660);
|
||||
|
||||
private Tones() {}
|
||||
|
||||
private static List<short[]> frames(double first, double second) {
|
||||
int note = Opus.SAMPLE_RATE * NOTE_MILLIS / 1000;
|
||||
int gap = Opus.SAMPLE_RATE * GAP_MILLIS / 1000;
|
||||
short[] pcm = new short[2 * note + gap];
|
||||
tone(pcm, 0, note, first);
|
||||
tone(pcm, note + gap, note, second);
|
||||
|
||||
List<short[]> frames = new ArrayList<>();
|
||||
for (int offset = 0; offset < pcm.length; offset += Opus.FRAME_SAMPLES) {
|
||||
short[] frame = new short[Opus.FRAME_SAMPLES];
|
||||
System.arraycopy(pcm, offset, frame, 0, Math.min(Opus.FRAME_SAMPLES, pcm.length - offset));
|
||||
frames.add(frame);
|
||||
}
|
||||
return List.copyOf(frames);
|
||||
}
|
||||
|
||||
/** Sinus mit kurzem Ein- und Ausblenden, damit es nicht knackt. */
|
||||
private static void tone(short[] pcm, int start, int length, double frequency) {
|
||||
int fade = length / 8;
|
||||
for (int i = 0; i < length; i++) {
|
||||
double envelope = Math.min(1.0, Math.min(i, length - 1 - i) / (double) fade);
|
||||
pcm[start + i] = (short) (AMPLITUDE * envelope * Math.sin(2 * Math.PI * frequency * i / Opus.SAMPLE_RATE));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,13 @@ import net.dv8tion.jda.api.audio.OpusPacket;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.dv8tion.jda.api.entities.channel.concrete.Category;
|
||||
import net.dv8tion.jda.api.entities.channel.attribute.IVoiceStatusChannel;
|
||||
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
|
||||
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import net.dv8tion.jda.api.managers.AudioManager;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import net.dv8tion.jda.api.utils.MarkdownSanitizer;
|
||||
import net.dv8tion.jda.api.utils.MemberCachePolicy;
|
||||
import net.dv8tion.jda.api.utils.cache.CacheFlag;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -29,6 +31,8 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -137,15 +141,56 @@ public final class DiscordRoomBot implements AudioSendHandler, AudioReceiveHandl
|
||||
return channel;
|
||||
}
|
||||
|
||||
/** Menschen im Raum-Channel (Bots zählen nicht). */
|
||||
public int humans() {
|
||||
/** Menschen im Raum-Channel (User-ID → Anzeigename), Bots zählen nicht. */
|
||||
public Map<String, String> participants() {
|
||||
VoiceChannel channel = channel();
|
||||
if (channel == null) return Map.of();
|
||||
Map<String, String> result = new TreeMap<>();
|
||||
for (Member member : channel.getMembers()) {
|
||||
if (!member.getUser().isBot()) result.put(member.getId(), member.getEffectiveName());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Anzeigename eines Users, für die Sprecher-Anzeige. */
|
||||
public String name(long userId) {
|
||||
Guild guild = this.guild;
|
||||
if (guild == null || channelId == 0) return 0;
|
||||
VoiceChannel channel = guild.getVoiceChannelById(channelId);
|
||||
if (channel == null) return 0;
|
||||
int count = 0;
|
||||
for (Member member : channel.getMembers()) if (!member.getUser().isBot()) count++;
|
||||
return count;
|
||||
Member member = guild == null ? null : guild.getMemberById(userId);
|
||||
return member == null ? "?" : member.getEffectiveName();
|
||||
}
|
||||
|
||||
/** Ob der Bot eingeloggt ist und seinen Channel kennt. */
|
||||
public boolean ready() {
|
||||
return guild != null && channelId != 0;
|
||||
}
|
||||
|
||||
/** Ob der Bot gerade im Voice-Channel ist. */
|
||||
public boolean inVoice() {
|
||||
Guild guild = this.guild;
|
||||
return guild != null && joined && guild.getAudioManager().isConnected();
|
||||
}
|
||||
|
||||
/** Nachricht im Text-Chat des Voice-Channels. */
|
||||
public void sendText(String text) {
|
||||
VoiceChannel channel = channel();
|
||||
if (channel == null) return;
|
||||
channel.sendMessage(MarkdownSanitizer.escape(text)).setSuppressedNotifications(true).queue(null,
|
||||
e -> LOG.warn("{}: Nachricht nicht gesendet ({}). Hat der Bot \"Nachrichten senden\"?", room.name(), e.getMessage()));
|
||||
}
|
||||
|
||||
/** Status unter dem Voice-Channel (leer = löschen). Geht nur, solange der Bot im Channel ist. */
|
||||
public void setStatus(String status) {
|
||||
VoiceChannel channel = channel();
|
||||
if (channel == null) return;
|
||||
String text = status.length() > IVoiceStatusChannel.MAX_STATUS_LENGTH
|
||||
? status.substring(0, IVoiceStatusChannel.MAX_STATUS_LENGTH) : status;
|
||||
channel.modifyStatus(text).queue(null,
|
||||
e -> LOG.warn("{}: Status nicht gesetzt ({}). Hat der Bot \"Voice-Channel-Status setzen\"?", room.name(), e.getMessage()));
|
||||
}
|
||||
|
||||
private VoiceChannel channel() {
|
||||
Guild guild = this.guild;
|
||||
return guild == null || channelId == 0 ? null : guild.getVoiceChannelById(channelId);
|
||||
}
|
||||
|
||||
public void setConnected(boolean connected) {
|
||||
|
||||
@@ -65,6 +65,18 @@ final class TeamspeakRoomClient implements Microphone, TS3Listener {
|
||||
return socket.getClientId();
|
||||
}
|
||||
|
||||
boolean connected() {
|
||||
return !closing && socket.isConnected();
|
||||
}
|
||||
|
||||
void sendChannelMessage(String text) {
|
||||
try {
|
||||
socket.sendChannelMessage(channel, text);
|
||||
} catch (Exception e) {
|
||||
LOG.debug("{}: Textnachricht nicht gesendet: {}", room.name(), e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
closing = true;
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -34,7 +35,7 @@ public final class TeamspeakSide {
|
||||
private static final long RETRY_MIN_MILLIS = 30_000;
|
||||
private static final long RETRY_MAX_MILLIS = 300_000;
|
||||
|
||||
private record TsClient(int channel, int type) {}
|
||||
private record TsClient(int channel, int type, String name) {}
|
||||
private record TsChannel(int parent, String name) {}
|
||||
|
||||
private final BridgeConfig.Teamspeak config;
|
||||
@@ -73,17 +74,51 @@ public final class TeamspeakSide {
|
||||
return ready;
|
||||
}
|
||||
|
||||
/** Menschen im Raum-Channel, ohne unsere eigenen Clients und ohne ServerQuery. */
|
||||
public int humansIn(Room room) {
|
||||
/** Menschen im Raum-Channel (Client-ID → Nickname), ohne unsere eigenen Clients und ohne ServerQuery. */
|
||||
public Map<String, String> participants(Room room) {
|
||||
Integer channel = roomChannels.get(room.key());
|
||||
if (!ready || channel == null) return 0;
|
||||
if (!ready || channel == null) return Map.of();
|
||||
Set<Integer> own = ownClientIds();
|
||||
int count = 0;
|
||||
Map<String, String> result = new TreeMap<>();
|
||||
for (Map.Entry<Integer, TsClient> e : clients.entrySet()) {
|
||||
TsClient client = e.getValue();
|
||||
if (client.channel() == channel && client.type() == CLIENT_TYPE_VOICE && !own.contains(e.getKey())) count++;
|
||||
if (client.channel() == channel && client.type() == CLIENT_TYPE_VOICE && !own.contains(e.getKey())) {
|
||||
result.put(Integer.toString(e.getKey()), client.name());
|
||||
}
|
||||
}
|
||||
return count;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Nickname eines Clients, für die Sprecher-Anzeige. */
|
||||
public String nickname(int clientId) {
|
||||
TsClient client = clients.get(clientId);
|
||||
return client == null ? "?" : client.name();
|
||||
}
|
||||
|
||||
/** Ob der Raum-Client gerade im Channel ist. */
|
||||
public boolean roomConnected(Room room) {
|
||||
TeamspeakRoomClient client = roomClients.get(room.key());
|
||||
return client != null && client.connected();
|
||||
}
|
||||
|
||||
/** Textnachricht des Raum-Clients in seinen Channel. */
|
||||
public void sendRoomMessage(Room room, String text) {
|
||||
TeamspeakRoomClient client = roomClients.get(room.key());
|
||||
if (client != null && client.connected()) executor.execute(() -> client.sendChannelMessage(text));
|
||||
}
|
||||
|
||||
/** Channel-Thema per Query setzen (leer = löschen). */
|
||||
public void setRoomTopic(Room room, String topic) {
|
||||
Integer channel = roomChannels.get(room.key());
|
||||
TsQuery q = query;
|
||||
if (!ready || q == null || channel == null) return;
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
q.send("channeledit", "cid", Integer.toString(channel), "channel_topic", topic);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("{}: Channel-Thema nicht gesetzt: {}", room.name(), e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,7 +235,8 @@ public final class TeamspeakSide {
|
||||
private void loadClients(TsQuery q) throws IOException {
|
||||
Map<Integer, TsClient> fresh = new ConcurrentHashMap<>();
|
||||
for (Map<String, String> c : q.send("clientlist")) {
|
||||
fresh.put(parse(c.get("clid"), -1), new TsClient(parse(c.get("cid"), 0), parse(c.get("client_type"), 0)));
|
||||
fresh.put(parse(c.get("clid"), -1), new TsClient(parse(c.get("cid"), 0), parse(c.get("client_type"), 0),
|
||||
c.getOrDefault("client_nickname", "?")));
|
||||
}
|
||||
clients.clear();
|
||||
clients.putAll(fresh);
|
||||
@@ -269,10 +305,15 @@ public final class TeamspeakSide {
|
||||
int clid = parse(f.get("clid"), -1);
|
||||
int cid = parse(f.get("cid"), -1);
|
||||
switch (n.name()) {
|
||||
case "notifycliententerview" -> clients.put(clid, new TsClient(parse(f.get("ctid"), 0), parse(f.get("client_type"), 0)));
|
||||
case "notifycliententerview" -> clients.put(clid, new TsClient(parse(f.get("ctid"), 0), parse(f.get("client_type"), 0),
|
||||
f.getOrDefault("client_nickname", "?")));
|
||||
case "notifyclientleftview" -> clients.remove(clid);
|
||||
case "notifyclientmoved" -> clients.compute(clid, (id, old) ->
|
||||
new TsClient(parse(f.get("ctid"), 0), old == null ? CLIENT_TYPE_VOICE : old.type()));
|
||||
new TsClient(parse(f.get("ctid"), 0), old == null ? CLIENT_TYPE_VOICE : old.type(), old == null ? "?" : old.name()));
|
||||
case "notifyclientupdated" -> {
|
||||
String name = f.get("client_nickname");
|
||||
if (name != null) clients.computeIfPresent(clid, (id, old) -> new TsClient(old.channel(), old.type(), name));
|
||||
}
|
||||
case "notifychannelcreated" -> channels.put(cid, new TsChannel(parse(f.get("cpid"), 0), f.getOrDefault("channel_name", "")));
|
||||
case "notifychanneledited" -> {
|
||||
String name = f.get("channel_name");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package eu.mhsl.voicebridge.bridge;
|
||||
|
||||
import eu.mhsl.voicebridge.bridge.Room.Side;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AnnouncerTest {
|
||||
|
||||
@Test
|
||||
void othersSkipsOwnAndEmptySides() {
|
||||
Map<Side, Map<String, String>> roster = new EnumMap<>(Side.class);
|
||||
roster.put(Side.MINECRAFT, new TreeMap<>(Map.of("a", "Alex", "b", "Steve")));
|
||||
roster.put(Side.TEAMSPEAK, Map.of());
|
||||
roster.put(Side.DISCORD, Map.of("1", "Anna"));
|
||||
|
||||
assertEquals("Minecraft: Alex, Steve", Announcer.others(roster, Side.DISCORD, " · "));
|
||||
assertEquals("Minecraft: Alex, Steve | Discord: Anna", Announcer.others(roster, Side.TEAMSPEAK, " | "));
|
||||
assertEquals("Discord: Anna", Announcer.others(roster, Side.MINECRAFT, " · "));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user