Search in sources :

Example 1 with User

use of kml.auth.user.User in project Krothium-Launcher by DarkLBP.

the class MainFX method loadTextures.

/**
 * Loads the skin preview for the logged user
 */
private void loadTextures() {
    if (loadingTextures) {
        return;
    }
    selectSkin.setDisable(true);
    selectCape.setDisable(true);
    deleteSkin.setDisable(true);
    deleteCape.setDisable(true);
    includeCape.setDisable(true);
    if (Kernel.USE_LOCAL) {
        return;
    }
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                console.print("Loading textures...");
                loadingTextures = true;
                if (alex == null || steve == null) {
                    // Load placeholder skins
                    alex = new Image("/kml/gui/textures/alex.png");
                    steve = new Image("/kml/gui/textures/steve.png");
                }
                User selected = kernel.getAuthentication().getSelectedUser();
                String domain;
                if (selected.getType() == UserType.MOJANG) {
                    domain = "sessionserver.mojang.com/session/minecraft/profile/";
                    skinActions.setVisible(false);
                    skinActions.setManaged(false);
                } else {
                    domain = "mc.krothium.com/profiles/";
                    skinActions.setVisible(true);
                    skinActions.setManaged(true);
                }
                String profileURL = "https://" + domain + selected.getSelectedProfile() + "?unsigned=true";
                JSONObject root = new JSONObject(Utils.readURL(profileURL));
                JSONArray properties = root.getJSONArray("properties");
                for (int i = 0; i < properties.length(); i++) {
                    JSONObject property = properties.getJSONObject(i);
                    if ("textures".equalsIgnoreCase(property.getString("name"))) {
                        JSONObject data = new JSONObject(Utils.fromBase64(property.getString("value")));
                        JSONObject textures = data.getJSONObject("textures");
                        skin = null;
                        cape = null;
                        boolean slim = false;
                        if (textures.has("SKIN")) {
                            JSONObject skinData = textures.getJSONObject("SKIN");
                            if (skinData.has("metadata")) {
                                if ("slim".equalsIgnoreCase(skinData.getJSONObject("metadata").getString("model"))) {
                                    slim = true;
                                }
                            }
                            InputStream stream = Utils.readCachedStream(textures.getJSONObject("SKIN").getString("url"));
                            skin = new Image(stream);
                            stream.close();
                        }
                        if (skin == null || skin.getHeight() == 0 && !slim) {
                            skin = steve;
                        } else if (skin.getHeight() == 0) {
                            skin = alex;
                        } else {
                            deleteSkin.setDisable(false);
                        }
                        if (textures.has("CAPE")) {
                            InputStream stream = Utils.readCachedStream(textures.getJSONObject("CAPE").getString("url"));
                            cape = new Image(stream);
                            stream.close();
                            includeCape.setDisable(false);
                            deleteCape.setDisable(false);
                        }
                        if (slim) {
                            skinSlim.setSelected(true);
                        } else {
                            skinClassic.setSelected(true);
                        }
                        texturesLoaded = true;
                        console.print("Textures loaded.");
                        MainFX.this.updatePreview();
                    }
                }
                selectSkin.setDisable(false);
                selectCape.setDisable(false);
            } catch (Exception ex) {
                console.print("Failed to parse remote profile textures.");
                ex.printStackTrace(console.getWriter());
            }
            loadingTextures = false;
        }
    });
    t.start();
}
Also used : User(kml.auth.user.User) JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) JSONArray(org.json.JSONArray) Image(javafx.scene.image.Image) AuthenticationException(kml.exceptions.AuthenticationException) DownloaderException(kml.exceptions.DownloaderException) IOException(java.io.IOException) GameLauncherException(kml.exceptions.GameLauncherException)

Example 2 with User

use of kml.auth.user.User in project Krothium-Launcher by DarkLBP.

the class MainFX method refresh.

/**
 * Refreshes user selected from the existing user list
 */
public final void refresh() {
    User selected = existingUsers.getSelectionModel().getSelectedItem();
    Authentication auth = kernel.getAuthentication();
    try {
        auth.setSelectedUser(selected);
        auth.refresh();
        kernel.saveProfiles();
        texturesLoaded = false;
        showLoginPrompt(false);
        fetchAds();
    } catch (AuthenticationException ex) {
        kernel.showAlert(Alert.AlertType.ERROR, Language.get(62), ex.getMessage());
        updateExistingUsers();
    }
}
Also used : User(kml.auth.user.User) AuthenticationException(kml.exceptions.AuthenticationException) Authentication(kml.auth.Authentication)

