Even more refactoring

This commit is contained in:
Norbi Peti 2019-04-24 17:50:13 +02:00
parent 59066ce09a
commit 2500572e0d
4 changed files with 54 additions and 66 deletions

View file

@ -18,6 +18,7 @@ import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.PrivateChannel; import discord4j.core.object.entity.PrivateChannel;
import discord4j.core.object.entity.TextChannel; import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User;
import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.EmbedCreateSpec;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -25,14 +26,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.User;
import sx.blah.discord.handle.obj.Message;
import sx.blah.discord.handle.obj.MessageChannel;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.MissingPermissionsException;
import java.awt.*; import java.awt.*;
import java.time.Instant; import java.time.Instant;
@ -265,22 +258,21 @@ public class MCChatListener implements Listener {
} }
private void processDiscordToMC() { private void processDiscordToMC() {
@val MessageCreateEvent event;
sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent event;
try { try {
event = recevents.take(); event = recevents.take();
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
rectask.cancel(); rectask.cancel();
return; return;
} }
val sender = event.getMessage().getAuthor(); val sender = event.getMessage().getAuthor().orElse(null);
String dmessage = event.getMessage().getContent(); String dmessage = event.getMessage().getContent().orElse("");
try { try {
final DiscordSenderBase dsender = MCChatUtils.getSender(event.getMessage().getChannel(), sender); final DiscordSenderBase dsender = MCChatUtils.getSender(event.getMessage().getChannelId(), sender);
val user = dsender.getChromaUser(); val user = dsender.getChromaUser();
for (User u : event.getMessage().getMentions()) { for (User u : event.getMessage().getUserMentions()) { //TODO: Role mentions
dmessage = dmessage.replace(u.mention(false), "@" + u.getName()); // TODO: IG Formatting dmessage = dmessage.replace(u.me(false), "@" + u.getName()); // TODO: IG Formatting
final String nick = u.getNicknameForGuild(DiscordPlugin.mainServer); final String nick = u.getNicknameForGuild(DiscordPlugin.mainServer);
dmessage = dmessage.replace(u.mention(true), "@" + (nick != null ? nick : u.getName())); dmessage = dmessage.replace(u.mention(true), "@" + (nick != null ? nick : u.getName()));
} }

View file

@ -4,6 +4,7 @@ import buttondevteam.discordplugin.DiscordConnectedPlayer;
import buttondevteam.discordplugin.DiscordPlayer; import buttondevteam.discordplugin.DiscordPlayer;
import buttondevteam.discordplugin.DiscordPlugin; import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
import discord4j.core.object.entity.MessageChannel;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.Event; import org.bukkit.event.Event;

View file

@ -1,14 +1,11 @@
package buttondevteam.discordplugin.mcchat; package buttondevteam.discordplugin.mcchat;
import buttondevteam.core.ComponentManager; import buttondevteam.core.ComponentManager;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.discordplugin.*; import buttondevteam.discordplugin.*;
import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule; import buttondevteam.discordplugin.broadcaster.GeneralEventBroadcasterModule;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
import discord4j.core.object.entity.Message; import discord4j.core.object.entity.*;
import discord4j.core.object.entity.MessageChannel; import discord4j.core.object.util.Snowflake;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User;
import io.netty.util.collection.LongObjectHashMap; import io.netty.util.collection.LongObjectHashMap;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.experimental.var; import lombok.experimental.var;
@ -35,12 +32,12 @@ public class MCChatUtils {
/** /**
* May contain P<DiscordID> as key for public chat * May contain P<DiscordID> as key for public chat
*/ */
public static final HashMap<String, HashMap<Channel, DiscordSender>> UnconnectedSenders = new HashMap<>(); public static final HashMap<String, HashMap<Snowflake, DiscordSender>> UnconnectedSenders = new HashMap<>();
public static final HashMap<String, HashMap<Channel, DiscordConnectedPlayer>> ConnectedSenders = new HashMap<>(); public static final HashMap<String, HashMap<Snowflake, DiscordConnectedPlayer>> ConnectedSenders = new HashMap<>();
/** /**
* May contain P&lt;DiscordID&gt; as key for public chat * May contain P&lt;DiscordID&gt; as key for public chat
*/ */
public static final HashMap<String, HashMap<Channel, DiscordPlayerSender>> OnlineSenders = new HashMap<>(); public static final HashMap<String, HashMap<Snowflake, DiscordPlayerSender>> OnlineSenders = new HashMap<>();
static @Nullable LastMsgData lastmsgdata; static @Nullable LastMsgData lastmsgdata;
static LongObjectHashMap<Message> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks static LongObjectHashMap<Message> lastmsgfromd = new LongObjectHashMap<>(); // Last message sent by a Discord user, used for clearing checkmarks
private static MinecraftChatModule module; private static MinecraftChatModule module;
@ -76,31 +73,31 @@ public class MCChatUtils {
lmd.channel.edit(tce -> tce.setTopic(String.join("\n----\n", s)).setReason("Player list update")).subscribe(); //Don't wait lmd.channel.edit(tce -> tce.setTopic(String.join("\n----\n", s)).setReason("Player list update")).subscribe(); //Don't wait
} }
public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<Channel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<Snowflake, T>> senders,
User user, T sender) { User user, T sender) {
return addSender(senders, user.getId().asString(), sender); return addSender(senders, user.getId().asString(), sender);
} }
public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<MessageChannel, T>> senders, public static <T extends DiscordSenderBase> T addSender(HashMap<String, HashMap<Snowflake, T>> senders,
String did, T sender) { String did, T sender) {
var map = senders.get(did); var map = senders.get(did);
if (map == null) if (map == null)
map = new HashMap<>(); map = new HashMap<>();
map.put(sender.getChannel(), sender); map.put(sender.getChannel().getId(), sender);
senders.put(did, map); senders.put(did, map);
return sender; return sender;
} }
public static <T extends DiscordSenderBase> T getSender(HashMap<String, HashMap<MessageChannel, T>> senders, public static <T extends DiscordSenderBase> T getSender(HashMap<String, HashMap<Snowflake, T>> senders,
MessageChannel channel, User user) { Snowflake channel, User user) {
var map = senders.get(user.getId().asString()); var map = senders.get(user.getId().asString());
if (map != null) if (map != null)
return map.get(channel); return map.get(channel);
return null; return null;
} }
public static <T extends DiscordSenderBase> T removeSender(HashMap<String, HashMap<Channel, T>> senders, public static <T extends DiscordSenderBase> T removeSender(HashMap<String, HashMap<Snowflake, T>> senders,
Channel channel, User user) { Snowflake channel, User user) {
var map = senders.get(user.getId().asString()); var map = senders.get(user.getId().asString());
if (map != null) if (map != null)
return map.remove(channel); return map.remove(channel);
@ -176,7 +173,7 @@ public class MCChatUtils {
if (event.getChannel().isGlobal()) if (event.getChannel().isGlobal())
action.accept(module.chatChannel().get()); action.accept(module.chatChannel().get());
for (LastMsgData data : MCChatPrivate.lastmsgPerUser) for (LastMsgData data : MCChatPrivate.lastmsgPerUser)
if (event.shouldSendTo(getSender(data.channel, data.user))) if (event.shouldSendTo(getSender(data.channel.getId(), data.user)))
action.accept(data.channel); action.accept(data.channel);
MCChatCustom.lastmsgCustom.stream().filter(clmd -> { MCChatCustom.lastmsgCustom.stream().filter(clmd -> {
if (!clmd.brtoggles.contains(event.getTarget())) if (!clmd.brtoggles.contains(event.getTarget()))
@ -188,14 +185,14 @@ public class MCChatUtils {
/** /**
* This method will find the best sender to use: if the player is online, use that, if not but connected then use that etc. * This method will find the best sender to use: if the player is online, use that, if not but connected then use that etc.
*/ */
static DiscordSenderBase getSender(MessageChannel channel, final User author) { static DiscordSenderBase getSender(Snowflake channel, final User author) {
//noinspection OptionalGetWithoutIsPresent //noinspection OptionalGetWithoutIsPresent
return Stream.<Supplier<Optional<DiscordSenderBase>>>of( // https://stackoverflow.com/a/28833677/2703239 return Stream.<Supplier<Optional<DiscordSenderBase>>>of( // https://stackoverflow.com/a/28833677/2703239
() -> Optional.ofNullable(getSender(OnlineSenders, channel, author)), // Find first non-null () -> Optional.ofNullable(getSender(OnlineSenders, channel, author)), // Find first non-null
() -> Optional.ofNullable(getSender(ConnectedSenders, channel, author)), // This doesn't support the public chat, but it'll always return null for it () -> Optional.ofNullable(getSender(ConnectedSenders, channel, author)), // This doesn't support the public chat, but it'll always return null for it
() -> Optional.ofNullable(getSender(UnconnectedSenders, channel, author)), // () -> Optional.ofNullable(getSender(UnconnectedSenders, channel, author)), //
() -> Optional.of(addSender(UnconnectedSenders, author, () -> Optional.of(addSender(UnconnectedSenders, author,
new DiscordSender(author, channel)))).map(Supplier::get).filter(Optional::isPresent).map(Optional::get).findFirst().get(); new DiscordSender(author, (MessageChannel) DiscordPlugin.dc.getChannelById(channel).block())))).map(Supplier::get).filter(Optional::isPresent).map(Optional::get).findFirst().get();
} }
/** /**
@ -207,11 +204,11 @@ public class MCChatUtils {
public static void resetLastMessage(Channel channel) { public static void resetLastMessage(Channel channel) {
if (notEnabled()) return; if (notEnabled()) return;
if (channel.getId().asLong() == module.chatChannel().get().getId().asLong()) { if (channel.getId().asLong() == module.chatChannel().get().getId().asLong()) {
(lastmsgdata == null ? lastmsgdata = new LastMsgData(module.chatChannel().get(), null) (lastmsgdata == null ? lastmsgdata = new LastMsgData((TextChannel) module.chatChannel().get(), null)
: lastmsgdata).message = null; : lastmsgdata).message = null;
return; return;
} // Don't set the whole object to null, the player and channel information should be preserved } // Don't set the whole object to null, the player and channel information should be preserved
for (LastMsgData data : channel.isPrivate() ? MCChatPrivate.lastmsgPerUser : MCChatCustom.lastmsgCustom) { for (LastMsgData data : channel instanceof PrivateChannel ? MCChatPrivate.lastmsgPerUser : MCChatCustom.lastmsgCustom) {
if (data.channel.getId().asLong() == channel.getId().asLong()) { if (data.channel.getId().asLong() == channel.getId().asLong()) {
data.message = null; data.message = null;
return; return;

View file

@ -6,6 +6,9 @@ import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.player.*; import buttondevteam.lib.player.*;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import discord4j.core.object.entity.Role;
import discord4j.core.object.entity.User;
import discord4j.core.object.util.Snowflake;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.val; import lombok.val;
import net.ess3.api.events.AfkStatusChangeEvent; import net.ess3.api.events.AfkStatusChangeEvent;
@ -23,10 +26,9 @@ import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.BroadcastMessageEvent; import org.bukkit.event.server.BroadcastMessageEvent;
import sx.blah.discord.handle.obj.IRole; import reactor.core.publisher.Mono;
import sx.blah.discord.handle.obj.User;
import sx.blah.discord.util.DiscordException; import java.util.Objects;
import sx.blah.discord.util.MissingPermissionsException;
@RequiredArgsConstructor @RequiredArgsConstructor
class MCListener implements Listener { class MCListener implements Listener {
@ -49,9 +51,9 @@ class MCListener implements Listener {
final Player p = e.getPlayer(); final Player p = e.getPlayer();
DiscordPlayer dp = e.GetPlayer().getAs(DiscordPlayer.class); DiscordPlayer dp = e.GetPlayer().getAs(DiscordPlayer.class);
if (dp != null) { if (dp != null) {
val user = DiscordPlugin.dc.getUserByID(Long.parseLong(dp.getDiscordID())); val user = DiscordPlugin.dc.getUserById(Snowflake.of(dp.getDiscordID())).block();
MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(), MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(),
new DiscordPlayerSender(user, user.getOrCreatePMChannel(), p)); new DiscordPlayerSender(user, Objects.requireNonNull(user).getPrivateChannel().block(), p));
MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(), MCChatUtils.addSender(MCChatUtils.OnlineSenders, dp.getDiscordID(),
new DiscordPlayerSender(user, module.chatChannel().get(), p)); //Stored per-channel new DiscordPlayerSender(user, module.chatChannel().get(), p)); //Stored per-channel
} }
@ -99,38 +101,34 @@ class MCListener implements Listener {
MCChatUtils.forAllowedCustomAndAllMCChat(MCChatUtils.send(msg), base, ChannelconBroadcast.AFK, false); MCChatUtils.forAllowedCustomAndAllMCChat(MCChatUtils.send(msg), base, ChannelconBroadcast.AFK, false);
} }
private ConfigData<IRole> muteRole() { private ConfigData<Role> muteRole() {
return DPUtils.roleData(module.getConfig(), "muteRole", "Muted"); return DPUtils.roleData(module.getConfig(), "muteRole", "Muted");
} }
@EventHandler @EventHandler
public void onPlayerMute(MuteStatusChangeEvent e) { public void onPlayerMute(MuteStatusChangeEvent e) {
try { final Role role = muteRole().get();
DPUtils.performNoWait(() -> { if (role == null) return;
final IRole role = muteRole().get(); final CommandSource source = e.getAffected().getSource();
if (role == null) return; if (!source.isPlayer())
final CommandSource source = e.getAffected().getSource(); return;
if (!source.isPlayer()) final DiscordPlayer p = TBMCPlayerBase.getPlayer(source.getPlayer().getUniqueId(), TBMCPlayer.class)
return; .getAs(DiscordPlayer.class);
final DiscordPlayer p = TBMCPlayerBase.getPlayer(source.getPlayer().getUniqueId(), TBMCPlayer.class) if (p == null) return;
.getAs(DiscordPlayer.class); DiscordPlugin.dc.getUserById(Snowflake.of(p.getDiscordID()))
if (p == null) return; .flatMap(user -> user.asMember(DiscordPlugin.mainServer.getId()))
final User user = DiscordPlugin.dc.getUserByID( .flatMap(user -> {
Long.parseLong(p.getDiscordID()));
if (e.getValue()) if (e.getValue())
user.addRole(role); user.addRole(role.getId());
else else
user.removeRole(role); user.removeRole(role.getId());
val modlog = module.modlogChannel().get(); val modlog = module.modlogChannel().get();
String msg = (e.getValue() ? "M" : "Unm") + "uted user: " + user.getName(); String msg = (e.getValue() ? "M" : "Unm") + "uted user: " + user.getUsername() + "#" + user.getDiscriminator();
if (modlog != null)
DiscordPlugin.sendMessageToChannel(modlog, msg);
DPUtils.getLogger().info(msg); DPUtils.getLogger().info(msg);
}); if (modlog != null)
} catch (DiscordException | MissingPermissionsException ex) { return modlog.createMessage(msg);
TBMCCoreAPI.SendException("Failed to give/take Muted role to player " + e.getAffected().getName() + "!", return Mono.empty();
ex); }).subscribe();
}
} }
@EventHandler @EventHandler
@ -148,8 +146,8 @@ class MCListener implements Listener {
String name = event.getSender() instanceof Player ? ((Player) event.getSender()).getDisplayName() String name = event.getSender() instanceof Player ? ((Player) event.getSender()).getDisplayName()
: event.getSender().getName(); : event.getSender().getName();
//Channel channel = ChromaGamerBase.getFromSender(event.getSender()).channel().get(); - TODO //Channel channel = ChromaGamerBase.getFromSender(event.getSender()).channel().get(); - TODO
val yeehaw = DiscordPlugin.mainServer.getEmojiByName("YEEHAW"); DiscordPlugin.mainServer.getEmojis().filter(e -> "YEEHAW".equals(e.getName())).subscribe(yeehaw ->
MCChatUtils.forAllMCChat(MCChatUtils.send(name + (yeehaw != null ? " <:YEEHAW:" + yeehaw.getId().asString() + ">s" : " YEEHAWs"))); MCChatUtils.forAllMCChat(MCChatUtils.send(name + (yeehaw != null ? " <:YEEHAW:" + yeehaw.getId().asString() + ">s" : " YEEHAWs"))));
} }
@EventHandler @EventHandler