Search in sources :

Example 1 with EventClientConnection

use of me.semx11.autotip.event.impl.EventClientConnection in project Hyperium by HyperiumClient.

the class Autotip method setup.

private void setup() {
    try {
        fileUtil = new FileUtil(this);
        gson = new GsonBuilder().registerTypeAdapter(Config.class, new ConfigCreator(this)).registerTypeAdapter(StatsDaily.class, new StatsDailyCreator(this)).setExclusionStrategies(new AnnotationExclusionStrategy()).setPrettyPrinting().create();
        config = new Config(this);
        reloadGlobalSettings();
        reloadLocale();
        sessionManager = new SessionManager(this);
        statsManager = new StatsManager(this);
        migrationManager = new MigrationManager(this);
        fileUtil.createDirectories();
        config.load();
        taskManager.getExecutor().execute(() -> migrationManager.migrateLegacyFiles());
        registerEvents(new EventClientConnection(this), new EventChatReceived(this));
        registerCommands(new CommandAutotip(this), new CommandLimbo(this));
        Runtime.getRuntime().addShutdownHook(new Thread(sessionManager::logout));
        initialized = true;
    } catch (IOException e) {
        messageUtil.send("Autotip is disabled because it couldn't create the required files.");
        ErrorReport.reportException(e);
    } catch (IllegalStateException e) {
        messageUtil.send("Autotip is disabled because it couldn't connect to the API.");
        ErrorReport.reportException(e);
    }
}
Also used : ConfigCreator(me.semx11.autotip.gson.creator.ConfigCreator) CommandAutotip(me.semx11.autotip.command.impl.CommandAutotip) GsonBuilder(com.google.gson.GsonBuilder) EventClientConnection(me.semx11.autotip.event.impl.EventClientConnection) Config(me.semx11.autotip.config.Config) SessionManager(me.semx11.autotip.core.SessionManager) CommandLimbo(me.semx11.autotip.command.impl.CommandLimbo) StatsDailyCreator(me.semx11.autotip.gson.creator.StatsDailyCreator) IOException(java.io.IOException) MigrationManager(me.semx11.autotip.core.MigrationManager) AnnotationExclusionStrategy(me.semx11.autotip.gson.exclusion.AnnotationExclusionStrategy) StatsManager(me.semx11.autotip.core.StatsManager) EventChatReceived(me.semx11.autotip.event.impl.EventChatReceived) FileUtil(me.semx11.autotip.util.FileUtil)

Example 2 with EventClientConnection

use of me.semx11.autotip.event.impl.EventClientConnection in project Hyperium by HyperiumClient.

the class CommandAutotip method onExecute.

