Search in sources :

Example 1 with ConsoleAppender

use of github.scarsz.discordsrv.objects.log4j.ConsoleAppender in project DiscordSRV by Scarsz.

the class DiscordSRV method init.

public void init() {
    // check if the person is trying to use the plugin without updating to ASM 5
    try {
        File specialSourceFile = new File("libraries/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
        if (!specialSourceFile.exists())
            specialSourceFile = new File("bin/net/md-5/SpecialSource/1.7-SNAPSHOT/SpecialSource-1.7-SNAPSHOT.jar");
        if (specialSourceFile.exists() && DigestUtils.md5Hex(FileUtils.readFileToByteArray(specialSourceFile)).equalsIgnoreCase("096777a1b6098130d6c925f1c04050a3")) {
            DiscordSRV.warning(LangUtil.InternalMessage.ASM_WARNING.toString().replace("{specialsourcefolder}", specialSourceFile.getParentFile().getPath()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // remove all event listeners from existing jda to prevent having multiple listeners when jda is recreated
    if (jda != null)
        jda.getRegisteredListeners().forEach(o -> jda.removeEventListener(o));
    // make sure configuration file exists, save default ones if they don't
    if (!configFile.exists()) {
        LangUtil.saveConfig();
        reloadConfig();
    }
    // make sure lang file exists, save default ones if they don't
    if (!messagesFile.exists()) {
        LangUtil.saveMessages();
        LangUtil.reloadMessages();
    }
    ConfigUtil.migrate();
    try {
        getConfig();
    } catch (IllegalArgumentException e) {
        DiscordSRV.error(LangUtil.InternalMessage.INVALID_CONFIG + ": " + e.getMessage());
        try {
            new Yaml().load(FileUtils.readFileToString(getConfigFile(), Charset.forName("UTF-8")));
        } catch (IOException io) {
            DiscordSRV.error(io.getMessage());
        }
        return;
    }
    // update check
    if (!getConfig().getBoolean("UpdateCheckDisabled")) {
        updateIsAvailable = UpdateUtil.checkForUpdates();
        // don't load other shit if the plugin was disabled by the update checker
        if (!isEnabled())
            return;
    }
    // cool kids club thank yous
    if (!getConfig().getBoolean("CoolKidsClubThankYousDisabled")) {
        String thankYou = HttpUtil.requestHttp("https://github.com/Scarsz/DiscordSRV/raw/randomaccessfiles/coolkidsclub").replace("\n", "");
        if (thankYou.length() > 1)
            DiscordSRV.info(LangUtil.InternalMessage.DONATOR_THANKS + ": " + thankYou);
    }
    // random phrases for debug handler
    if (!getConfig().getBoolean("RandomPhrasesDisabled"))
        Collections.addAll(randomPhrases, HttpUtil.requestHttp("https://raw.githubusercontent.com/Scarsz/DiscordSRV/randomaccessfiles/randomphrases").split("\n"));
    // shutdown previously existing jda if plugin gets reloaded
    if (jda != null)
        try {
            jda.shutdown();
            jda = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    // set proxy just in case this JVM is fucking stupid
    if (ProxySelector.getDefault() == null) {
        ProxySelector.setDefault(new ProxySelector() {

            private final List<Proxy> DIRECT_CONNECTION = Collections.unmodifiableList(Collections.singletonList(Proxy.NO_PROXY));

            public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) {
            }

            public List<Proxy> select(URI uri) {
                return DIRECT_CONNECTION;
            }
        });
    }
    // check log4j capabilities
    boolean serverIsLog4jCapable = false;
    try {
        serverIsLog4jCapable = Class.forName("org.apache.logging.log4j.core.Logger") != null;
    } catch (ClassNotFoundException e) {
        error("Log4j classes are NOT available, console channel will not be attached");
    }
    // add log4j filter for JDA messages
    if (serverIsLog4jCapable)
        ((org.apache.logging.log4j.core.Logger) org.apache.logging.log4j.LogManager.getRootLogger()).addFilter(new JdaFilter());
    // log in to discord
    try {
        jda = new JDABuilder(AccountType.BOT).setAudioEnabled(false).setAutoReconnect(true).setBulkDeleteSplittingEnabled(false).setToken(getConfig().getString("BotToken")).addEventListener(new DiscordBanListener()).addEventListener(new DiscordChatListener()).addEventListener(new DiscordConsoleListener()).addEventListener(new DiscordDebugListener()).addEventListener(new DiscordAccountLinkListener()).buildAsync();
    } catch (LoginException e) {
        DiscordSRV.error(LangUtil.InternalMessage.FAILED_TO_CONNECT_TO_DISCORD + ": " + e.getMessage());
        return;
    } catch (Exception e) {
        DiscordSRV.error("An unknown error occurred building JDA...");
        e.printStackTrace();
        return;
    }
    while (jda.getStatus() != JDA.Status.CONNECTED) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    // game status
    if (!getConfig().getString("DiscordGameStatus").isEmpty()) {
        DiscordUtil.setGameStatus(getConfig().getString("DiscordGameStatus"));
    }
    // print the things the bot can see
    for (Guild server : jda.getGuilds()) {
        DiscordSRV.info(LangUtil.InternalMessage.FOUND_SERVER + " " + server);
        for (TextChannel channel : server.getTextChannels()) DiscordSRV.info("- " + channel);
    }
    // show warning if bot wasn't in any guilds
    if (jda.getGuilds().size() == 0) {
        DiscordSRV.error(LangUtil.InternalMessage.BOT_NOT_IN_ANY_SERVERS);
        return;
    }
    // set console channel
    String consoleChannelId = getConfig().getString("DiscordConsoleChannelId");
    if (consoleChannelId != null)
        consoleChannel = DiscordUtil.getTextChannelById(consoleChannelId);
    // see if console channel exists; if it does, tell user where it's been assigned & add console appender
    if (serverIsLog4jCapable && consoleChannel != null) {
        DiscordSRV.info(LangUtil.InternalMessage.CONSOLE_FORWARDING_ASSIGNED_TO_CHANNEL + " " + consoleChannel);
        // attach appender to queue console messages
        new ConsoleAppender();
        // start console message queue worker thread
        if (consoleMessageQueueWorker != null) {
            if (consoleMessageQueueWorker.getState() == Thread.State.NEW) {
                consoleMessageQueueWorker.start();
            } else {
                consoleMessageQueueWorker.interrupt();
                consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
                consoleMessageQueueWorker.start();
            }
        } else {
            consoleMessageQueueWorker = new ConsoleMessageQueueWorker();
            consoleMessageQueueWorker.start();
        }
    } else {
        DiscordSRV.info(LangUtil.InternalMessage.NOT_FORWARDING_CONSOLE_OUTPUT.toString());
    }
    // load channels
    for (Map.Entry<String, Object> channelEntry : ((MemorySection) getConfig().get("Channels")).getValues(true).entrySet()) channels.put(channelEntry.getKey(), DiscordUtil.getTextChannelById((String) channelEntry.getValue()));
    // warn if no channels have been linked
    if (getMainTextChannel() == null)
        DiscordSRV.warning(LangUtil.InternalMessage.NO_CHANNELS_LINKED);
    if (getMainTextChannel() == null && consoleChannel == null)
        DiscordSRV.error(LangUtil.InternalMessage.NO_CHANNELS_LINKED_NOR_CONSOLE);
    // warn if the console channel is connected to a chat channel
    if (getMainTextChannel() != null && consoleChannel != null && getMainTextChannel().getId().equals(consoleChannel.getId()))
        DiscordSRV.warning(LangUtil.InternalMessage.CONSOLE_CHANNEL_ASSIGNED_TO_LINKED_CHANNEL);
    // send server startup message
    DiscordUtil.sendMessage(getMainTextChannel(), LangUtil.Message.SERVER_STARTUP_MESSAGE.toString(), 0, false);
    // start channel topic updater
    if (serverWatchdog != null) {
        if (serverWatchdog.getState() == Thread.State.NEW) {
            serverWatchdog.start();
        } else {
            serverWatchdog.interrupt();
            serverWatchdog = new ServerWatchdog();
            serverWatchdog.start();
        }
    } else {
        serverWatchdog = new ServerWatchdog();
        serverWatchdog.start();
    }
    // start lag (tps) monitor
    Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L);
    // cancellation detector
    if (getConfig().getInt("DebugLevel") > 0) {
        if (cancellationDetector != null) {
            cancellationDetector.close();
            cancellationDetector = null;
        }
        cancellationDetector = new CancellationDetector<>(AsyncPlayerChatEvent.class);
        cancellationDetector.addListener((plugin, event) -> DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_CANCELLED_CHAT_EVENT.toString().replace("{plugin}", plugin.toString()).replace("{author}", event.getPlayer().getName()).replace("{message}", event.getMessage())));
        DiscordSRV.info(LangUtil.InternalMessage.CHAT_CANCELLATION_DETECTOR_ENABLED);
    }
    // load account links
    accountLinkManager = new AccountLinkManager();
    // register events
    Bukkit.getPluginManager().registerEvents(this, this);
    new PlayerAchievementsListener();
    try {
        if (Class.forName("org.bukkit.advancement.Advancement") != null)
            new PlayerAdvancementDoneListener();
    } catch (ClassNotFoundException ignored) {
    }
    new PlayerBanListener();
    new PlayerDeathListener();
    new PlayerJoinLeaveListener();
    // in-game chat events
    if (PluginUtil.pluginHookIsEnabled("herochat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "HeroChat"));
        getServer().getPluginManager().registerEvents(new HerochatHook(), this);
    } else if (PluginUtil.pluginHookIsEnabled("legendchat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LegendChat"));
        getServer().getPluginManager().registerEvents(new LegendChatHook(), this);
    } else if (PluginUtil.pluginHookIsEnabled("lunachat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "LunaChat"));
        getServer().getPluginManager().registerEvents(new LunaChatHook(), this);
    } else if (PluginUtil.checkIfPluginEnabled("towny") && PluginUtil.pluginHookIsEnabled("townychat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "TownyChat"));
        getServer().getPluginManager().registerEvents(new TownyChatHook(), this);
    } else if (PluginUtil.pluginHookIsEnabled("ultimatechat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "UltimateChat"));
        getServer().getPluginManager().registerEvents(new UltimateChatHook(), this);
    } else if (PluginUtil.pluginHookIsEnabled("venturechat")) {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOK_ENABLING.toString().replace("{plugin}", "VentureChat"));
        getServer().getPluginManager().registerEvents(new VentureChatHook(), this);
    } else {
        DiscordSRV.info(LangUtil.InternalMessage.PLUGIN_HOOKS_NOT_ENABLED);
        getServer().getPluginManager().registerEvents(new PlayerChatListener(), this);
    }
    // load user-defined colors
    colors.clear();
    for (Map.Entry<String, Object> colorEntry : ((MemorySection) getConfig().get("DiscordChatChannelColorTranslations")).getValues(true).entrySet()) colors.put(colorEntry.getKey().toUpperCase(), (String) colorEntry.getValue());
    // load canned responses
    responses.clear();
    for (Map.Entry<String, Object> responseEntry : ((MemorySection) getConfig().get("DiscordCannedResponses")).getValues(true).entrySet()) responses.put(responseEntry.getKey(), (String) responseEntry.getValue());
    // start server watchdog
    if (channelTopicUpdater != null) {
        if (channelTopicUpdater.getState() == Thread.State.NEW) {
            channelTopicUpdater.start();
        } else {
            channelTopicUpdater.interrupt();
            channelTopicUpdater = new ChannelTopicUpdater();
            channelTopicUpdater.start();
        }
    } else {
        channelTopicUpdater = new ChannelTopicUpdater();
        channelTopicUpdater.start();
    }
    // enable metrics
    if (!getConfig().getBoolean("MetricsDisabled")) {
        try {
            MCStats MCStats = new MCStats(this);
            MCStats.start();
        } catch (IOException e) {
            DiscordSRV.warning("Unable to start metrics: " + e.getMessage());
        }
        BStats bStats = new BStats(this);
        bStats.addCustomChart(new BStats.LambdaSimplePie("linked_channels", () -> String.valueOf(channels.size())));
        bStats.addCustomChart(new BStats.LambdaSimplePie("console_channel_enabled", () -> String.valueOf(consoleChannel != null)));
        bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_discord", () -> metrics.get("messages_sent_to_discord")));
        bStats.addCustomChart(new BStats.LambdaSingleLineChart("messages_sent_to_minecraft", () -> metrics.get("messages_sent_to_minecraft")));
        bStats.addCustomChart(new BStats.LambdaSingleLineChart("console_commands_processed", () -> metrics.get("console_commands_processed")));
        bStats.addCustomChart(new BStats.LambdaSimpleBarChart("hooked_plugins", () -> new HashMap<String, Integer>() {

            {
                if (hookedPlugins.size() == 0) {
                    put("none", 1);
                } else {
                    for (String hookedPlugin : hookedPlugins) {
                        put(hookedPlugin.toLowerCase(), 1);
                    }
                }
            }
        }));
        bStats.addCustomChart(new BStats.LambdaSingleLineChart("minecraft-discord_account_links", () -> accountLinkManager.getLinkedAccounts().size()));
    }
    // dummy sync target to initialize class
    GroupSynchronizationUtil.reSyncGroups(null);
    // set ready status
    if (jda.getStatus() == JDA.Status.CONNECTED)
        isReady = true;
}
Also used : DiscordGuildMessagePostBroadcastEvent(github.scarsz.discordsrv.api.events.DiscordGuildMessagePostBroadcastEvent) LoginException(javax.security.auth.login.LoginException) SocketAddress(java.net.SocketAddress) MemorySection(org.bukkit.configuration.MemorySection) Player(org.bukkit.entity.Player) StringUtils(org.apache.commons.lang3.StringUtils) GsonBuilder(com.google.gson.GsonBuilder) ProxySelector(java.net.ProxySelector) Proxy(java.net.Proxy) Gson(com.google.gson.Gson) URI(java.net.URI) Method(java.lang.reflect.Method) ChannelTopicUpdater(github.scarsz.discordsrv.objects.threads.ChannelTopicUpdater) Bukkit(org.bukkit.Bukkit) Lag(github.scarsz.discordsrv.objects.Lag) CommandSender(org.bukkit.command.CommandSender) github.scarsz.discordsrv.hooks.chat(github.scarsz.discordsrv.hooks.chat) ConsoleMessageQueueWorker(github.scarsz.discordsrv.objects.threads.ConsoleMessageQueueWorker) Collectors(java.util.stream.Collectors) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) AccountLinkManager(github.scarsz.discordsrv.objects.managers.AccountLinkManager) Command(org.bukkit.command.Command) MCStats(github.scarsz.discordsrv.objects.metrics.MCStats) CancellationDetector(github.scarsz.discordsrv.objects.CancellationDetector) java.util(java.util) VaultHook(github.scarsz.discordsrv.hooks.VaultHook) Getter(lombok.Getter) net.dv8tion.jda.core(net.dv8tion.jda.core) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Yaml(org.yaml.snakeyaml.Yaml) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) Charset(java.nio.charset.Charset) github.scarsz.discordsrv.listeners(github.scarsz.discordsrv.listeners) JdaFilter(github.scarsz.discordsrv.objects.log4j.JdaFilter) AsyncPlayerChatEvent(org.bukkit.event.player.AsyncPlayerChatEvent) ApiManager(github.scarsz.discordsrv.api.ApiManager) GameChatMessagePostProcessEvent(github.scarsz.discordsrv.api.events.GameChatMessagePostProcessEvent) github.scarsz.discordsrv.util(github.scarsz.discordsrv.util) Listener(org.bukkit.event.Listener) BStats(github.scarsz.discordsrv.objects.metrics.BStats) GameChatMessagePreProcessEvent(github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent) ConsoleAppender(github.scarsz.discordsrv.objects.log4j.ConsoleAppender) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) File(java.io.File) Guild(net.dv8tion.jda.core.entities.Guild) CommandManager(github.scarsz.discordsrv.objects.managers.CommandManager) User(net.dv8tion.jda.core.entities.User) MetricsManager(github.scarsz.discordsrv.objects.managers.MetricsManager) ServerWatchdog(github.scarsz.discordsrv.objects.threads.ServerWatchdog) MultiverseCoreHook(github.scarsz.discordsrv.hooks.world.MultiverseCoreHook) DigestUtils(org.apache.commons.codec.digest.DigestUtils) ConsoleAppender(github.scarsz.discordsrv.objects.log4j.ConsoleAppender) ProxySelector(java.net.ProxySelector) TextChannel(net.dv8tion.jda.core.entities.TextChannel) BStats(github.scarsz.discordsrv.objects.metrics.BStats) SocketAddress(java.net.SocketAddress) net.dv8tion.jda.core(net.dv8tion.jda.core) ConsoleMessageQueueWorker(github.scarsz.discordsrv.objects.threads.ConsoleMessageQueueWorker) LoginException(javax.security.auth.login.LoginException) File(java.io.File) Guild(net.dv8tion.jda.core.entities.Guild) URI(java.net.URI) Proxy(java.net.Proxy) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) LoginException(javax.security.auth.login.LoginException) IOException(java.io.IOException) ChannelTopicUpdater(github.scarsz.discordsrv.objects.threads.ChannelTopicUpdater) Lag(github.scarsz.discordsrv.objects.Lag) MCStats(github.scarsz.discordsrv.objects.metrics.MCStats) JdaFilter(github.scarsz.discordsrv.objects.log4j.JdaFilter) ServerWatchdog(github.scarsz.discordsrv.objects.threads.ServerWatchdog) AsyncPlayerChatEvent(org.bukkit.event.player.AsyncPlayerChatEvent) AccountLinkManager(github.scarsz.discordsrv.objects.managers.AccountLinkManager)

Aggregations

Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 ApiManager (github.scarsz.discordsrv.api.ApiManager)1 DiscordGuildMessagePostBroadcastEvent (github.scarsz.discordsrv.api.events.DiscordGuildMessagePostBroadcastEvent)1 GameChatMessagePostProcessEvent (github.scarsz.discordsrv.api.events.GameChatMessagePostProcessEvent)1 GameChatMessagePreProcessEvent (github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent)1 VaultHook (github.scarsz.discordsrv.hooks.VaultHook)1 github.scarsz.discordsrv.hooks.chat (github.scarsz.discordsrv.hooks.chat)1 MultiverseCoreHook (github.scarsz.discordsrv.hooks.world.MultiverseCoreHook)1 github.scarsz.discordsrv.listeners (github.scarsz.discordsrv.listeners)1 CancellationDetector (github.scarsz.discordsrv.objects.CancellationDetector)1 Lag (github.scarsz.discordsrv.objects.Lag)1 ConsoleAppender (github.scarsz.discordsrv.objects.log4j.ConsoleAppender)1 JdaFilter (github.scarsz.discordsrv.objects.log4j.JdaFilter)1 AccountLinkManager (github.scarsz.discordsrv.objects.managers.AccountLinkManager)1 CommandManager (github.scarsz.discordsrv.objects.managers.CommandManager)1 MetricsManager (github.scarsz.discordsrv.objects.managers.MetricsManager)1 BStats (github.scarsz.discordsrv.objects.metrics.BStats)1 MCStats (github.scarsz.discordsrv.objects.metrics.MCStats)1 ChannelTopicUpdater (github.scarsz.discordsrv.objects.threads.ChannelTopicUpdater)1