Search in sources :

Example 1 with JSONConfig

use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.

the class CurrencyConversionUtil method getNormalCurrency.

private static CurrencyComparison getNormalCurrency(String from, String to) throws IOException {
    Response response = WebUtils.get(new Request.Builder().get().url(CurrencyApiRoutes.NormalApi.LATEST_WITH_SYMBOLS_AND_BASE.getCompiledUrl(to, from)));
    if (!response.isSuccessful() || response.body() == null)
        return null;
    JSONConfig config = new JSONConfig(response.body().byteStream());
    response.close();
    if (config.getString("base").isPresent() && config.getDouble("rates." + to).isPresent()) {
        Double conversion = config.getDouble("rates." + to).getAsDouble();
        return new CurrencyComparison(from, to, conversion);
    }
    return null;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) JSONConfig(io.github.binaryoverload.JSONConfig)

Example 2 with JSONConfig

use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.

the class CurrencyConversionUtil method getCryptoCurrency.

private static CurrencyComparison getCryptoCurrency(String from, String to) throws IOException {
    Response res = WebUtils.get(new Request.Builder().get().url(CurrencyApiRoutes.CrytoApi.BASIC_TICKER.getCompiledUrl(from, to)));
    if (!res.isSuccessful() || res.body() == null)
        return null;
    JSONConfig config = new JSONConfig(res.body().byteStream());
    res.close();
    if (config.getBoolean("success").isPresent() && config.getBoolean("success").get()) {
        String price = config.getString("ticker.price").get();
        Double priceDouble;
        try {
            priceDouble = Double.parseDouble(price);
        } catch (NumberFormatException e) {
            return null;
        }
        return new CurrencyComparison(from, to, priceDouble);
    }
    return null;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) JSONConfig(io.github.binaryoverload.JSONConfig)

Example 3 with JSONConfig

use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.

the class FlareBot method main.

