Search in sources :

Example 1 with OfflineBungeeVote

use of com.bencodez.votingplugin.bungee.OfflineBungeeVote in project VotingPlugin by Ben12345rocks.

the class VotingPluginVelocity method checkCachedVotes.

public synchronized void checkCachedVotes(RegisteredServer serverToCheck) {
    if (!serverToCheck.getPlayersConnected().isEmpty()) {
        if (cachedVotes.containsKey(serverToCheck) && !config.getBlockedServers().contains(serverToCheck.getServerInfo().getName())) {
            ArrayList<OfflineBungeeVote> c = cachedVotes.get(serverToCheck);
            ArrayList<OfflineBungeeVote> newSet = new ArrayList<OfflineBungeeVote>();
            if (!c.isEmpty()) {
                for (OfflineBungeeVote cache : c) {
                    boolean toSend = true;
                    if (getConfig().getWaitForUserOnline()) {
                        Player p = null;
                        if (server.getPlayer(UUID.fromString(cache.getUuid())).isPresent()) {
                            p = server.getPlayer(UUID.fromString(cache.getUuid())).get();
                        }
                        if (p == null || !p.isActive()) {
                            toSend = false;
                        } else if (p != null && p.isActive() && !p.getCurrentServer().get().getServerInfo().getName().equals(serverToCheck.getServerInfo().getName())) {
                            toSend = false;
                        }
                    }
                    if (toSend) {
                        sendPluginMessageServer(serverToCheck, "Vote", cache.getPlayerName(), cache.getUuid(), cache.getService(), "" + cache.getTime(), Boolean.FALSE.toString(), "" + cache.isRealVote(), cache.getText(), "" + getConfig().getBungeeManageTotals(), "" + BungeeVersion.getPluginMessageVersion(), "" + config.getBroadcast());
                    } else {
                        debug("Not sending vote because user isn't on server " + serverToCheck + ": " + cache.toString());
                        newSet.add(cache);
                    }
                }
                cachedVotes.put(serverToCheck, newSet);
            }
        }
    }
}
Also used : Player(com.velocitypowered.api.proxy.Player) OfflineBungeeVote(com.bencodez.votingplugin.bungee.OfflineBungeeVote) ArrayList(java.util.ArrayList)

Example 2 with OfflineBungeeVote

use of com.bencodez.votingplugin.bungee.OfflineBungeeVote in project VotingPlugin by Ben12345rocks.

the class VotingPluginVelocity method onProxyDisable.

@Subscribe
public void onProxyDisable(ProxyShutdownEvent event) {
    if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
        logger.info("VotingPlugin saving vote cache: " + cachedVotes.size() + "/" + cachedOnlineVotes.size());
        for (Entry<RegisteredServer, ArrayList<OfflineBungeeVote>> entry : cachedVotes.entrySet()) {
            RegisteredServer server = entry.getKey();
            int num = 0;
            for (OfflineBungeeVote voteData : entry.getValue()) {
                voteCacheFile.addVote(server.getServerInfo().getName(), num, voteData);
                num++;
            }
        }
        for (Entry<String, ArrayList<OfflineBungeeVote>> entry : cachedOnlineVotes.entrySet()) {
            String name = entry.getKey();
            int num = 0;
            for (OfflineBungeeVote voteData : entry.getValue()) {
                voteCacheFile.addVoteOnline(name, num, voteData);
                num++;
            }
        }
    }
    if (timeHandle != null) {
        timeHandle.save();
    }
    voteCacheFile.save();
    nonVotedPlayersCache.save();
    if (mysql != null) {
        mysql.shutDown();
    }
    logger.info("VotingPlugin disabled");
}
Also used : OfflineBungeeVote(com.bencodez.votingplugin.bungee.OfflineBungeeVote) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) ArrayList(java.util.ArrayList) DataValueString(com.bencodez.advancedcore.api.user.usercache.value.DataValueString) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 3 with OfflineBungeeVote

use of com.bencodez.votingplugin.bungee.OfflineBungeeVote in project VotingPlugin by Ben12345rocks.

the class VotingPluginVelocity method onProxyInitialization.

