Search in sources :

Example 1 with WithDumpException

use of com.github.mob41.osumer.debug.WithDumpException in project osumer by mob41.

the class PreferencesController method initialize.

@Override
public void initialize(URL location, ResourceBundle resources) {
    saveBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            save();
            Stage stage = (Stage) saveBtn.getScene().getWindow();
            stage.close();
        }
    });
    applyBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            save();
        }
    });
    cancelBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Stage stage = (Stage) cancelBtn.getScene().getWindow();
            stage.close();
        }
    });
    startOsuWithOverlayBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            try {
                d.startOsuWithOverlay();
                if (autoCloseOsumerAfterOverlayCheckbox.isSelected()) {
                    Platform.exit();
                    System.exit(0);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
                Alert alert = new Alert(AlertType.ERROR, "Could not call daemon to start osu!:\n" + e.getMessage(), ButtonType.OK);
                alert.showAndWait();
            }
        }
    });
    toneBeforeDwnSelectBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Stage stage = (Stage) toneBeforeDwnSelectBtn.getScene().getWindow();
            FileChooser fileChooser = new FileChooser();
            File sf = fileChooser.showOpenDialog(stage);
            if (sf != null) {
                if (sf.exists() && sf.isFile()) {
                    toneBeforeDwnText.setText(sf.getAbsolutePath());
                } else {
                    Alert alert = new Alert(AlertType.ERROR, "You must select a file that exists.", ButtonType.OK);
                    alert.showAndWait();
                }
            }
        }
    });
    toneAfterDwnSelectBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Stage stage = (Stage) toneAfterDwnSelectBtn.getScene().getWindow();
            FileChooser fileChooser = new FileChooser();
            File sf = fileChooser.showOpenDialog(stage);
            if (sf != null) {
                if (sf.exists() && sf.isFile()) {
                    toneAfterDwnText.setText(sf.getAbsolutePath());
                } else {
                    Alert alert = new Alert(AlertType.ERROR, "You must select a file that exists.", ButtonType.OK);
                    alert.showAndWait();
                }
            }
        }
    });
    dwnFolderSelectBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Stage stage = (Stage) dwnFolderSelectBtn.getScene().getWindow();
            DirectoryChooser chooser = new DirectoryChooser();
            File file = new File(importFolderText.getText());
            if (file.exists() && file.isDirectory()) {
                chooser.setInitialDirectory(file);
            }
            File sf = chooser.showDialog(stage);
            if (sf != null) {
                if (sf.exists() && sf.isDirectory()) {
                    importFolderText.setText(sf.getAbsolutePath());
                } else {
                    Alert alert = new Alert(AlertType.ERROR, "You must select a folder that exists.", ButtonType.OK);
                    alert.showAndWait();
                }
            }
        }
    });
    addCredentialsBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            FXMLLoader loader0 = new FXMLLoader();
            loader0.setLocation(AppMain.class.getResource("/view/LoginDialogLayout.fxml"));
            DialogPane loginPane = null;
            try {
                loginPane = (DialogPane) loader0.load();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            LoginDialogController loginController = loader0.getController();
            Alert loginDialog = new Alert(AlertType.NONE);
            loginDialog.initStyle(StageStyle.UTILITY);
            loginDialog.initModality(Modality.APPLICATION_MODAL);
            loginDialog.setTitle("");
            loginDialog.setDialogPane(loginPane);
            loginDialog.getButtonTypes().add(ButtonType.OK);
            loginDialog.getButtonTypes().add(ButtonType.CANCEL);
            FXMLLoader loader1 = new FXMLLoader();
            loader1.setLocation(AppMain.class.getResource("/view/ProgressDialogLayout.fxml"));
            DialogPane progressPane = null;
            try {
                progressPane = (DialogPane) loader1.load();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            ProgressDialogController progressController = loader1.getController();
            progressController.getHeaderText().setText("Login");
            progressController.getStatusText().setText("Status: Logging in...");
            progressController.getProgressBar().setProgress(-1);
            Alert progressDialog = new Alert(AlertType.NONE);
            progressDialog.initStyle(StageStyle.UTILITY);
            progressDialog.initModality(Modality.APPLICATION_MODAL);
            progressDialog.setTitle("");
            progressDialog.setDialogPane(progressPane);
            progressDialog.getButtonTypes().add(ButtonType.CANCEL);
            loginDialog.showAndWait();
            if (loginDialog.getResult() == ButtonType.OK) {
                final String usr = loginController.getUser();
                final String pwd = loginController.getPwd();
                if (usr == null || pwd == null || usr.isEmpty() || pwd.isEmpty()) {
                    Alert alert = new Alert(AlertType.WARNING, "Username or password must not be empty.", ButtonType.OK);
                    alert.showAndWait();
                    return;
                }
                Thread thread = new Thread() {

                    public void run() {
                        // TODO Allow the use of new parser
                        Osums osums = new OsumsOldParser();
                        // Osums osums = config.isUseOldParser() ? new OsumsOldParser() : new OsumsNewParser();
                        boolean err = false;
                        try {
                            osums.login(usr, pwd);
                        } catch (WithDumpException e1) {
                            err = true;
                        }
                        Platform.runLater(new Runnable() {

                            @Override
                            public void run() {
                                progressDialog.close();
                            }
                        });
                        if (err) {
                            Platform.runLater(new Runnable() {

                                @Override
                                public void run() {
                                    Alert alert = new Alert(AlertType.WARNING, "", ButtonType.YES);
                                    alert.setTitle("Attempting to login");
                                    alert.setHeaderText("Login Failed");
                                    alert.setContentText("Cannot login into this osu! account.\nDo you still want to save it?");
                                    alert.getButtonTypes().add(ButtonType.NO);
                                    alert.showAndWait();
                                    if (alert.getResult() == ButtonType.YES) {
                                        updateLoginUi(config, loginController);
                                    }
                                }
                            });
                        } else {
                            Platform.runLater(new Runnable() {

                                @Override
                                public void run() {
                                    updateLoginUi(config, loginController);
                                }
                            });
                        }
                    }
                };
                progressDialog.show();
                thread.start();
            }
        }
    });
    removeCredentialsBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Alert alert = new Alert(AlertType.WARNING, "Are you sure to remove your credentials?", ButtonType.YES);
            alert.getButtonTypes().add(ButtonType.NO);
            alert.setHeaderText("Removing Credentials");
            alert.showAndWait();
            if (alert.getResult() == ButtonType.YES) {
                config.setUser("");
                config.setPass("");
                credentialsStatus.setText(CRED_STATUS_NOT_EXIST);
            }
        }
    });
    NumberFormat format = NumberFormat.getIntegerInstance();
    UnaryOperator<TextFormatter.Change> filter = c -> {
        if (c.isContentChange()) {
            ParsePosition parsePosition = new ParsePosition(0);
            // NumberFormat evaluates the beginning of the text
            format.parse(c.getControlNewText(), parsePosition);
            if (parsePosition.getIndex() == 0 || parsePosition.getIndex() < c.getControlNewText().length()) {
                // reject parsing the complete text failed
                return null;
            }
        }
        return c;
    };
    TextFormatter<Integer> numFormatter0 = new TextFormatter<Integer>(new IntegerStringConverter(), 0, filter);
    TextFormatter<Integer> numFormatter1 = new TextFormatter<Integer>(new IntegerStringConverter(), 0, filter);
    SpinnerValueFactory<Integer> valueFactory0 = new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 16, 0);
    SpinnerValueFactory<Integer> valueFactory1 = new SpinnerValueFactory.IntegerSpinnerValueFactory(50, 30000, 0);
    simRunningQueues.setValueFactory(valueFactory0);
    nextQueueCheckDelay.setValueFactory(valueFactory1);
    simRunningQueues.getEditor().setTextFormatter(numFormatter0);
    nextQueueCheckDelay.getEditor().setTextFormatter(numFormatter1);
}
Also used : EventHandler(javafx.event.EventHandler) Button(javafx.scene.control.Button) StageStyle(javafx.stage.StageStyle) Initializable(javafx.fxml.Initializable) IntegerStringConverter(javafx.util.converter.IntegerStringConverter) Osums(com.github.mob41.osums.Osums) URL(java.net.URL) ButtonType(javafx.scene.control.ButtonType) ParsePosition(java.text.ParsePosition) UnaryOperator(java.util.function.UnaryOperator) OsumsNewParser(com.github.mob41.osums.OsumsNewParser) TextFormatter(javafx.scene.control.TextFormatter) NumberFormat(java.text.NumberFormat) Base64(org.apache.commons.codec.binary.Base64) OsumsOldParser(com.github.mob41.osums.OsumsOldParser) ResourceBundle(java.util.ResourceBundle) AlertType(javafx.scene.control.Alert.AlertType) ComboBox(javafx.scene.control.ComboBox) Installer(com.github.mob41.osumer.installer.Installer) FXMLLoader(javafx.fxml.FXMLLoader) Configuration(com.github.mob41.osumer.Configuration) DirectoryChooser(javafx.stage.DirectoryChooser) Alert(javafx.scene.control.Alert) TextField(javafx.scene.control.TextField) Modality(javafx.stage.Modality) Label(javafx.scene.control.Label) IDaemon(com.github.mob41.osumer.rmi.IDaemon) CheckBox(javafx.scene.control.CheckBox) IOException(java.io.IOException) Spinner(javafx.scene.control.Spinner) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) RemoteException(java.rmi.RemoteException) Platform(javafx.application.Platform) FXML(javafx.fxml.FXML) FileChooser(javafx.stage.FileChooser) List(java.util.List) ActionEvent(javafx.event.ActionEvent) DialogPane(javafx.scene.control.DialogPane) WithDumpException(com.github.mob41.osumer.debug.WithDumpException) Stage(javafx.stage.Stage) RadioButton(javafx.scene.control.RadioButton) SpinnerValueFactory(javafx.scene.control.SpinnerValueFactory) TextFormatter(javafx.scene.control.TextFormatter) ActionEvent(javafx.event.ActionEvent) IntegerStringConverter(javafx.util.converter.IntegerStringConverter) FXMLLoader(javafx.fxml.FXMLLoader) FileChooser(javafx.stage.FileChooser) Osums(com.github.mob41.osums.Osums) Stage(javafx.stage.Stage) ParsePosition(java.text.ParsePosition) WithDumpException(com.github.mob41.osumer.debug.WithDumpException) IOException(java.io.IOException) DialogPane(javafx.scene.control.DialogPane) OsumsOldParser(com.github.mob41.osums.OsumsOldParser) Alert(javafx.scene.control.Alert) RemoteException(java.rmi.RemoteException) File(java.io.File) DirectoryChooser(javafx.stage.DirectoryChooser) NumberFormat(java.text.NumberFormat)