Example 3 with User

use of kml.auth.user.User in project Krothium-Launcher by DarkLBP.

the class MainFX method refreshSession.

/**
 * Refreshes latest session
 */
private void refreshSession() {
    console.print("Refreshing session...");
    Authentication a = kernel.getAuthentication();
    User u = a.getSelectedUser();
    try {
        if (u != null) {
            a.refresh();
            texturesLoaded = false;
            kernel.saveProfiles();
            console.print("Session refreshed.");
        } else {
            console.print("No user is selected.");
        }
    } catch (AuthenticationException ex) {
        if (u.getType() == UserType.KROTHIUM) {
            authKrothium.setSelected(true);
            username.setText(u.getUsername().replace("krothium://", ""));
        } else {
            authMojang.setSelected(true);
            username.setText(u.getUsername());
        }
        console.print("Couldn't refresh your session.");
    } finally {
        if (a.isAuthenticated()) {
            showLoginPrompt(false);
            fetchAds();
        } else {
            showLoginPrompt(true);
        }
    }
}
Also used : User(kml.auth.user.User) AuthenticationException(kml.exceptions.AuthenticationException) Authentication(kml.auth.Authentication)

Example 4 with User

use of kml.auth.user.User in project Krothium-Launcher by DarkLBP.

the class GameLauncher method launch.

/**
 * Prepares and launcher the game
 * @throws GameLauncherException If an error has been thrown
 */