@Override
public void onExecute(String[] args) {
    Config config = autotip.getConfig();
    MessageUtil messageUtil = autotip.getMessageUtil();
    TaskManager taskManager = autotip.getTaskManager();
    SessionManager manager = autotip.getSessionManager();
    StatsManager stats = autotip.getStatsManager();
    GlobalSettings settings = autotip.getGlobalSettings();
    if (args.length <= 0) {
        messageUtil.sendKey("command.usage");
        return;
    }
    switch(args[0].toLowerCase()) {
        case "s":
        case "stats":
            LocalDate now = LocalDate.now();
            if (args.length <= 1) {
                stats.get(now).print();
                return;
            }
            String param = args[1].toLowerCase();
            switch(param) {
                case "d":
                case "day":
                case "daily":
                case "today":
                    stats.get(now).print();
                    break;
                case "yd":
                case "yesterday":
                    stats.get(now.minusDays(1)).print();
                    break;
                case "w":
                case "week":
                case "weekly":
                    stats.getRange(now.with(DayOfWeek.MONDAY), now.with(DayOfWeek.SUNDAY)).print();
                    break;
                case "m":
                case "month":
                case "monthly":
                    stats.getRange(now.withDayOfMonth(1), now.withDayOfMonth(now.lengthOfMonth())).print();
                    break;
                case "y":
                case "year":
                case "yearly":
                    stats.getRange(now.withDayOfYear(1), now.withDayOfYear(now.lengthOfYear())).print();
                    break;
                case "a":
                case "all":
                case "total":
                case "life":
                case "lifetime":
                    stats.getAll().print();
                    break;
                default:
                    if (param.contains("-")) {
                        List<LocalDate> dates = Arrays.stream(param.split("-")).map(string -> {
                            try {
                                return LocalDate.parse(string, DATE_FORMAT);
                            } catch (DateTimeParseException e) {
                                return null;
                            }
                        }).filter(Objects::nonNull).limit(2).sorted().collect(Collectors.toList());
                        if (dates.size() != 2) {
                            messageUtil.sendKey("command.stats.invalidRange");
                            return;
                        }
                        stats.getRange(dates.get(0), dates.get(1)).print();
                    } else if (param.contains("/")) {
                        try {
                            LocalDate date = LocalDate.parse(param, DATE_FORMAT);
                            stats.get(date).print();
                        } catch (DateTimeParseException e) {
                            messageUtil.sendKey("command.stats.invalidDate");
                        }
                    } else {
                        messageUtil.sendKey("command.stats.usage");
                    }
                    break;
            }
            break;
        case "?":
        case "info":
            StatsDaily today = stats.get();
            messageUtil.getKeyHelper("command.info").separator().sendKey("version", autotip.getVersion()).withKey("credits", context -> context.getBuilder().setHover(context.getKey("creditsHover")).send()).sendKey("status." + (config.isEnabled() ? "enabled" : "disabled")).sendKey("messages", config.getMessageOption()).sendKey("tipsSent", today.getTipsSent()).sendKey("tipsReceived", today.getTipsReceived()).sendKey("statsCommand").separator();
            break;
        case "m":
        case "messages":
            try {
                if (args.length > 1) {
                    MessageOption option = MessageOption.valueOfIgnoreCase(args[1]);
                    config.setMessageOption(option).save();
                } else {
                    config.nextMessageOption().save();
                }
                messageUtil.sendKey("command.messages.next", config.getMessageOption());
            } catch (IllegalArgumentException e) {
                messageUtil.sendKey("command.messages.error", args.length > 1 ? args[1] : null);
            }
            break;
        case "t":
        case "toggle":
            if (!manager.isOnHypixel()) {
                config.toggleEnabled().save();
                messageUtil.getKeyHelper("command.toggle").sendKey(config.isEnabled() ? "enabled" : "disabled");
                return;
            }
            if (!config.isEnabled()) {
                if (!manager.isLoggedIn()) {
                    taskManager.executeTask(TaskType.LOGIN, manager::login);
                    config.setEnabled(true).save();
                    messageUtil.sendKey("command.toggle.enabled");
                } else {
                    messageUtil.sendKey("command.toggle.error");
                }
            } else {
                if (manager.isLoggedIn()) {
                    taskManager.executeTask(TaskType.LOGOUT, manager::logout);
                    config.setEnabled(false).save();
                    messageUtil.sendKey("command.toggle.disabled");
                } else {
                    messageUtil.sendKey("command.toggle.error");
                }
            }
            break;
        case "w":
        case "wave":
            if (!config.isEnabled()) {
                messageUtil.sendKey("error.disabled");
                return;
            }
            if (!manager.isOnHypixel()) {
                messageUtil.sendKey("error.disabledHypixel");
                return;
            }
            if (manager.getNextTipWave() == 0) {
                messageUtil.sendKey("command.wave.error");
                return;
            }
            long t = System.currentTimeMillis();
            String next = LocalTime.MIN.plusSeconds((manager.getNextTipWave() - t) / 1000 + 1).format(WAVE_FORMAT);
            String last = LocalTime.MIN.plusSeconds((t - manager.getLastTipWave()) / 1000).format(WAVE_FORMAT);
            messageUtil.getKeyHelper("command.wave").separator().sendKey("nextWave", next).sendKey("lastWave", last).separator();
            break;
        case "changelog":
            messageUtil.getKeyHelper("command.changelog").separator().sendKey("version", autotip.getVersion()).withKey("entry", context -> settings.getVersionInfo(autotip.getVersion()).getChangelog().forEach(context::send)).separator();
            break;
        case "debug":
            EventClientConnection event = autotip.getEvent(EventClientConnection.class);
            Object header = event.getHeader();
            messageUtil.getKeyHelper("command.debug").separator().sendKey("serverIp", event.getServerIp()).sendKey("mcVersion", autotip.getMcVersion()).sendKey("header." + (header == null ? "none" : "present"), UniversalUtil.getUnformattedText(header)).separator();
            break;
        case "reload":
            try {
                autotip.reloadGlobalSettings();
                autotip.reloadLocale();
                messageUtil.sendKey("command.reload.success");
            } catch (IllegalStateException e) {
                messageUtil.sendKey("command.reload.error");
            }
            break;
        default:
            messageUtil.send(getUsage());
            break;
    }
}
Also used : Autotip(me.semx11.autotip.Autotip) MessageOption(me.semx11.autotip.chat.MessageOption) TaskType(me.semx11.autotip.core.TaskManager.TaskType) Arrays(java.util.Arrays) CommandAbstract(me.semx11.autotip.command.CommandAbstract) SessionManager(me.semx11.autotip.core.SessionManager) TaskManager(me.semx11.autotip.core.TaskManager) EventClientConnection(me.semx11.autotip.event.impl.EventClientConnection) Collectors(java.util.stream.Collectors) StatsDaily(me.semx11.autotip.stats.StatsDaily) UniversalUtil(me.semx11.autotip.universal.UniversalUtil) Objects(java.util.Objects) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) Config(me.semx11.autotip.config.Config) DayOfWeek(java.time.DayOfWeek) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) MessageUtil(me.semx11.autotip.chat.MessageUtil) LocalTime(java.time.LocalTime) CommandBase.getListOfStringsMatchingLastWord(net.minecraft.command.CommandBase.getListOfStringsMatchingLastWord) StatsManager(me.semx11.autotip.core.StatsManager) GlobalSettings(me.semx11.autotip.config.GlobalSettings) Collections(java.util.Collections) EventClientConnection(me.semx11.autotip.event.impl.EventClientConnection) Config(me.semx11.autotip.config.Config) SessionManager(me.semx11.autotip.core.SessionManager) GlobalSettings(me.semx11.autotip.config.GlobalSettings) LocalDate(java.time.LocalDate) DateTimeParseException(java.time.format.DateTimeParseException) TaskManager(me.semx11.autotip.core.TaskManager) MessageUtil(me.semx11.autotip.chat.MessageUtil) StatsManager(me.semx11.autotip.core.StatsManager) MessageOption(me.semx11.autotip.chat.MessageOption) StatsDaily(me.semx11.autotip.stats.StatsDaily)

