<commit_before>/*
 * The MIT License (MIT)
 * Copyright (c) 2016 <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package fredboat;

import fredboat.agent.CarbonAgent;
import fredboat.agent.CarbonitexAgent;
import fredboat.audio.MusicPersistenceHandler;
import fredboat.audio.PlayerRegistry;
import fredboat.command.admin.*;
import fredboat.command.fun.*;
import fredboat.command.maintenance.GetIdCommand;
import fredboat.command.maintenance.StatsCommand;
import fredboat.command.maintenance.TestCommand;
import fredboat.command.maintenance.VersionCommand;
import fredboat.command.music.*;
import fredboat.command.util.*;
import fredboat.commandmeta.CommandRegistry;
import fredboat.event.EventListenerBoat;
import fredboat.event.EventListenerSelf;
import fredboat.event.EventLogger;
import fredboat.sharding.FredBoatAPIServer;
import fredboat.sharding.ShardTracker;
import fredboat.util.BotConstants;
import fredboat.util.DiscordUtil;
import fredboat.util.DistributionEnum;
import fredboat.util.log.SimpleLogToSLF4JAdapter;
import frederikam.jca.JCA;
import frederikam.jca.JCABuilder;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.JDAInfo;
import net.dv8tion.jda.core.client.JDAClientBuilder;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FredBoat {

    private static final Logger log = LoggerFactory.getLogger(FredBoat.class);
    private static JSONObject config = null;

    private static int scopes = 0;
    public static volatile JDA jdaBot;
    public static volatile JDA jdaSelf;
    public static JCA jca;
    public static final long START_TIME = System.currentTimeMillis();
    private static String accountToken;
    public static String mashapeKey;

    public static String MALPassword;

    public static int readyEvents = 0;
    public static int readyEventsRequired = 0;

    public static int shardId = 0;
    public static int numShards = 1;

    private static JSONObject credsjson = null;
    public static DistributionEnum distribution = DistributionEnum.BETA;

    public static final int UNKNOWN_SHUTDOWN_CODE = -991023;
    public static int shutdownCode = UNKNOWN_SHUTDOWN_CODE;//Used when specifying the intended code for shutdown hooks

    private final static List<String> GOOGLE_KEYS = new ArrayList<>();

    private static EventListenerBoat listenerBot;
    private static EventListenerSelf listenerSelf;

    private FredBoat() {
    }

    public static void main(String[] args) throws LoginException, IllegalArgumentException, InterruptedException, IOException {
        Runtime.getRuntime().addShutdownHook(new Thread(ON_SHUTDOWN));

        //Attach log adapter
        SimpleLog.addListener(new SimpleLogToSLF4JAdapter());

        //Make JDA not print to console, we have Logback for that
        SimpleLog.LEVEL = SimpleLog.Level.OFF;

        try {
            scopes = Integer.parseInt(args[0]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) {
            log.info("Invalid scope, defaulting to scopes 0x101");
            scopes = 0x110;
        }

        try {
            shardId = Integer.parseInt(args[1]);
            numShards = Integer.parseInt(args[2]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) {
            log.info("Invalid shards, defaulting to 0 of 1 shards");
        }

        log.info("Starting with scopes:"
                + "\n\tMain: " + ((scopes & 0x100) == 0x100)
                + "\n\tMusic: " + ((scopes & 0x010) == 0x010)
                + "\n\tSelf: " + ((scopes & 0x001) == 0x001));

        log.info("Starting as shard " + shardId + " of " + numShards);

        //Load credentials and config files
        InputStream is = new FileInputStream(new File("./credentials.json"));
        Scanner scanner = new Scanner(is);
        credsjson = new JSONObject(scanner.useDelimiter("\\A").next());
        scanner.close();

        is = new FileInputStream(new File("./config.json"));
        scanner = new Scanner(is);
        config = new JSONObject(scanner.useDelimiter("\\A").next());
        scanner.close();

        mashapeKey = credsjson.getString("mashapeKey");
        String clientToken = credsjson.getString("clientToken");
        MALPassword = credsjson.getString("malPassword");
        String carbonHost = credsjson.optString("carbonHost");

        JSONArray gkeys = credsjson.optJSONArray("googleServerKeys");
        if (gkeys != null) {
            gkeys.forEach((Object str) -> {
                GOOGLE_KEYS.add((String) str);
            });
        }

        if (credsjson.has("scopePasswords")) {
            JSONObject scopePasswords = credsjson.getJSONObject("scopePasswords");
            for (String k : scopePasswords.keySet()) {
                scopePasswords.put(k, scopePasswords.getString(k));
            }
        }

        if (config.optBoolean("patron")) {
            distribution = DistributionEnum.PATRON;
        } else //Determine distribution
        if (BotConstants.IS_BETA) {
            distribution = DistributionEnum.BETA;
        } else {
            distribution = DiscordUtil.isMainBot() ? DistributionEnum.MAIN : DistributionEnum.MUSIC;
        }
        accountToken = credsjson.getJSONObject("token").getString(distribution.getId());

        log.info("Determined distribution: " + distribution);

        //Initialise event listeners
        listenerBot = new EventListenerBoat(scopes & 0x110, BotConstants.DEFAULT_BOT_PREFIX);
        listenerSelf = new EventListenerSelf(scopes & 0x001, BotConstants.DEFAULT_SELF_PREFIX);

        /* Init JDA */
        //Doing increments here because concurrency
        if ((scopes & 0x110) != 0) {
            readyEventsRequired++;
        }

        if ((scopes & 0x001) != 0) {
            readyEventsRequired++;
        }

        if ((scopes & 0x110) != 0) {
            JDABuilder builder = new JDABuilder()
                    .addListener(listenerBot)
                    .addListener(new EventLogger("216689009110417408"))
                    .setBotToken(accountToken)
                    .setBulkDeleteSplittingEnabled(true);
            if (numShards > 1) {
                builder.useSharding(shardId, numShards);
            }
            jdaBot = builder.buildAsync();
        }

        if ((scopes & 0x001) != 0 && shardId == 0) {
            jdaSelf = new JDAClientBuilder()
                    .addListener(listenerSelf)
                    .setClientToken(clientToken)
                    .buildAsync();
        }

        /* JDA initialising */
        log.info("JDA version:\t" + JDAInfo.VERSION);

        //Initialise JCA
        String cbUser = credsjson.getString("cbUser");<commit_msg>Dealt with a couple main class problems<commit_after>/*
 * The MIT License (MIT)
 * Copyright (c) 2016 <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package fredboat;

import fredboat.agent.CarbonAgent;
import fredboat.agent.CarbonitexAgent;
import fredboat.audio.MusicPersistenceHandler;
import fredboat.audio.PlayerRegistry;
import fredboat.command.admin.*;
import fredboat.command.fun.*;
import fredboat.command.maintenance.GetIdCommand;
import fredboat.command.maintenance.StatsCommand;
import fredboat.command.maintenance.TestCommand;
import fredboat.command.maintenance.VersionCommand;
import fredboat.command.music.*;
import fredboat.command.util.*;
import fredboat.commandmeta.CommandRegistry;
import fredboat.event.EventListenerBoat;
import fredboat.event.EventListenerSelf;
import fredboat.event.EventLogger;
import fredboat.sharding.FredBoatAPIServer;
import fredboat.sharding.ShardTracker;
import fredboat.util.BotConstants;
import fredboat.util.DiscordUtil;
import fredboat.util.DistributionEnum;
import fredboat.util.log.SimpleLogToSLF4JAdapter;
import frederikam.jca.JCA;
import frederikam.jca.JCABuilder;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.JDAInfo;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FredBoat {

    private static final Logger log = LoggerFactory.getLogger(FredBoat.class);
    private static JSONObject config = null;

    private static int scopes = 0;
    public static volatile JDA jdaBot;
    public static volatile JDA jdaSelf;
    public static JCA jca;
    public static final long START_TIME = System.currentTimeMillis();
    private static String accountToken;
    public static String mashapeKey;

    public static String MALPassword;

    public static int readyEvents = 0;
    public static int readyEventsRequired = 0;

    public static int shardId = 0;
    public static int numShards = 1;

    private static JSONObject credsjson = null;
    public static DistributionEnum distribution = DistributionEnum.BETA;

    public static final int UNKNOWN_SHUTDOWN_CODE = -991023;
    public static int shutdownCode = UNKNOWN_SHUTDOWN_CODE;//Used when specifying the intended code for shutdown hooks

    private final static List<String> GOOGLE_KEYS = new ArrayList<>();

    private static EventListenerBoat listenerBot;
    private static EventListenerSelf listenerSelf;

    private FredBoat() {
    }

    public static void main(String[] args) throws LoginException, IllegalArgumentException, InterruptedException, IOException {
        Runtime.getRuntime().addShutdownHook(new Thread(ON_SHUTDOWN));

        //Attach log adapter
        SimpleLog.addListener(new SimpleLogToSLF4JAdapter());

        //Make JDA not print to console, we have Logback for that
        SimpleLog.LEVEL = SimpleLog.Level.OFF;

        try {
            scopes = Integer.parseInt(args[0]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) {
            log.info("Invalid scope, defaulting to scopes 0x101");
            scopes = 0x110;
        }

        try {
            shardId = Integer.parseInt(args[1]);
            numShards = Integer.parseInt(args[2]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) {
            log.info("Invalid shards, defaulting to 0 of 1 shards");
        }

        log.info("Starting with scopes:"
                + "\n\tMain: " + ((scopes & 0x100) == 0x100)
                + "\n\tMusic: " + ((scopes & 0x010) == 0x010)
                + "\n\tSelf: " + ((scopes & 0x001) == 0x001));

        log.info("Starting as shard " + shardId + " of " + numShards);

        //Load credentials and config files
        InputStream is = new FileInputStream(new File("./credentials.json"));
        Scanner scanner = new Scanner(is);
        credsjson = new JSONObject(scanner.useDelimiter("\\A").next());
        scanner.close();

        is = new FileInputStream(new File("./config.json"));
        scanner = new Scanner(is);
        config = new JSONObject(scanner.useDelimiter("\\A").next());
        scanner.close();

        mashapeKey = credsjson.getString("mashapeKey");
        String clientToken = credsjson.getString("clientToken");
        MALPassword = credsjson.getString("malPassword");
        String carbonHost = credsjson.optString("carbonHost");

        JSONArray gkeys = credsjson.optJSONArray("googleServerKeys");
        if (gkeys != null) {
            gkeys.forEach((Object str) -> {
                GOOGLE_KEYS.add((String) str);
            });
        }

        if (credsjson.has("scopePasswords")) {
            JSONObject scopePasswords = credsjson.getJSONObject("scopePasswords");
            for (String k : scopePasswords.keySet()) {
                scopePasswords.put(k, scopePasswords.getString(k));
            }
        }

        if (config.optBoolean("patron")) {
            distribution = DistributionEnum.PATRON;
        } else //Determine distribution
        if (BotConstants.IS_BETA) {
            distribution = DistributionEnum.BETA;
        } else {
            distribution = DiscordUtil.isMainBot() ? DistributionEnum.MAIN : DistributionEnum.MUSIC;
        }
        accountToken = credsjson.getJSONObject("token").getString(distribution.getId());

        log.info("Determined distribution: " + distribution);

        //Initialise event listeners
        listenerBot = new EventListenerBoat(scopes & 0x110, BotConstants.DEFAULT_BOT_PREFIX);
        listenerSelf = new EventListenerSelf(scopes & 0x001, BotConstants.DEFAULT_SELF_PREFIX);

        /* Init JDA */
        //Doing increments here because concurrency
        if ((scopes & 0x110) != 0) {
            readyEventsRequired++;
        }

        if ((scopes & 0x001) != 0) {
            readyEventsRequired++;
        }

        if ((scopes & 0x110) != 0) {
            JDABuilder builder = new JDABuilder(AccountType.BOT)
                    .addListener(listenerBot)
                    .addListener(new EventLogger("216689009110417408"))
                    .setToken(accountToken)
                    .setBulkDeleteSplittingEnabled(true);
            if (numShards > 1) {
                builder.useSharding(shardId, numShards);
            }
            jdaBot = builder.buildAsync();
        }

        if ((scopes & 0x001) != 0 && shardId == 0) {
            jdaSelf = new JDABuilder(AccountType.CLIENT)
                    .addListener(listenerSelf)
                    .setToken(clientToken)
                    .buildAsync();
        }

        /* JDA initialising */
        log.info("JDA version:\t" + JDAInfo.VERSION);

        //Initialise JCA
        String cbUser = credsjson.getString("cbUser");
{'fraction_non_alphanumeric': 0.09358485928474868, 'fraction_numerical': 0.013518495760108148, 'mean_word_length': 3.010596352883194, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6072316', 'n_tokens_mistral': 4761, 'n_tokens_neox': 4447, 'n_words': 1225}