public static void main(String[] args) {
    Spark.port(8080);
    try {
        File file = new File("config.json");
        if (!file.exists() && !file.createNewFile())
            throw new IllegalStateException("Can't create config file!");
        try {
            config = new JSONConfig(new File("config.json"), '.', new char[] { '-', '_', '<', '>', '@' });
        } catch (NullPointerException e) {
            LOGGER.error("Invalid JSON!", e);
            System.exit(1);
        }
    } catch (IOException e) {
        LOGGER.error("Unable to create config.json!", e);
        System.exit(1);
    }
    List<String> required = new ArrayList<>();
    required.add("bot.token");
    required.add("cassandra.username");
    required.add("cassandra.password");
    required.add("misc.yt");
    required.add("redis.host");
    required.add("redis.port");
    required.add("redis.password");
    required.add("sentry.dsn");
    boolean good = true;
    for (String req : required) {
        if (config.getString(req) != null) {
            if (!config.getString(req).isPresent()) {
                good = false;
                LOGGER.error("Missing required json " + req);
            }
        } else {
            good = false;
            LOGGER.error("Missing required json " + req);
        }
    }
    if (!good) {
        LOGGER.error("One or more of the required JSON objects where missing. Exiting to prevent problems");
        System.exit(1);
    }
    new CassandraController(config);
    new RedisController(config);
    FlareBot.youtubeApi = config.getString("misc.yt").get();
    if (config.getArray("options").isPresent()) {
        for (JsonElement em : config.getArray("options").get()) {
            if (em.getAsString() != null) {
                if (em.getAsString().equals("tb")) {
                    FlareBot.testBot = true;
                }
                if (em.getAsString().equals("debug")) {
                    ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)).setLevel(Level.DEBUG);
                }
            }
        }
    }
    SentryClient sentryClient = Sentry.init(config.getString("sentry.dsn").get() + "?stacktrace.app.packages=stream.flarebot.flarebot");
    sentryClient.setEnvironment(testBot ? "TestBot" : "Production");
    sentryClient.setServerName(testBot ? "Test Server" : "Production Server");
    sentryClient.setRelease(GitHandler.getLatestCommitId());
    if (!config.getString("misc.apiKey").isPresent() || config.getString("misc.apiKey").get().isEmpty())
        apiEnabled = false;
    Thread.setDefaultUncaughtExceptionHandler(((t, e) -> LOGGER.error("Uncaught exception in thread " + t, e)));
    Thread.currentThread().setUncaughtExceptionHandler(((t, e) -> LOGGER.error("Uncaught exception in thread " + t, e)));
    try {
        (instance = new FlareBot()).init();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : WebSocketListener(stream.flarebot.flarebot.ws.WebSocketListener) Metrics(stream.flarebot.flarebot.metrics.Metrics) VoiceChannelCleanup(stream.flarebot.flarebot.tasks.VoiceChannelCleanup) ConcurrentHashSet(org.eclipse.jetty.util.ConcurrentHashSet) ShardUtils(stream.flarebot.flarebot.util.ShardUtils) GsonBuilder(com.google.gson.GsonBuilder) Map(java.util.Map) DataInterceptor(stream.flarebot.flarebot.web.DataInterceptor) Request(okhttp3.Request) PlayerCache(stream.flarebot.flarebot.objects.PlayerCache) WebUtils(stream.flarebot.flarebot.util.WebUtils) Set(java.util.Set) PlayerManager(com.arsenarsen.lavaplayerbridge.PlayerManager) ErrorResponseException(net.dv8tion.jda.core.exceptions.ErrorResponseException) PlayerListener(stream.flarebot.flarebot.audio.PlayerListener) DefaultShardManagerBuilder(net.dv8tion.jda.bot.sharding.DefaultShardManagerBuilder) WebhookClient(net.dv8tion.jda.webhook.WebhookClient) ZipOutputStream(java.util.zip.ZipOutputStream) Row(com.datastax.driver.core.Row) TextChannel(net.dv8tion.jda.core.entities.TextChannel) GuildCountAnalytics(stream.flarebot.flarebot.analytics.GuildCountAnalytics) LocalDateTime(java.time.LocalDateTime) SimpleDateFormat(java.text.SimpleDateFormat) MigrationHandler(stream.flarebot.flarebot.util.MigrationHandler) ShardManager(net.dv8tion.jda.bot.sharding.ShardManager) GeneralUtils(stream.flarebot.flarebot.util.general.GeneralUtils) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Scheduler(stream.flarebot.flarebot.scheduler.Scheduler) ApiRoute(stream.flarebot.flarebot.api.ApiRoute) ApiRequester(stream.flarebot.flarebot.api.ApiRequester) Properties(java.util.Properties) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) RestAction(net.dv8tion.jda.core.requests.RestAction) InputStreamReader(java.io.InputStreamReader) ApiFactory(stream.flarebot.flarebot.web.ApiFactory) File(java.io.File) Guild(net.dv8tion.jda.core.entities.Guild) WebhookClientBuilder(net.dv8tion.jda.webhook.WebhookClientBuilder) OkHttpClient(okhttp3.OkHttpClient) CassandraController(stream.flarebot.flarebot.database.CassandraController) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) ConnectionPool(okhttp3.ConnectionPool) BufferedReader(java.io.BufferedReader) NativeAudioSendFactory(com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory) JsonObject(com.google.gson.JsonObject) ScheduledFuture(java.util.concurrent.ScheduledFuture) FlareBotTask(stream.flarebot.flarebot.scheduler.FlareBotTask) URLDecoder(java.net.URLDecoder) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) SelfUser(net.dv8tion.jda.core.entities.SelfUser) RedisController(stream.flarebot.flarebot.database.RedisController) JSONObject(org.json.JSONObject) Permission(net.dv8tion.jda.core.Permission) Gson(com.google.gson.Gson) WebSocketFactory(stream.flarebot.flarebot.ws.WebSocketFactory) JDA(net.dv8tion.jda.core.JDA) ZipEntry(java.util.zip.ZipEntry) ActivityAnalytics(stream.flarebot.flarebot.analytics.ActivityAnalytics) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) QueueListener(stream.flarebot.flarebot.music.QueueListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) List(java.util.List) LocalDate(java.time.LocalDate) stream.flarebot.flarebot.commands(stream.flarebot.flarebot.commands) UnknownBindingException(com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LibraryFactory(com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory) RequestBody(okhttp3.RequestBody) JsonElement(com.google.gson.JsonElement) ResultSet(com.datastax.driver.core.ResultSet) FutureAction(stream.flarebot.flarebot.scheduler.FutureAction) Constants(stream.flarebot.flarebot.util.Constants) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) Sentry(io.sentry.Sentry) Nonnull(javax.annotation.Nonnull) JSONConfig(io.github.binaryoverload.JSONConfig) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) Logger(org.slf4j.Logger) SentryClient(io.sentry.SentryClient) Game(net.dv8tion.jda.core.entities.Game) DateTime(org.joda.time.DateTime) FileInputStream(java.io.FileInputStream) AnalyticsHandler(stream.flarebot.flarebot.analytics.AnalyticsHandler) NINOListener(stream.flarebot.flarebot.mod.nino.NINOListener) TimeUnit(java.util.concurrent.TimeUnit) Level(ch.qos.logback.classic.Level) GuildAnalytics(stream.flarebot.flarebot.analytics.GuildAnalytics) JDAMultiShard(com.arsenarsen.lavaplayerbridge.utils.JDAMultiShard) Spark(spark.Spark) JSONArray(org.json.JSONArray) CassandraController(stream.flarebot.flarebot.database.CassandraController) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Logger(org.slf4j.Logger) ErrorResponseException(net.dv8tion.jda.core.exceptions.ErrorResponseException) IOException(java.io.IOException) UnknownBindingException(com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException) JsonElement(com.google.gson.JsonElement) RedisController(stream.flarebot.flarebot.database.RedisController) JSONConfig(io.github.binaryoverload.JSONConfig) SentryClient(io.sentry.SentryClient) File(java.io.File)

