diff --git a/README.md b/README.md index eeddcb1..bfb9024 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,130 @@ # NS-USBloader -NS-USBloader is a PC-side TinFoil and GoldLeaf NSP USB uploader. Replacement for default *usb_install_pc.py* and *GoldTree*. +NS-USBloader is a PC-side TinFoil (USB and Network) and GoldLeaf (USB) NSP installer. Replacement for default **usb_install_pc.py**, **remote_install_pc.py** *(never ever use this. even if you brave. no idea why it works.)* and **GoldTree**. -With GUI and cookies. +With GUI and cookies. Wokrs on Windows, macOS and Linux. -Read more: https://developersu.blogspot.com/2019/02/ns-usbloader-en.html - -Here is the version of 'not perfect but anyway' [tinfoil I use](https://cloud.mail.ru/public/DwbX/H8d2p3aYR). -Ok, I'm almost sure that this version has bugs. I don't remember where I downloaded it. But it works for me somehow.. - -Let's rephrase, if you have working version of TinFoil DO NOT use this one. +Sometimes I add new posts [on my home page](https://developersu.blogspot.com/search/label/NS-USBloader) about this project. ![Screenshot](https://farm8.staticflickr.com/7834/47133893471_37fd9689c4_o.png) -## License +### License Source code spreads under the GNU General Public License v.3. You can find it in LICENSE file. -## Used libraries +### Used libraries * [OpenJFX](https://wiki.openjdk.java.net/display/OpenJFX/Main) * [usb4java](https://mvnrepository.com/artifact/org.usb4java/usb4java) * Few icons taken from: [materialdesignicons](http://materialdesignicons.com/) -## Requirements +### System requirements -JRE 8u60 or higher. See below. +JRE 8u60 or higher. -## Usage -### Linux: +### Usage +#### How to start it on.. +##### Linux: 1. Install JRE/JDK 8u60 or higher (openJDK is good. Oracle's one is also good). JavaFX not needed, if you're interested (it's embedded). 2. `root # java -jar /path/to/NS-USBloader.jar` -### macOS +##### macOS -See 'Linux' section. +Double-click on downloaded .jar file. Follow instructions. Or see 'Linux' section. Set 'Security & Privacy' settings if needed. -### Windows: +If you use different MacOS (not Mojave) - check release section for another JAR file. -* Download Zadig: https://zadig.akeo.ie/ -* Open tinfoil. Set 'Title Managment' -> 'Usb install NSP' +##### Windows: + +* Download Zadig: [https://zadig.akeo.ie/](https://zadig.akeo.ie/) +* Open TinFoil. Set 'Title Management' -> 'Usb install NSP' * Connect NS to PC -* Open Zadig, select NS in dropdown, select 'libusbK (v3.0.7.0)' (version may vary), click 'Install WCID Driver' +* Open Zadig +* Click 'Options' and select 'List All Devices' +* Select NS in dropdown, select 'libusbK (v3.0.7.0)' (version may vary), click 'Install WCID Driver' * Check that in device list of you system you have 'libusbK USB Devices' folder and your NS inside of it * Download and install Java JRE (8+) * Get this application (JAR file) double-click on on it (alternatively open 'cmd', go to place where jar located and execute via `java -jar thisAppName.jar`) * Remember to have fun! -## Tips&tricks -### Linux: Add user to udev rules to use NS not-from-root-account -`root # vim /etc/udev/rules.d/99-NS.rules` +#### And how to use it? -`SUBSYSTEM=="usb", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="3000", GROUP="plugdev"` +The first thing you should do it install TinFoil ([Adubbz](https://github.com/Adubbz/Tinfoil/)) or GoldLeaf ([XorTroll](https://github.com/XorTroll/Goldleaf)) on your NS. I recommend using TinFoil, but it ups to you. Take a look on app, find where is the option to install from USB and/or Network. Maybe [this article](https://developersu.blogspot.com/2019/02/ns-usbloader-en.html) will be helpful. -`root # udevadm control --reload-rules && udevadm trigger` +Here is the version of 'not perfect but anyway' [tinfoil I use](https://cloud.mail.ru/public/DwbX/H8d2p3aYR). +Ok, I'm almost sure that this version has bugs. I don't remember where I downloaded it. But it works for me somehow. -## Known bugs -* Unable to interrupt transmission when libusb awaiting for read event (when user sent NSP list but didn't selected anything on NS). +Let's rephrase, if you have working version of TinFoil **DO NOT** use this one. Ok. let's begin. -## NOTES -Table 'Status' = 'Uploaded' does not means that file installed. It means that it has been sent to NS without any issues! That's what this app about. +There are three tabs. Firs one is main. + +##### First tab. + +At the top of you selecting from drop-down application and protocol that you're going to use. For GoldLeaf only USB is available. Lamp icon stands for switching themes (light or dark). + +Then you may drag-n-drop folder with NSPs OR files to application or use 'Select NSP files' button. Multiple selection for files available. Click it again and select files from another folder it you want, it will be added into the table. + +Table. + +There you can select checkbox for files that will be send to application (TF/GL). Since GoldLeaf allow you only one file transmission per time, only one file is available for selection. Also you can use space to select/un-select files and 'delete' button for deleting. By right-mouse-click you can see context menu where you can delete one OR all items from the table. + +##### Second tab. + +Here you can configure settings for network file transmission. Usually you shouldn't change anything. But it you're cool hacker, go ahead! The most interesting option here is 'Don't serve requests'. Architecture of the TinFoil networking is working interesting way. When you select in TF network NSP transfer, application will wait at port 2000 for the information about where should it take files from. Like '192.168.1.5:6060/my_file.nsp'. Usually NS-USBloader serves requests by implementing simplified HTTP server and bringing it up and so on. But if this option selected, you can define path to remote location of the files. For example if you set in settings 'shared.lan:80/ROMS/NS/' and add in table file 'my file.nsp' then NS-USBloader will simply tell TinFoil "Hey, go take files from 'shared.lan:80/ROMS/NS/my+file.nsp' ". Of course you have to bring 'shared.lan' host up and make file accessible from such address. All this requires more investigation. BTW, the issue could be that NS-USBloader encodes 'space' char as '+' and some web-servers understand 'space' as '%20D'. It could be fixed in later versions of NS-USBloader if I go deeper in it or you leave me feedback with information/request. As I said, this feature is interesting, but I guess won't be popular. + +##### Third tab. + +That's where all logs dropped. Verbose information about transmissions comes here. + +Why when 'Net' once started it never ends? + +Because there is HTTP server inside of application. It can't determine the moment when all transmissions finished (unless they failed). So you have to look on your NS screen and 'Interrupt' is once done. + +### Tips&tricks +#### Linux: Add user to 'udev' rules to use NS not-from-root-account +``` +root # vim /etc/udev/rules.d/99-NS.rules +SUBSYSTEM=="usb", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="3000", GROUP="plugdev" +root # udevadm control --reload-rules && udevadm trigger +``` + +### Known bugs +* Unable to interrupt transmission when libusb awaiting for read event (when user sent NSP list but didn't selected anything on NS). Also, sometimes, when network transmission started and nothing received from NS. + +#### NOTES +Table 'Status' = 'Uploaded' does not mean that file installed. It means that it has been sent to NS without any issues! That's what this app about. Handling successful/failed installation is a purpose of the other side application (TinFoil/GoldLeaf). (And they don't provide any feedback interfaces so I can't detect success/failure.) -## TODO: -- [x] macOS QA v0.1 -- [ ] macOS QA v0.2 (partly) +usb4java since NS-USBloader-v0.2.3 switched to 1.2.0 instead of 1.3.0. This shouldn't impact anyone except users of macOS High Sierra (and Sierra?) where previous versions of NS-USBloader didn't work. + +### Translators! Traductores! Übersetzer! Թարգմանիչներ! +If you want to see this app translated to your language, go grab [this file](https://github.com/developersu/ns-usbloader/blob/master/src/main/resources/locale.properties) and translate it. +Upload somewhere (pastebin? google drive? whatever else). [Create new issue](https://github.com/developersu/ns-usbloader/issues) and post a link. I'll grab it and add. + +#### Thanks for great work done by our translater~~s team~~! + +Français by [Stephane Meden (JackFromNice)](https://github.com/JackFromNice) + + +#### TODO (maybe): +- [x] macOS QA v0.1 (Mojave) +- [x] macOS QA v0.2.2 (Mojave) +- [x] macOS QA v0.2.3-DEV (High Sierra) +- [ ] macOS QA v0.3 (Mojave, High Sierra) - [x] Windows support -- [ ] code refactoring (almost. todo: printLog() ) +- [x] code refactoring - [x] GoldLeaf support - [ ] XCI support - [ ] File order sort (non-critical) - [ ] More deep file analyze before uploading. +- [x] Network mode support for TinFoil -## Thanks +#### Thanks Appreciate assistance and support of both Vitaliy and Konstantin. Without you all this magic would not have happened. [Konstanin Kelemen](https://github.com/konstantin-kelemen) - -[Vitaliy Natarov](https://github.com/SebastianUA) \ No newline at end of file + +[Vitaliy Natarov](https://github.com/SebastianUA) \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5665658..30bc6e0 100644 --- a/pom.xml +++ b/pom.xml @@ -8,11 +8,11 @@ NS-USBloader ns-usbloader - 0.2.2-SNAPSHOT + 0.3-SNAPSHOT https://github.com/developersu/ns-usbloader/ - NSP USB loader for TinFoil and GoldLeaf + NSP USB loader for TinFoil (USB and Network) and GoldLeaf 2019 @@ -140,7 +140,7 @@ org.usb4java usb4java - 1.3.0 + 1.2.0 compile @@ -155,6 +155,18 @@ 1.8 + + + maven-jar-plugin + 2.4 + + + default-jar + none + + + + org.apache.maven.plugins maven-assembly-plugin diff --git a/src/main/java/nsusbloader/AppPreferences.java b/src/main/java/nsusbloader/AppPreferences.java index 62baa86..83d03b1 100644 --- a/src/main/java/nsusbloader/AppPreferences.java +++ b/src/main/java/nsusbloader/AppPreferences.java @@ -10,6 +10,33 @@ public class AppPreferences { private AppPreferences(){ preferences = Preferences.userRoot().node("NS-USBloader"); } + public void setAll( + String Protocol, + String PreviouslyOpened, + String NetUsb, + String NsIp, + boolean NsIpValidate, + boolean ExpertMode, + boolean AutoIp, + boolean RandPort, + boolean NotServe, + String HostIp, + String HostPort, + String HostExtra + ){ + setProtocol(Protocol); + setRecent(PreviouslyOpened); + setNetUsb(NetUsb); + setNsIp(NsIp); + setNsIpValidationNeeded(NsIpValidate); + setExpertMode(ExpertMode); + setAutoDetectIp(AutoIp); + setRandPort(RandPort); + setNotServeRequests(NotServe); + setHostIp(HostIp); + setHostPort(HostPort); + setHostExtra(HostExtra); + } public String getTheme(){ String theme = preferences.get("THEME", "/res/app_dark.css"); // Don't let user to change settings manually if (!theme.matches("(^/res/app_dark.css$)|(^/res/app_light.css$)")) @@ -22,10 +49,50 @@ public class AppPreferences { protocol = "TinFoil"; return protocol; } + public String getNetUsb(){ + String netUsb = preferences.get("NETUSB", "USB"); // Don't let user to change settings manually + if (!netUsb.matches("(^USB$)|(^NET$)")) + netUsb = "USB"; + return netUsb; + } public void setTheme(String theme){ preferences.put("THEME", theme); } public void setProtocol(String protocol){ preferences.put("PROTOCOL", protocol); } + public void setNetUsb(String netUsb){ preferences.put("NETUSB", netUsb); } + public void setNsIp(String ip){preferences.put("NSIP", ip);} + public String getNsIp(){return preferences.get("NSIP", "192.168.1.42");} public String getRecent(){ return preferences.get("RECENT", System.getProperty("user.home")); } public void setRecent(String path){ preferences.put("RECENT", path); } + //------------ SETTINGS ------------------// + public boolean getNsIpValidationNeeded() {return preferences.getBoolean("NSIPVALIDATION", true);} + public void setNsIpValidationNeeded(boolean need){preferences.putBoolean("NSIPVALIDATION", need);} + + public boolean getExpertMode(){return preferences.getBoolean("EXPERTMODE", false);} + public void setExpertMode(boolean mode){preferences.putBoolean("EXPERTMODE", mode);} + + public boolean getAutoDetectIp(){return preferences.getBoolean("AUTOHOSTIP", true);} + public void setAutoDetectIp(boolean mode){preferences.putBoolean("AUTOHOSTIP", mode);} + + public boolean getRandPort(){return preferences.getBoolean("RANDHOSTPORT", true);} + public void setRandPort(boolean mode){preferences.putBoolean("RANDHOSTPORT", mode);} + + public boolean getNotServeRequests(){return preferences.getBoolean("DONTSERVEREQ", false);} + public void setNotServeRequests(boolean mode){preferences.putBoolean("DONTSERVEREQ", mode);} + + public String getHostIp(){ return preferences.get("HOSTIP", "0.0.0.0").replaceAll("(\\s)|(\t)", "");} // who the hell said 'paranoid'? + public void setHostIp(String ip){preferences.put("HOSTIP", ip);} + + public String getHostPort(){ + String value = preferences.get("HOSTPORT", "6042"); + if (!value.matches("^[0-9]{1,5}$")) + return "6042"; + if ((Integer.parseInt(value) > 65535) || (Integer.parseInt(value) < 1)) + return "6042"; + return value; + } + public void setHostPort(String port){preferences.put("HOSTPORT", port);} + + public String getHostExtra(){ return preferences.get("HOSTEXTRA", "").replaceAll("(\\s)|(\t)", "");} // oh just shut up... + public void setHostExtra(String postfix){preferences.put("HOSTEXTRA", postfix);} } diff --git a/src/main/java/nsusbloader/Controllers/NSLMainController.java b/src/main/java/nsusbloader/Controllers/NSLMainController.java index 3befcbd..9787119 100644 --- a/src/main/java/nsusbloader/Controllers/NSLMainController.java +++ b/src/main/java/nsusbloader/Controllers/NSLMainController.java @@ -2,19 +2,25 @@ package nsusbloader.Controllers; import javafx.collections.FXCollections; import javafx.collections.ObservableList; +import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; +import javafx.scene.input.DragEvent; +import javafx.scene.input.TransferMode; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import nsusbloader.AppPreferences; import nsusbloader.MediatorControl; +import nsusbloader.NET.NETCommunications; import nsusbloader.NSLMain; -import nsusbloader.UsbCommunications; +import nsusbloader.ServiceWindow; +import nsusbloader.USB.UsbCommunications; import java.io.File; -import java.net.URL; +import java.net.*; +import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; @@ -32,7 +38,7 @@ public class NSLMainController implements Initializable { @FXML public ProgressBar progressBar; // Accessible from Mediator @FXML - private ChoiceBox choiceProtocol; + private ChoiceBox choiceProtocol, choiceNetUsb; @FXML private Button switchThemeBtn; @@ -41,9 +47,15 @@ public class NSLMainController implements Initializable { @FXML public NSTableViewController tableFilesListController; // Accessible from Mediator + @FXML + private SettingsController SettingsTabController; + @FXML + private TextField nsIpTextField; + @FXML + private Label nsIpLbl; - private UsbCommunications usbCommunications; - private Thread usbThread; + private Task usbNetCommunications; + private Thread workThread; private String previouslyOpenedPath; @@ -75,10 +87,51 @@ public class NSLMainController implements Initializable { ObservableList choiceProtocolList = FXCollections.observableArrayList("TinFoil", "GoldLeaf"); choiceProtocol.setItems(choiceProtocolList); - choiceProtocol.getSelectionModel().select(AppPreferences.getInstance().getProtocol()); // TODO: shared settings - choiceProtocol.setOnAction(e->tableFilesListController.setNewProtocol(choiceProtocol.getSelectionModel().getSelectedItem())); // Add listener to notify tableView controller + choiceProtocol.getSelectionModel().select(AppPreferences.getInstance().getProtocol()); + choiceProtocol.setOnAction(e-> { + tableFilesListController.setNewProtocol(choiceProtocol.getSelectionModel().getSelectedItem()); + if (choiceProtocol.getSelectionModel().getSelectedItem().equals("GoldLeaf")) { + choiceNetUsb.setDisable(true); + nsIpLbl.setVisible(false); + nsIpTextField.setVisible(false); + } + else { + choiceNetUsb.setDisable(false); + if (choiceNetUsb.getSelectionModel().getSelectedItem().equals("NET")) { + nsIpLbl.setVisible(true); + nsIpTextField.setVisible(true); + } + } + }); // Add listener to notify tableView controller tableFilesListController.setNewProtocol(choiceProtocol.getSelectionModel().getSelectedItem()); // Notify tableView controller + ObservableList choiceNetUsbList = FXCollections.observableArrayList("USB", "NET"); + choiceNetUsb.setItems(choiceNetUsbList); + choiceNetUsb.getSelectionModel().select(AppPreferences.getInstance().getNetUsb()); + if (choiceProtocol.getSelectionModel().getSelectedItem().equals("GoldLeaf")) { + choiceNetUsb.setDisable(true); + } + choiceNetUsb.setOnAction(e->{ + if (choiceNetUsb.getSelectionModel().getSelectedItem().equals("NET")){ + nsIpLbl.setVisible(true); + nsIpTextField.setVisible(true); + } + else{ + nsIpLbl.setVisible(false); + nsIpTextField.setVisible(false); + } + }); + nsIpTextField.setText(AppPreferences.getInstance().getNsIp()); + if (choiceProtocol.getSelectionModel().getSelectedItem().equals("TinFoil") && choiceNetUsb.getSelectionModel().getSelectedItem().equals("NET")){ + nsIpLbl.setVisible(true); + nsIpTextField.setVisible(true); + } + nsIpTextField.setTextFormatter(new TextFormatter<>(change -> { + if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t")) + return null; + else + return change; + })); this.previouslyOpenedPath = null; Region btnSwitchImage = new Region(); @@ -125,37 +178,67 @@ public class NSLMainController implements Initializable { uploadStopBtn.setDisable(false); previouslyOpenedPath = filesList.get(0).getParent(); } - else{ - tableFilesListController.setFiles(null); - uploadStopBtn.setDisable(true); - } } /** * It's button listener when no transmission executes * */ private void uploadBtnAction(){ - if (usbThread == null || !usbThread.isAlive()){ + if ((workThread == null || !workThread.isAlive())){ + // Collect files List nspToUpload; - if ((nspToUpload = tableFilesListController.getFiles()) == null) { - resourceBundle.getString("logsNoFolderFileSelected"); + if ((nspToUpload = tableFilesListController.getFilesForUpload()) == null) { + logArea.setText(resourceBundle.getString("logsNoFolderFileSelected")); return; - }else { + } + else { logArea.setText(resourceBundle.getString("logsFilesToUploadTitle")+"\n"); for (File item: nspToUpload) logArea.appendText(" "+item.getAbsolutePath()+"\n"); } - usbCommunications = new UsbCommunications(nspToUpload, choiceProtocol.getSelectionModel().getSelectedItem()); - usbThread = new Thread(usbCommunications); - usbThread.setDaemon(true); - usbThread.start(); + // If USB selected + if (choiceProtocol.getSelectionModel().getSelectedItem().equals("GoldLeaf") || + ( + choiceProtocol.getSelectionModel().getSelectedItem().equals("TinFoil") + && choiceNetUsb.getSelectionModel().getSelectedItem().equals("USB") + ) + ){ + usbNetCommunications = new UsbCommunications(nspToUpload, choiceProtocol.getSelectionModel().getSelectedItem()); + workThread = new Thread(usbNetCommunications); + workThread.setDaemon(true); + workThread.start(); + } + else { // NET INSTALL OVER TINFOIL + if (SettingsTabController.isNsIpValidate() && !nsIpTextField.getText().matches("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$")) + if (!ServiceWindow.getConfirmationWindow(resourceBundle.getString("windowTitleBadIp"),resourceBundle.getString("windowBodyBadIp"))) + return; + + String nsIP = nsIpTextField.getText(); + + if (!SettingsTabController.getExpertModeSelected()) + usbNetCommunications = new NETCommunications(nspToUpload, nsIP, false, "", "", ""); + else { + usbNetCommunications = new NETCommunications( + nspToUpload, + nsIP, + SettingsTabController.getNotServeSelected(), + SettingsTabController.getAutoIpSelected()?"":SettingsTabController.getHostIp(), + SettingsTabController.getRandPortSelected()?"":SettingsTabController.getHostPort(), + SettingsTabController.getNotServeSelected()?SettingsTabController.getHostExtra():"" + ); + } + + workThread = new Thread(usbNetCommunications); + workThread.setDaemon(true); + workThread.start(); + } } } /** * It's button listener when transmission in progress * */ private void stopBtnAction(){ - if (usbThread != null && usbThread.isAlive()){ - usbCommunications.cancel(false); + if (workThread != null && workThread.isAlive()){ + usbNetCommunications.cancel(false); // TODO: add something abstract to use also for network } } /** @@ -188,11 +271,65 @@ public class NSLMainController implements Initializable { uploadStopBtn.getStyleClass().add("buttonUp"); } } + /** + * Crunch. Now you see that I'm not a programmer.. This function called from NSTableViewController + * */ + public void disableUploadStopBtn(boolean disable){ + uploadStopBtn.setDisable(disable); + } + /** + * Drag-n-drop support (dragOver consumer) + * */ + @FXML + private void handleDragOver(DragEvent event){ + if (event.getDragboard().hasFiles()) + event.acceptTransferModes(TransferMode.ANY); + } + /** + * Drag-n-drop support (drop consumer) + * */ + @FXML + private void handleDrop(DragEvent event){ + if (MediatorControl.getInstance().getTransferActive()) { + event.setDropCompleted(true); + return; + } + List filesDropped = new ArrayList<>(); + try { + for (File fileOrDir : event.getDragboard().getFiles()) { + if (fileOrDir.getName().toLowerCase().endsWith(".nsp")) + filesDropped.add(fileOrDir); + else if (fileOrDir.isDirectory()) + for (File file : fileOrDir.listFiles()) + if (file.getName().toLowerCase().endsWith(".nsp")) + filesDropped.add(file); + } + } + catch (SecurityException se){ + se.printStackTrace(); + } + if (!filesDropped.isEmpty()) + tableFilesListController.setFiles(filesDropped); + + event.setDropCompleted(true); + } /** * Save preferences before exit * */ - public void exit(){ - AppPreferences.getInstance().setProtocol(choiceProtocol.getSelectionModel().getSelectedItem()); - AppPreferences.getInstance().setRecent(previouslyOpenedPath); + public void exit(){ // TODO: add method to set all in AppPreferences + AppPreferences.getInstance().setAll( + choiceProtocol.getSelectionModel().getSelectedItem(), + previouslyOpenedPath, + choiceNetUsb.getSelectionModel().getSelectedItem(), + nsIpTextField.getText().trim(), + SettingsTabController.isNsIpValidate(), + SettingsTabController.getExpertModeSelected(), + SettingsTabController.getAutoIpSelected(), + SettingsTabController.getRandPortSelected(), + SettingsTabController.getNotServeSelected(), + SettingsTabController.getHostIp(), + SettingsTabController.getHostPort(), + SettingsTabController.getHostExtra() + ); } } diff --git a/src/main/java/nsusbloader/Controllers/NSLRowModel.java b/src/main/java/nsusbloader/Controllers/NSLRowModel.java index afd3f17..baa592e 100644 --- a/src/main/java/nsusbloader/Controllers/NSLRowModel.java +++ b/src/main/java/nsusbloader/Controllers/NSLRowModel.java @@ -16,7 +16,12 @@ public class NSLRowModel { this.nspFile = nspFile; this.markForUpload = checkBoxValue; this.nspFileName = nspFile.getName(); - this.nspFileSize = String.format("%.2f", nspFile.length()/1024.0/1024.0); + if (nspFile.length()/1024.0/1024.0/1024.0 > 1) + this.nspFileSize = String.format("%.2f", nspFile.length()/1024.0/1024.0/1024.0)+" GB"; + else if (nspFile.length()/1024.0/1024.0 > 1) + this.nspFileSize = String.format("%.2f", nspFile.length()/1024.0/1024.0)+" MB"; + else + this.nspFileSize = String.format("%.2f", nspFile.length()/1024.0)+" kB"; this.status = ""; } // Model methods start @@ -45,11 +50,14 @@ public class NSLRowModel { case FAILED: this.status = "Failed"; break; - case UNKNOWN: + case INDETERMINATE: this.status = "..."; break; + case UNKNOWN: + this.status = "Unknown"; + break; case INCORRECT_FILE_FAILED: - this.status = "Failed: Incorrect file"; + this.status = "Failed: Bad file"; markForUpload = false; break; } diff --git a/src/main/java/nsusbloader/Controllers/NSTableViewController.java b/src/main/java/nsusbloader/Controllers/NSTableViewController.java index 9e1670c..ba20ffa 100644 --- a/src/main/java/nsusbloader/Controllers/NSTableViewController.java +++ b/src/main/java/nsusbloader/Controllers/NSTableViewController.java @@ -1,19 +1,24 @@ package nsusbloader.Controllers; +import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; -import javafx.scene.control.Label; -import javafx.scene.control.TableCell; -import javafx.scene.control.TableColumn; -import javafx.scene.control.TableView; +import javafx.scene.control.*; import javafx.scene.control.cell.CheckBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; import javafx.util.Callback; +import nsusbloader.MediatorControl; import nsusbloader.NSLDataTypes.EFileStatus; import java.io.File; @@ -32,13 +37,42 @@ public class NSTableViewController implements Initializable { @Override public void initialize(URL url, ResourceBundle resourceBundle) { rowsObsLst = FXCollections.observableArrayList(); + table.setPlaceholder(new Label()); + table.setEditable(false); // At least with hacks it works as expected. Otherwise - null pointer exception + table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); + table.setOnKeyPressed(new EventHandler() { + @Override + public void handle(KeyEvent keyEvent) { + if (!rowsObsLst.isEmpty()) { + if (keyEvent.getCode() == KeyCode.DELETE && !MediatorControl.getInstance().getTransferActive()) { + rowsObsLst.removeAll(table.getSelectionModel().getSelectedItems()); + if (rowsObsLst.isEmpty()) + MediatorControl.getInstance().getContoller().disableUploadStopBtn(true); // TODO: change to something better + table.refresh(); + } else if (keyEvent.getCode() == KeyCode.SPACE) { + for (NSLRowModel item : table.getSelectionModel().getSelectedItems()) { + item.setMarkForUpload(!item.isMarkForUpload()); + restrictSelection(item); + } + table.refresh(); + } + } + keyEvent.consume(); + } + }); TableColumn statusColumn = new TableColumn<>(resourceBundle.getString("tableStatusLbl")); TableColumn fileNameColumn = new TableColumn<>(resourceBundle.getString("tableFileNameLbl")); TableColumn fileSizeColumn = new TableColumn<>(resourceBundle.getString("tableSizeLbl")); TableColumn uploadColumn = new TableColumn<>(resourceBundle.getString("tableUploadLbl")); + + statusColumn.setEditable(false); + fileNameColumn.setEditable(false); + fileSizeColumn.setEditable(false); + uploadColumn.setEditable(true); + // See https://bugs.openjdk.java.net/browse/JDK-8157687 statusColumn.setMinWidth(100.0); statusColumn.setPrefWidth(100.0); @@ -75,7 +109,6 @@ public class NSTableViewController implements Initializable { restrictSelection(model); } }); - return booleanProperty; } }); @@ -87,7 +120,56 @@ public class NSTableViewController implements Initializable { return cell; } }); + table.setRowFactory( // this shit is made to implement context menu. It's such a pain.. + new Callback, TableRow>() { + @Override + public TableRow call(TableView nslRowModelTableView) { + final TableRow row = new TableRow<>(); + ContextMenu contextMenu = new ContextMenu(); + MenuItem deleteMenuItem = new MenuItem(resourceBundle.getString("contextMenuBtnDelete")); + deleteMenuItem.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent actionEvent) { + rowsObsLst.remove(row.getItem()); + if (rowsObsLst.isEmpty()) + MediatorControl.getInstance().getContoller().disableUploadStopBtn(true); // TODO: change to something better + table.refresh(); + } + }); + MenuItem deleteAllMenuItem = new MenuItem(resourceBundle.getString("contextMenuBtnDeleteAll")); + deleteAllMenuItem.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent actionEvent) { + rowsObsLst.clear(); + MediatorControl.getInstance().getContoller().disableUploadStopBtn(true); // TODO: change to something better + table.refresh(); + } + }); + contextMenu.getItems().addAll(deleteMenuItem, deleteAllMenuItem); + row.setContextMenu(contextMenu); + row.contextMenuProperty().bind( + Bindings.when( + Bindings.isNotNull( + row.itemProperty())) + .then(MediatorControl.getInstance().getTransferActive()?(ContextMenu)null:contextMenu) + .otherwise((ContextMenu) null) + ); + row.setOnMouseClicked(new EventHandler() { // Just.. don't ask.. + @Override + public void handle(MouseEvent mouseEvent) { + if (!row.isEmpty() && mouseEvent.getButton() == MouseButton.PRIMARY){ + NSLRowModel thisItem = row.getItem(); + thisItem.setMarkForUpload(!thisItem.isMarkForUpload()); + restrictSelection(thisItem); + } + mouseEvent.consume(); + } + }); + return row; + } + } + ); table.setItems(rowsObsLst); table.getColumns().addAll(statusColumn, fileNameColumn, fileSizeColumn, uploadColumn); } @@ -100,36 +182,42 @@ public class NSTableViewController implements Initializable { if (model != modelChecked) model.setMarkForUpload(false); } - table.refresh(); } + table.refresh(); } /** * Add files when user selected them * */ - public void setFiles(List files){ - rowsObsLst.clear(); // TODO: consider table refresh - if (files == null) { - return; - } - if (protocol.equals("TinFoil")){ - for (File nspFile: files){ - rowsObsLst.add(new NSLRowModel(nspFile, true)); - } + public void setFiles(List newFiles){ + if (!rowsObsLst.isEmpty()){ + List filesAlreayInList = new ArrayList<>(); + for (NSLRowModel model : rowsObsLst) + filesAlreayInList.add(model.getNspFileName()); + for (File file: newFiles) + if (!filesAlreayInList.contains(file.getName())) { + if (protocol.equals("TinFoil")) + rowsObsLst.add(new NSLRowModel(file, true)); + else + rowsObsLst.add(new NSLRowModel(file, false)); + } } else { - rowsObsLst.clear(); - for (File nspFile: files){ - rowsObsLst.add(new NSLRowModel(nspFile, false)); - } - rowsObsLst.get(0).setMarkForUpload(true); + for (File file: newFiles) + if (protocol.equals("TinFoil")) + rowsObsLst.add(new NSLRowModel(file, true)); + else + rowsObsLst.add(new NSLRowModel(file, false)); + MediatorControl.getInstance().getContoller().disableUploadStopBtn(false); } + rowsObsLst.get(0).setMarkForUpload(true); + table.refresh(); } /** * Return files ready for upload. Requested from NSLMainController only -> uploadBtnAction() //TODO: set undefined * @return null if no files marked for upload * List if there are files * */ - public List getFiles(){ + public List getFilesForUpload(){ List files = new ArrayList<>(); if (rowsObsLst.isEmpty()) return null; @@ -137,7 +225,7 @@ public class NSTableViewController implements Initializable { for (NSLRowModel model: rowsObsLst){ if (model.isMarkForUpload()){ files.add(model.getNspFile()); - model.setStatus(EFileStatus.UNKNOWN); + model.setStatus(EFileStatus.INDETERMINATE); } } if (!files.isEmpty()) { @@ -178,4 +266,4 @@ public class NSTableViewController implements Initializable { table.refresh(); } -} +} \ No newline at end of file diff --git a/src/main/java/nsusbloader/Controllers/SettingsController.java b/src/main/java/nsusbloader/Controllers/SettingsController.java new file mode 100644 index 0000000..8289f49 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/SettingsController.java @@ -0,0 +1,146 @@ +package nsusbloader.Controllers; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.control.CheckBox; +import javafx.scene.control.TextField; +import javafx.scene.control.TextFormatter; +import javafx.scene.layout.VBox; +import nsusbloader.AppPreferences; +import nsusbloader.ServiceWindow; + +import java.net.URL; +import java.util.ResourceBundle; + +public class SettingsController implements Initializable { + + @FXML + private CheckBox validateNSHostNameCb; + @FXML + private CheckBox expertModeCb; + @FXML + private CheckBox autoDetectIpCb; + @FXML + private CheckBox randPortCb; + + @FXML + private TextField pcIpTextField; + @FXML + private TextField pcPortTextField; + @FXML + private TextField pcExtraTextField; + + @FXML + private CheckBox dontServeCb; + + @FXML + private VBox expertSettingsVBox; + + @Override + public void initialize(URL url, ResourceBundle resourceBundle) { + validateNSHostNameCb.setSelected(AppPreferences.getInstance().getNsIpValidationNeeded()); + + expertSettingsVBox.setDisable(!AppPreferences.getInstance().getExpertMode()); + + expertModeCb.setSelected(AppPreferences.getInstance().getExpertMode()); + expertModeCb.setOnAction(e->{ + expertSettingsVBox.setDisable(!expertModeCb.isSelected()); + }); + + autoDetectIpCb.setSelected(AppPreferences.getInstance().getAutoDetectIp()); + pcIpTextField.setDisable(AppPreferences.getInstance().getAutoDetectIp()); + autoDetectIpCb.setOnAction(e->{ + pcIpTextField.setDisable(autoDetectIpCb.isSelected()); + if (!autoDetectIpCb.isSelected()) + pcIpTextField.requestFocus(); + }); + + randPortCb.setSelected(AppPreferences.getInstance().getRandPort()); + pcPortTextField.setDisable(AppPreferences.getInstance().getRandPort()); + randPortCb.setOnAction(e->{ + pcPortTextField.setDisable(randPortCb.isSelected()); + if (!randPortCb.isSelected()) + pcPortTextField.requestFocus(); + }); + + if (AppPreferences.getInstance().getNotServeRequests()){ + dontServeCb.setSelected(true); + + autoDetectIpCb.setSelected(false); + autoDetectIpCb.setDisable(true); + pcIpTextField.setDisable(false); + + randPortCb.setSelected(false); + randPortCb.setDisable(true); + pcPortTextField.setDisable(false); + } + pcExtraTextField.setDisable(!AppPreferences.getInstance().getNotServeRequests()); + + dontServeCb.setOnAction(e->{ + if (dontServeCb.isSelected()){ + autoDetectIpCb.setSelected(false); + autoDetectIpCb.setDisable(true); + pcIpTextField.setDisable(false); + + randPortCb.setSelected(false); + randPortCb.setDisable(true); + pcPortTextField.setDisable(false); + + pcExtraTextField.setDisable(false); + pcIpTextField.requestFocus(); + } + else { + autoDetectIpCb.setDisable(false); + autoDetectIpCb.setSelected(true); + pcIpTextField.setDisable(true); + + randPortCb.setDisable(false); + randPortCb.setSelected(true); + pcPortTextField.setDisable(true); + + pcExtraTextField.setDisable(true); + } + }); + + pcIpTextField.setText(AppPreferences.getInstance().getHostIp()); + pcPortTextField.setText(AppPreferences.getInstance().getHostPort()); + pcExtraTextField.setText(AppPreferences.getInstance().getHostExtra()); + + pcIpTextField.setTextFormatter(new TextFormatter<>(change -> { + if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t")) + return null; + else + return change; + })); + pcPortTextField.setTextFormatter(new TextFormatter(change -> { + if (change.getControlNewText().matches("^[0-9]{0,5}$")) { + if (!change.getControlNewText().isEmpty() + && ((Integer.parseInt(change.getControlNewText()) > 65535) || (Integer.parseInt(change.getControlNewText()) == 0)) + ) { + ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleErrorPort"), resourceBundle.getString("windowBodyErrorPort")); + return null; + } + return change; + } + else + return null; + })); + pcExtraTextField.setTextFormatter(new TextFormatter<>(change -> { + if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t")) + return null; + else + return change; + })); + } + + public boolean getExpertModeSelected(){ return expertModeCb.isSelected(); } + public boolean getAutoIpSelected(){ return autoDetectIpCb.isSelected(); } + public boolean getRandPortSelected(){ return randPortCb.isSelected(); } + public boolean getNotServeSelected(){ return dontServeCb.isSelected(); } + + public boolean isNsIpValidate(){ return validateNSHostNameCb.isSelected(); } + + public String getHostIp(){ return pcIpTextField.getText(); } + public String getHostPort(){ return pcPortTextField.getText(); } + public String getHostExtra(){ return pcExtraTextField.getText(); } +} \ No newline at end of file diff --git a/src/main/java/nsusbloader/MediatorControl.java b/src/main/java/nsusbloader/MediatorControl.java index 5544864..e828571 100644 --- a/src/main/java/nsusbloader/MediatorControl.java +++ b/src/main/java/nsusbloader/MediatorControl.java @@ -18,7 +18,7 @@ public class MediatorControl { public void setController(NSLMainController controller){ this.applicationController = controller; } - NSLMainController getContoller(){ return this.applicationController; } + public NSLMainController getContoller(){ return this.applicationController; } public synchronized void setTransferActive(boolean state) { isTransferActive.set(state); diff --git a/src/main/java/nsusbloader/ModelControllers/LogPrinter.java b/src/main/java/nsusbloader/ModelControllers/LogPrinter.java new file mode 100644 index 0000000..8a6edb7 --- /dev/null +++ b/src/main/java/nsusbloader/ModelControllers/LogPrinter.java @@ -0,0 +1,74 @@ +package nsusbloader.ModelControllers; + +import nsusbloader.NSLDataTypes.EFileStatus; +import nsusbloader.NSLDataTypes.EMsgType; + +import java.io.File; +import java.util.HashMap; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class LogPrinter { + private MessagesConsumer msgConsumer; + private BlockingQueue msgQueue; + private BlockingQueue progressQueue; + private HashMap statusMap; // BlockingQueue for literally one object. TODO: read more books ; replace to hashMap + + public LogPrinter(){ + this.msgQueue = new LinkedBlockingQueue<>(); + this.progressQueue = new LinkedBlockingQueue<>(); + this.statusMap = new HashMap<>(); + this.msgConsumer = new MessagesConsumer(this.msgQueue, this.progressQueue, this.statusMap); + this.msgConsumer.start(); + } + /** + * This is what will print to textArea of the application. + * */ + public void print(String message, EMsgType type){ + try { + switch (type){ + case PASS: + msgQueue.put("[ PASS ] "+message+"\n"); + break; + case FAIL: + msgQueue.put("[ FAIL ] "+message+"\n"); + break; + case INFO: + msgQueue.put("[ INFO ] "+message+"\n"); + break; + case WARNING: + msgQueue.put("[ WARN ] "+message+"\n"); + break; + default: + msgQueue.put(message); + } + }catch (InterruptedException ie){ + ie.printStackTrace(); + } + } + /** + * Update progress for progress bar + * */ + public void updateProgress(Double value) throws InterruptedException{ + progressQueue.put(value); + } + /** + * When we're done - update status + * */ + public void update(HashMap nspMap, EFileStatus status){ + for (File file: nspMap.values()) + statusMap.putIfAbsent(file.getName(), status); + } + /** + * When we're done - update status + * */ + public void update(File file, EFileStatus status){ + statusMap.putIfAbsent(file.getName(), status); + } + /** + * When we're done - close it + * */ + public void close(){ + msgConsumer.interrupt(); + } +} diff --git a/src/main/java/nsusbloader/MessagesConsumer.java b/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java similarity index 96% rename from src/main/java/nsusbloader/MessagesConsumer.java rename to src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java index 303580a..9ffb253 100644 --- a/src/main/java/nsusbloader/MessagesConsumer.java +++ b/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java @@ -1,10 +1,11 @@ -package nsusbloader; +package nsusbloader.ModelControllers; import javafx.animation.AnimationTimer; import javafx.scene.control.ProgressBar; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.TextArea; import nsusbloader.Controllers.NSTableViewController; +import nsusbloader.MediatorControl; import nsusbloader.NSLDataTypes.EFileStatus; import java.util.ArrayList; @@ -69,7 +70,7 @@ public class MessagesConsumer extends AnimationTimer { } } - void interrupt(){ + public void interrupt(){ this.isInterrupted = true; } } \ No newline at end of file diff --git a/src/main/java/nsusbloader/NET/NETCommunications.java b/src/main/java/nsusbloader/NET/NETCommunications.java new file mode 100644 index 0000000..aa85300 --- /dev/null +++ b/src/main/java/nsusbloader/NET/NETCommunications.java @@ -0,0 +1,356 @@ +package nsusbloader.NET; + +import javafx.concurrent.Task; +import nsusbloader.NSLDataTypes.EFileStatus; +import nsusbloader.ModelControllers.LogPrinter; +import nsusbloader.NSLDataTypes.EMsgType; + +import java.io.*; +import java.net.*; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class NETCommunications extends Task { // todo: thows IOException? + + private LogPrinter logPrinter; + + private String hostIP; + private int hostPort; + private String extras; + + private String switchIP; + + private HashMap nspMap; + + private ServerSocket serverSocket; + + private boolean isValid; + private boolean doNotServeRequests; + + private OutputStream currSockOS; + private PrintWriter currSockPW; + /** + * Simple constructor that everybody uses + * */ + public NETCommunications(List filesList, String switchIP, boolean doNotServeRequests, String hostIPaddr, String hostPortNum, String extras){ + this.doNotServeRequests = doNotServeRequests; + if (doNotServeRequests) + this.extras = extras; + else + this.extras = ""; + this.switchIP = switchIP; + this.logPrinter = new LogPrinter(); + this.nspMap = new HashMap<>(); + // Collect and encode NSP files list + try { + for (File nspFile : filesList) + nspMap.put(URLEncoder.encode(nspFile.getName(), "UTF-8"), nspFile); + } + catch (UnsupportedEncodingException uee){ + isValid = false; + logPrinter.print("NET: Unsupported encoding for 'URLEncoder'. Internal issue you can't fix. Please report. . Returned:\n\t"+uee.getMessage(), EMsgType.FAIL); + for (File nspFile : filesList) + nspMap.put(nspFile.getName(), nspFile); + close(EFileStatus.FAILED); + return; + } + // Resolve IP + if (hostIPaddr.isEmpty()) { + DatagramSocket socket; + try { // todo: check other method if internet unavaliable + socket = new DatagramSocket(); + socket.connect(InetAddress.getByName("8.8.8.8"), 10002); // Google + hostIP = socket.getLocalAddress().getHostAddress(); + socket.close(); + } catch (SocketException | UnknownHostException e) { + logPrinter.print("NET: Can't get your computer IP using Google DNS server. Returned:\n\t"+e.getMessage(), EMsgType.INFO); + try { + socket = new DatagramSocket(); + socket.connect(InetAddress.getByName("193.0.14.129"), 10002); // RIPE NCC + hostIP = socket.getLocalAddress().getHostAddress(); + socket.close(); + } catch (SocketException | UnknownHostException e1) { + logPrinter.print("NET: Can't get your computer IP using RIPE NCC root server. Returned:\n\t"+e1.getMessage(), EMsgType.INFO); + try { + socket = new DatagramSocket(); + socket.connect(InetAddress.getByName("people.com.cn"), 10002); // Renmin Ribao + hostIP = socket.getLocalAddress().getHostAddress(); + socket.close(); + } catch (SocketException | UnknownHostException e2) { + logPrinter.print("NET: Can't get your computer IP using Renmin Ribao server. Returned:\n\t"+e2.getMessage(), EMsgType.FAIL); + logPrinter.print("Try using 'Expert mode' and set IP manually.", EMsgType.INFO); + try { + Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); + while (enumeration.hasMoreElements()) { + NetworkInterface n = (NetworkInterface) enumeration.nextElement(); + Enumeration enumeration1 = n.getInetAddresses(); + while (enumeration1.hasMoreElements()) { + InetAddress i = (InetAddress) enumeration1.nextElement(); + logPrinter.print("Check for: " + i.getHostAddress(), EMsgType.INFO); + } + } + } catch (SocketException socketException) { // Good block. + logPrinter.print("Can't determine possible variants. Returned:\n\t"+socketException.getMessage(), EMsgType.FAIL); + } + isValid = false; + close(EFileStatus.FAILED); + return; + } + } + } + logPrinter.print("NET: Your IP detected as: " + hostIP, EMsgType.PASS); + } + else { + this.hostIP = hostIPaddr; + logPrinter.print("NET: Your IP defined as: " + hostIP, EMsgType.PASS); + } + + // Get port + if (hostPortNum.isEmpty()) { + Random portRandomizer = new Random(); + for (int i = 0; i < 5; i++) { + try { + this.hostPort = portRandomizer.nextInt(999) + 6000; + serverSocket = new ServerSocket(hostPort); //System.out.println(serverSocket.getInetAddress()); 0.0.0.0 + logPrinter.print("NET: Your port detected as: " + hostPort, EMsgType.PASS); + break; + } catch (IOException ioe) { + if (i == 4) { + logPrinter.print("NET: Can't find good port", EMsgType.FAIL); + logPrinter.print("Try using 'Expert mode' and set port by yourself.", EMsgType.INFO); + isValid = false; + close(EFileStatus.FAILED); + return; + } else + logPrinter.print("NET: Can't use port " + hostPort + "\nLooking for another one.", EMsgType.WARNING); + } + } + } + else { + try { + this.hostPort = Integer.parseInt(hostPortNum); + serverSocket = new ServerSocket(hostPort); + logPrinter.print("NET: Using defined port number: " + hostPort, EMsgType.PASS); + } + catch (NumberFormatException | IOException exeption){ // Literally never happens. + logPrinter.print("NET: Can't use port defined in settings: " + hostPortNum + "\nIt's not a valid number!", EMsgType.WARNING); + isValid = false; + close(EFileStatus.FAILED); + return; + } + } + isValid = true; + } + /** + * Override cancel block to close connection by ourselves + * */ + @Override + protected void cancelled() { + this.close(EFileStatus.UNKNOWN); + super.cancelled(); + } + + @Override + protected Void call() { + if (!isValid | isCancelled()) + return null; + logPrinter.print("\tStart chain", EMsgType.INFO); + // Create string that we'll send to TF and which initiates chain + StringBuilder myStrBuilder; + + myStrBuilder = new StringBuilder(); + for (String fileNameEncoded : nspMap.keySet()) { + myStrBuilder.append(hostIP); + myStrBuilder.append(':'); + myStrBuilder.append(hostPort); + myStrBuilder.append('/'); + myStrBuilder.append(extras); + myStrBuilder.append(fileNameEncoded); + myStrBuilder.append('\n'); + } + + byte[] nspListNames = myStrBuilder.toString().getBytes(StandardCharsets.UTF_8); // Follow the + byte[] nspListSize = ByteBuffer.allocate(Integer.BYTES).putInt(nspListNames.length).array(); // defining order + + try { + Socket handShakeSocket = new Socket(InetAddress.getByName(switchIP), 2000); + OutputStream os = handShakeSocket.getOutputStream(); + + os.write(nspListSize); + os.write(nspListNames); + os.flush(); + + handShakeSocket.close(); + } + catch (IOException uhe){ + logPrinter.print("NET: Unable to connect to NS and send files list. Returned:\n\t"+uhe.getMessage(), EMsgType.FAIL); + close(EFileStatus.UNKNOWN); + return null; + } + // Check if we should serve requests + if (this.doNotServeRequests){ + logPrinter.print("NET: List of files transferred. Replies won't be served.", EMsgType.PASS); + close(EFileStatus.UNKNOWN); + return null; + } + logPrinter.print("NET: Initiation files list has been sent to NS.", EMsgType.PASS); + + // Go transfer + Socket clientSocket; + work_routine: + while (true){ + try { + clientSocket = serverSocket.accept(); + BufferedReader br = new BufferedReader( + new InputStreamReader(clientSocket.getInputStream()) + ); + + currSockOS = clientSocket.getOutputStream(); + currSockPW = new PrintWriter(new OutputStreamWriter(currSockOS)); + + String line; + LinkedList tcpPacket = new LinkedList<>(); + + while ((line = br.readLine()) != null) { + //System.out.println(line); // TODO: remove DBG + if (line.trim().isEmpty()) { // If TCP packet is ended + if (handleRequest(tcpPacket)) // Proceed required things + break work_routine; + tcpPacket.clear(); // Clear data and wait for next TCP packet + } + else + tcpPacket.add(line); // Otherwise collect data + } + // and reopen client sock + clientSocket.close(); + } + catch (IOException ioe){ // If server socket closed, then client socket also closed. + break; + } + } + if (!isCancelled()) + close(EFileStatus.UNKNOWN); + return null; + } + + // 200 206 400 (inv range) 404 416 (Range Not Satisfiable ) + /** + * Handle requests + * @return true if failed + * */ + private boolean handleRequest(LinkedList packet){ + //private boolean handleRequest(LinkedList packet, OutputStreamWriter pw){ + File requestedFile; + requestedFile = nspMap.get(packet.get(0).replaceAll("(^[A-z\\s]+/)|(\\s+?.*$)", "")); + if (!requestedFile.exists() || requestedFile.length() == 0){ // well.. tell 404 if file exists with 0 length is against standard, but saves time + currSockPW.write(NETPacket.getCode404()); + currSockPW.flush(); + logPrinter.print("NET: File "+requestedFile.getName()+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL); + logPrinter.update(requestedFile, EFileStatus.FAILED); + return true; + } + if (packet.get(0).startsWith("HEAD")){ + currSockPW.write(NETPacket.getCode200(requestedFile.length())); + currSockPW.flush(); + logPrinter.print("NET: Replying for requested file: "+requestedFile.getName(), EMsgType.INFO); + return false; + } + if (packet.get(0).startsWith("GET")) { + for (String line: packet) { + if (line.toLowerCase().startsWith("range")) { //todo: fix + try { + String[] rangeStr = line.toLowerCase().replaceAll("^range:\\s+?bytes=", "").split("-", 2); + if (!rangeStr[0].isEmpty() && !rangeStr[1].isEmpty()) { // If both ranges defined: Read requested + if (Long.parseLong(rangeStr[0]) > Long.parseLong(rangeStr[1])){ // If start bytes greater then end bytes + currSockPW.write(NETPacket.getCode400()); + currSockPW.flush(); + logPrinter.print("NET: Requested range for "+requestedFile.getName()+" is incorrect. Returning 400", EMsgType.FAIL); + logPrinter.update(requestedFile, EFileStatus.FAILED); + return true; + } + if (writeToSocket(requestedFile, Long.parseLong(rangeStr[0]), Long.parseLong(rangeStr[1]))) // DO WRITE + return true; + + } + else if (!rangeStr[0].isEmpty()) { // If only START defined: Read all + if (writeToSocket(requestedFile, Long.parseLong(rangeStr[0]), requestedFile.length())) // DO WRITE + return true; + } + else if (!rangeStr[1].isEmpty()) { // If only END defined: Try to read last 500 bytes + if (requestedFile.length() > 500){ + if (writeToSocket(requestedFile, requestedFile.length()-500, requestedFile.length())) // DO WRITE + return true; + } + else { // If file smaller than 500 bytes + currSockPW.write(NETPacket.getCode416()); + currSockPW.flush(); + logPrinter.print("NET: File size requested for "+requestedFile.getName()+" while actual size of it: "+requestedFile.length()+". Returning 416", EMsgType.FAIL); + logPrinter.update(requestedFile, EFileStatus.FAILED); + return true; + } + } + else { + currSockPW.write(NETPacket.getCode400()); // If Range not defined: like "Range: bytes=-" + currSockPW.flush(); + logPrinter.print("NET: Requested range for "+requestedFile.getName()+" is incorrect (empty start & end). Returning 400", EMsgType.FAIL); + logPrinter.update(requestedFile, EFileStatus.FAILED); + return true; + } + break; + } + catch (NumberFormatException nfe){ + currSockPW.write(NETPacket.getCode400()); + currSockPW.flush(); + logPrinter.print("NET: Requested range for "+requestedFile.getName()+" has incorrect format. Returning 400\n\t"+nfe.getMessage(), EMsgType.FAIL); + logPrinter.update(requestedFile, EFileStatus.FAILED); + return true; + } + } + } + } + return false; + } + /** + * Send files. + * */ + private boolean writeToSocket(File file, long start, long end){ + currSockPW.write(NETPacket.getCode206(file.length(), start, end)); + currSockPW.flush(); + try{ + long count = end - start; + + RandomAccessFile raf = new RandomAccessFile(file, "r"); + raf.seek(start); + for (int i=0; i <= count; i++) + currSockOS.write(raf.read()); + currSockOS.flush(); + raf.close(); + } + catch (IOException ioe){ + logPrinter.print("IO Exception:\n "+ioe.getMessage(), EMsgType.FAIL); + ioe.printStackTrace(); + return true; + } + return false; + } + /** + * Close when done + * */ + private void close(EFileStatus status){ + if (isCancelled()) + logPrinter.print("NET: Interrupted by user.", EMsgType.INFO); + try { + serverSocket.close(); + logPrinter.print("NET: Closing server socket.", EMsgType.PASS); + } + catch (IOException | NullPointerException ioe){ + logPrinter.print("NET: Closing server socket failed. Sometimes it's not an issue.", EMsgType.WARNING); + } + if (status != null) { + logPrinter.update(nspMap, status); + } + logPrinter.print("\tEnd chain", EMsgType.INFO); + logPrinter.close(); + } +} \ No newline at end of file diff --git a/src/main/java/nsusbloader/NET/NETPacket.java b/src/main/java/nsusbloader/NET/NETPacket.java new file mode 100644 index 0000000..ed4dec3 --- /dev/null +++ b/src/main/java/nsusbloader/NET/NETPacket.java @@ -0,0 +1,64 @@ +package nsusbloader.NET; + +import nsusbloader.NSLMain; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class NETPacket { + private static final String CODE_200 = + "HTTP/1.0 200 OK\r\n" + + "Server: NS-USBloader-"+NSLMain.appVersion+"\r\n" + + "Date: %s\r\n" + + "Content-type: application/octet-stream\r\n" + + "Accept-Ranges: bytes\r\n" + + "Content-Range: bytes 0-%d/%d\r\n" + + "Content-Length: %d\r\n" + + "Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT\r\n\r\n"; + private static final String CODE_206 = + "HTTP/1.0 206 Partial Content\r\n"+ + "Server: NS-USBloader-"+NSLMain.appVersion+"\r\n" + + "Date: %s\r\n" + + "Content-type: application/octet-stream\r\n"+ + "Accept-Ranges: bytes\r\n"+ + "Content-Range: bytes %d-%d/%d\r\n"+ + "Content-Length: %d\r\n"+ + "Last-Modified: Mon, 18 Mar 2019 12:57:33 GMT\r\n\r\n"; + private static final String CODE_400 = + "HTTP/1.0 400 invalid range\r\n"+ + "Server: NS-USBloader-"+NSLMain.appVersion+"\r\n" + + "Date: %s\r\n" + + "Connection: close\r\n"+ + "Content-Type: text/html;charset=utf-8\r\n"+ + "Content-Length: 0\r\n\r\n"; + private static final String CODE_404 = + "HTTP/1.0 404 Not Found\r\n"+ + "Server: NS-USBloader-"+NSLMain.appVersion+"\r\n" + + "Date: %s\r\n" + + "Connection: close\r\n"+ + "Content-Type: text/html;charset=utf-8\r\n"+ + "Content-Length: 0\r\n\r\n"; + private static final String CODE_416 = + "HTTP/1.0 416 Requested Range Not Satisfiable\r\n"+ + "Server: NS-USBloader-"+NSLMain.appVersion+"\r\n" + + "Date: %s\r\n" + + "Connection: close\r\n"+ + "Content-Type: text/html;charset=utf-8\r\n"+ + "Content-Length: 0\r\n\r\n"; + public static String getCode200(long nspFileSize){ + return String.format(CODE_200, ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME), nspFileSize-1, nspFileSize, nspFileSize); + } + public static String getCode206(long nspFileSize, long startPos, long endPos){ + return String.format(CODE_206, ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME), startPos, endPos, nspFileSize, endPos-startPos+1); + } + public static String getCode404(){ + return String.format(CODE_404, ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME)); + } + public static String getCode416(){ + return String.format(CODE_416, ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME)); + } + public static String getCode400(){ + return String.format(CODE_400, ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME)); + } +} diff --git a/src/main/java/nsusbloader/NSLDataTypes/EFileStatus.java b/src/main/java/nsusbloader/NSLDataTypes/EFileStatus.java index 9d75dfd..67b123b 100644 --- a/src/main/java/nsusbloader/NSLDataTypes/EFileStatus.java +++ b/src/main/java/nsusbloader/NSLDataTypes/EFileStatus.java @@ -1,5 +1,5 @@ package nsusbloader.NSLDataTypes; public enum EFileStatus { - UPLOADED, INCORRECT_FILE_FAILED, FAILED, UNKNOWN + UPLOADED, INCORRECT_FILE_FAILED, FAILED, INDETERMINATE, UNKNOWN } diff --git a/src/main/java/nsusbloader/NSLMain.java b/src/main/java/nsusbloader/NSLMain.java index c1b4828..e16d748 100644 --- a/src/main/java/nsusbloader/NSLMain.java +++ b/src/main/java/nsusbloader/NSLMain.java @@ -12,17 +12,14 @@ import java.util.Locale; import java.util.ResourceBundle; public class NSLMain extends Application { - public static final String appVersion = "v0.2.2"; + public static final String appVersion = "v0.3"; @Override public void start(Stage primaryStage) throws Exception{ FXMLLoader loader = new FXMLLoader(getClass().getResource("/NSLMain.fxml")); - ResourceBundle rb; - if (Locale.getDefault().getISO3Language().equals("rus")) - rb = ResourceBundle.getBundle("locale", new Locale("ru")); - else - rb = ResourceBundle.getBundle("locale", new Locale("en")); + Locale userLocale = new Locale(Locale.getDefault().getISO3Language()); // NOTE: user locale based on ISO3 Language codes + ResourceBundle rb = ResourceBundle.getBundle("locale", userLocale); loader.setResources(rb); Parent root = loader.load(); diff --git a/src/main/java/nsusbloader/ServiceWindow.java b/src/main/java/nsusbloader/ServiceWindow.java index 2982201..dfc2b47 100644 --- a/src/main/java/nsusbloader/ServiceWindow.java +++ b/src/main/java/nsusbloader/ServiceWindow.java @@ -10,7 +10,6 @@ public class ServiceWindow { /** * Create window with notification * */ - /* // not used public static void getErrorNotification(String title, String body){ Alert alertBox = new Alert(Alert.AlertType.ERROR); alertBox.setTitle(title); @@ -20,10 +19,9 @@ public class ServiceWindow { alertBox.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alertBox.setResizable(true); // Java bug workaround for JDR11/OpenJFX. TODO: nothing. really. alertBox.setResizable(false); - alertBox.getDialogPane().getStylesheets().add("/res/app.css"); + alertBox.getDialogPane().getStylesheets().add(AppPreferences.getInstance().getTheme()); alertBox.show(); } - */ /** * Create notification window with confirm/deny * */ diff --git a/src/main/java/nsusbloader/PFS/NCAFile.java b/src/main/java/nsusbloader/USB/PFS/NCAFile.java similarity index 97% rename from src/main/java/nsusbloader/PFS/NCAFile.java rename to src/main/java/nsusbloader/USB/PFS/NCAFile.java index ea537ce..9b52e12 100644 --- a/src/main/java/nsusbloader/PFS/NCAFile.java +++ b/src/main/java/nsusbloader/USB/PFS/NCAFile.java @@ -1,4 +1,4 @@ -package nsusbloader.PFS; +package nsusbloader.USB.PFS; import java.nio.ByteBuffer; import java.nio.ByteOrder; diff --git a/src/main/java/nsusbloader/PFS/PFSProvider.java b/src/main/java/nsusbloader/USB/PFS/PFSProvider.java similarity index 70% rename from src/main/java/nsusbloader/PFS/PFSProvider.java rename to src/main/java/nsusbloader/USB/PFS/PFSProvider.java index 6888b80..0ce87ad 100644 --- a/src/main/java/nsusbloader/PFS/PFSProvider.java +++ b/src/main/java/nsusbloader/USB/PFS/PFSProvider.java @@ -1,5 +1,6 @@ -package nsusbloader.PFS; +package nsusbloader.USB.PFS; +import nsusbloader.ModelControllers.LogPrinter; import nsusbloader.NSLDataTypes.EMsgType; import nsusbloader.ServiceWindow; @@ -8,15 +9,14 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.*; -import java.util.concurrent.BlockingQueue; /** * Used in GoldLeaf USB protocol * */ public class PFSProvider { private static final byte[] PFS0 = new byte[]{(byte)0x50, (byte)0x46, (byte)0x53, (byte)0x30}; // PFS0, and what did you think? - - private BlockingQueue msgQueue; + + private LogPrinter logPrinter; private ResourceBundle rb; private RandomAccessFile randAccessFile; @@ -25,20 +25,18 @@ public class PFSProvider { private long bodySize; private int ticketID = -1; - public PFSProvider(File nspFile, BlockingQueue msgQueue){ - this.msgQueue = msgQueue; + public PFSProvider(File nspFile, LogPrinter logPrinter){ + this.logPrinter = logPrinter; try { this.randAccessFile = new RandomAccessFile(nspFile, "r"); nspFileName = nspFile.getName(); } catch (FileNotFoundException fnfe){ - printLog("PFS File not founnd: \n "+fnfe.getMessage(), EMsgType.FAIL); + logPrinter.print("PFS File not founnd: \n "+fnfe.getMessage(), EMsgType.FAIL); nspFileName = null; } - if (Locale.getDefault().getISO3Language().equals("rus")) - rb = ResourceBundle.getBundle("locale", new Locale("ru")); - else - rb = ResourceBundle.getBundle("locale", new Locale("en")); + Locale userLocale = new Locale(Locale.getDefault().getISO3Language()); + rb = ResourceBundle.getBundle("locale", userLocale); } public boolean init() { @@ -48,22 +46,22 @@ public class PFSProvider { int filesCount; int header; - printLog("PFS Start NSP file analyze for ["+nspFileName+"]", EMsgType.INFO); + logPrinter.print("PFS Start NSP file analyze for ["+nspFileName+"]", EMsgType.INFO); try { byte[] fileStartingBytes = new byte[12]; // Read PFS0, files count, header, padding (4 zero bytes) if (randAccessFile.read(fileStartingBytes) == 12) - printLog("PFS Read file starting bytes.", EMsgType.PASS); + logPrinter.print("PFS Read file starting bytes.", EMsgType.PASS); else { - printLog("PFS Read file starting bytes.", EMsgType.FAIL); + logPrinter.print("PFS Read file starting bytes.", EMsgType.FAIL); randAccessFile.close(); return false; } // Check PFS0 if (Arrays.equals(PFS0, Arrays.copyOfRange(fileStartingBytes, 0, 4))) - printLog("PFS Read 'PFS0'.", EMsgType.PASS); + logPrinter.print("PFS Read 'PFS0'.", EMsgType.PASS); else { - printLog("PFS Read 'PFS0'.", EMsgType.WARNING); + logPrinter.print("PFS Read 'PFS0'.", EMsgType.WARNING); if (!ServiceWindow.getConfirmationWindow(nspFileName+"\n"+rb.getString("windowTitleConfirmWrongPFS0"), rb.getString("windowBodyConfirmWrongPFS0"))) { randAccessFile.close(); return false; @@ -72,19 +70,19 @@ public class PFSProvider { // Get files count filesCount = ByteBuffer.wrap(Arrays.copyOfRange(fileStartingBytes, 4, 8)).order(ByteOrder.LITTLE_ENDIAN).getInt(); if (filesCount > 0 ) { - printLog("PFS Read files count [" + filesCount + "]", EMsgType.PASS); + logPrinter.print("PFS Read files count [" + filesCount + "]", EMsgType.PASS); } else { - printLog("PFS Read files count", EMsgType.FAIL); + logPrinter.print("PFS Read files count", EMsgType.FAIL); randAccessFile.close(); return false; } // Get header header = ByteBuffer.wrap(Arrays.copyOfRange(fileStartingBytes, 8, 12)).order(ByteOrder.LITTLE_ENDIAN).getInt(); if (header > 0 ) - printLog("PFS Read header ["+header+"]", EMsgType.PASS); + logPrinter.print("PFS Read header ["+header+"]", EMsgType.PASS); else { - printLog("PFS Read header ", EMsgType.FAIL); + logPrinter.print("PFS Read header ", EMsgType.FAIL); randAccessFile.close(); return false; } @@ -103,10 +101,10 @@ public class PFSProvider { for (int i=0; i= 0?EMsgType.PASS:EMsgType.WARNING); - printLog(" NCA size check: "+nca_size, nca_size >= 0?EMsgType.PASS: EMsgType.WARNING); - printLog(" NCA name offset check: "+nca_name_offset, nca_name_offset >= 0?EMsgType.PASS:EMsgType.WARNING); + logPrinter.print(" Padding check", offset == 0?EMsgType.PASS:EMsgType.WARNING); + logPrinter.print(" NCA offset check: "+nca_offset, nca_offset >= 0?EMsgType.PASS:EMsgType.WARNING); + logPrinter.print(" NCA size check: "+nca_size, nca_size >= 0?EMsgType.PASS: EMsgType.WARNING); + logPrinter.print(" NCA name offset check: "+nca_name_offset, nca_name_offset >= 0?EMsgType.PASS:EMsgType.WARNING); NCAFile ncaFile = new NCAFile(); ncaFile.setNcaOffset(nca_offset); @@ -130,15 +128,15 @@ public class PFSProvider { // Final offset byte[] bufForInt = new byte[4]; if ((randAccessFile.read(bufForInt) == 4) && (Arrays.equals(bufForInt, new byte[4]))) - printLog("PFS Final padding check", EMsgType.PASS); + logPrinter.print("PFS Final padding check", EMsgType.PASS); else - printLog("PFS Final padding check", EMsgType.WARNING); + logPrinter.print("PFS Final padding check", EMsgType.WARNING); // Calculate position including header for body size offset bodySize = randAccessFile.getFilePointer()+header; //********************************************************************************************* // Collect file names from NCAs - printLog("PFS Collecting file names", EMsgType.INFO); + logPrinter.print("PFS Collecting file names", EMsgType.INFO); List ncaFN; // Temporary byte[] b = new byte[1]; // Temporary for (int i=0; i { private final int DEFAULT_INTERFACE = 0; - private BlockingQueue msgQueue; - private BlockingQueue progressQueue; - private HashMap statusMap; // BlockingQueue for literally one object. TODO: read more books ; replace to hashMap + private LogPrinter logPrinter; private EFileStatus status = EFileStatus.FAILED; - private MessagesConsumer msgConsumer; - private HashMap nspMap; private Context contextNS; @@ -52,39 +45,35 @@ public class UsbCommunications extends Task { this.nspMap = new HashMap<>(); for (File f: nspList) nspMap.put(f.getName(), f); - this.msgQueue = new LinkedBlockingQueue<>(); - this.progressQueue = new LinkedBlockingQueue<>(); - this.statusMap = new HashMap<>(); - this.msgConsumer = new MessagesConsumer(this.msgQueue, this.progressQueue, this.statusMap); + this.logPrinter = new LogPrinter(); } @Override protected Void call() { - this.msgConsumer.start(); int result = -9999; - printLog("\tStart chain", EMsgType.INFO); + logPrinter.print("\tStart chain", EMsgType.INFO); // Creating Context required by libusb. Optional. TODO: Consider removing. contextNS = new Context(); result = LibUsb.init(contextNS); if (result != LibUsb.SUCCESS) { - printLog("libusb initialization\n Returned: "+result, EMsgType.FAIL); + logPrinter.print("libusb initialization\n Returned: "+result, EMsgType.FAIL); close(); return null; } else - printLog("libusb initialization", EMsgType.PASS); + logPrinter.print("libusb initialization", EMsgType.PASS); // Searching for NS in devices: obtain list of all devices DeviceList deviceList = new DeviceList(); result = LibUsb.getDeviceList(contextNS, deviceList); if (result < 0) { - printLog("Get device list\n Returned: "+result, EMsgType.FAIL); + logPrinter.print("Get device list\n Returned: "+result, EMsgType.FAIL); close(); return null; } else { - printLog("Get device list", EMsgType.PASS); + logPrinter.print("Get device list", EMsgType.PASS); } // Searching for NS in devices: looking for NS DeviceDescriptor descriptor; @@ -93,14 +82,14 @@ public class UsbCommunications extends Task { descriptor = new DeviceDescriptor(); // mmm.. leave it as is. result = LibUsb.getDeviceDescriptor(device, descriptor); if (result != LibUsb.SUCCESS){ - printLog("Read file descriptors for USB devices\n Returned: "+result, EMsgType.FAIL); + logPrinter.print("Read file descriptors for USB devices\n Returned: "+result, EMsgType.FAIL); LibUsb.freeDeviceList(deviceList, true); close(); return null; } if ((descriptor.idVendor() == 0x057E) && descriptor.idProduct() == 0x3000){ deviceNS = device; - printLog("Read file descriptors for USB devices", EMsgType.PASS); + logPrinter.print("Read file descriptors for USB devices", EMsgType.PASS); break; } } @@ -114,19 +103,17 @@ public class UsbCommunications extends Task { switch (result){ case 0: - System.out.println("SUCCES"); - System.out.println("\n"+configDescriptor.dump()); + logPrinter.print("DBG: getActiveConfigDescriptor\n"+configDescriptor.dump(), EMsgType.PASS); break; case LibUsb.ERROR_NOT_FOUND: - System.out.println("ERROR_NOT_FOUND "+result); + logPrinter.print("DBG: getActiveConfigDescriptor: ERROR_NOT_FOUND", EMsgType.FAIL); break; default: - System.out.println("UNKNOWN "+result); + logPrinter.print("DBG: getActiveConfigDescriptor: "+result, EMsgType.FAIL); break; } - System.out.println(); - //LibUsb.freeConfigDescriptor(configDescriptor); + LibUsb.freeConfigDescriptor(configDescriptor); //*/ /* * So what did we learn? @@ -143,10 +130,10 @@ public class UsbCommunications extends Task { ////////////////////////////////////////// DEBUG INFORMATION END ///////////////////////////////////////////// if (deviceNS != null){ - printLog("NS in connected USB devices found", EMsgType.PASS); + logPrinter.print("NS in connected USB devices found", EMsgType.PASS); } else { - printLog("NS in connected USB devices not found", EMsgType.FAIL); + logPrinter.print("NS in connected USB devices not found", EMsgType.FAIL); close(); return null; } @@ -154,27 +141,16 @@ public class UsbCommunications extends Task { handlerNS = new DeviceHandle(); result = LibUsb.open(deviceNS, handlerNS); if (result != LibUsb.SUCCESS) { - switch (result){ - case LibUsb.ERROR_ACCESS: - printLog("Open NS USB device\n Returned: ERROR_ACCESS", EMsgType.FAIL); - printLog("Double check that you have administrator privileges (you're 'root') or check 'udev' rules set for this user (linux only)!", EMsgType.INFO); - break; - case LibUsb.ERROR_NO_MEM: - printLog("Open NS USB device\n Returned: ERROR_NO_MEM", EMsgType.FAIL); - break; - case LibUsb.ERROR_NO_DEVICE: - printLog("Open NS USB device\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - default: - printLog("Open NS USB device\n Returned:" + result, EMsgType.FAIL); - } + logPrinter.print("Open NS USB device\n Returned: "+UsbErrorCodes.getErrCode(result), EMsgType.FAIL); + if (result == LibUsb.ERROR_ACCESS) + logPrinter.print("Double check that you have administrator privileges (you're 'root') or check 'udev' rules set for this user (linux only)!", EMsgType.INFO); close(); return null; } else - printLog("Open NS USB device", EMsgType.PASS); + logPrinter.print("Open NS USB device", EMsgType.PASS); - printLog("Free device list", EMsgType.INFO); + logPrinter.print("Free device list", EMsgType.INFO); LibUsb.freeDeviceList(deviceList, true); // DO some stuff to connected NS @@ -182,90 +158,55 @@ public class UsbCommunications extends Task { boolean canDetach = LibUsb.hasCapability(LibUsb.CAP_SUPPORTS_DETACH_KERNEL_DRIVER); // if cant, it's windows ot old lib if (canDetach){ int usedByKernel = LibUsb.kernelDriverActive(handlerNS, DEFAULT_INTERFACE); - if (usedByKernel == LibUsb.SUCCESS){ - printLog("Can proceed with libusb driver", EMsgType.PASS); // we're good - } - else { - switch (usedByKernel){ - case 1: // used by kernel - result = LibUsb.detachKernelDriver(handlerNS, DEFAULT_INTERFACE); - printLog("Detach kernel required", EMsgType.INFO); - if (result != 0) { - switch (result){ - case LibUsb.ERROR_NOT_FOUND: - printLog("Detach kernel\n Returned: ERROR_NOT_FOUND", EMsgType.FAIL); - break; - case LibUsb.ERROR_INVALID_PARAM: - printLog("Detach kernel\n Returned: ERROR_INVALID_PARAM", EMsgType.FAIL); - break; - case LibUsb.ERROR_NO_DEVICE: - printLog("Detach kernel\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - case LibUsb.ERROR_NOT_SUPPORTED: // Should never appear only if libusb buggy - printLog("Detach kernel\n Returned: ERROR_NOT_SUPPORTED", EMsgType.FAIL); - break; - default: - printLog("Detach kernel\n Returned: " + result, EMsgType.FAIL); - break; - } - close(); - return null; - } - else { - printLog("Detach kernel", EMsgType.PASS); - break; - } - case LibUsb.ERROR_NO_DEVICE: - printLog("Can't proceed with libusb driver\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - case LibUsb.ERROR_NOT_SUPPORTED: - printLog("Can't proceed with libusb driver\n Returned: ERROR_NOT_SUPPORTED", EMsgType.FAIL); - break; - default: - printLog("Can't proceed with libusb driver\n Returned: "+result, EMsgType.FAIL); - } - } + if (usedByKernel == LibUsb.SUCCESS){ + logPrinter.print("Can proceed with libusb driver", EMsgType.PASS); // we're good + } + else if (usedByKernel == 1) { // used by kernel + result = LibUsb.detachKernelDriver(handlerNS, DEFAULT_INTERFACE); + logPrinter.print("Detach kernel required", EMsgType.INFO); + if (result != 0) { + logPrinter.print("Detach kernel\n Returned: " + UsbErrorCodes.getErrCode(result), EMsgType.FAIL); + close(); + return null; + } else + logPrinter.print("Detach kernel", EMsgType.PASS); + } + else + logPrinter.print("Can't proceed with libusb driver\n Returned: "+UsbErrorCodes.getErrCode(usedByKernel), EMsgType.FAIL); } else - printLog("libusb doesn't supports function 'CAP_SUPPORTS_DETACH_KERNEL_DRIVER'. Proceeding.", EMsgType.WARNING); - + logPrinter.print("libusb doesn't support function 'CAP_SUPPORTS_DETACH_KERNEL_DRIVER'. It's normal. Proceeding.", EMsgType.WARNING); + /* + // Reset device + result = LibUsb.resetDevice(handlerNS); + if (result == 0) + logPrinter.print("Reset device", EMsgType.PASS); + else { + logPrinter.print("Reset device returned: " + result, EMsgType.FAIL); + updateAndClose(); + return null; + } + */ // Set configuration (soft reset if needed) result = LibUsb.setConfiguration(handlerNS, 1); // 1 - configuration all we need if (result != LibUsb.SUCCESS){ - switch (result){ - case LibUsb.ERROR_NOT_FOUND: - printLog("Set active configuration to device\n Returned: ERROR_NOT_FOUND", EMsgType.FAIL); - break; - case LibUsb.ERROR_BUSY: - printLog("Set active configuration to device\n Returned: ERROR_BUSY", EMsgType.FAIL); - break; - case LibUsb.ERROR_NO_DEVICE: - printLog("Set active configuration to device\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - case LibUsb.ERROR_INVALID_PARAM: - printLog("Set active configuration to device\n Returned: ERROR_INVALID_PARAM", EMsgType.FAIL); - break; - default: - printLog("Set active configuration to device\n Returned: "+result, EMsgType.FAIL); - break; - } + logPrinter.print("Set active configuration to device\n Returned: "+UsbErrorCodes.getErrCode(result), EMsgType.FAIL); close(); return null; } else { - printLog("Set active configuration to device.", EMsgType.PASS); + logPrinter.print("Set active configuration to device.", EMsgType.PASS); } - // Claim interface result = LibUsb.claimInterface(handlerNS, DEFAULT_INTERFACE); if (result != LibUsb.SUCCESS) { - printLog("Claim interface\n Returned: "+result, EMsgType.FAIL); + logPrinter.print("Claim interface\n Returned: "+UsbErrorCodes.getErrCode(result), EMsgType.FAIL); close(); return null; } else - printLog("Claim interface", EMsgType.PASS); + logPrinter.print("Claim interface", EMsgType.PASS); //-------------------------------------------------------------------------------------------------------------- if (protocol.equals("TinFoil")) { @@ -275,7 +216,6 @@ public class UsbCommunications extends Task { } close(); - printLog("\tEnd chain", EMsgType.INFO); return null; } /** @@ -297,11 +237,11 @@ public class UsbCommunications extends Task { // Send list of NSP files: // Proceed "TUL0" if (!writeToUsb("TUL0".getBytes(StandardCharsets.US_ASCII))) { // new byte[]{(byte) 0x54, (byte) 0x55, (byte) 0x76, (byte) 0x30} - printLog("TF Send list of files: handshake", EMsgType.FAIL); + logPrinter.print("TF Send list of files: handshake", EMsgType.FAIL); return false; } else - printLog("TF Send list of files: handshake", EMsgType.PASS); + logPrinter.print("TF Send list of files: handshake", EMsgType.PASS); //Collect file names StringBuilder nspListNamesBuilder = new StringBuilder(); // Add every title to one stringBuilder for(String nspFileName: nspMap.keySet()) { @@ -316,24 +256,24 @@ public class UsbCommunications extends Task { //byteBuffer.reset(); // Sending NSP list - printLog("TF Send list of files", EMsgType.INFO); + logPrinter.print("TF Send list of files", EMsgType.INFO); if (!writeToUsb(nspListSize)) { // size of the list we're going to transfer goes... - printLog(" [send list length]", EMsgType.FAIL); + logPrinter.print(" [send list length]", EMsgType.FAIL); return false; } - printLog(" [send list length]", EMsgType.PASS); + logPrinter.print(" [send list length]", EMsgType.PASS); if (!writeToUsb(new byte[8])) { // 8 zero bytes goes... - printLog(" [send padding]", EMsgType.FAIL); + logPrinter.print(" [send padding]", EMsgType.FAIL); return false; } - printLog(" [send padding]", EMsgType.PASS); + logPrinter.print(" [send padding]", EMsgType.PASS); if (!writeToUsb(nspListNames)) { // list of the names goes... - printLog(" [send list itself]", EMsgType.FAIL); + logPrinter.print(" [send list itself]", EMsgType.FAIL); return false; } - printLog(" [send list itself]", EMsgType.PASS); + logPrinter.print(" [send list itself]", EMsgType.PASS); return true; } @@ -341,7 +281,7 @@ public class UsbCommunications extends Task { * After we sent commands to NS, this chain starts * */ private boolean proceedCommands(){ - printLog("TF Awaiting for NS commands.", EMsgType.INFO); + logPrinter.print("TF Awaiting for NS commands.", EMsgType.INFO); /* byte[] magic = new byte[4]; ByteBuffer bb = StandardCharsets.UTF_8.encode("TUC0").rewind().get(magic); @@ -363,11 +303,11 @@ public class UsbCommunications extends Task { // 8th to 12th(explicits) bytes in returned data stands for command ID as unsigned integer (Little-endian). Actually, we have to compare arrays here, but in real world it can't be greater then 0/1/2, thus: // BTW also protocol specifies 4th byte to be 0x00 kinda indicating that that this command is valid. But, as you may see, never happens other situation when it's not = 0. if (receivedArray[8] == 0x00){ //0x00 - exit - printLog("TF Received EXIT command. Terminating.", EMsgType.PASS); + logPrinter.print("TF Received EXIT command. Terminating.", EMsgType.PASS); return true; // All interaction with USB device should be ended (expected); } else if ((receivedArray[8] == 0x01) || (receivedArray[8] == 0x02)){ //0x01 - file range; 0x02 unknown bug on backend side (dirty hack). - printLog("TF Received FILE_RANGE command. Proceeding: [0x0"+receivedArray[8]+"]", EMsgType.PASS); + logPrinter.print("TF Received FILE_RANGE command. Proceeding: [0x0"+receivedArray[8]+"]", EMsgType.PASS); /*// We can get in this pocket a length of file name (+32). Why +32? I dunno man.. Do we need this? Definitely not. This app can live without it. long receivedSize = ByteBuffer.wrap(Arrays.copyOfRange(receivedArray, 12,20)).order(ByteOrder.LITTLE_ENDIAN).getLong(); logsArea.appendText("[V] Received FILE_RANGE command. Size: "+Long.toUnsignedString(receivedSize)+"\n"); // this shit returns string that will be chosen next '+32'. And, BTW, can't be greater then 512 @@ -407,7 +347,7 @@ public class UsbCommunications extends Task { return false; String receivedRequestedNSP = new String(receivedArray, StandardCharsets.UTF_8); - printLog("TF Reply to requested file: "+receivedRequestedNSP + logPrinter.print("TF Reply to requested file: "+receivedRequestedNSP +"\n Range Size: "+receivedRangeSize +"\n Range Offset: "+receivedRangeOffset, EMsgType.INFO); @@ -421,7 +361,7 @@ public class UsbCommunications extends Task { byte[] bufferCurrent ;//= new byte[1048576]; // eq. Allocate 1mb int bufferLength; if (bufferedInStream.skip(receivedRangeOffset) != receivedRangeOffset){ - printLog("TF Requested skip is out of file size. Nothing to transmit.", EMsgType.FAIL); + logPrinter.print("TF Requested skip is out of file size. Nothing to transmit.", EMsgType.FAIL); return false; } @@ -439,11 +379,11 @@ public class UsbCommunications extends Task { if (isProgessBarInitiated){ try { if (currentOffset+readPice == receivedRangeOffset){ - progressQueue.put(1.0); + logPrinter.updateProgress(1.0); isProgessBarInitiated = false; } else - progressQueue.put((currentOffset+readPice)/(receivedRangeSize/100.0) / 100.0); + logPrinter.updateProgress((currentOffset+readPice)/(receivedRangeSize/100.0) / 100.0); }catch (InterruptedException ie){ getException().printStackTrace(); // TODO: Do something with this } @@ -461,28 +401,28 @@ public class UsbCommunications extends Task { if (bufferLength != -1){ //write to USB if (!writeToUsb(bufferCurrent)) { - printLog("TF Failure during NSP transmission.", EMsgType.FAIL); + logPrinter.print("TF Failure during NSP transmission.", EMsgType.FAIL); return false; } currentOffset += readPice; } else { - printLog("TF Reading of stream suddenly ended.", EMsgType.WARNING); + logPrinter.print("TF Reading of stream suddenly ended.", EMsgType.WARNING); return false; } } bufferedInStream.close(); } catch (FileNotFoundException fnfe){ - printLog("TF FileNotFoundException:\n "+fnfe.getMessage(), EMsgType.FAIL); + logPrinter.print("TF FileNotFoundException:\n "+fnfe.getMessage(), EMsgType.FAIL); fnfe.printStackTrace(); return false; } catch (IOException ioe){ - printLog("TF IOException:\n "+ioe.getMessage(), EMsgType.FAIL); + logPrinter.print("TF IOException:\n "+ioe.getMessage(), EMsgType.FAIL); ioe.printStackTrace(); return false; } catch (ArithmeticException ae){ - printLog("TF ArithmeticException (can't cast end offset minus current to 'integer'):\n "+ae.getMessage(), EMsgType.FAIL); + logPrinter.print("TF ArithmeticException (can't cast end offset minus current to 'integer'):\n "+ae.getMessage(), EMsgType.FAIL); ae.printStackTrace(); return false; } @@ -495,26 +435,26 @@ public class UsbCommunications extends Task { * false if failed * */ private boolean sendResponse(byte[] rangeSize){ // This method as separate function itself for application needed as a cookie in the middle of desert. - printLog("TF Sending response", EMsgType.INFO); + logPrinter.print("TF Sending response", EMsgType.INFO); if (!writeToUsb(new byte[] { (byte) 0x54, (byte) 0x55, (byte) 0x43, (byte) 0x30, // 'TUC0' (byte) 0x01, // CMD_TYPE_RESPONSE = 1 (byte) 0x00, (byte) 0x00, (byte) 0x00, // kinda padding. Guys, didn't you want to use integer value for CMD semantic? (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00} ) // Send integer value of '1' in Little-endian format. ){ - printLog(" [1/3]", EMsgType.FAIL); + logPrinter.print(" [1/3]", EMsgType.FAIL); return false; } - printLog(" [1/3]", EMsgType.PASS); + logPrinter.print(" [1/3]", EMsgType.PASS); if(!writeToUsb(rangeSize)) { // Send EXACTLY what has been received - printLog(" [2/3]", EMsgType.FAIL); + logPrinter.print(" [2/3]", EMsgType.FAIL); return false; } - printLog(" [2/3]", EMsgType.PASS); + logPrinter.print(" [2/3]", EMsgType.PASS); if(!writeToUsb(new byte[12])) { // kinda another one padding - printLog(" [3/3]", EMsgType.FAIL); + logPrinter.print(" [3/3]", EMsgType.FAIL); return false; } - printLog(" [3/3]", EMsgType.PASS); + logPrinter.print(" [3/3]", EMsgType.PASS); return true; } @@ -535,14 +475,14 @@ public class UsbCommunications extends Task { private final byte[] CMD_Finish = new byte[]{0x47, 0x4c, 0x55, 0x43, 0x07, 0x00, 0x00, 0x00}; GoldLeaf(){ - printLog("===========================================================================", EMsgType.INFO); - PFSProvider pfsElement = new PFSProvider(nspMap.get(nspMap.keySet().toArray()[0]), msgQueue); + logPrinter.print("===========================================================================", EMsgType.INFO); + PFSProvider pfsElement = new PFSProvider(nspMap.get(nspMap.keySet().toArray()[0]), logPrinter); if (!pfsElement.init()) { - printLog("GL File provided have incorrect structure and won't be uploaded", EMsgType.FAIL); + logPrinter.print("GL File provided have incorrect structure and won't be uploaded", EMsgType.FAIL); status = EFileStatus.INCORRECT_FILE_FAILED; return; } - printLog("GL File structure validated and it will be uploaded", EMsgType.PASS); + logPrinter.print("GL File structure validated and it will be uploaded", EMsgType.PASS); if (initGoldLeafProtocol(pfsElement)) status = EFileStatus.UPLOADED; // else - no change status that is already set to FAILED @@ -553,9 +493,9 @@ public class UsbCommunications extends Task { // Go connect to GoldLeaf if (writeToUsb(CMD_ConnectionRequest)) - printLog("GL Initiating GoldLeaf connection", EMsgType.PASS); + logPrinter.print("GL Initiating GoldLeaf connection", EMsgType.PASS); else { - printLog("GL Initiating GoldLeaf connection", EMsgType.FAIL); + logPrinter.print("GL Initiating GoldLeaf connection", EMsgType.FAIL); return false; } while (true) { @@ -588,7 +528,7 @@ public class UsbCommunications extends Task { continue; } if (Arrays.equals(readByte, CMD_Finish)) { - printLog("GL Closing GoldLeaf connection: Transfer successful.", EMsgType.PASS); + logPrinter.print("GL Closing GoldLeaf connection: Transfer successful.", EMsgType.PASS); break; } } @@ -598,24 +538,24 @@ public class UsbCommunications extends Task { * ConnectionResponse command handler * */ private boolean handleConnectionResponse(PFSProvider pfsElement){ - printLog("GL 'ConnectionResonse' command:", EMsgType.INFO); + logPrinter.print("GL 'ConnectionResponse' command:", EMsgType.INFO); if (!writeToUsb(CMD_NSPName)) { - printLog(" [1/3]", EMsgType.FAIL); + logPrinter.print(" [1/3]", EMsgType.FAIL); return false; } - printLog(" [1/3]", EMsgType.PASS); + logPrinter.print(" [1/3]", EMsgType.PASS); if (!writeToUsb(pfsElement.getBytesNspFileNameLength())) { - printLog(" [2/3]", EMsgType.FAIL); + logPrinter.print(" [2/3]", EMsgType.FAIL); return false; } - printLog(" [2/3]", EMsgType.PASS); + logPrinter.print(" [2/3]", EMsgType.PASS); if (!writeToUsb(pfsElement.getBytesNspFileName())) { - printLog(" [3/3]", EMsgType.FAIL); + logPrinter.print(" [3/3]", EMsgType.FAIL); return false; } - printLog(" [3/3]", EMsgType.PASS); + logPrinter.print(" [3/3]", EMsgType.PASS); return true; } @@ -623,43 +563,43 @@ public class UsbCommunications extends Task { * Start command handler * */ private boolean handleStart(PFSProvider pfsElement){ - printLog("GL Handle 'Start' command:", EMsgType.INFO); + logPrinter.print("GL Handle 'Start' command:", EMsgType.INFO); if (!writeToUsb(CMD_NSPData)) { - printLog(" [Send command]", EMsgType.FAIL); + logPrinter.print(" [Send command]", EMsgType.FAIL); return false; } - printLog(" [Send command]", EMsgType.PASS); + logPrinter.print(" [Send command]", EMsgType.PASS); if (!writeToUsb(pfsElement.getBytesCountOfNca())) { - printLog(" [Send length]", EMsgType.FAIL); + logPrinter.print(" [Send length]", EMsgType.FAIL); return false; } - printLog(" [Send length]", EMsgType.PASS); + logPrinter.print(" [Send length]", EMsgType.PASS); int ncaCount = pfsElement.getIntCountOfNca(); - printLog(" [Send information for "+ncaCount+" files]", EMsgType.INFO); + logPrinter.print(" [Send information for "+ncaCount+" files]", EMsgType.INFO); for (int i = 0; i < ncaCount; i++){ if (!writeToUsb(pfsElement.getNca(i).getNcaFileNameLength())) { - printLog(" [1/4] File #"+i, EMsgType.FAIL); + logPrinter.print(" [1/4] File #"+i, EMsgType.FAIL); return false; } - printLog(" [1/4] File #"+i, EMsgType.PASS); + logPrinter.print(" [1/4] File #"+i, EMsgType.PASS); if (!writeToUsb(pfsElement.getNca(i).getNcaFileName())) { - printLog(" [2/4] File #"+i, EMsgType.FAIL); + logPrinter.print(" [2/4] File #"+i, EMsgType.FAIL); return false; } - printLog(" [2/4] File #"+i, EMsgType.PASS); + logPrinter.print(" [2/4] File #"+i, EMsgType.PASS); if (!writeToUsb(ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(pfsElement.getBodySize()+pfsElement.getNca(i).getNcaOffset()).array())) { // offset. real. - printLog(" [2/4] File #"+i, EMsgType.FAIL); + logPrinter.print(" [2/4] File #"+i, EMsgType.FAIL); return false; } - printLog(" [3/4] File #"+i, EMsgType.PASS); + logPrinter.print(" [3/4] File #"+i, EMsgType.PASS); if (!writeToUsb(ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(pfsElement.getNca(i).getNcaSize()).array())) { // size - printLog(" [4/4] File #"+i, EMsgType.FAIL); + logPrinter.print(" [4/4] File #"+i, EMsgType.FAIL); return false; } - printLog(" [4/4] File #"+i, EMsgType.PASS); + logPrinter.print(" [4/4] File #"+i, EMsgType.PASS); } return true; } @@ -672,18 +612,18 @@ public class UsbCommunications extends Task { int requestedNcaID; boolean isProgessBarInitiated = false; if (isItRawRequest) { - printLog("GL Handle 'Content' command", EMsgType.INFO); + logPrinter.print("GL Handle 'Content' command", EMsgType.INFO); byte[] readByte = readFromUsb(); if (readByte == null || readByte.length != 4) { - printLog(" [Read requested ID]", EMsgType.FAIL); + logPrinter.print(" [Read requested ID]", EMsgType.FAIL); return false; } requestedNcaID = ByteBuffer.wrap(readByte).order(ByteOrder.LITTLE_ENDIAN).getInt(); - printLog(" [Read requested ID = "+requestedNcaID+" ]", EMsgType.PASS); + logPrinter.print(" [Read requested ID = "+requestedNcaID+" ]", EMsgType.PASS); } else { requestedNcaID = pfsElement.getNcaTicketID(); - printLog("GL Handle 'Ticket' command (ID = "+requestedNcaID+" )", EMsgType.INFO); + logPrinter.print("GL Handle 'Ticket' command (ID = "+requestedNcaID+" )", EMsgType.INFO); } long realNcaOffset = pfsElement.getNca(requestedNcaID).getNcaOffset()+pfsElement.getBodySize(); @@ -716,11 +656,11 @@ public class UsbCommunications extends Task { if (isProgessBarInitiated){ try { if (readFrom+readPice == realNcaSize){ - progressQueue.put(1.0); + logPrinter.updateProgress(1.0); isProgessBarInitiated = false; } else - progressQueue.put((readFrom+readPice)/(realNcaSize/100.0) / 100.0); + logPrinter.updateProgress((readFrom+readPice)/(realNcaSize/100.0) / 100.0); }catch (InterruptedException ie){ getException().printStackTrace(); // TODO: Do something with this } @@ -735,7 +675,7 @@ public class UsbCommunications extends Task { bufferedInStream.close(); } catch (IOException ioe){ - printLog(" Failed to read NCA ID "+requestedNcaID+". IO Exception:\n "+ioe.getMessage(), EMsgType.FAIL); + logPrinter.print(" Failed to read NCA ID "+requestedNcaID+". IO Exception:\n "+ioe.getMessage(), EMsgType.FAIL); ioe.printStackTrace(); return false; } @@ -747,30 +687,29 @@ public class UsbCommunications extends Task { * Correct exit * */ private void close(){ - // close handler in the end + // Close handler in the end if (handlerNS != null) { // Try to release interface int result = LibUsb.releaseInterface(handlerNS, DEFAULT_INTERFACE); if (result != LibUsb.SUCCESS) - printLog("Release interface\n Returned: "+result+" (sometimes it's not an issue)", EMsgType.WARNING); + logPrinter.print("Release interface\n Returned: "+result+" (sometimes it's not an issue)", EMsgType.WARNING); else - printLog("Release interface", EMsgType.PASS); + logPrinter.print("Release interface", EMsgType.PASS); LibUsb.close(handlerNS); - printLog("Requested handler close", EMsgType.INFO); + logPrinter.print("Requested handler updateAndClose", EMsgType.INFO); } - // close context in the end + // Close context in the end if (contextNS != null) { LibUsb.exit(contextNS); - printLog("Requested context close", EMsgType.INFO); + logPrinter.print("Requested context updateAndClose", EMsgType.INFO); } - // Report status - for (String fileName: nspMap.keySet()) - statusMap.put(fileName, status); - - msgConsumer.interrupt(); + // Report status and close + logPrinter.update(nspMap, status); + logPrinter.print("\tEnd chain", EMsgType.INFO); + logPrinter.close(); } /** * Sending any byte array to USB device @@ -785,27 +724,12 @@ public class UsbCommunications extends Task { int result; result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 0); // last one is TIMEOUT. 0 stands for unlimited. Endpoint OUT = 0x01 if (result != LibUsb.SUCCESS){ - switch (result){ - case LibUsb.ERROR_TIMEOUT: - printLog("Data transfer (write) issue\n Returned: ERROR_TIMEOUT", EMsgType.FAIL); - break; - case LibUsb.ERROR_PIPE: //WUT?? I dunno man looks overkill in here.. - printLog("Data transfer (write) issue\n Returned: ERROR_PIPE", EMsgType.FAIL); - break; - case LibUsb.ERROR_OVERFLOW: - printLog("Data transfer (write) issue\n Returned: ERROR_OVERFLOW", EMsgType.FAIL); - break; - case LibUsb.ERROR_NO_DEVICE: - printLog("Data transfer (write) issue\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - default: - printLog("Data transfer (write) issue\n Returned: "+result, EMsgType.FAIL); - } - printLog("Execution stopped", EMsgType.FAIL); + logPrinter.print("Data transfer (write) issue\n Returned: "+ UsbErrorCodes.getErrCode(result), EMsgType.FAIL); + logPrinter.print("Execution stopped", EMsgType.FAIL); return false; }else { if (writeBufTransferred.get() != message.length){ - printLog("Data transfer (write) issue\n Requested: "+message.length+"\n Transferred: "+writeBufTransferred.get(), EMsgType.FAIL); + logPrinter.print("Data transfer (write) issue\n Requested: "+message.length+"\n Transferred: "+writeBufTransferred.get(), EMsgType.FAIL); return false; } else { @@ -827,26 +751,8 @@ public class UsbCommunications extends Task { result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 0); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81 if (result != LibUsb.SUCCESS){ - switch (result){ - case LibUsb.ERROR_TIMEOUT: - printLog("Data transfer (read) issue\n Returned: ERROR_TIMEOUT", EMsgType.FAIL); - break; - case LibUsb.ERROR_PIPE: //WUT?? I dunno man looks overkill in here.. - printLog("Data transfer (read) issue\n Returned: ERROR_PIPE", EMsgType.FAIL); - break; - case LibUsb.ERROR_OVERFLOW: - printLog("Data transfer (read) issue\n Returned: ERROR_OVERFLOW", EMsgType.FAIL); - break; - case LibUsb.ERROR_NO_DEVICE: - printLog("Data transfer (read) issue\n Returned: ERROR_NO_DEVICE", EMsgType.FAIL); - break; - case LibUsb.ERROR_IO: - printLog("Data transfer (read) issue\n Returned: ERROR_IO", EMsgType.FAIL); - break; - default: - printLog("Data transfer (read) issue\n Returned: "+result, EMsgType.FAIL); - } - printLog("Execution stopped", EMsgType.FAIL); + logPrinter.print("Data transfer (read) issue\n Returned: "+UsbErrorCodes.getErrCode(result), EMsgType.FAIL); + logPrinter.print("Execution stopped", EMsgType.FAIL); return null; } else { int trans = readBufTransferred.get(); @@ -858,30 +764,4 @@ public class UsbCommunications extends Task { return receivedBytes; } } - - /** - * This is what will print to textArea of the application. - * */ - private void printLog(String message, EMsgType type){ - try { - switch (type){ - case PASS: - msgQueue.put("[ PASS ] "+message+"\n"); - break; - case FAIL: - msgQueue.put("[ FAIL ] "+message+"\n"); - break; - case INFO: - msgQueue.put("[ INFO ] "+message+"\n"); - break; - case WARNING: - msgQueue.put("[ WARN ] "+message+"\n"); - break; - default: - msgQueue.put(message); - } - }catch (InterruptedException ie){ - ie.printStackTrace(); - } - } } \ No newline at end of file diff --git a/src/main/java/nsusbloader/USB/UsbErrorCodes.java b/src/main/java/nsusbloader/USB/UsbErrorCodes.java new file mode 100644 index 0000000..3c7ffde --- /dev/null +++ b/src/main/java/nsusbloader/USB/UsbErrorCodes.java @@ -0,0 +1,38 @@ +package nsusbloader.USB; + +import org.usb4java.LibUsb; + +class UsbErrorCodes { + static String getErrCode(int value){ + switch (value){ + case LibUsb.ERROR_ACCESS: + return "ERROR_ACCESS"; + case LibUsb.ERROR_BUSY: + return "ERROR_BUSY"; + case LibUsb.ERROR_INTERRUPTED: + return "ERROR_INTERRUPTED"; + case LibUsb.ERROR_INVALID_PARAM: + return "ERROR_INVALID_PARAM"; + case LibUsb.ERROR_IO: + return "ERROR_IO"; + case LibUsb.ERROR_NO_DEVICE: + return "ERROR_NO_DEVICE"; + case LibUsb.ERROR_NO_MEM: + return "ERROR_NO_MEM"; + case LibUsb.ERROR_NOT_FOUND: + return "ERROR_NOT_FOUND"; + case LibUsb.ERROR_NOT_SUPPORTED: + return "ERROR_NOT_SUPPORTED"; + case LibUsb.ERROR_OTHER: + return "ERROR_OTHER"; + case LibUsb.ERROR_OVERFLOW: + return "ERROR_OVERFLOW"; + case LibUsb.ERROR_PIPE: + return "ERROR_PIPE"; + case LibUsb.ERROR_TIMEOUT: + return "ERROR_TIMEOUT"; + default: + return Integer.toString(value); + } + } +} diff --git a/src/main/resources/NSLMain.fxml b/src/main/resources/NSLMain.fxml index ae1ddba..e4b7c8b 100644 --- a/src/main/resources/NSLMain.fxml +++ b/src/main/resources/NSLMain.fxml @@ -3,10 +3,12 @@ + + @@ -17,7 +19,7 @@ - + @@ -30,6 +32,9 @@ + +