Search in sources :

Example 1 with SimplePostRequest

use of io.xol.chunkstories.net.http.SimplePostRequest in project chunkstories by Hugobros3.

the class LoginPrompt method connect.

private void connect() {
    if (usernameForm.getText().equals("OFFLINE")) {
        Client.offline = true;
        Client.username = "OfflineUser" + (int) (Math.random() * 1000);
        gameWindow.setLayer(new MainMenu(gameWindow, parentLayer));
    } else {
        logging_in = true;
        RequestResultAction postAction = (result) -> {
            gameWindow.getClient().logger().debug("Received login answer");
            logging_in = false;
            if (result == null) {
                failed_login = true;
                message = "Can't connect to server.";
                return;
            }
            if (result.startsWith("ok")) {
                String session = result.split(":")[1];
                Client.username = usernameForm.getText();
                Client.session_key = session;
                Client.getInstance().getConfiguration().getOption("client.login.auto").trySetting("ok");
                Client.getInstance().getConfiguration().getOption("client.login.username").trySetting(usernameForm.getText());
                Client.getInstance().getConfiguration().getOption("client.login.password").trySetting(passwordForm.getText());
                if (Client.username.equals("Gobrosse") || Client.username.equals("kektest")) {
                    ClientLimitations.isDebugAllowed = true;
                }
                // If the user didn't opt-out, look for crash files and upload those
                if (Client.getInstance().getConfiguration().getStringOption("client.game.log-policy").equals("send")) {
                    JavaCrashesUploader t = new JavaCrashesUploader(Client.getInstance());
                    t.start();
                }
                can_next = true;
            } else if (result.startsWith("ko")) {
                failed_login = true;
                String reason = result.split(":")[1];
                if (reason.equals("notpremium"))
                    message = ("User is not premium");
                else if (reason.equals("invalidcredentials"))
                    message = ("Invalid credentials");
            } else {
                message = ("Unknown error");
            }
        };
        new SimplePostRequest("https://chunkstories.xyz/api/login.php", "user=" + usernameForm.getText() + "&pass=" + passwordForm.getText(), postAction);
    }
}
Also used : RequestResultAction(io.xol.chunkstories.net.http.RequestResultAction) JavaCrashesUploader(io.xol.chunkstories.bugsreporter.JavaCrashesUploader) LanguageSelectionScreen(io.xol.chunkstories.gui.layer.config.LanguageSelectionScreen) ObjectRenderer(io.xol.chunkstories.renderer.opengl.util.ObjectRenderer) Layer(io.xol.chunkstories.api.gui.Layer) ClientLimitations(io.xol.chunkstories.client.ClientLimitations) RenderingInterface(io.xol.chunkstories.api.rendering.RenderingInterface) SimplePostRequest(io.xol.chunkstories.net.http.SimplePostRequest) BaseButton(io.xol.chunkstories.api.gui.elements.BaseButton) GuiElement(io.xol.chunkstories.api.gui.GuiElement) InputText(io.xol.chunkstories.api.gui.elements.InputText) Client(io.xol.chunkstories.client.Client) Input(io.xol.chunkstories.api.input.Input) GameWindow(io.xol.chunkstories.api.rendering.GameWindow) FocusableGuiElement(io.xol.chunkstories.api.gui.FocusableGuiElement) Vector4f(org.joml.Vector4f) RequestResultAction(io.xol.chunkstories.net.http.RequestResultAction) SimplePostRequest(io.xol.chunkstories.net.http.SimplePostRequest) JavaCrashesUploader(io.xol.chunkstories.bugsreporter.JavaCrashesUploader)

Example 2 with SimplePostRequest

use of io.xol.chunkstories.net.http.SimplePostRequest in project chunkstories by Hugobros3.

the class ConnectionSequence method run.