public final void launch(final MainFX mainFX) throws GameLauncherException {
    console.print("Game launch work has started.");
    Profile p = kernel.getProfiles().getSelectedProfile();
    if (isRunning()) {
        throw new GameLauncherException("Game is already started!");
    }
    Versions versions = kernel.getVersions();
    VersionMeta verID;
    switch(p.getType()) {
        case CUSTOM:
            verID = p.hasVersion() ? p.getVersionID() : versions.getLatestRelease();
            break;
        case RELEASE:
            verID = versions.getLatestRelease();
            break;
        default:
            verID = versions.getLatestSnapshot();
            break;
    }
    if (verID == null) {
        throw new GameLauncherException("Version ID is null.");
    }
    Version ver = versions.getVersion(verID);
    if (ver == null) {
        throw new GameLauncherException("Version info could not be obtained.");
    }
    File workingDir = Kernel.APPLICATION_WORKING_DIR;
    console.print("Deleting old natives.");
    File nativesRoot = new File(workingDir + File.separator + "versions" + File.separator + ver.getID());
    if (nativesRoot.isDirectory()) {
        File[] files = nativesRoot.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory() && f.getName().contains("natives")) {
                    Utils.deleteDirectory(f);
                }
            }
        }
    }
    final File nativesDir = new File(workingDir, "versions" + File.separator + ver.getID() + File.separator + ver.getID() + "-natives-" + System.nanoTime());
    if (!nativesDir.isDirectory()) {
        nativesDir.mkdirs();
    }
    console.print("Launching Minecraft " + ver.getID() + " on " + workingDir.getAbsolutePath());
    console.print("Using natives dir: " + nativesDir);
    console.print("Extracting natives.");
    List<String> gameArgs = new ArrayList<>();
    if (p.hasJavaDir()) {
        gameArgs.add(p.getJavaDir().getAbsolutePath());
    } else {
        gameArgs.add(Utils.getJavaDir());
    }
    if (!p.hasJavaArgs()) {
        if (Utils.getOSArch() == OSArch.OLD) {
            gameArgs.add("-Xmx1G");
        } else {
            gameArgs.add("-Xmx2G");
        }
        gameArgs.add("-Xmn128M");
    } else {
        String javaArgs = p.getJavaArgs();
        String[] args = javaArgs.split(" ");
        Collections.addAll(gameArgs, args);
    }
    gameArgs.add("-Djava.library.path=" + nativesDir.getAbsolutePath());
    gameArgs.add("-cp");
    StringBuilder libraries = new StringBuilder();
    List<Library> libs = ver.getLibraries();
    String separator = System.getProperty("path.separator");
    Authentication a = kernel.getAuthentication();
    User u = a.getSelectedUser();
    if (u.getType() == UserType.KROTHIUM) {
        try {
            File launchPath = new File(GameLauncher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
            libraries.append(launchPath.getAbsolutePath()).append(separator);
        } catch (URISyntaxException ex) {
            console.print("Failed to load GameStarter.");
        }
    }
    for (Library lib : libs) {
        if (!lib.isCompatible()) {
            continue;
        }
        if (lib.isNative()) {
            try {
                File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + lib.getRelativeNativePath());
                FileInputStream input = new FileInputStream(completePath);
                Utils.decompressZIP(input, nativesDir, lib.getExtractExclusions());
            } catch (IOException ex) {
                console.print("Failed to extract native: " + lib.getName());
                ex.printStackTrace(console.getWriter());
            }
        } else {
            File completePath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + lib.getRelativePath());
            libraries.append(completePath.getAbsolutePath()).append(separator);
        }
    }
    console.print("Preparing game args.");
    File verPath = new File(Kernel.APPLICATION_WORKING_DIR + File.separator + ver.getRelativeJar());
    libraries.append(verPath.getAbsolutePath());
    File assetsDir;
    AssetIndex index = ver.getAssetIndex();
    File assetsRoot = new File(workingDir, "assets");
    if ("legacy".equals(index.getID())) {
        assetsDir = new File(assetsRoot, "virtual" + File.separator + "legacy");
        if (!assetsDir.isDirectory()) {
            assetsDir.mkdirs();
        }
        console.print("Building virtual asset folder.");
        File indexJSON = new File(assetsRoot, "indexes" + File.separator + index.getID() + ".json");
        try {
            JSONObject o = new JSONObject(new String(Files.readAllBytes(indexJSON.toPath()), "ISO-8859-1"));
            JSONObject objects = o.getJSONObject("objects");
            Set s = objects.keySet();
            for (Object value : s) {
                String name = value.toString();
                File assetFile = new File(assetsDir, name);
                JSONObject asset = objects.getJSONObject(name);
                String sha = asset.getString("hash");
                if (!Utils.verifyChecksum(assetFile, sha, "SHA-1")) {
                    File objectFile = new File(assetsRoot, "objects" + File.separator + sha.substring(0, 2) + File.separator + sha);
                    if (assetFile.getParentFile() != null) {
                        assetFile.getParentFile().mkdirs();
                    }
                    Files.copy(objectFile.toPath(), assetFile.toPath());
                }
            }
        } catch (Exception ex) {
            console.print("Failed to create virtual asset folder.");
            ex.printStackTrace(console.getWriter());
        }
    } else {
        assetsDir = assetsRoot;
    }
    gameArgs.add(libraries.toString());
    if (u.getType() == UserType.KROTHIUM) {
        gameArgs.add("kml.game.GameStarter");
    }
    gameArgs.add(ver.getMainClass());
    console.print("Full game launcher parameters: ");
    String[] versionArgs = ver.getMinecraftArguments().split(" ");
    for (int i = 0; i < versionArgs.length; i++) {
        if (versionArgs[i].startsWith("$")) {
            switch(versionArgs[i]) {
                case "${auth_player_name}":
                    versionArgs[i] = versionArgs[i].replace("${auth_player_name}", u.getDisplayName());
                    break;
                case "${version_name}":
                    versionArgs[i] = versionArgs[i].replace("${version_name}", ver.getID());
                    break;
                case "${game_directory}":
                    if (p.hasGameDir()) {
                        File gameDir = p.getGameDir();
                        if (!gameDir.isDirectory()) {
                            gameDir.mkdirs();
                        }
                        versionArgs[i] = versionArgs[i].replace("${game_directory}", gameDir.getAbsolutePath());
                    } else {
                        versionArgs[i] = versionArgs[i].replace("${game_directory}", workingDir.getAbsolutePath());
                    }
                    break;
                case "${assets_root}":
                    versionArgs[i] = versionArgs[i].replace("${assets_root}", assetsDir.getAbsolutePath());
                    break;
                case "${game_assets}":
                    versionArgs[i] = versionArgs[i].replace("${game_assets}", assetsDir.getAbsolutePath());
                    break;
                case "${assets_index_name}":
                    versionArgs[i] = versionArgs[i].replace("${assets_index_name}", index.getID());
                    break;
                case "${auth_uuid}":
                    versionArgs[i] = versionArgs[i].replace("${auth_uuid}", u.getSelectedProfile());
                    break;
                case "${auth_access_token}":
                    versionArgs[i] = versionArgs[i].replace("${auth_access_token}", u.getAccessToken());
                    break;
                case "${version_type}":
                    versionArgs[i] = versionArgs[i].replace("${version_type}", ver.getType().name());
                    break;
                case "${user_properties}":
                    versionArgs[i] = versionArgs[i].replace("${user_properties}", "{}");
                    break;
                case "${user_type}":
                    versionArgs[i] = versionArgs[i].replace("${user_type}", "mojang");
                    break;
                case "${auth_session}":
                    versionArgs[i] = versionArgs[i].replace("${auth_session}", "token:" + u.getAccessToken() + ':' + u.getSelectedProfile().replace("-", ""));
                    break;
            }
        }
    }
    Collections.addAll(gameArgs, versionArgs);
    if (p.hasResolution()) {
        gameArgs.add("--width");
        gameArgs.add(String.valueOf(p.getResolutionWidth()));
        gameArgs.add("--height");
        gameArgs.add(String.valueOf(p.getResolutionHeight()));
    }
    for (String arg : gameArgs) {
        console.print(arg);
    }
    ProcessBuilder pb = new ProcessBuilder(gameArgs);
    pb.directory(workingDir);
    try {
        process = pb.start();
        if (kernel.getSettings().getShowGameLog()) {
            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(GameLauncher.this.getClass().getResource("/kml/gui/fxml/Output.fxml"));
                    Parent parent;
                    try {
                        parent = loader.load();
                    } catch (IOException e) {
                        parent = null;
                        console.print("Failed to initialize Output GUI!");
                        e.printStackTrace(console.getWriter());
                    }
                    Stage stage = new Stage();
                    stage.getIcons().add(Kernel.APPLICATION_ICON);
                    stage.setTitle("Krothium Minecraft Launcher - " + Language.get(69));
                    stage.setScene(new Scene(parent));
                    stage.setResizable(true);
                    stage.setMaximized(false);
                    stage.show();
                    output = loader.getController();
                    outputGUI = stage;
                }
            });
        }
        Thread log_info = new Thread(new Runnable() {

            @Override
            public void run() {
                GameLauncher.this.pipeOutput(process.getInputStream());
            }
        });
        log_info.start();
        Thread log_error = new Thread(new Runnable() {

            @Override
            public void run() {
                GameLauncher.this.pipeOutput(process.getErrorStream());
            }
        });
        log_error.start();
        final Timer timer = new Timer();
        TimerTask process_status = new TimerTask() {

            @Override
            public void run() {
                if (!GameLauncher.this.isRunning()) {
                    boolean error;
                    if (GameLauncher.this.process.exitValue() != 0) {
                        error = true;
                        GameLauncher.this.console.print("Game stopped unexpectedly.");
                    } else {
                        error = false;
                    }
                    GameLauncher.this.console.print("Deleteting natives dir.");
                    Utils.deleteDirectory(nativesDir);
                    timer.cancel();
                    timer.purge();
                    mainFX.gameEnded(error);
                }
            }
        };
        timer.schedule(process_status, 0, 25);
    } catch (IOException ex) {
        ex.printStackTrace(console.getWriter());
        throw new GameLauncherException("Game returned an error code.");
    }
}
Also used : User(kml.auth.user.User) Parent(javafx.scene.Parent) URISyntaxException(java.net.URISyntaxException) FXMLLoader(javafx.fxml.FXMLLoader) Profile(kml.game.profile.Profile) Version(kml.game.version.Version) Stage(javafx.stage.Stage) VersionMeta(kml.game.version.VersionMeta) AssetIndex(kml.game.version.asset.AssetIndex) Scene(javafx.scene.Scene) URISyntaxException(java.net.URISyntaxException) GameLauncherException(kml.exceptions.GameLauncherException) Versions(kml.game.version.Versions) JSONObject(org.json.JSONObject) Authentication(kml.auth.Authentication) JSONObject(org.json.JSONObject) GameLauncherException(kml.exceptions.GameLauncherException) Library(kml.game.version.library.Library)