Example 4 with JSONConfig

use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.

the class GuildWrapperLoader method load.

@Override
@ParametersAreNonnullByDefault
public GuildWrapper load(String id) {
    long start = System.currentTimeMillis();
    ResultSet set = CassandraController.execute("SELECT data FROM " + FlareBotManager.instance().GUILD_DATA_TABLE + " WHERE guild_id = '" + id + "'");
    GuildWrapper wrapper;
    Row row = set != null ? set.one() : null;
    String json = null;
    JSONConfig data;
    try {
        if (row != null) {
            json = row.getString("data");
            if (json.isEmpty() || json.equalsIgnoreCase("null")) {
                return new GuildWrapper(id);
            }
            data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
            if (data.getLong("dataVersion").isPresent() && data.getLong("dataVersion").getAsLong() == 0)
                data = firstMigration(data);
            wrapper = FlareBot.GSON.fromJson(data.getObject().toString(), GuildWrapper.class);
        } else
            return new GuildWrapper(id);
    } catch (Exception e) {
        if (json == null) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + (row != null ? row.getString("data") : "New guild data!") + "\n" + "Error: " + e.getMessage(), e);
            return null;
        }
        try {
            data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
        } catch (Exception e1) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
            throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
        }
        if (!data.getLong("dataVersion").isPresent()) {
            try {
                data = firstMigration(data);
            } catch (Exception e1) {
                FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
                throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
            }
            data.set("dataVersion", 1);
        }
        long version = data.getLong("dataVersion").getAsLong();
        if (version != GuildWrapper.DATA_VERSION) {
        // Migrations
        }
        json = data.getObject().toString();
        try {
            wrapper = FlareBot.GSON.fromJson(json, GuildWrapper.class);
        } catch (Exception e1) {
            FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e1.getMessage(), e1);
            return null;
        }
    }
    long total = (System.currentTimeMillis() - start);
    loadTimes.add(total);
    if (total >= 200) {
        Constants.getImportantLogChannel().sendMessage(MessageUtils.getEmbed().setColor(new Color(166, 0, 255)).setTitle("Long guild load time!", null).setDescription("Guild " + id + " loaded!").addField("Time", "Millis: " + System.currentTimeMillis() + "\nTime: " + LocalDateTime.now().toString(), false).addField("Load time", total + "ms", false).build()).queue();
    }
    return wrapper;
}
Also used : Color(java.awt.Color) ResultSet(com.datastax.driver.core.ResultSet) JSONConfig(io.github.binaryoverload.JSONConfig) Row(com.datastax.driver.core.Row) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault)

Example 5 with JSONConfig

use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.

the class GuildWrapperLoader method firstMigration.

private JSONConfig firstMigration(JSONConfig data) {
    if (data.getSubConfig("permissions.groups").isPresent()) {
        List<Group> groups = new ArrayList<>();
        data.setAllowedSpecialCharacters(ALLOWED_SPECIAL_CHARACTERS);
        JSONConfig config = data.getSubConfig("permissions.groups").get();
        for (String s : config.getKeys(false)) {
            if (config.getElement(s).isPresent()) {
                groups.add(FlareBot.GSON.fromJson(config.getElement(s).get().getAsJsonObject().toString(), Group.class));
            }
        }
        data.set("permissions.groups", groups);
    }
    return data;
}
Also used : Group(stream.flarebot.flarebot.permissions.Group) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) JSONConfig(io.github.binaryoverload.JSONConfig)

Aggregations

JSONConfig (io.github.binaryoverload.JSONConfig)8 Request (okhttp3.Request)5 Response (okhttp3.Response)4 ResultSet (com.datastax.driver.core.ResultSet)2 Row (com.datastax.driver.core.Row)2 JsonElement (com.google.gson.JsonElement)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Level (ch.qos.logback.classic.Level)1 PlayerManager (com.arsenarsen.lavaplayerbridge.PlayerManager)1 LibraryFactory (com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory)1 UnknownBindingException (com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException)1 JDAMultiShard (com.arsenarsen.lavaplayerbridge.utils.JDAMultiShard)1 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 JsonObject (com.google.gson.JsonObject)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 NativeAudioSendFactory (com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory)1 Sentry (io.sentry.Sentry)1 SentryClient (io.sentry.SentryClient)1