@Override
public void run() {
    logger.info("Connection sequence initialized.");
    try {
        if (!connection.connect())
            abort("Failed to establish connection");
        if (Client.offline) {
            connection.sendTextMessage("login/start");
            connection.sendTextMessage("login/username:" + Client.username);
            connection.sendTextMessage("login/logintoken:nopenopenopenopenope");
            connection.sendTextMessage("login/version:" + VersionInfo.networkProtocolVersion);
            connection.sendTextMessage("login/confirm");
            status = new ConnectionStep("Offline-mode enabled, skipping login token phase");
        } else {
            status = new ConnectionStep("Requesting a login token...");
            SimplePostRequest spr = new SimplePostRequest("https://chunkstories.xyz/api/serverTokenObtainer.php", "username=" + Client.username + "&sessid=" + Client.session_key);
            String reply = spr.result();
            if (reply != null && reply.startsWith("ok")) {
                String loginToken = reply.split(":")[1];
                connection.sendTextMessage("login/start");
                connection.sendTextMessage("login/username:" + Client.username);
                connection.sendTextMessage("login/logintoken:" + loginToken);
                connection.sendTextMessage("login/version:" + VersionInfo.networkProtocolVersion);
                connection.sendTextMessage("login/confirm");
                status = new ConnectionStep("Token obtained, logging in...");
            } else {
                abort("Failed to obtain a login token from the servers");
            }
        }
        if (!authSemaphore.tryAcquire(5, TimeUnit.SECONDS))
            abort("Server login timed out");
        // Obtain the mods list, check if we have them enabled
        this.status = new ConnectionStep("Asking server required mods...");
        connection.sendTextMessage("mods");
        if (!modsSemaphore.tryAcquire(5, TimeUnit.SECONDS))
            abort("Failed to obtain mods list from server");
        Set<String> requiredMd5s = new HashSet<String>();
        for (String requiredMod : modsString.split(";")) {
            if (!requiredMod.contains(":"))
                continue;
            String[] properties = requiredMod.split(":");
            if (properties.length < 3)
                continue;
            String modInternalName = properties[0];
            String modMd5Hash = properties[1];
            long modSizeInBytes = Long.parseLong(properties[2]);
            // String md5Required = requiredMod.contains(":") ? requiredMod.split(":")[0] : requiredMod;
            Client.getInstance().logger().info("Server asks for mod " + modInternalName + " (" + modSizeInBytes + " bytes), md5=" + modMd5Hash);
            requiredMd5s.add(modMd5Hash);
            File cached = new File(GameDirectory.getGameFolderPath() + "/servermods/" + modMd5Hash + ".zip");
            if (!cached.exists()) {
                // Sequentially download all the mods from the server
                status = connection.obtainModFile(modMd5Hash, cached);
                status.waitForEnd();
            }
            // Check their size and signature
            if (cached.length() != modSizeInBytes) {
                Client.getInstance().logger().info("Invalid filesize for downloaded mod " + modInternalName + " (hash: " + modMd5Hash + ")" + " expected filesize = " + modSizeInBytes + " != actual filesize = " + cached.length());
                // Delete suspicious file
                cached.delete();
                abort("Failed to download " + modInternalName + ", wrong file size. You can try again.");
            }
            // Test if the mod loads
            ModZip testHash = null;
            try {
                testHash = new ModZip(cached);
            } catch (ModLoadFailureException e) {
                e.printStackTrace();
                Client.getInstance().logger().info("Could not load downloaded mod " + modInternalName + " (hash: " + modMd5Hash + "), see stack trace");
                // Delete suspicious file
                cached.delete();
                abort("Failed to load " + modInternalName + ", check error log.");
            }
            // Test the md5 hash wasn't tampered with
            String actualMd5Hash = testHash.getMD5Hash();
            if (!actualMd5Hash.equals(modMd5Hash)) {
                Client.getInstance().logger().info("Invalid md5 hash for mod " + modInternalName + " expected md5 hash = " + modMd5Hash + " != actual md5 hash = " + actualMd5Hash);
                // Delete suspicious file
                cached.delete();
                abort("Mod " + modInternalName + " hash did not match.");
            }
        }
        // Build the string to pass to the modsManager as to ask it to enable said mods
        String[] requiredMods = new String[requiredMd5s.size()];
        int i = 0;
        for (String m : requiredMd5s) {
            requiredMods[i++] = "md5:" + m;
        }
        Client.getInstance().getContent().modsManager().setEnabledMods(requiredMods);
        status = new ConnectionStep("Reloading mods...");
        Client.getInstance().reloadAssets();
        status = new ConnectionStep("Loading ContentTranslator...");
        connection.sendTextMessage("world/translator");
        if (!translatorSemaphore.tryAcquire(5, TimeUnit.SECONDS))
            abort("Timed out waiting for content translator");
        // Ask the server world info and if allowed where to spawn and preload chunks
        connection.sendTextMessage("world/enter");
        if (!worldSemaphore.tryAcquire(15, TimeUnit.SECONDS))
            abort("Timed out waiting for world");
        status = new ConnectionStep("Loading world...");
        // TODO
        synchronized (this) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // We are good.
        isDone = true;
    } catch (AbortException e) {
        logger.info("Connection sequence aborted.");
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
}
Also used : SimplePostRequest(io.xol.chunkstories.net.http.SimplePostRequest) ModZip(io.xol.chunkstories.content.mods.ModZip) ModLoadFailureException(io.xol.chunkstories.api.exceptions.content.mods.ModLoadFailureException) File(java.io.File) HashSet(java.util.HashSet)

Aggregations

SimplePostRequest (io.xol.chunkstories.net.http.SimplePostRequest)2 ModLoadFailureException (io.xol.chunkstories.api.exceptions.content.mods.ModLoadFailureException)1 FocusableGuiElement (io.xol.chunkstories.api.gui.FocusableGuiElement)1 GuiElement (io.xol.chunkstories.api.gui.GuiElement)1 Layer (io.xol.chunkstories.api.gui.Layer)1 BaseButton (io.xol.chunkstories.api.gui.elements.BaseButton)1 InputText (io.xol.chunkstories.api.gui.elements.InputText)1 Input (io.xol.chunkstories.api.input.Input)1 GameWindow (io.xol.chunkstories.api.rendering.GameWindow)1 RenderingInterface (io.xol.chunkstories.api.rendering.RenderingInterface)1 JavaCrashesUploader (io.xol.chunkstories.bugsreporter.JavaCrashesUploader)1 Client (io.xol.chunkstories.client.Client)1 ClientLimitations (io.xol.chunkstories.client.ClientLimitations)1 ModZip (io.xol.chunkstories.content.mods.ModZip)1 LanguageSelectionScreen (io.xol.chunkstories.gui.layer.config.LanguageSelectionScreen)1 RequestResultAction (io.xol.chunkstories.net.http.RequestResultAction)1 ObjectRenderer (io.xol.chunkstories.renderer.opengl.util.ObjectRenderer)1 File (java.io.File)1 HashSet (java.util.HashSet)1 Vector4f (org.joml.Vector4f)1