diff options
author | Florian Rinke <develop@torui.de> | 2021-09-30 20:41:46 +0200 |
---|---|---|
committer | Florian Rinke <develop@torui.de> | 2021-09-30 20:41:46 +0200 |
commit | 593611f745cab688ee251c047855b1beae41f9ef (patch) | |
tree | 85b6c067552b74e7f36fe511d638f5860eb8cbfd /src | |
parent | 832403ba363d29d0252702c626405cbc9ba4d7bd (diff) | |
download | COFL-593611f745cab688ee251c047855b1beae41f9ef.tar.gz COFL-593611f745cab688ee251c047855b1beae41f9ef.tar.bz2 COFL-593611f745cab688ee251c047855b1beae41f9ef.zip |
implements #2, #3 #5, #1 Session IDs
Diffstat (limited to 'src')
5 files changed, 355 insertions, 56 deletions
diff --git a/src/main/java/de/torui/coflsky/CoflSky.java b/src/main/java/de/torui/coflsky/CoflSky.java index e5be925..fece43d 100644 --- a/src/main/java/de/torui/coflsky/CoflSky.java +++ b/src/main/java/de/torui/coflsky/CoflSky.java @@ -17,12 +17,15 @@ import java.util.UUID; import com.google.gson.JsonArray; import com.google.gson.stream.JsonReader; +import de.torui.coflsky.minecraft_integration.PlayerDataProvider; +import de.torui.coflsky.minecraft_integration.TemporarySession; import de.torui.coflsky.websocket.WSClient; import de.torui.coflsky.websocket.WSClientWrapper; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; @@ -43,79 +46,43 @@ public class CoflSky public void init(FMLInitializationEvent event) throws URISyntaxException { - Minecraft.getSessionInfo().forEach((a,b) -> System.out.println("Key=" + a + " value=" + b)); + System.out.println(">>>> "+ TemporarySession.GetTempFileFolder().toString()); + //Minecraft.getSessionInfo().forEach((a,b) -> System.out.println("Key=" + a + " value=" + b)); //System.out.println("Loggerfactory: " + LoggerFactory.getILoggerFactory()); // Logger log = LoggerFactory.getLogger(CoflSky.class); // log.debug("Testing"); + + // some example code System.out.println("Initializing"); //new Thread(new WSClient(new URI("ws://localhost:8080"))).start(); System.out.println(">>>Started"); - String username = Minecraft.getSessionInfo().get("X-Minecraft-Username"); - String uuid = QueryUUID(username); + String username = PlayerDataProvider.getUsername(); + String uuid = PlayerDataProvider.getActivePlayerUUID(); System.out.println(">>> Username= " + username + " with UUID=" + uuid ); - String URI = "https://api.mojang.com/profiles/minecraft"; + String tempUUID = UUID.randomUUID().toString(); + try { + TemporarySession.UpdateSessions(); + tempUUID = TemporarySession.GetSession(username).SessionUUID; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } //CoflSky.Wrapper = new WSClientWrapper("wss://sky-commands.coflnet.com/modsocket?version=" + CoflSky.VERSION + "&uuid="); - CoflSky.Wrapper = new WSClientWrapper("ws://sky-mod.coflnet.com/modsocket?version=" + CoflSky.VERSION + "&uuid=" + uuid); + CoflSky.Wrapper = new WSClientWrapper("ws://sky-mod.coflnet.com/modsocket?version=" + CoflSky.VERSION + "&SId=" + tempUUID + "&uuid=" + uuid); if(event.getSide() == Side.CLIENT) ClientCommandHandler.instance.registerCommand(new CoflSkyCommand()); MinecraftForge.EVENT_BUS.register(new EventRegistry()); } - private static class UUIDHelper { - public String id; - public String name; - } - public static String QueryUUID(String username) { - - try { - URL url = new URL("https://api.mojang.com/profiles/minecraft"); - HttpURLConnection con; - con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("POST"); - - con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); - con.setRequestProperty("Accept", "application/json"); - con.setDoInput(true); - con.setDoOutput(true); - // ... - - OutputStream os = con.getOutputStream(); - byte[] bytes = ("[\"" + username + "\"]").getBytes("UTF-8"); - os.write(bytes); - os.close(); - - InputStream in = new BufferedInputStream(con.getInputStream()); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - for (int length; (length = in.read(buffer)) != -1; ) { - result.write(buffer, 0, length); - } - // StandardCharsets.UTF_8.name() > JDK 7 - String resString = result.toString("UTF-8"); - - System.out.println("Result= " + resString); - UUIDHelper[] helpers = WSClient.gson.fromJson(resString, UUIDHelper[].class); - if(helpers.length == 1) { - return helpers[0].id; - } - - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return UUID.randomUUID().toString(); - } - /* @EventHandler public void init(FMLServerStartingEvent event) diff --git a/src/main/java/de/torui/coflsky/CoflSkyCommand.java b/src/main/java/de/torui/coflsky/CoflSkyCommand.java index 6bb50de..6fc78a1 100644 --- a/src/main/java/de/torui/coflsky/CoflSkyCommand.java +++ b/src/main/java/de/torui/coflsky/CoflSkyCommand.java @@ -30,7 +30,17 @@ public class CoflSkyCommand extends CommandBase { @Override public String getCommandUsage(ICommandSender sender) { - return "/cofl token <token> to register\n/coflsky start to connect\n/coflsky stop to stop"; + return HelpText; + } + + public static final String HelpText = "Available sub-commands:\n" + + "start: starts a new connection\n" + + "stop: stops the connection"; + + @Override + public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { + // TODO Auto-generated method stub + return super.addTabCompletionOptions(sender, args, pos); } @Override @@ -55,18 +65,29 @@ public class CoflSkyCommand extends CommandBase { CallbackCommand(args); break; default: + QueryServerCommands.QueryCommands(); sender.addChatMessage(new ChatComponentText("" + args[0] +"is not a valid subcommand!")); System.out.println(args[0] +"is not a valid subcommand!"); return; } - } + } - /*if(args.length == 2 && args[0].equals("token")) { - //todo: send authorisation message - }*/ + else { + ListHelp(sender); + } } + public void CommandNotRecognized(String[] args, ICommandSender sender) { + sender.addChatMessage(new ChatComponentText(HelpText)); + sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); + } + + public void ListHelp(ICommandSender sender) { + sender.addChatMessage(new ChatComponentText(HelpText)); + sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); + } + public void CallbackCommand(String[] args) { String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); diff --git a/src/main/java/de/torui/coflsky/QueryServerCommands.java b/src/main/java/de/torui/coflsky/QueryServerCommands.java new file mode 100644 index 0000000..4b99783 --- /dev/null +++ b/src/main/java/de/torui/coflsky/QueryServerCommands.java @@ -0,0 +1,104 @@ +package de.torui.coflsky; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import scala.actors.threadpool.Arrays; + +public class QueryServerCommands { + + private static Gson gson = new GsonBuilder().create(); + + public static String QueryCommands() { + + String queryResult = GetRequest("https://sky-commands.coflnet.com/api/mod/commands"); + + if(queryResult != null) { + CommandInfo[] commands = gson.fromJson(queryResult, CommandInfo[].class); + + System.out.println(">>> "+Arrays.toString(commands)); + + StringBuilder sb = new StringBuilder(); + + if(commands.length>0) { + for(CommandInfo cm : commands) { + sb.append(cm + "\n"); + } + } + return sb.toString().trim(); + + } + + return "§4ERROR: Could not connect to command server!"; + } + + private static class CommandInfo { + + public String subCommand; + public String description; + + public CommandInfo() {} + + public CommandInfo(String subCommand, String description) { + super(); + this.subCommand = subCommand; + this.description = description; + } + + @Override + public String toString() { + return subCommand + ": " + description; + } + + + + } + private static String GetRequest(String uri) { + + try { + System.out.println("Get request"); + URL url = new URL(uri); + HttpURLConnection con; + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + //con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("User-Agent", "CoflMod"); + //con.setDoInput(true); + con.setDoInput(true); + + // ... + + /*OutputStream os = con.getOutputStream(); + byte[] bytes = ("[\"" + getUsername() + "\"]").getBytes("UTF-8"); + os.write(bytes); + os.close(); + */ + System.out.println("InputStream"); + InputStream in = new BufferedInputStream(con.getInputStream()); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + for (int length; (length = in.read(buffer)) != -1; ) { + result.write(buffer, 0, length); + } + // StandardCharsets.UTF_8.name() > JDK 7 + String resString = result.toString("UTF-8"); + + System.out.println("Result= " + resString); + return resString; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } +} diff --git a/src/main/java/de/torui/coflsky/minecraft_integration/PlayerDataProvider.java b/src/main/java/de/torui/coflsky/minecraft_integration/PlayerDataProvider.java new file mode 100644 index 0000000..4c3c39b --- /dev/null +++ b/src/main/java/de/torui/coflsky/minecraft_integration/PlayerDataProvider.java @@ -0,0 +1,70 @@ +package de.torui.coflsky.minecraft_integration; + +import java.io.BufferedInputStream; +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.util.UUID; + + +import de.torui.coflsky.websocket.WSClient; +import net.minecraft.client.Minecraft; + +public class PlayerDataProvider { + + private static class UUIDHelper { + public String id; + public String name; + } + + public static String getActivePlayerUUID() { + try { + URL url = new URL("https://api.mojang.com/profiles/minecraft"); + HttpURLConnection con; + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + + con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); + con.setRequestProperty("Accept", "application/json"); + con.setDoInput(true); + con.setDoOutput(true); + + // ... + + OutputStream os = con.getOutputStream(); + byte[] bytes = ("[\"" + getUsername() + "\"]").getBytes("UTF-8"); + os.write(bytes); + os.close(); + + InputStream in = new BufferedInputStream(con.getInputStream()); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + for (int length; (length = in.read(buffer)) != -1; ) { + result.write(buffer, 0, length); + } + // StandardCharsets.UTF_8.name() > JDK 7 + String resString = result.toString("UTF-8"); + + System.out.println("Result= " + resString); + UUIDHelper[] helpers = WSClient.gson.fromJson(resString, UUIDHelper[].class); + if(helpers.length == 1) { + return helpers[0].id; + } + + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return UUID.randomUUID().toString(); + } + + public static String getUsername() { + String username = Minecraft.getSessionInfo().get("X-Minecraft-Username"); + return username; + } + +} diff --git a/src/main/java/de/torui/coflsky/minecraft_integration/TemporarySession.java b/src/main/java/de/torui/coflsky/minecraft_integration/TemporarySession.java new file mode 100644 index 0000000..542bd53 --- /dev/null +++ b/src/main/java/de/torui/coflsky/minecraft_integration/TemporarySession.java @@ -0,0 +1,137 @@ +package de.torui.coflsky.minecraft_integration; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import net.minecraftforge.fml.common.Loader; + +public class TemporarySession { + private static Gson gson = new GsonBuilder() .registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() { + @Override + public void write(JsonWriter out, ZonedDateTime value) throws IOException { + out.value(value.toString()); + } + + @Override + public ZonedDateTime read(JsonReader in) throws IOException { + return ZonedDateTime.parse(in.nextString()); + } + }) + .enableComplexMapKeySerialization().create(); + public static class TempSession { + + public String SessionUUID; + public ZonedDateTime timestampCreated; + public TempSession() {} + public TempSession(String sessionUUID, ZonedDateTime timestampCreated) { + super(); + SessionUUID = sessionUUID; + this.timestampCreated = timestampCreated; + } + + } + + public static void UpdateSessions() throws IOException { + Map<String, TempSession> sessions = GetSessions(); + + for (String username : sessions.keySet()) { + if(!isValidSession(sessions.get(username))) { + DeleteTempSession(username); + } + } + } + + public static Path GetTempFileFolder() { + + Path dataPath = Paths.get(Loader.instance().getConfigDir().getPath(), "CoflSky", "sessions"); + dataPath.toFile().mkdirs(); + + return dataPath; + } + + public static Map<String, TempSession> GetSessions() throws IOException{ + + File[] sessions = GetTempFileFolder().toFile().listFiles(); + + Map<String, TempSession> map = new HashMap<>(); + + for (int i= 0; i<sessions.length;i++) { + map.put(sessions[i].getName(), GetSession(sessions[i].getName())); + } + + return map; + } + + public static boolean isValidSession(TempSession session) { + if(session.timestampCreated.plus(Duration.ofDays(7)).isAfter(ZonedDateTime.now())) { + return true; + } + return false; + } + + private static Path GetUserPath(String username) { + return Paths.get(GetTempFileFolder().toString() + "/" + username); + } + public static void DeleteTempSession(String username) { + Path path =GetUserPath(username); + path.toFile().delete(); + } + + public static TempSession GetSession(String username) throws IOException { + Path path = GetUserPath(username); + File file = path.toFile(); + + if(!file.exists()) { + TempSession session = new TempSession(UUID.randomUUID().toString(), ZonedDateTime.now()); + OverwriteTempSession(username, session); + return session; + } + + BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file))); + String raw = reader.lines().collect(Collectors.joining("\n")); + + reader.close(); + TempSession session = gson.fromJson(raw, TempSession.class); + return session; + } + + public static boolean OverwriteTempSession(String username, TempSession session) throws IOException { + + + Path path = GetUserPath(username); + File file = path.toFile(); + file.createNewFile(); + + String data = gson.toJson(session); + + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); + bw.append(data); + bw.flush(); + bw.close(); + + return true; + } +} |