Example 2 with WithDumpException

use of com.github.mob41.osumer.debug.WithDumpException in project osumer by mob41.

the class OsumsOldParser method parseStarfield.

private static float parseStarfield(String debugElementName, Element el) throws WithDumpException {
    Element el_a = el.select("div.starfield").first();
    if (el_a == null) {
        throw new WithDumpException(el.html(), "Select \"div.starfield\" from el and assign to el_a", "Validate el_a is null or not", "Get style total width", "No " + debugElementName + " (starfield) related data. Page broke?", false);
    }
    String styleStr = el_a.attr("style");
    // TODO Do PX validation
    int indexPx = styleStr.indexOf("px");
    float totalWidth = -1;
    try {
        totalWidth = Float.parseFloat(styleStr.substring(6, indexPx));
    } catch (NumberFormatException e) {
        throw new WithDumpException(el.html(), "Validate el_a is null or no", "Get style total width", "Select \"div.active\" from el_a and assign to el_a", "Invalid float value: " + styleStr, false, e);
    }
    el_a = el_a.select("div.active").first();
    if (el_a == null) {
        throw new WithDumpException(el.html(), "Select \"div.active\" from el_a and assign to el_a", "Validate el_a is null or not", "Get style width of starfield active", "No " + debugElementName + " active (starfield active) related data. Page broke?", false);
    }
    styleStr = el_a.attr("style");
    indexPx = styleStr.indexOf("px");
    float activeWidth = -1;
    try {
        activeWidth = Float.parseFloat(styleStr.substring(6, indexPx));
    } catch (NumberFormatException e) {
        throw new WithDumpException(el.html(), "Validate el_a is null or no", "Get style active width", "Calculate " + debugElementName, "Invalid float value: " + styleStr, false, e);
    }
    System.out.println(debugElementName + ": " + activeWidth / totalWidth * 10);
    return activeWidth / totalWidth * 10;
}
Also used : WithDumpException(com.github.mob41.osumer.debug.WithDumpException) Element(org.jsoup.nodes.Element)