Example 3 with EventClientConnection

use of me.semx11.autotip.event.impl.EventClientConnection in project Hyperium by HyperiumClient.

the class ErrorReport method reportException.

public static void reportException(Throwable t) {
    Autotip.LOGGER.error(t.getMessage(), t);
    HttpURLConnection conn = null;
    try {
        URL url = new URL("https://api.autotip.pro/error_report.php");
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        JsonObjectBuilder builder = JsonObjectBuilder.newBuilder().addString("username", autotip.getGameProfile().getName()).addString("uuid", autotip.getGameProfile().getId()).addString("v", autotip.getVersion()).addString("mc", autotip.getMcVersion()).addString("os", System.getProperty("os.name")).addString("forge", "hyperium").addString("stackTrace", ExceptionUtils.getStackTrace(t)).addNumber("time", System.currentTimeMillis());
        if (autotip.isInitialized()) {
            EventClientConnection event = autotip.getEvent(EventClientConnection.class);
            builder.addString("sessionKey", autotip.getSessionManager().getKey()).addString("serverIp", event.getServerIp());
        }
        byte[] jsonBytes = builder.build().toString().getBytes(StandardCharsets.UTF_8);
        conn.setFixedLengthStreamingMode(jsonBytes.length);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("User-Agent", "Autotip v" + autotip.getVersion());
        conn.connect();
        try (OutputStream out = conn.getOutputStream()) {
            out.write(jsonBytes);
        }
        InputStream input = conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST ? conn.getInputStream() : conn.getErrorStream();
        String json = IOUtils.toString(input, StandardCharsets.UTF_8);
        Autotip.LOGGER.info("Error JSON: " + json);
        input.close();
        conn.disconnect();
    } catch (IOException e) {
        // Hmm... what would happen if I were to report this one?
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) EventClientConnection(me.semx11.autotip.event.impl.EventClientConnection) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

EventClientConnection (me.semx11.autotip.event.impl.EventClientConnection)3 IOException (java.io.IOException)2 Config (me.semx11.autotip.config.Config)2 SessionManager (me.semx11.autotip.core.SessionManager)2 StatsManager (me.semx11.autotip.core.StatsManager)2 GsonBuilder (com.google.gson.GsonBuilder)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 DayOfWeek (java.time.DayOfWeek)1 LocalDate (java.time.LocalDate)1 LocalTime (java.time.LocalTime)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 DateTimeParseException (java.time.format.DateTimeParseException)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Objects (java.util.Objects)1 Collectors (java.util.stream.Collectors)1