package net.voterank.votescript;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import net.voterank.votescript.bridge.VoteBox;
import net.voterank.votescript.bridge.VoteQueue;
import net.voterank.votescript.bridge.VotifierServer;
/**
* Votes for a RuneScape private server, or any other Java game server: what
* Votifier is for Minecraft, inside your own process.
*
*
* // when the server starts
* votes = VoteServer.start(new File("data/votes"), new VoteServer.Game() { ... four short methods ... });
* // in your command handler
* if (votes.command(player.getUsername(), text)) return;
*
*
* With an API key in votescript.properties it pays what VoteScript has for the
* players who are online. With votifier=true it also listens for lists that
* send Votifier or NuVotifier votes. Without a key those votes are paid from
* the rewards in the same file, and no VoteScript account is needed.
*/
public final class VoteServer implements Closeable {
/** Your game. Every method except run is called on the game thread. */
public interface Game {
/** Runs the task on the game thread, e.g. in the next tick. Called from other threads. */
void run(Runnable task);
/** Names of the players who are online now. */
Collection online();
/**
* Gives the items. Return true only when the player has all of them, or false
* when there is no room or they left; then nothing may have been given.
*/
boolean give(String player, VoteScript.Claim claim);
void message(String player, String text);
}
private final Game game;
private final Properties p;
private final File dir;
private final boolean auto;
private final long every;
private VoteScript api;
private VoteRewards rewards;
private VoteQueue queue;
private VoteBox box;
private VotifierServer votifier;
private final Map later = new ConcurrentHashMap<>();
private volatile boolean open = true;
private final Thread thread;
/** Reads folder/votescript.properties, or writes it first. Never throws: voting must not stop a game from starting. */
public static VoteServer start(File folder, Game game) {
return start(folder, game, null);
}
/** The same, and VoteScript keeps back what these actions cannot give. */
public static VoteServer start(File folder, Game game, VoteActions> actions) {
try {
return new VoteServer(folder, game, actions);
} catch (Exception e) {
System.err.println("[VoteScript] could not start: " + e);
return null;
}
}
public VoteServer(File folder, Game game) throws Exception {
this(folder, game, null);
}
public VoteServer(File folder, Game game, VoteActions> actions) throws Exception {
this.game = game;
this.dir = folder;
this.p = config(folder);
this.auto = !no("automatic");
this.every = Math.max(3, Integer.parseInt(get("every", "10"))) * 1000L;
String key = get("key", "");
if (!key.isEmpty()) {
api = new VoteScript(get("url", "https://votescript.voterank.net"), key);
api.types(VoteActions.list(actions));
rewards = new VoteRewards(api, game::run, new File(folder, "pending.properties"));
}
if (get("votifier", "false").equalsIgnoreCase("true")) {
VotifierServer.Listener to;
if (api != null) {
queue = new VoteQueue(api, new File(folder, "queue"), VoteServer::log);
to = queue::add;
} else {
box = new VoteBox(new File(folder, "votes"), Integer.parseInt(get("hours-between", "1")), Integer.parseInt(get("keep-days", "60")));
to = this::received;
}
Map tokens = new HashMap<>();
for (String k : p.stringPropertyNames()) if (k.startsWith("token.")) tokens.put(k.substring(6), p.getProperty(k).trim());
tokens.put("default", get("token", ""));
votifier = new VotifierServer(get("host", "0.0.0.0"), Integer.parseInt(get("port", "8192")), new File(folder, "rsa"), tokens, !no("v1"), to);
log("Votifier listens on port " + votifier.port() + ". Public key and token are in " + new File(folder, "rsa/public.key") + " and votescript.properties.");
}
if (api == null && votifier == null) log("Set key=, or votifier=true, in " + new File(folder, "votescript.properties") + " and restart.");
thread = new Thread(this::loop, "VoteScript votes");
thread.setDaemon(true);
thread.start();
}
/** True when the text was one of the vote commands: claimvote, claimvote CODE, auth CODE. With or without "::". */
public boolean command(String player, String text) {
String[] w = text.trim().replaceFirst("^(::|/|;;)", "").split("\\s+");
String c = w[0].toLowerCase(Locale.ROOT);
if (c.equals("auth") || c.equals("claimvote") && w.length > 1) {
if (w.length < 2) game.run(() -> game.message(player, "Type ::auth and the code from the vote page."));
else code(player, w[1]);
return true;
}
if (!c.equals("claimvote") && !c.equals("claimvotes")) return false;
claim(player);
return true;
}
/** Pays what the player has waiting. */
public void claim(String player) {
if (rewards != null) rewards.claim(player, new Pay(player, true));
else if (box != null) game.run(() -> fromBox(player, true));
else game.run(() -> game.message(player, "Votes are not set up yet."));
}
/** Pays a code from the vote page. */
public void code(String player, String code) {
if (rewards != null) rewards.claimCode(player, code, new Pay(player, true));
else game.run(() -> game.message(player, "Codes are not used on this server. Type ::claimvote."));
}
/** What lists ask for as Votifier public key, or "" when Votifier is off. */
public String publicKey() {
return votifier == null ? "" : votifier.publicKey();
}
/** The port votes come in on, or 0. */
public int port() {
return votifier == null ? 0 : votifier.port();
}
private void received(String service, String player, String time) {
log("Vote from " + service + " for " + player + (box.put(service, player, time) ? "" : ": already counted"));
}
/* ------------------------------------------------------- paying */
private final class Pay implements VoteRewards.Handler {
private final String player;
private final boolean talk;
Pay(String player, boolean talk) {
this.player = player;
this.talk = talk;
}
@Override
public boolean give(VoteScript.Claim claim) {
boolean ok = game.give(player, claim);
if (!ok) pause(player);
return ok;
}
@Override
public void message(String text) {
if (talk || text.startsWith("Thank") || text.startsWith("Something") || text.startsWith("Your rewards are waiting")) game.message(player, text);
}
}
/** A full inventory is not asked about again every few seconds. */
private void pause(String player) {
later.put(VoteBox.key(player), System.currentTimeMillis() + 60_000);
}
/** Game thread. */
private void fromBox(String player, boolean talk) {
List votes = box.of(player);
if (votes.isEmpty()) {
if (talk) game.message(player, "You have no votes to claim.");
return;
}
Map sum = new LinkedHashMap<>();
for (VoteBox.Vote v : votes) for (String r : get("reward." + v.service, get("reward", "")).split(",")) {
String[] x = r.trim().split(":");
try {
if (!x[0].isEmpty()) sum.merge(x[0], x.length > 1 ? Math.max(0, Long.parseLong(x[1].trim())) : 1, Long::sum);
} catch (NumberFormatException e) {
log("This reward is not KEY:AMOUNT: " + r);
}
}
List items = new ArrayList<>();
sum.forEach((k, n) -> items.add(new VoteScript.Item(k, k, (int) Math.min(n, Integer.MAX_VALUE))));
try {
if (!game.give(player, new VoteScript.Claim(true, null, votes.size(), Collections.unmodifiableList(items)))) {
pause(player);
game.message(player, "Your rewards are waiting. Make room, leave any fight and try again.");
return;
}
} catch (RuntimeException | Error e) {
// Half of it may have been given, so it is not given again.
box.done(votes);
System.err.println("[VoteScript] The reward code failed for " + player + ". Check what they got of: " + sum);
e.printStackTrace();
game.message(player, "Something went wrong with your vote reward. Please tell the staff.");
return;
}
box.done(votes);
game.message(player, "Thank you for voting! Rewards received for " + votes.size() + (votes.size() == 1 ? " vote." : " votes."));
}
/* ------------------------------------------------- who is online */
private void loop() {
boolean failing = false;
while (open) {
try {
Thread.sleep(failing ? Math.max(30_000, every) : every);
if (auto && (rewards != null || box != null)) look();
failing = false;
} catch (InterruptedException e) {
return;
} catch (IOException | RuntimeException e) {
if (!failing) log("Votes cannot be checked right now: " + e.getMessage());
failing = true;
}
}
}
private void look() throws IOException, InterruptedException {
List online = new ArrayList<>();
CountDownLatch got = new CountDownLatch(1);
game.run(() -> {
try {
for (String n : game.online()) {
if (n == null || n.isEmpty()) continue;
if (box != null) {
if (ready(n) && !box.of(n).isEmpty()) fromBox(n, false);
} else if (ready(n)) online.add(n);
}
} finally {
got.countDown();
}
});
if (!got.await(10, TimeUnit.SECONDS) || box != null || online.isEmpty()) return;
Map names = new HashMap<>();
for (String n : online) names.put(VoteBox.key(n), n);
List all = new ArrayList<>(names.keySet());
for (int i = 0; i < all.size() && open; i += 200) {
for (String n : api.waiting(all.subList(i, Math.min(all.size(), i + 200)))) {
String here = names.get(VoteBox.key(n));
if (here != null) rewards.claim(here, new Pay(here, false));
}
}
}
private boolean ready(String player) {
Long t = later.get(VoteBox.key(player));
if (t == null) return true;
if (System.currentTimeMillis() < t) return false;
later.remove(VoteBox.key(player));
return true;
}
/* ------------------------------------------------------ settings */
private String get(String key, String other) {
return p.getProperty(key, other).trim();
}
private boolean no(String key) {
return get(key, "true").equalsIgnoreCase("false");
}
private static void log(String text) {
System.out.println("[VoteScript] " + text.replaceAll("[\\p{Cntrl}]", " "));
}
private static Properties config(File dir) throws IOException {
Files.createDirectories(dir.toPath());
File f = new File(dir, "votescript.properties");
if (!f.isFile()) {
byte[] b = new byte[20];
new SecureRandom().nextBytes(b);
StringBuilder t = new StringBuilder();
for (byte x : b) t.append(String.format("%02x", x));
Files.write(f.toPath(), String.join("\n",
"# VoteScript. Restart the server after a change.",
"url=https://votescript.voterank.net",
"# API key from Game server in your dashboard. Empty: no VoteScript account, only Votifier below.",
"key=",
"# Pay players while they play, not only when they type ::claimvote.",
"automatic=true",
"# Seconds between looks",
"every=10",
"",
"# Receive votes from lists that send Votifier or NuVotifier. Open the port in your firewall.",
"votifier=false",
"host=0.0.0.0",
"port=8192",
"# Token for NuVotifier (v2). token.SERVICE=... gives one list its own.",
"token=" + t,
"# The old protocol proves nothing about the sender. Set false if all your lists use the token.",
"v1=true",
"",
"# Only without a key: what a vote pays, as KEY:AMOUNT,KEY:AMOUNT, such as 995:1000,vip/gold:1. reward.SERVICE=... for one list.",
"reward=995:100000",
"# A second vote from the same list for the same player within this many hours is ignored (0 to 48).",
"hours-between=1",
"keep-days=60", "").getBytes(StandardCharsets.UTF_8));
f.setReadable(false, false);
f.setReadable(true, true);
}
Properties p = new Properties();
try (InputStream in = new FileInputStream(f)) {
p.load(in);
}
return p;
}
@Override
public void close() {
open = false;
thread.interrupt();
if (votifier != null) votifier.close();
if (queue != null) queue.close();
if (rewards != null) rewards.close();
}
}