Example 3 with WithDumpException

use of com.github.mob41.osumer.debug.WithDumpException in project osumer by mob41.

the class OsumsOldParser method login.

@Override
public int login(String username, String password) throws WithDumpException {
    if (loggedIn) {
        return ALREADY_LOGGED_IN;
    }
    try {
        String urlPara = "login=Login&" + "username=" + username + // Username
        "&" + "password=" + password + // Password
        "&" + "autologin=" + true + // Log me on automatically each
        "&" + // visit
        "viewonline=" + true + // Hide my online this session
        "&" + "redirect=" + "index.php" + // Redirect (To check
        "&" + // success)
        "sid=";
        // Session ID, not distributed once
        byte[] postData = urlPara.getBytes(StandardCharsets.UTF_8);
        int postLen = postData.length;
        URL url = new URL(LOGIN_URL);
        HttpURLConnection conn = prepareUrlConnectionPost(url);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postLen));
        conn.setRequestProperty("Origin", "https://old.ppy.sh");
        conn.setRequestProperty("Referer", "https://old.ppy.sh");
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(dos, "UTF-8"));
        wr.write(urlPara);
        wr.close();
        Map<String, List<String>> headerFields = conn.getHeaderFields();
        List<String> locationHeader = headerFields.get("Location");
        if (locationHeader == null || locationHeader.size() != 1 || !locationHeader.get(0).startsWith(INDEX_LOCATION_URL)) {
            throw new WithDumpException("", "Get \"Location\" from headerFields and assign to locationHeader", "Validate locationHeader is not null or locationHeader.size() is 1 or locationHeader.get(0) is equal to INDEX_LOCATION_URL", "Get \"Set-Cookie\" from headerFields and assign to cookiesHeader", "Login failed. Redirected to a non-index page.", true);
        }
        retrieveCookies(headerFields);
        loggedIn = true;
        return SUCCESS;
    } catch (Exception e) {
        throw new WithDumpException("", "(Try&catch try) Logging in", "Throw debuggable exception on catch", "(End of function)", "Error occurred when logging in", true, e);
    }
}
Also used : WithDumpException(com.github.mob41.osumer.debug.WithDumpException) DataOutputStream(java.io.DataOutputStream) URL(java.net.URL) IOException(java.io.IOException) WithDumpException(com.github.mob41.osumer.debug.WithDumpException) BufferedWriter(java.io.BufferedWriter) HttpURLConnection(java.net.HttpURLConnection) OutputStreamWriter(java.io.OutputStreamWriter) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with WithDumpException

