package net.voterank.votescript; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * VoteScript client. Java 8+, no dependencies. Thread-safe. * * Calls block on the network: never run them on the game thread. Most servers * want {@link VoteRewards}, which handles threads, retries and crashes. * claim() retries on its own with the same ref, so a lost answer can neither * eat a reward nor pay it twice. Pass a new UUID per command typed. */ public final class VoteScript { public static final class Item { public final String key; public final String name; public final int amount; Item(String key, String name, int amount) { this.key = key; this.name = name; this.amount = amount; } /** "item" for a plain key such as 995, or what stands before the slash: "vip" in vip/gold. */ public String type() { int at = key.indexOf('/'); String t = at < 0 ? "" : key.substring(0, at); return TYPES.contains(t) ? t : "item"; } /** The parts after the type: arg(0) is "gold" in vip/gold. "" when there is none. For items arg(0) is the key. */ public String arg(int n) { if (type().equals("item")) return n == 0 ? key : ""; String rest = key.substring(key.indexOf('/') + 1); if (type().equals("custom")) return n == 0 ? rest : ""; String[] p = rest.split("/"); return n < p.length ? p[n] : ""; } /** arg(n) as a whole number. Throws when it is not one between these two. */ public int number(int n, int from, int to) { String a = arg(n); if (!a.matches("-?[0-9]{1,9}") || Integer.parseInt(a) < from || Integer.parseInt(a) > to) throw new IllegalArgumentException(key + ": " + a + " is not a number between " + from + " and " + to); return Integer.parseInt(a); } /** The coordinates of teleport/X,Y,Z, or null when it names a place. */ public double[] position() { if (!type().equals("teleport") || !arg(0).matches("-?[0-9]{1,7}(\\.[0-9]{1,2})?(,-?[0-9]{1,7}(\\.[0-9]{1,2})?){2}")) return null; String[] p = arg(0).split(","); return new double[]{Double.parseDouble(p[0]), Double.parseDouble(p[1]), Double.parseDouble(p[2])}; } /** .../forever instead of a number of days. */ public boolean forever() { return arg(1).equals("forever"); } /** arg(0) with spaces: "Vote Hero" for title/Vote_Hero. */ public String words() { return arg(0).replace('_', ' '); } } private static final Set TYPES = new HashSet<>(Arrays.asList("vip", "group", "permission", "title", "teleport", "storage", "until", "unlock", "xp", "boost", "effect", "outfit", "mount", "spell", "badge", "run", "custom")); public static final class Claim { /** False only for a code that is unknown or already used; see error. */ public final boolean ok; public final String error; public final int votes; public final List items; /** Rewards that stay waiting because this game cannot give them yet. */ public final int held; Claim(boolean ok, String error, int votes, List items) { this(ok, error, votes, items, 0); } Claim(boolean ok, String error, int votes, List items, int held) { this.ok = ok; this.error = error; this.votes = votes; this.items = items; this.held = held; } } private static final int TRIES = 3; private final String base; private final String key; private volatile String types = ""; /** @param url address of the vote page, e.g. https://example.com/vote/ */ public VoteScript(String url, String apiKey) { // index.php?r= works with and without clean URLs. this.base = url.replaceAll("/+$", "") + "/index.php?r=api/v1/"; this.key = apiKey; } /** What this game can give, such as item, vip/gold, teleport. Rewards with anything else stay waiting. Empty: everything is handed out. */ public void types(Collection can) { types = String.join(",", can); } private String can() throws IOException { return types.isEmpty() ? "" : "&types=" + enc(types); } /** Claims everything the player has waiting. */ public Claim claim(String player, String ref) throws IOException { return post("claim", "player=" + enc(player) + "&ref=" + enc(ref) + can()); } /** Redeems one code from the vote page. */ public Claim claimCode(String player, String code, String ref) throws IOException { return post("claim-code", "player=" + enc(player) + "&code=" + enc(code) + "&ref=" + enc(ref) + can()); } /** Which of these players (at most 200) have something to claim. */ public List waiting(Collection players) throws IOException { List out = new ArrayList<>(); Object rows = request("pending", "limit=200&players=" + enc(String.join(",", players)) + can()).get("players"); if (rows instanceof List) for (Object r : (List) rows) out.add(String.valueOf(((Map) r).get("player"))); return out; } /** Reports a vote received over Votifier. Returns counted, duplicate, ignored or unknown-service. */ public String votifier(String service, String player, String time, String ref) throws IOException { return String.valueOf(request("votifier", "service=" + enc(service) + "&player=" + enc(player) + "&time=" + enc(time) + "&ref=" + enc(ref)).get("result")); } private Claim post(String method, String body) throws IOException { return claimOf(request(method, body)); } private Map request(String method, String body) throws IOException { IOException last = null; for (int i = 0; i < TRIES; i++) { if (i > 0) { try { Thread.sleep(700L * i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted", e); } } HttpURLConnection c = (HttpURLConnection) new URL(base + method).openConnection(); int status; String text; try { c.setConnectTimeout(5000); c.setReadTimeout(8000); c.setRequestMethod("POST"); c.setDoOutput(true); c.setInstanceFollowRedirects(false); c.setRequestProperty("X-Api-Key", key); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); try (OutputStream out = c.getOutputStream()) { out.write(body.getBytes(StandardCharsets.UTF_8)); } status = c.getResponseCode(); text = read(status < 400 ? c.getInputStream() : c.getErrorStream()); } catch (IOException e) { last = e; continue; } finally { c.disconnect(); } if (status >= 500) { last = new IOException("VoteScript answered " + status); continue; } return object(status, text); } throw last; } private static Map object(int status, String text) throws IOException { Object o; try { o = new Json(text).value(); } catch (RuntimeException e) { throw new IOException("VoteScript answered " + status + " with something that is not JSON. Is the URL right?"); } if (!(o instanceof Map)) throw new IOException("Unexpected answer from VoteScript (" + status + ")"); Map m = (Map) o; if (status != 200) throw new IOException("VoteScript: " + m.get("error") + " (" + status + ")"); return m; } private static Claim claimOf(Map m) { List items = new ArrayList<>(); if (m.get("items") instanceof List) { for (Object i : (List) m.get("items")) { Map x = (Map) i; // Several rewards can add up past an int; cap instead of overflowing. long n = ((Number) x.get("amount")).longValue(); items.add(new Item((String) x.get("key"), (String) x.get("name"), (int) Math.min(n, Integer.MAX_VALUE))); } } Object votes = m.get("votes"); Object held = m.get("held"); return new Claim(Boolean.TRUE.equals(m.get("ok")), (String) m.get("error"), votes instanceof Number ? ((Number) votes).intValue() : 0, items, held instanceof Number ? ((Number) held).intValue() : 0); } private static String read(InputStream in) throws IOException { if (in == null) return ""; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; for (int n; (n = in.read(buf)) > 0 && out.size() < 1 << 20; ) out.write(buf, 0, n); return new String(out.toByteArray(), StandardCharsets.UTF_8); } private static String enc(String s) throws IOException { return URLEncoder.encode(s, "UTF-8"); } /** Just enough JSON. */ private static final class Json { private final String s; private int i; Json(String s) { this.s = s; } private char next() { while (Character.isWhitespace(s.charAt(i))) i++; return s.charAt(i); } Object value() { char c = next(); if (c == '{') { Map m = new LinkedHashMap<>(); i++; while (next() != '}') { String k = string(); if (next() != ':') throw new IllegalStateException(); i++; m.put(k, value()); if (next() == ',') i++; } i++; return m; } if (c == '[') { List l = new ArrayList<>(); i++; while (next() != ']') { l.add(value()); if (next() == ',') i++; } i++; return l; } if (c == '"') return string(); int from = i; while (i < s.length() && ",]} \r\n\t".indexOf(s.charAt(i)) < 0) i++; String w = s.substring(from, i); switch (w) { case "true": return Boolean.TRUE; case "false": return Boolean.FALSE; case "null": return null; default: return Double.valueOf(w); } } private String string() { if (next() != '"') throw new IllegalStateException(); StringBuilder b = new StringBuilder(); for (i++; s.charAt(i) != '"'; i++) { char c = s.charAt(i); if (c != '\\') { b.append(c); continue; } c = s.charAt(++i); switch (c) { case 'n': b.append('\n'); break; case 't': b.append('\t'); break; case 'r': b.append('\r'); break; case 'b': b.append('\b'); break; case 'f': b.append('\f'); break; case 'u': b.append((char) Integer.parseInt(s.substring(i + 1, i + 5), 16)); i += 4; break; default: b.append(c); } } i++; return b.toString(); } } }