@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
    File configFile = new File(dataDirectory.toFile(), "bungeeconfig.yml");
    configFile.getParentFile().mkdirs();
    if (!configFile.exists()) {
        try {
            configFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream toCopyStream = VotingPluginVelocity.class.getClassLoader().getResourceAsStream("bungeeconfig.yml");
        try (FileOutputStream fos = new FileOutputStream(configFile)) {
            byte[] buf = new byte[2048];
            int r;
            while (-1 != (r = toCopyStream.read(buf))) {
                fos.write(buf, 0, r);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    config = new Config(configFile);
    server.getChannelRegistrar().register(CHANNEL);
    method = BungeeMethod.getByName(config.getBungeeMethod());
    boolean mysqlLoaded = true;
    try {
        if (!config.getString(config.getNode("Host"), "").isEmpty()) {
            loadMysql();
        } else {
            mysqlLoaded = false;
            logger.error("MySQL settings not set in bungeeconfig.yml");
        }
    } catch (Exception e) {
        mysqlLoaded = false;
        e.printStackTrace();
    }
    CommandMeta meta = server.getCommandManager().metaBuilder("votingpluginbungee").aliases("vpb").build();
    server.getCommandManager().register(meta, new VotingPluginVelocityCommand(this));
    if (mysqlLoaded) {
        uuidPlayerNameCache = mysql.getRowsUUIDNameQuery();
        voteCacheFile = new VoteCache(new File(dataDirectory.toFile(), "votecache.yml"));
        nonVotedPlayersCache = new NonVotedPlayersCache(new File(dataDirectory.toFile(), "nonvotedplayerscache.yml"), this);
        timeHandle = new TimeHandle(voteCacheFile.getNode("Time", "Month").getString(""), voteCacheFile.getNode("Time", "Day").getInt(), voteCacheFile.getNode("Time", "Week").getInt()) {

            @Override
            public void save() {
                voteCacheFile.getNode("Time", "Month").setValue(timeHandle.getMonth());
                voteCacheFile.getNode("Time", "Day").setValue(timeHandle.getDay());
                voteCacheFile.getNode("Time", "Week").setValue(timeHandle.getWeek());
            }
        };
        if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
            try {
                for (String serverToCheck : voteCacheFile.getServers()) {
                    ArrayList<OfflineBungeeVote> vote = new ArrayList<OfflineBungeeVote>();
                    for (String num : voteCacheFile.getServerVotes(serverToCheck)) {
                        ConfigurationNode data = voteCacheFile.getServerVotes(serverToCheck, num);
                        vote.add(new OfflineBungeeVote(data.getNode("Name").getString(), data.getNode("UUID").getString(), data.getNode("Service").getString(), data.getNode("Time").getLong(), data.getNode("Real").getBoolean(), data.getNode("TEXT").getString()));
                    }
                    cachedVotes.put(server.getServer(serverToCheck).get(), vote);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                for (String player : voteCacheFile.getPlayers()) {
                    ArrayList<OfflineBungeeVote> vote = new ArrayList<OfflineBungeeVote>();
                    for (String num : voteCacheFile.getOnlineVotes(player)) {
                        ConfigurationNode data = voteCacheFile.getOnlineVotes(player, num);
                        vote.add(new OfflineBungeeVote(data.getNode("Name").getString(), data.getNode("UUID").getString(), data.getNode("Service").getString(), data.getNode("Time").getLong(), data.getNode("Real").getBoolean(), data.getNode("TEXT").getString()));
                    }
                    cachedOnlineVotes.put(player, vote);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            voteCacheFile.clearData();
            server.getScheduler().buildTask(this, () -> {
                for (RegisteredServer server : cachedVotes.keySet()) {
                    checkCachedVotes(server);
                }
                for (String player : cachedOnlineVotes.keySet()) {
                    if (server.getPlayer(UUID.fromString(player)).isPresent()) {
                        checkOnlineVotes(server.getPlayer(UUID.fromString(player)).get(), player, null);
                    }
                }
            }).delay(15L, TimeUnit.SECONDS).repeat(30l, TimeUnit.SECONDS).schedule();
            server.getScheduler().buildTask(this, () -> {
                if (nonVotedPlayersCache != null) {
                    debug("Checking nonvotedplayerscache.yml...");
                    nonVotedPlayersCache.check();
                }
            }).delay(1L, TimeUnit.MINUTES).repeat(60l, TimeUnit.MINUTES).schedule();
        } else if (method.equals(BungeeMethod.SOCKETS)) {
            encryptionHandler = new EncryptionHandler(new File(dataDirectory.toFile(), "secretkey.key"));
            socketHandler = new SocketHandler(server.getPluginManager().getPlugin("votingplugin").get().getDescription().getVersion().get(), config.getBungeeHost(), config.getBungeePort(), encryptionHandler, config.getDebug());
            socketHandler.add(new SocketReceiver() {

                @Override
                public void onReceive(String[] data) {
                    if (data.length > 1) {
                        if (data.length > 2) {
                            if (data[0].equalsIgnoreCase("Broadcast")) {
                                sendServerMessage(data);
                            }
                        }
                    }
                }
            });
            socketHandler.add(new SocketReceiver() {

                @Override
                public void onReceive(String[] data) {
                    if (data.length > 1) {
                        if (data[0].equalsIgnoreCase("StatusOkay")) {
                            String server = data[1];
                            logger.info("Voting communicaton okay with " + server);
                        }
                    }
                }
            });
            clientHandles = new HashMap<String, ClientHandler>();
            List<String> l = config.getBlockedServers();
            for (ConfigurationNode d : config.getSpigotServers()) {
                String s = d.getKey().toString();
                if (!l.contains(s)) {
                    clientHandles.put(s, new ClientHandler(d.getNode("Host").getString("0.0.0.0"), d.getNode("Port").getInt(1298), encryptionHandler, config.getDebug()));
                }
            }
        }
    }
    currentVotePartyVotesRequired = getConfig().getVotePartyVotesRequired() + voteCacheFile.getVotePartyInreaseVotesRequired();
    votePartyVotes = voteCacheFile.getVotePartyCurrentVotes();
    try {
        getVersionFile();
        if (versionFile != null) {
            versionFile.delete();
            versionFile.getParentFile().delete();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    Metrics metrics = metricsFactory.make(this, 11547);
    metrics.addCustomChart(new SimplePie("bungee_method", () -> getConfig().getBungeeMethod().toString()));
    metrics.addCustomChart(new SimplePie("sendtoallservers", () -> "" + getConfig().getSendVotesToAllServers()));
    metrics.addCustomChart(new SimplePie("allowunjoined", () -> "" + getConfig().getAllowUnJoined()));
    metrics.addCustomChart(new SimplePie("pointsonvote", () -> "" + getConfig().getPointsOnVote()));
    metrics.addCustomChart(new SimplePie("bungeemanagetotals", () -> "" + getConfig().getBungeeManageTotals()));
    metrics.addCustomChart(new SimplePie("waitforuseronline", () -> "" + getConfig().getWaitForUserOnline()));
    metrics.addCustomChart(new SimplePie("plugin_version", () -> "" + version));
    if (!buildNumber.equals("NOTSET")) {
        metrics.addCustomChart(new SimplePie("dev_build_number", () -> "" + buildNumber));
    }
    logger.info("VotingPlugin velocity loaded, method: " + method.toString() + ", PluginMessagingVersion: " + BungeeVersion.getPluginMessageVersion() + ", Internal Jar Version: " + version);
    if (!buildNumber.equals("NOTSET")) {
        logger.info("Detected using dev build number: " + buildNumber);
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) SocketHandler(com.bencodez.advancedcore.bungeeapi.sockets.SocketHandler) SocketReceiver(com.bencodez.advancedcore.bungeeapi.sockets.SocketReceiver) ArrayList(java.util.ArrayList) SimplePie(org.bstats.charts.SimplePie) DataValueString(com.bencodez.advancedcore.api.user.usercache.value.DataValueString) EncryptionHandler(com.bencodez.advancedcore.api.misc.encryption.EncryptionHandler) Metrics(org.bstats.velocity.Metrics) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) List(java.util.List) ArrayList(java.util.ArrayList) CommandMeta(com.velocitypowered.api.command.CommandMeta) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) OfflineBungeeVote(com.bencodez.votingplugin.bungee.OfflineBungeeVote) ClientHandler(com.bencodez.advancedcore.bungeeapi.sockets.ClientHandler) IOException(java.io.IOException) SQLException(java.sql.SQLException) IOException(java.io.IOException) TimeHandle(com.bencodez.votingplugin.bungee.TimeHandle) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 4 with OfflineBungeeVote

use of com.bencodez.votingplugin.bungee.OfflineBungeeVote in project VotingPlugin by Ben12345rocks.

the class VotingPluginVelocity method vote.

public synchronized void vote(String player, String service, boolean realVote) {
    try {
        if (player == null || player.isEmpty()) {
            logger.info("No name from vote on " + service);
            return;
        }
        String uuid = getUUID(player);
        if (uuid.isEmpty()) {
            if (config.getAllowUnJoined()) {
                debug("Fetching UUID online, since allowunjoined is enabled");
                UUID u = null;
                try {
                    u = fetchUUID(player);
                } catch (Exception e) {
                    if (getConfig().getDebug()) {
                        e.printStackTrace();
                    }
                }
                if (u == null) {
                    debug("Failed to get uuid for " + player);
                    return;
                }
                uuid = u.toString();
            } else {
                logger.info("Ignoring vote from " + player + " since player hasn't joined before");
                return;
            }
        }
        player = getProperName(uuid, player);
        BungeeMessageData text = null;
        addVoteParty();
        if (getConfig().getBungeeManageTotals()) {
            if (mysql == null) {
                logger.error("Mysql is not loaded correctly, stopping vote processing");
                return;
            }
            if (!mysql.getUuids().contains(uuid)) {
                mysql.update(uuid, "PlayerName", new DataValueString(player));
            }
            ArrayList<Column> data = mysql.getExactQuery(new Column("uuid", new DataValueString(uuid)));
            int allTimeTotal = getValue(data, "AllTimeTotal", 1);
            int monthTotal = getValue(data, "MonthTotal", 1);
            int weeklyTotal = getValue(data, "WeeklyTotal", 1);
            int dailyTotal = getValue(data, "DailyTotal", 1);
            int points = getValue(data, "Points", getConfig().getPointsOnVote());
            int milestoneCount = getValue(data, "MilestoneCount", 1);
            text = new BungeeMessageData(allTimeTotal, monthTotal, weeklyTotal, dailyTotal, points, milestoneCount, votePartyVotes, currentVotePartyVotesRequired);
            ArrayList<Column> update = new ArrayList<Column>();
            update.add(new Column("AllTimeTotal", new DataValueInt(allTimeTotal)));
            update.add(new Column("MonthTotal", new DataValueInt(monthTotal)));
            update.add(new Column("WeeklyTotal", new DataValueInt(weeklyTotal)));
            update.add(new Column("DailyTotal", new DataValueInt(dailyTotal)));
            update.add(new Column("Points", new DataValueInt(points)));
            update.add(new Column("MilestoneCount", new DataValueInt(milestoneCount)));
            debug("Setting totals " + text.toString());
            mysql.update(uuid, update);
        } else {
            text = new BungeeMessageData(0, 0, 0, 0, 0, 0, votePartyVotes, currentVotePartyVotesRequired);
        }
        /*
			 * String text = mysqlUpdate(data, uuid, "AllTimeTotal", 1) + "//" +
			 * mysqlUpdate(data, uuid, "MonthTotal", 1) + "//" + mysqlUpdate(data, uuid,
			 * "WeeklyTotal", 1) + "//" + mysqlUpdate(data, uuid, "DailyTotal", 1) + "//" +
			 * mysqlUpdate(data, uuid, "Points", 1) + "//" + mysqlUpdate(data, uuid,
			 * "MilestoneCount", 1);
			 */
        long time = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
            if (config.getSendVotesToAllServers()) {
                for (RegisteredServer s : server.getAllServers()) {
                    if (!config.getBlockedServers().contains(s.getServerInfo().getName())) {
                        boolean forceCache = false;
                        Player p = null;
                        if (server.getPlayer(UUID.fromString(uuid)).isPresent()) {
                            p = server.getPlayer(UUID.fromString(uuid)).get();
                        }
                        if ((p == null || !p.isActive()) && getConfig().getWaitForUserOnline()) {
                            forceCache = true;
                            debug("Forcing vote to cache");
                        }
                        if (s.getPlayersConnected().isEmpty() || forceCache) {
                            // cache
                            if (!cachedVotes.containsKey(s)) {
                                cachedVotes.put(s, new ArrayList<OfflineBungeeVote>());
                            }
                            ArrayList<OfflineBungeeVote> list = cachedVotes.get(s);
                            list.add(new OfflineBungeeVote(player, uuid, service, time, realVote, text.toString()));
                            cachedVotes.put(s, list);
                            debug("Caching vote for " + player + " on " + service + " for " + s);
                        } else {
                            // send
                            sendPluginMessageServer(s, "Vote", player, uuid, service, "" + time, Boolean.TRUE.toString(), "" + realVote, text.toString(), "" + getConfig().getBungeeManageTotals(), "" + BungeeVersion.getPluginMessageVersion(), "" + config.getBroadcast());
                        }
                        if (config.getBroadcast()) {
                            sendPluginMessageServer(s, "VoteBroadcast", uuid, player, service);
                        }
                    }
                }
            } else {
                Player p = null;
                if (server.getPlayer(UUID.fromString(uuid)).isPresent()) {
                    p = server.getPlayer(UUID.fromString(uuid)).get();
                }
                if (p != null && p.isActive() && !config.getBlockedServers().contains(p.getCurrentServer().get().getServerInfo().getName())) {
                    sendPluginMessageServer(p.getCurrentServer().get().getServer(), "VoteOnline", player, uuid, service, "" + time, Boolean.TRUE.toString(), "" + realVote, text.toString(), "" + getConfig().getBungeeManageTotals(), "" + BungeeVersion.getPluginMessageVersion(), "" + config.getBroadcast());
                } else {
                    if (!cachedOnlineVotes.containsKey(uuid)) {
                        cachedOnlineVotes.put(uuid, new ArrayList<OfflineBungeeVote>());
                    }
                    ArrayList<OfflineBungeeVote> list = cachedOnlineVotes.get(uuid);
                    if (list == null) {
                        list = new ArrayList<OfflineBungeeVote>();
                    }
                    list.add(new OfflineBungeeVote(player, uuid, service, time, realVote, text.toString()));
                    cachedOnlineVotes.put(uuid, list);
                    debug("Caching online vote for " + player + " on " + service);
                }
                for (RegisteredServer s : server.getAllServers()) {
                    sendPluginMessageServer(s, "VoteUpdate", uuid, "" + votePartyVotes, "" + currentVotePartyVotesRequired);
                    if (config.getBroadcast()) {
                        sendPluginMessageServer(s, "VoteBroadcast", uuid, player, service);
                    }
                }
            }
        } else if (method.equals(BungeeMethod.SOCKETS)) {
            sendSocketVote(player, service, text);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Player(com.velocitypowered.api.proxy.Player) OfflineBungeeVote(com.bencodez.votingplugin.bungee.OfflineBungeeVote) ArrayList(java.util.ArrayList) DataValueString(com.bencodez.advancedcore.api.user.usercache.value.DataValueString) SQLException(java.sql.SQLException) IOException(java.io.IOException) DataValueInt(com.bencodez.advancedcore.api.user.usercache.value.DataValueInt) Column(com.bencodez.advancedcore.api.user.userstorage.Column) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) DataValueString(com.bencodez.advancedcore.api.user.usercache.value.DataValueString) UUID(java.util.UUID) BungeeMessageData(com.bencodez.votingplugin.bungee.BungeeMessageData)

Aggregations

OfflineBungeeVote (com.bencodez.votingplugin.bungee.OfflineBungeeVote)4 ArrayList (java.util.ArrayList)4 DataValueString (com.bencodez.advancedcore.api.user.usercache.value.DataValueString)3 RegisteredServer (com.velocitypowered.api.proxy.server.RegisteredServer)3 Subscribe (com.velocitypowered.api.event.Subscribe)2 Player (com.velocitypowered.api.proxy.Player)2 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 EncryptionHandler (com.bencodez.advancedcore.api.misc.encryption.EncryptionHandler)1 DataValueInt (com.bencodez.advancedcore.api.user.usercache.value.DataValueInt)1 Column (com.bencodez.advancedcore.api.user.userstorage.Column)1 ClientHandler (com.bencodez.advancedcore.bungeeapi.sockets.ClientHandler)1 SocketHandler (com.bencodez.advancedcore.bungeeapi.sockets.SocketHandler)1 SocketReceiver (com.bencodez.advancedcore.bungeeapi.sockets.SocketReceiver)1 BungeeMessageData (com.bencodez.votingplugin.bungee.BungeeMessageData)1 TimeHandle (com.bencodez.votingplugin.bungee.TimeHandle)1 CommandMeta (com.velocitypowered.api.command.CommandMeta)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 DataInputStream (java.io.DataInputStream)1 File (java.io.File)1