use of com.github.mob41.osumer.debug.WithDumpException in project osumer by mob41.

the class OsumsOldParser method parseSearch.

@Override
public SongResult[] parseSearch(String category, Document doc) throws WithDumpException {
    List<SongResult> maps = new ArrayList<SongResult>();
    Element beatmapsDiv = doc.select("div.beatmapListing").first();
    Iterator<Element> it = beatmapsDiv.children().iterator();
    while (it.hasNext()) {
        Element el = it.next();
        Element artistEl = el.select("div.maintext span.artist").first();
        if (artistEl == null) {
            continue;
        }
        String artist = artistEl.html();
        if (artist.isEmpty()) {
            continue;
        }
        Element titleEl = el.select("div.maintext a.title").first();
        if (titleEl == null) {
            continue;
        }
        String title = titleEl.html();
        if (title.isEmpty()) {
            continue;
        }
        Element creatorEl = el.select("div.left-aligned div a").first();
        if (creatorEl == null) {
            continue;
        }
        String creator = creatorEl.html();
        if (creator.isEmpty()) {
            continue;
        }
        int id = -1;
        try {
            id = Integer.parseInt(el.attr("id"));
        } catch (NumberFormatException e) {
            continue;
        }
        List<String> tagsList = new ArrayList<String>(30);
        Element tagsEl = el.select("div.right-aligned div.tags").first();
        if (tagsEl == null) {
            continue;
        }
        Iterator<Element> tagsChildIt = tagsEl.children().iterator();
        while (tagsChildIt.hasNext()) {
            Element childIt = tagsChildIt.next();
            tagsList.add(childIt.html());
        }
        // TODO: Implement Hearts and Plays readings
        String[] tags = new String[tagsList.size()];
        for (int j = 0; j < tags.length; j++) {
            tags[j] = tagsList.get(j);
        }
        Element thumbEl = el.select("div.bmlistt").first();
        String styleStr = thumbEl.attr("style");
        // 17
        int startingIndex = styleStr.indexOf("background: url(\"");
        // 4
        int endingIndex = styleStr.indexOf("\")");
        if (startingIndex == -1 || endingIndex == -1) {
            System.out.println(styleStr);
            return null;
        }
        maps.add(new SongResult(id, category, artist, title, creator, tags, -1, -1));
    }
    SongResult[] out = new SongResult[maps.size()];
    for (int i = 0; i < out.length; i++) {
        out[i] = maps.get(i);
    }
    return out;
}
Also used : SongResult(com.github.mob41.osums.search.SongResult) Element(org.jsoup.nodes.Element) ArrayList(java.util.ArrayList)

