Fork of Poseidon providing Bukkit #1060 to older Beta versions (b1.0-b1.7.3)
at develop 66 lines 2.9 kB view raw
1package com.legacyminecraft.poseidon.util; 2 3import org.json.simple.JSONObject; 4import org.json.simple.parser.JSONParser; 5 6import javax.net.ssl.HttpsURLConnection; 7import java.io.BufferedReader; 8import java.io.InputStreamReader; 9import java.net.URL; 10 11/** 12 * A wrapper class for the Minecraft session API 13 * <p> 14 * TODO maybe make the HTTP requests asynchronous? idk if it really matters 15 * 16 * @author moderator_man 17 */ 18public class SessionAPI { 19 public static final String SESSION_BASE = "http://session.minecraft.net/game/"; 20 21 public static boolean hasJoined(String username, String serverId) { 22 HTTPResponse response = httpGetRequest(SESSION_BASE + String.format("checkserver.jsp?user=%s&serverId=%s", username, serverId)); 23 if (response.getResponse() != "YES") return false; 24 return true; 25 } 26 27 public static void hasJoined(String username, String serverId, String ip, SessionRequestRunnable callback) { 28 try { 29 boolean checkIP = ip == "127.0.0.1" || ip == "localhost"; 30 StringBuilder sb = new StringBuilder(); 31 sb.append("https://sessionserver.mojang.com/session/minecraft/hasJoined"); 32 sb.append("?username=" + username); 33 sb.append("&serverId=" + serverId); 34 if (checkIP) sb.append("&ip=" + ip); 35 String requestUrl = sb.toString(); 36 37 HTTPResponse response = httpGetRequest(requestUrl); 38 JSONObject obj = (JSONObject) new JSONParser().parse(response.getResponse()); 39 String res_username = (obj.containsKey("name") ? (String) obj.get("name") : "nousername"); 40 String res_uuid = (obj.containsKey("id") ? (String) obj.get("id") : "nouuid"); 41 String res_ip = (obj.containsKey("ip") ? (String) obj.get("ip") : "noip"); 42 callback.callback(response.getResponseCode(), res_username, res_uuid, res_ip); 43 } catch (Exception ex) { 44 System.out.println(String.format("Failed to authenticate session for '%s': %s", username, ex.getMessage())); 45 // TODO: if debug, print the stack trace 46 } 47 } 48 49 private static HTTPResponse httpGetRequest(String url) { 50 try { 51 URL obj = new URL(url); 52 HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 53 con.setRequestMethod("GET"); 54 con.setRequestProperty("User-Agent", "Project-Poseidon/0"); 55 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 56 String inputLine; 57 StringBuffer response = new StringBuffer(); 58 while ((inputLine = in.readLine()) != null) { response.append(inputLine); } 59 in.close(); 60 return new HTTPResponse(response.toString(), con.getResponseCode()); 61 } catch (Exception ex) { 62 ex.printStackTrace(); 63 return new HTTPResponse("", -1); 64 } 65 } 66}