package net.voterank.votescript; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Claims votes for players of a game server, safely. * *
 * VoteRewards rewards = new VoteRewards(new VoteScript(URL, KEY), gameThread, new File("data/votes.properties"));
 * // in ::claimvote
 * rewards.claim(player.getUsername(), new VoteRewards.Handler() {
 *     public boolean give(VoteScript.Claim claim) {            // game thread
 *         if (!player.isOnline()) return false;                // kept for next time
 *         for (VoteScript.Item i : claim.items) player.addItem(Integer.parseInt(i.key), i.amount);
 *         return true;
 *     }
 *     public void message(String text) { player.sendMessage(text); }
 * });
 * 
* * For more than items, such as donator days or teleports, see {@link VoteActions}. * * The network runs on worker threads. The reference of a claim is written to * the file before asking, so if the server crashes or the answer is lost, the * next claim repeats the same one: nothing is lost and nothing is paid twice. */ public final class VoteRewards { public interface Handler { /** Runs on the game thread. Return false if the items could not be given; they are kept. */ boolean give(VoteScript.Claim claim); /** Runs on the game thread. */ void message(String text); } private final VoteScript api; private final Executor gameThread; private final File file; private final Properties pending = new Properties(); private final Set busy = ConcurrentHashMap.newKeySet(); private final ExecutorService workers = Executors.newFixedThreadPool(2, r -> { Thread t = new Thread(r, "VoteScript"); t.setDaemon(true); return t; }); /** * @param gameThread runs tasks on the game thread, e.g. task -> World.submit(task) * @param file where unfinished claims are kept */ public VoteRewards(VoteScript api, Executor gameThread, File file) throws IOException { this.api = api; this.gameThread = gameThread; this.file = file; if (file.getAbsoluteFile().getParentFile() != null) file.getAbsoluteFile().getParentFile().mkdirs(); if (file.isFile()) { try (InputStream in = new FileInputStream(file)) { pending.load(in); } } } /** Tells VoteScript what this game can give. Rewards with anything else stay waiting. */ public void can(VoteActions actions) { api.types(VoteActions.list(actions)); } /** Claims by player name. */ public void claim(String player, Handler handler) { start(player, null, handler); } /** Redeems a code shown on the vote page. */ public void claimCode(String player, String code, Handler handler) { start(player, code, handler); } private void start(String player, String code, Handler handler) { String id = player.toLowerCase(Locale.ROOT); if (!busy.add(id)) { handler.message("Your votes are already being checked."); return; } workers.execute(() -> run(id, player, code, handler)); } private void run(String id, String player, String code, Handler h) { String slot = code == null ? id : id + "|" + code.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); try { boolean repeat; String ref; synchronized (pending) { String old = pending.getProperty(slot); repeat = old != null; ref = repeat ? old : UUID.randomUUID().toString(); if (!repeat) { pending.setProperty(slot, ref); save(); } } VoteScript.Claim claim = code == null ? api.claim(player, ref) : api.claimCode(player, code, ref); gameThread.execute(() -> { boolean again = false; try { if (!claim.ok) { forget(slot); h.message(claim.error); } else if (claim.votes == 0 && claim.items.isEmpty()) { forget(slot); again = repeat && code == null; if (!again) h.message(claim.held > 0 ? "Your vote reward cannot be given on this server yet. It stays waiting." : "You have no votes to claim."); } else if (give(h, claim, player, slot)) { h.message("Thank you for voting! Rewards received for " + claim.votes + (claim.votes == 1 ? " vote." : " votes.")); again = repeat && code == null; // a finished old claim: look for newer votes } else { h.message("Your rewards are waiting. Make room, leave any fight and try again."); } } catch (Failed e) { return; // reported; the game loop goes on } finally { busy.remove(id); } if (again) start(player, null, h); }); } catch (IOException | RuntimeException e) { // Nothing is forgotten: the same reference is used next time. busy.remove(id); gameThread.execute(() -> h.message("Votes cannot be checked right now. Try again in a minute.")); System.err.println("[VoteScript] " + e.getMessage()); } } /** True when given. An error halfway must not pay the first half again, so it ends the claim. */ private boolean give(Handler h, VoteScript.Claim claim, String player, String slot) { try { if (!h.give(claim)) return false; } catch (RuntimeException | Error e) { forget(slot); StringBuilder b = new StringBuilder(); for (VoteScript.Item i : claim.items) b.append(' ').append(i.amount).append("x").append(i.key); System.err.println("[VoteScript] The reward code failed for " + player + ". Check what they got of:" + b); e.printStackTrace(); h.message("Something went wrong with your vote reward. Please tell the staff."); throw new Failed(); } forget(slot); return true; } private static final class Failed extends RuntimeException { private static final long serialVersionUID = 1; } private void forget(String slot) { synchronized (pending) { pending.remove(slot); save(); } } private void save() { File tmp = new File(file.getPath() + ".tmp"); try { try (OutputStream out = new FileOutputStream(tmp)) { pending.store(out, "VoteScript: unfinished claims"); } java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { System.err.println("[VoteScript] could not save " + file + ": " + e.getMessage()); } } public void close() { workers.shutdown(); } }