Example 5 with WithDumpException

use of com.github.mob41.osumer.debug.WithDumpException in project osumer by mob41.

the class OsumsOldParser method parseSong.

@Override
public OsuSong parseSong(String originalUrl, Document doc) throws WithDumpException {
    boolean pageBeatmap = originalUrl.contains("/b/");
    Elements dwnLinks = doc.getElementsByClass("beatmap_download_link");
    if (dwnLinks.size() == 0) {
        throw new WithDumpException("", "Get elements by class \"beatmap_download_link\"", "Validate download link element. Throw exception if size() equal to 0", "Get the first element of the download links elements", "No element with class \"beatmap_download_link\", which should be at least one in a beatmap info page. Invalid beatmap URL?", true);
    }
    Element alnk = dwnLinks.get(0);
    String dwnLnk = alnk.attr("href");
    Element contentWithBgEl = doc.select("div.content-with-bg").first();
    if (contentWithBgEl == null) {
        throw new WithDumpException("", "Select \"div.content-with-bg\" and get the first element, assign to contentWithBgEl", "Validate contentWithBgEl is null or not", "Select \"div#tablist ul\" and get the first element, assign to tabList", "No div element with class \"content-with-bg\"", true);
    }
    // Element header1 = contentWithBgEl.select("h1").first();
    Element tabList = contentWithBgEl.select("div#tablist ul").first();
    if (tabList == null) {
        throw new WithDumpException("", "Select \"div#tablist ul\" and get the first element, assign to tabList", "Validate tabList is null or not", "Get tabList children and assign to tabListLi", "No div element with class \"tablist\" with ul", true);
    }
    Elements tabListLi = tabList.children();
    /*
		String[] tabStr = new String[tabListLi.size()];
		for (int i = 0; i < tabListLi.size(); i++){
			//<a> tag should be inside the <li> according to online code
			Element el = tabListLi.get(i).select(".beatmapTab span").first();
			
			if (el == null){
				throw new WithDumpException(
						tabListLi.get(i).html(),
						"(Loop of element tabList children) Select \".beatmapTab span\" from children and get the first element, assign to el",
						"Validate el is null or not",
						"Get the inner HTML of <span>",
						"No <a>/<span> tag in the difficulties tab index " + i + ". Page broke?",
						false);
			}
			
			tabStr[i] = el.html();
		}
		*/
    Element songInfo = contentWithBgEl.select("div table#songinfo tbody").first();
    if (songInfo == null) {
        throw new WithDumpException("", "Select \"div table#songinfo tbody# in contentWithBgEl and get the first element, assign to songInfo", "Validate songInfo is null or not", "Get songInfo children", "No songinfo element in contentWithBgEl. Page broke?", true);
    }
    Elements songInfoTrs = songInfo.children();
    if (songInfoTrs.size() < 7) {
        throw new WithDumpException(songInfoTrs.html(), "Get songInfo children", "Validate songInfo is enough <tr> elements (more than 7)", "(Lots of code) Get song info data from table", "No song info table <tr> / not enough <tr>. Only " + songInfoTrs.size() + "/7 Page broke?", false);
    }
    String[] tags = null;
    String genre = null;
    String source = null;
    String creator = null;
    String artist = null;
    String title = null;
    float circleSize = -1;
    float approachRate = -1;
    float hpDrain = -1;
    float accuracy = -1;
    float starDifficulty = -1;
    float bpm = -1;
    int good_rating = -1;
    int bad_rating = -1;
    float success_rate = -1;
    for (int i = 0; i < songInfoTrs.size(); i++) {
        Elements tr = songInfoTrs.get(i).children();
        Element el;
        Element el_a;
        switch(// even number index <td> elements are labels
        i) {
            case // [1]Artist[3]Circle size (starfield)[5]Approach rate(starfield)
            0:
                for (int j = 0; j < tr.size(); j++) {
                    // tr.size() should be 6
                    el = tr.get(j);
                    switch(j) {
                        case 0:
                            break;
                        case 1:
                            el_a = el.select("a[href]").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to artist", "No artist related data. Page broke?", false);
                            }
                            artist = el_a.html();
                            break;
                        case 2:
                            break;
                        case // Circle size (Starfield)
                        3:
                            if (pageBeatmap) {
                                circleSize = parseStarfield("Circle Size", el);
                            }
                            break;
                        case 4:
                            break;
                        case // Approach rate (Starfield)
                        5:
                            if (pageBeatmap) {
                                approachRate = parseStarfield("Approach Rate", el);
                            }
                            break;
                    }
                }
                break;
            case // [1]Title[3]HP Drain(starfield)[5]Star difficulty(starfield)
            1:
                for (int j = 0; j < tr.size(); j++) {
                    // tr.size() should be 6
                    el = tr.get(j);
                    switch(j) {
                        case 0:
                            break;
                        case 1:
                            el_a = el.select("a[href]").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to title", "No title related data. Page broke?", false);
                            }
                            title = el_a.html();
                            break;
                        case 2:
                            break;
                        case // HP Drain (Starfield)
                        3:
                            if (pageBeatmap) {
                                hpDrain = parseStarfield("HP Drain", el);
                            }
                            break;
                        case 4:
                            break;
                        case // Star Diff (Starfield)
                        5:
                            if (pageBeatmap) {
                                starDifficulty = parseStarfield("Star Difficulty", el);
                            }
                            break;
                    }
                }
                break;
            case // [1]Creator[3]Accuracy(starfield)[5]Length (format: x:xx (x:xx drain))
            2:
                for (int j = 0; j < tr.size(); j++) {
                    // tr.size() should be 6
                    el = tr.get(j);
                    switch(j) {
                        case 0:
                            break;
                        case 1:
                            el_a = el.select("a[href]").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to creator", "No creator related data. Page broke?", false);
                            }
                            creator = el_a.html();
                            break;
                        case 2:
                            break;
                        case // Accuracy (Starfield)
                        3:
                            if (pageBeatmap) {
                                accuracy = parseStarfield("Accuracy", el);
                            }
                            break;
                        case 4:
                            break;
                        case // Length (in format: x:xx (x:xx drain)) (figuring to get)
                        5:
                            break;
                    }
                }
                break;
            case // [1]Source[3]Genre[5]BPM
            3:
                for (int j = 0; j < tr.size(); j++) {
                    // tr.size() should be 6
                    el = tr.get(j);
                    switch(j) {
                        case 0:
                            break;
                        case 1:
                            el_a = el.select("a[href]").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to source", "No source related data. Page broke?", false);
                            }
                            source = el_a.html();
                            break;
                        case 2:
                            break;
                        case // Format: xx (xx), however we are not getting (xx)
                        3:
                            el_a = el.select("a[href]").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to genre", "No genre related data. Page broke?", false);
                            }
                            genre = el_a.html();
                            break;
                        case 4:
                            break;
                        case // Floating BPM
                        5:
                            if (el == null) {
                                throw new WithDumpException(null, "(Loop, switch)", "Validate el is null or not", "Parse float from el inner HTML", "No bpm related data. Page broke?", false);
                            }
                            try {
                                bpm = Float.parseFloat(el.html().replaceAll(",", ""));
                            } catch (NumberFormatException e) {
                                throw new WithDumpException(el.html(), "Validate el is null or not", "Parse float from el inner HTML", "(Break switch, Loop)", "Cannot parse float. BPM is not a floating number", false, e);
                            }
                            break;
                    }
                }
                break;
            case 4:
                for (int j = 0; j < tr.size(); j++) {
                    // tr.size() should be 6
                    el = tr.get(j);
                    switch(j) {
                        case 0:
                            break;
                        case 1:
                            Elements tagsEls = el.select("a[href]");
                            if (tagsEls.size() == 0) {
                                throw new WithDumpException(el.html(), "Select \"a[href]\" from el and assign to el_a", "Validate el_a is null or not", "Get inner HTML from <a> and assign to tags", "No tags related data. Page broke?", false);
                            }
                            tags = new String[tagsEls.size()];
                            for (int x = 0; x < tags.length; x++) {
                                tags[x] = tagsEls.get(x).html();
                            }
                            break;
                        case 2:
                            break;
                        case // Well this is tricky, a bad rating in the first <td>, and the good one in the second <td>
                        3:
                            Elements ratingEls = el.select("table tbody tr td");
                            if (ratingEls.size() < 2) {
                                throw new WithDumpException(el.html(), "Select \"table tbody tr td\" from el and assign to ratingEls", "Validate ratingEls elements is enough (more than 2)", "Get the first element in ratingEls and assign to el_a", "Not enough " + ratingEls.size() + "/2 / no rating related data. Page broke?", false);
                            }
                            el_a = ratingEls.get(0);
                            try {
                                bad_rating = Integer.parseInt(el_a.html().replaceAll(",", ""));
                            } catch (NumberFormatException e) {
                                throw new WithDumpException(el_a.html(), "Get the first element in ratingEls and assign to el_a", "Parse integer from el_a inner HTML", "Get the second element in ratingEls and assign to el_a", "Cannot parse integer. Bad rating is not an integer", false, e);
                            }
                            el_a = ratingEls.get(1);
                            try {
                                good_rating = Integer.parseInt(el_a.html().replaceAll(",", ""));
                            } catch (NumberFormatException e) {
                                throw new WithDumpException(el_a.html(), "Get the second element in ratingEls and assign to el_a", "Parse integer from el_a inner HTML", "(Break switch, Loop)", "Cannot parse integer. Good rating is not an integer", false, e);
                            }
                            break;
                        case 4:
                            break;
                        case // Floating success rate
                        5:
                            el_a = el.select("td").first();
                            if (el_a != null && el_a.html().contains("Not yet played!")) {
                                success_rate = -1;
                                break;
                            }
                            el_a = el.select("td b").first();
                            if (el_a == null) {
                                throw new WithDumpException(el.html(), "Select \"td b\" from el and assign to el_a", "Validate el_a is null or not", "(Try&catch scope) Get inner HTML from <a> and assign to str", "No success rate related data. Page broke?", false);
                            }
                            try {
                                String str = el_a.html();
                                int index = str.indexOf("%");
                                success_rate = Float.parseFloat(str.substring(0, index));
                            } catch (NumberFormatException e) {
                                throw new WithDumpException(el_a.html(), "Validate el_a is null or not", "Parse float from el_a inner HTML", "(Break switch, Loop)", "Cannot parse float. Success rate is not a floating number", false, e);
                            }
                            break;
                    }
                }
                break;
            case // figuring out
            5:
                break;
            case // figuring out
            6:
                break;
        }
    }
    Element thumbEl = contentWithBgEl.select("div.paddingboth div.posttext a[href] img[src].bmt").first();
    if (thumbEl == null) {
        throw new WithDumpException("", "Select \"div.paddingboth div.posttext a[href] img[src].bmt\" from contentWithBgEl and assign to thumbEl", "Validate thumbEl is null or not", "Get attribute \"src\" from thumbEl", "No thumb image related data. Page broke?", true);
    }
    String thumbUrl = thumbEl.attr("src");
    if (pageBeatmap) {
        return new OsuBeatmap(originalUrl, artist + " - " + title, title, artist, creator, source, genre, dwnLnk, thumbUrl, bad_rating, good_rating, bpm, circleSize, approachRate, hpDrain, accuracy, starDifficulty, success_rate, pageBeatmap);
    } else {
        return new OsuSong(originalUrl, artist + " - " + title, title, artist, creator, source, genre, dwnLnk, thumbUrl, bad_rating, good_rating, bpm, pageBeatmap);
    }
}
Also used : WithDumpException(com.github.mob41.osumer.debug.WithDumpException) OsuBeatmap(com.github.mob41.osums.beatmap.OsuBeatmap) Element(org.jsoup.nodes.Element) OsuSong(com.github.mob41.osums.beatmap.OsuSong) Elements(org.jsoup.select.Elements)

Aggregations

WithDumpException (com.github.mob41.osumer.debug.WithDumpException)18 IOException (java.io.IOException)11 URL (java.net.URL)7 JSONObject (org.json.JSONObject)6 MalformedURLException (java.net.MalformedURLException)5 HttpURLConnection (java.net.HttpURLConnection)4 ArrayList (java.util.ArrayList)4 OsuSong (com.github.mob41.osums.beatmap.OsuSong)3 Win32Exception (com.sun.jna.platform.win32.Win32Exception)3 BufferedReader (java.io.BufferedReader)3 File (java.io.File)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 List (java.util.List)3 Element (org.jsoup.nodes.Element)3 Configuration (com.github.mob41.osumer.Configuration)2 DebugDump (com.github.mob41.osumer.debug.DebugDump)2 InvalidSourceIntegerException (com.github.mob41.osumer.exceptions.InvalidSourceIntegerException)2 NoBuildsForVersionException (com.github.mob41.osumer.exceptions.NoBuildsForVersionException)2 NoSuchBuildNumberException (com.github.mob41.osumer.exceptions.NoSuchBuildNumberException)2