aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorFlorian Rinke <develop@torui.de>2021-10-11 17:52:17 +0200
committerFlorian Rinke <develop@torui.de>2021-10-11 17:52:17 +0200
commit16b9821f55eec8f4a77ee1743cbc3f9b4ba3e303 (patch)
treec7ede24fb2a7c0871c92c66fe4b4f7806344d326 /src
parent9e923dbdf82b2a1fbebcb9c4559400f921104229 (diff)
downloadCOFL-16b9821f55eec8f4a77ee1743cbc3f9b4ba3e303.tar.gz
COFL-16b9821f55eec8f4a77ee1743cbc3f9b4ba3e303.tar.bz2
COFL-16b9821f55eec8f4a77ee1743cbc3f9b4ba3e303.zip
implements #11, #8
Diffstat (limited to 'src')
-rw-r--r--src/main/java/de/torui/coflsky/CoflSky.java59
-rw-r--r--src/main/java/de/torui/coflsky/CoflSkyCommand.java24
-rw-r--r--src/main/java/de/torui/coflsky/minecraft_integration/CoflSessionManager.java141
-rw-r--r--src/main/java/de/torui/coflsky/websocket/WSClient.java68
-rw-r--r--src/main/java/de/torui/coflsky/websocket/WSClientWrapper.java106
5 files changed, 266 insertions, 132 deletions
diff --git a/src/main/java/de/torui/coflsky/CoflSky.java b/src/main/java/de/torui/coflsky/CoflSky.java
index cc762ca..85d05b6 100644
--- a/src/main/java/de/torui/coflsky/CoflSky.java
+++ b/src/main/java/de/torui/coflsky/CoflSky.java
@@ -1,13 +1,12 @@
package de.torui.coflsky;
-import java.io.IOException;
+
import java.net.URISyntaxException;
-import java.util.UUID;
+
import org.lwjgl.input.Keyboard;
-import de.torui.coflsky.minecraft_integration.PlayerDataProvider;
-import de.torui.coflsky.minecraft_integration.TemporarySession;
+
import de.torui.coflsky.websocket.WSClientWrapper;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.client.ClientCommandHandler;
@@ -27,46 +26,26 @@ public class CoflSky
public static WSClientWrapper Wrapper;
public static KeyBinding[] keyBindings;
-
+
+ public static final String[] webSocketURIPrefix = new String [] {
+ "wss://sky-commands.coflnet.com/modsocket",
+ "wss://sky-mod.coflnet.com/modsocket",
+ "ws://sky-commands.coflnet.com/modsocket",
+ "ws://sky-mod.coflnet.com/modsocket",
+ };
+
+ public static String CommandUri = "https://sky-commands.coflnet.com/api/mod/commands";
@EventHandler
public void init(FMLInitializationEvent event) throws URISyntaxException
{
- 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 = PlayerDataProvider.getUsername();
- String uuid = PlayerDataProvider.getActivePlayerUUID();
- System.out.println(">>> Username= " + username + " with UUID=" + uuid );
-
- String tempUUID = UUID.randomUUID().toString();
- try {
- TemporarySession.UpdateSessions();
- tempUUID = TemporarySession.GetSession(username).SessionUUID;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ System.out.println(">>>Started");
-
- //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 + "&SId=" + tempUUID + "&uuid=" + uuid);
+ CoflSky.Wrapper = new WSClientWrapper(webSocketURIPrefix);
keyBindings = new KeyBinding[] {
- new KeyBinding("key.replay_last.onclick", Keyboard.KEY_R, "SkyCofl")
+ new KeyBinding("key.replay_last.onclick", Keyboard.KEY_R, "SkyCofl"),
};
if(event.getSide() == Side.CLIENT) {
@@ -82,14 +61,6 @@ public class CoflSky
MinecraftForge.EVENT_BUS.register(new EventRegistry());
}
-
- /* @EventHandler
- public void init(FMLServerStartingEvent event)
- {
-
- if(event.getSide() == Side.CLIENT) return;
- //event.registerServerCommand(new CoflSkyCommand());
- }*/
}
\ No newline at end of file
diff --git a/src/main/java/de/torui/coflsky/CoflSkyCommand.java b/src/main/java/de/torui/coflsky/CoflSkyCommand.java
index 0cee4cb..7eacc16 100644
--- a/src/main/java/de/torui/coflsky/CoflSkyCommand.java
+++ b/src/main/java/de/torui/coflsky/CoflSkyCommand.java
@@ -6,6 +6,7 @@ import java.util.List;
import de.torui.coflsky.core.Command;
import de.torui.coflsky.core.CommandType;
import de.torui.coflsky.core.StringCommand;
+import de.torui.coflsky.minecraft_integration.CoflSessionManager;
import de.torui.coflsky.websocket.WSClient;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandBase;
@@ -42,14 +43,8 @@ public class CoflSkyCommand extends CommandBase {
public static final String HelpText = "Available local sub-commands:\n"
+ "start: starts a new connection\n"
+ "stop: stops the connection\n"
+ + "reset: resets all local session information and stops the connection\n"
+ "status: Emits status information\nServer-Only Commands:";
-
- @Override
- public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
- // TODO Auto-generated method stub
- return super.addTabCompletionOptions(sender, args, pos);
- }
-
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
System.out.println(Arrays.toString(args));
@@ -58,7 +53,8 @@ public class CoflSkyCommand extends CommandBase {
switch(args[0]) {
case "start":
//todo: start
- CoflSky.Wrapper.start();
+ sender.addChatMessage(new ChatComponentText("starting connection..."));
+ CoflSky.Wrapper.startConnection();
break;
case "stop":
CoflSky.Wrapper.stop();
@@ -84,6 +80,9 @@ public class CoflSkyCommand extends CommandBase {
case "status":
sender.addChatMessage(new ChatComponentText(StatusMessage()));
break;
+ case "reset":
+ HandleReset();
+ break;
default:
CommandNotRecognized(args, sender);
return;
@@ -96,6 +95,15 @@ public class CoflSkyCommand extends CommandBase {
}
+ private void HandleReset() {
+ CoflSky.Wrapper.stop();
+ Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Stopping Connection to CoflNet"));
+ CoflSessionManager.DeleteAllCoflSessions();
+ Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Deleting CoflNet sessions..."));
+ CoflSky.Wrapper.startConnection();
+ Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Started the Connection to CoflNet"));
+ }
+
public String StatusMessage() {
String vendor = System.getProperty("java.vm.vendor");
diff --git a/src/main/java/de/torui/coflsky/minecraft_integration/CoflSessionManager.java b/src/main/java/de/torui/coflsky/minecraft_integration/CoflSessionManager.java
new file mode 100644
index 0000000..ebff38a
--- /dev/null
+++ b/src/main/java/de/torui/coflsky/minecraft_integration/CoflSessionManager.java
@@ -0,0 +1,141 @@
+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 CoflSessionManager {
+ 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 CoflSession {
+
+ public String SessionUUID;
+ public ZonedDateTime timestampCreated;
+ public CoflSession() {}
+ public CoflSession(String sessionUUID, ZonedDateTime timestampCreated) {
+ super();
+ SessionUUID = sessionUUID;
+ this.timestampCreated = timestampCreated;
+ }
+
+ }
+
+ public static void UpdateCoflSessions() throws IOException {
+ Map<String, CoflSession> sessions = GetCoflSessions();
+
+ for (String username : sessions.keySet()) {
+ if(!isValidSession(sessions.get(username))) {
+ DeleteCoflSession(username);
+ }
+ }
+ }
+
+ public static Path GetTempFileFolder() {
+
+ Path dataPath = Paths.get(Loader.instance().getConfigDir().getPath(), "CoflSky", "sessions");
+ dataPath.toFile().mkdirs();
+
+ return dataPath;
+ }
+
+ public static Map<String, CoflSession> GetCoflSessions() throws IOException{
+
+ File[] sessions = GetTempFileFolder().toFile().listFiles();
+
+ Map<String, CoflSession> map = new HashMap<>();
+
+ for (int i= 0; i<sessions.length;i++) {
+ map.put(sessions[i].getName(), GetCoflSession(sessions[i].getName()));
+ }
+
+ return map;
+ }
+
+ public static boolean isValidSession(CoflSession 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 DeleteCoflSession(String username) {
+ Path path =GetUserPath(username);
+ path.toFile().delete();
+ }
+ public static void DeleteAllCoflSessions() {
+ Path path =GetTempFileFolder();
+ path.toFile().delete();
+ }
+
+ public static CoflSession GetCoflSession(String username) throws IOException {
+ Path path = GetUserPath(username);
+ File file = path.toFile();
+
+ if(!file.exists()) {
+ CoflSession session = new CoflSession(UUID.randomUUID().toString(), ZonedDateTime.now());
+ OverwriteCoflSession(username, session);
+ return session;
+ }
+
+ BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file)));
+ String raw = reader.lines().collect(Collectors.joining("\n"));
+
+ reader.close();
+ CoflSession session = gson.fromJson(raw, CoflSession.class);
+ return session;
+ }
+
+ public static boolean OverwriteCoflSession(String username, CoflSession 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;
+ }
+}
diff --git a/src/main/java/de/torui/coflsky/websocket/WSClient.java b/src/main/java/de/torui/coflsky/websocket/WSClient.java
index c4ad799..3cb2de2 100644
--- a/src/main/java/de/torui/coflsky/websocket/WSClient.java
+++ b/src/main/java/de/torui/coflsky/websocket/WSClient.java
@@ -14,7 +14,7 @@ import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketState;
import net.minecraft.client.Minecraft;
-
+import de.torui.coflsky.CoflSky;
import de.torui.coflsky.WSCommandHandler;
import de.torui.coflsky.core.Command;
import de.torui.coflsky.core.StringCommand;
@@ -38,10 +38,12 @@ public class WSClient extends WebSocketAdapter {
}
public URI uri;
public WebSocket socket;
+ public boolean shouldRun = false;
public WebSocketState currentState = WebSocketState.CLOSED;
public WSClient(URI uri) {
this.uri = uri;
+
}
public void start() throws IOException, WebSocketException, NoSuchAlgorithmException {
@@ -95,6 +97,11 @@ public class WSClient extends WebSocketAdapter {
public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception {
System.out.println("WebSocket Changed state to: " + newState);
currentState = newState;
+
+ if(newState == WebSocketState.CLOSED && shouldRun) {
+ CoflSky.Wrapper.restartWebsocketConnection();
+ }
+
super.onStateChanged(websocket, newState);
}
@@ -124,61 +131,4 @@ public class WSClient extends WebSocketAdapter {
-}
-
-/*
-public class WSClient extends WebSocketClient{
-
- public static Gson gson;
-
- public static WSClient Instancce;
-
-
- static {
- gson = new GsonBuilder()/*.setFieldNamingStrategy(new FieldNamingStrategy() {
- @Override
- public String translateName(Field f) {
-
- String name = f.getName();
- char firstChar = name.charAt(0);
- return Character.toLowerCase(firstChar) + name.substring(1);
- }
- })*.create();
- }
-
- public WSClient(URI serverUri) {
- super(serverUri);
-
- }
-
- @Override
- public void onOpen(ServerHandshake handshakedata) {
-
- }
-
- @Override
- public void onMessage(String message) {
- //System.out.println(message);
-
- Command cmd = gson.fromJson(message, Command.class);
- //System.out.println(cmd);
- WSCommandHandler.HandleCommand(cmd, Minecraft.getMinecraft().thePlayer);
- }
-
- @Override
- public void onClose(int code, String reason, boolean remote) {
- System.out.printf("code: %n reason:%s remote:%b", code, reason,remote);
- }
-
- @Override
- public void onError(Exception ex) {
- ex.printStackTrace();
- }
-
- public void SendCommand(Command command) {
- String json = gson.toJson(command);
- this.send(json);
- }
-
-}
-*/
+} \ No newline at end of file
diff --git a/src/main/java/de/torui/coflsky/websocket/WSClientWrapper.java b/src/main/java/de/torui/coflsky/websocket/WSClientWrapper.java
index 2cdfda1..7d66600 100644
--- a/src/main/java/de/torui/coflsky/websocket/WSClientWrapper.java
+++ b/src/main/java/de/torui/coflsky/websocket/WSClientWrapper.java
@@ -11,33 +11,100 @@ import com.neovisionaries.ws.client.WebSocketException;
import de.torui.coflsky.CoflSky;
import de.torui.coflsky.core.Command;
import de.torui.coflsky.core.StringCommand;
+import de.torui.coflsky.minecraft_integration.PlayerDataProvider;
+import de.torui.coflsky.minecraft_integration.CoflSessionManager;
public class WSClientWrapper {
public WSClient socket;
- public Thread thread;
+ // public Thread thread;
public boolean isRunning;
- public String uri = "";
- public WSClientWrapper(String uri) {
- this.uri = uri;
+ private String[] uris;
+
+
+ public WSClientWrapper(String[] uris) {
+ this.uris = uris;
+ }
+
+ public void restartWebsocketConnection() {
+ socket.socket.clearListeners();
+ socket.stop();
+
+ System.out.println("Sleeping...");
+
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ socket = new WSClient(socket.uri);
+ isRunning = false;
+ start();
}
- public synchronized void start() {
+
+ public boolean startConnection() {
+
+ if(isRunning)
+ return false;
+
+ for(String s : uris) {
+
+ System.out.println("Trying connection with uri=" + s);
+
+ if(initializeNewSocket(s)) {
+ return true;
+ }
+ }
+
+ throw new Error("Could not connect to any websocket remote!");
+ }
+
+
+
+ private boolean initializeNewSocket(String uriPrefix) {
+
+
+ String uri = uriPrefix;
+ uri += "?version=" + CoflSky.VERSION;
+
+ String username = PlayerDataProvider.getUsername();
+ uri += "&player=" + username;
+
+ //Generate a CoflSession
+
+ try {
+ CoflSessionManager.UpdateCoflSessions();
+ String coflSessionID = CoflSessionManager.GetCoflSession(username).SessionUUID;
+
+ uri += "&SId=" + coflSessionID;
+
+ socket = new WSClient(URI.create(uri));
+
+ boolean successfull = start();
+ if(successfull) {
+ socket.shouldRun = true;
+ }
+ return successfull;
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+
+ return false;
+
+ }
+
+ private synchronized boolean start() {
if(!isRunning) {
try {
- socket = new WSClient(new URI(uri));
- } catch (URISyntaxException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- /*thread = new Thread(socket);
- thread.start();
- isRunning=true;*/
- isRunning = true;
- try {
socket.start();
+ isRunning = true;
+
+ return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -48,17 +115,14 @@ public class WSClientWrapper {
// TODO Auto-generated catch block
e.printStackTrace();
}
+ return false;
}
+ return false;
}
public synchronized void stop() {
if(isRunning) {
- /* try {
- //socket.closeBlocking();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }*/
+ socket.shouldRun = false;
socket.stop();
isRunning = false;
socket = null;