Example 5 with User

use of kml.auth.user.User in project Krothium-Launcher by DarkLBP.

the class Authentication method authenticate.

/**
 * Performs an authenticate request to the server
 * @param username The username
 * @param password The password
 * @throws AuthenticationException If authentication failed
 */
public final void authenticate(String username, String password) throws AuthenticationException {
    JSONObject request = new JSONObject();
    JSONObject agent = new JSONObject();
    UserType type;
    agent.put("name", "Minecraft");
    agent.put("version", 1);
    request.put("agent", agent);
    String tmpUser;
    if (username.startsWith("krothium://")) {
        type = UserType.KROTHIUM;
        tmpUser = username.replace("krothium://", "");
    } else {
        type = UserType.MOJANG;
        tmpUser = username;
    }
    request.put("username", tmpUser);
    request.put("password", password);
    if (clientToken != null) {
        request.put("clientToken", clientToken);
    }
    request.put("requestUser", true);
    Map<String, String> postParams = new HashMap<>();
    postParams.put("Content-Type", "application/json; charset=utf-8");
    postParams.put("Content-Length", String.valueOf(request.toString().length()));
    String response;
    String authURL;
    if (type == UserType.MOJANG) {
        authURL = "https://" + mojangDomain + authenticatePath;
    } else {
        authURL = "https://" + krothiumDomain + authenticatePath;
    }
    try {
        response = Utils.sendPost(authURL, request.toString().getBytes(Charset.forName("UTF-8")), postParams);
    } catch (IOException ex) {
        console.print("Failed to send request to authentication server");
        ex.printStackTrace(console.getWriter());
        throw new AuthenticationException("Failed to send request to authentication server");
    }
    if (response.isEmpty()) {
        throw new AuthenticationException("Authentication server does not respond.");
    }
    JSONObject r;
    try {
        r = new JSONObject(response);
    } catch (JSONException ex) {
        throw new AuthenticationException("Failed to read authentication response.");
    }
    if (!r.has("error")) {
        try {
            String accessToken = r.getString("accessToken");
            String selectedProfile = r.getJSONObject("selectedProfile").getString("id");
            String userID = r.getJSONObject("user").getString("id");
            clientToken = r.getString("clientToken");
            ArrayList<UserProfile> userProfiles = new ArrayList<>();
            JSONArray uprofs = r.getJSONArray("availableProfiles");
            for (int i = 0; i < uprofs.length(); i++) {
                JSONObject prof = uprofs.getJSONObject(i);
                UserProfile up = new UserProfile(prof.getString("id"), prof.getString("name"));
                userProfiles.add(up);
            }
            User u = new User(userID, accessToken, username, type, userProfiles, selectedProfile);
            selectedAccount = u;
            authenticated = true;
            addUser(u);
        } catch (JSONException ex) {
            ex.printStackTrace(console.getWriter());
            throw new AuthenticationException("Authentication server replied wrongly.");
        }
    } else {
        authenticated = false;
        throwError(r);
    }
}
Also used : User(kml.auth.user.User) UserProfile(kml.auth.user.UserProfile) AuthenticationException(kml.exceptions.AuthenticationException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) UserType(kml.auth.user.UserType)

Aggregations

User (kml.auth.user.User)11 JSONObject (org.json.JSONObject)6 Authentication (kml.auth.Authentication)5 AuthenticationException (kml.exceptions.AuthenticationException)5 IOException (java.io.IOException)3 UserProfile (kml.auth.user.UserProfile)3 UserType (kml.auth.user.UserType)2 GameLauncherException (kml.exceptions.GameLauncherException)2 JSONArray (org.json.JSONArray)2 JSONException (org.json.JSONException)2 InputStream (java.io.InputStream)1 URISyntaxException (java.net.URISyntaxException)1 FXMLLoader (javafx.fxml.FXMLLoader)1 Parent (javafx.scene.Parent)1 Scene (javafx.scene.Scene)1 Image (javafx.scene.image.Image)1 Stage (javafx.stage.Stage)1 DownloaderException (kml.exceptions.DownloaderException)1 Profile (kml.game.profile.Profile)1 Version (kml.game.version.Version)1