Skip to content

Commit 267ffcf

Browse files
committed
Add updated brazilian portuguese translation by @almircanella! #64
Refactor NETCommunications. Not it's readable :D A lot of small changes, code refactoring, updates and fixes.
1 parent 96e8505 commit 267ffcf

22 files changed

+553
-522
lines changed

src/main/java/nsusbloader/COM/NET/NETCommunications.java

Lines changed: 245 additions & 415 deletions
Large diffs are not rendered by default.
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/*
2+
Copyright 2019-2020 Dmitry Isaenko
3+
4+
This file is part of NS-USBloader.
5+
6+
NS-USBloader is free software: you can redistribute it and/or modify
7+
it under the terms of the GNU General Public License as published by
8+
the Free Software Foundation, either version 3 of the License, or
9+
(at your option) any later version.
10+
11+
NS-USBloader is distributed in the hope that it will be useful,
12+
but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
GNU General Public License for more details.
15+
16+
You should have received a copy of the GNU General Public License
17+
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
18+
*/
19+
package nsusbloader.COM.NET;
20+
21+
import nsusbloader.ModelControllers.ILogPrinter;
22+
import nsusbloader.NSLDataTypes.EMsgType;
23+
24+
import java.io.File;
25+
import java.io.FileNotFoundException;
26+
import java.io.IOException;
27+
import java.io.UnsupportedEncodingException;
28+
import java.net.*;
29+
import java.util.*;
30+
31+
public class NetworkSetupValidator {
32+
33+
private String hostIP;
34+
private int hostPort;
35+
private final HashMap<String, UniFile> files;
36+
private ServerSocket serverSocket;
37+
private final boolean valid;
38+
private final ILogPrinter logPrinter;
39+
40+
private final boolean doNotServe;
41+
42+
NetworkSetupValidator(List<File> filesList,
43+
boolean doNotServe,
44+
String hostIP,
45+
String hostPortNum,
46+
ILogPrinter logPrinter) {
47+
this.files = new HashMap<>();
48+
this.logPrinter = logPrinter;
49+
this.doNotServe = doNotServe;
50+
51+
try {
52+
validateFiles(filesList);
53+
encodeAndAddFilesToMap(filesList);
54+
resolveIp(hostIP);
55+
resolvePort(hostPortNum);
56+
}
57+
catch (Exception e){
58+
logPrinter.print(e.getMessage(), EMsgType.FAIL);
59+
valid = false;
60+
return;
61+
}
62+
valid = true;
63+
}
64+
65+
private void validateFiles(List<File> filesList) {
66+
filesList.removeIf(f -> {
67+
if (f.isFile())
68+
return false;
69+
70+
File[] subFiles = f.listFiles((file, name) -> name.matches("[0-9]{2}"));
71+
72+
if (subFiles == null || subFiles.length == 0) {
73+
logPrinter.print("NET: Exclude folder: " + f.getName(), EMsgType.WARNING);
74+
return true;
75+
}
76+
77+
Arrays.sort(subFiles, Comparator.comparingInt(file -> Integer.parseInt(file.getName())));
78+
79+
for (int i = subFiles.length - 2; i > 0 ; i--){
80+
if (subFiles[i].length() < subFiles[i-1].length()) {
81+
logPrinter.print("NET: Exclude split file: "+f.getName()+
82+
"\n Chunk sizes of the split file are not the same, but has to be.", EMsgType.WARNING);
83+
return true;
84+
}
85+
}
86+
return false;
87+
});
88+
}
89+
90+
private void encodeAndAddFilesToMap(List<File> filesList) throws UnsupportedEncodingException, FileNotFoundException {
91+
for (File file : filesList){
92+
String encodedName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20"); // replace '+' to '%20'
93+
UniFile uniFile = new UniFile(file);
94+
files.put(encodedName, uniFile);
95+
}
96+
97+
if (files.size() == 0) {
98+
throw new FileNotFoundException("NET: No files to send.");
99+
}
100+
}
101+
102+
private void resolveIp(String hostIPaddr) throws IOException{
103+
if (! hostIPaddr.isEmpty()){
104+
this.hostIP = hostIPaddr;
105+
logPrinter.print("NET: Host IP defined as: " + hostIP, EMsgType.PASS);
106+
return;
107+
}
108+
109+
if (findIpUsingHost("google.com"))
110+
return;
111+
112+
if (findIpUsingHost("people.com.cn"))
113+
return;
114+
115+
throw new IOException("Try using 'Expert mode' and set IP manually. " + getAvaliableIpExamples());
116+
}
117+
118+
private boolean findIpUsingHost(String host) {
119+
try {
120+
Socket scoketK;
121+
scoketK = new Socket();
122+
scoketK.connect(new InetSocketAddress(host, 80));
123+
hostIP = scoketK.getLocalAddress().getHostAddress();
124+
scoketK.close();
125+
126+
logPrinter.print("NET: Host IP detected as: " + hostIP, EMsgType.PASS);
127+
return true;
128+
}
129+
catch (IOException e){
130+
logPrinter.print("NET: Can't get your computer IP using "
131+
+ host
132+
+ " server (InetSocketAddress). Returned:\n\t"+e.getMessage(), EMsgType.INFO);
133+
return false;
134+
}
135+
}
136+
137+
private String getAvaliableIpExamples(){
138+
try {
139+
StringBuilder builder = new StringBuilder("Check for:\n");
140+
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
141+
while (enumeration.hasMoreElements()) {
142+
NetworkInterface n = enumeration.nextElement();
143+
Enumeration<InetAddress> enumeration1 = n.getInetAddresses();
144+
while (enumeration1.hasMoreElements()){
145+
builder.append("- ");
146+
builder.append(enumeration1.nextElement().getHostAddress());
147+
builder.append("\n");
148+
}
149+
}
150+
return builder.toString();
151+
}
152+
catch (SocketException socketException) {
153+
return "";
154+
}
155+
}
156+
157+
private void resolvePort(String hostPortNum) throws Exception{
158+
if (! hostPortNum.isEmpty()) {
159+
parsePort(hostPortNum);
160+
return;
161+
}
162+
163+
if (doNotServe)
164+
throw new Exception("NET: Port must be defined if 'Don't serve requests' option selected!");
165+
166+
findPort();
167+
}
168+
169+
private void findPort() throws Exception{
170+
Random portRandomizer = new Random();
171+
for (int i = 0; i < 5; i++) {
172+
try {
173+
this.hostPort = portRandomizer.nextInt(999) + 6000;
174+
serverSocket = new ServerSocket(hostPort); //System.out.println(serverSocket.getInetAddress()); 0.0.0.0
175+
logPrinter.print("NET: Your port detected as: " + hostPort, EMsgType.PASS);
176+
break;
177+
}
178+
catch (IOException ioe) {
179+
if (i == 4) {
180+
throw new Exception("NET: Can't find good port\n"
181+
+ "Set port by in settings ('Expert mode').");
182+
}
183+
184+
logPrinter.print("NET: Can't use port " + hostPort + "\nLooking for another one.", EMsgType.WARNING);
185+
}
186+
}
187+
}
188+
189+
private void parsePort(String hostPortNum) throws Exception{
190+
try {
191+
this.hostPort = Integer.parseInt(hostPortNum);
192+
serverSocket = new ServerSocket(hostPort);
193+
logPrinter.print("NET: Using defined port number: " + hostPort, EMsgType.PASS);
194+
}
195+
catch (IllegalArgumentException | IOException eee){
196+
throw new Exception("NET: Can't use port defined in settings: " + hostPortNum + "\n\t"+eee.getMessage());
197+
}
198+
}
199+
200+
String getHostIP() { return hostIP; }
201+
int getHostPort() { return hostPort; }
202+
HashMap<String, UniFile> getFiles() { return files; }
203+
ServerSocket getServerSocket() { return serverSocket; }
204+
boolean isValid() { return valid; }
205+
}

src/main/java/nsusbloader/COM/INSTask.java renamed to src/main/java/nsusbloader/COM/NET/UniFile.java

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,29 @@
1616
You should have received a copy of the GNU General Public License
1717
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
1818
*/
19-
package nsusbloader.COM;
19+
package nsusbloader.COM.NET;
2020

21-
public interface INSTask extends Runnable {
22-
void cancel();
23-
boolean isCancelled();
21+
import java.io.File;
22+
23+
class UniFile {
24+
private final long size;
25+
private final File file;
26+
27+
UniFile(File file) {
28+
this.file = file;
29+
30+
if (file.isFile()) {
31+
size = file.length();
32+
}
33+
else {
34+
long fSize = 0;
35+
File[] subFiles = file.listFiles((myFile, name) -> name.matches("[0-9]{2}"));
36+
for (File subFile : subFiles)
37+
fSize += subFile.length();
38+
size = fSize;
39+
}
40+
}
41+
42+
public long getSize() { return size; }
43+
public File getFile() { return file; }
2444
}

src/main/java/nsusbloader/COM/USB/GoldLeaf_05.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
*/
1919
package nsusbloader.COM.USB;
2020

21-
import nsusbloader.COM.INSTask;
2221
import nsusbloader.ModelControllers.ILogPrinter;
2322
import nsusbloader.NSLDataTypes.EFileStatus;
2423
import nsusbloader.NSLDataTypes.EMsgType;
@@ -53,7 +52,7 @@ public class GoldLeaf_05 extends TransferModule {
5352
private RandomAccessFile raf; // NSP File
5453
private NSSplitReader nsr; // It'a also NSP File
5554

56-
GoldLeaf_05(DeviceHandle handler, LinkedHashMap<String, File> nspMap, INSTask task, ILogPrinter logPrinter){
55+
GoldLeaf_05(DeviceHandle handler, LinkedHashMap<String, File> nspMap, Runnable task, ILogPrinter logPrinter){
5756
super(handler, nspMap, task, logPrinter);
5857
status = EFileStatus.FAILED;
5958

@@ -335,7 +334,7 @@ private boolean writeUsb(byte[] message){
335334
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
336335
int result;
337336

338-
while (! task.isCancelled()) {
337+
while (! Thread.interrupted()) {
339338
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint OUT = 0x01
340339

341340
switch (result){
@@ -368,7 +367,7 @@ private byte[] readUsb(){
368367
IntBuffer readBufTransferred = IntBuffer.allocate(1);
369368

370369
int result;
371-
while (! task.isCancelled()) {
370+
while (! Thread.interrupted()) {
372371
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
373372

374373
switch (result) {

src/main/java/nsusbloader/COM/USB/GoldLeaf_07.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import javafx.application.Platform;
2222
import javafx.stage.FileChooser;
2323
import nsusbloader.COM.Helpers.NSSplitReader;
24-
import nsusbloader.COM.INSTask;
2524
import nsusbloader.MediatorControl;
2625
import nsusbloader.ModelControllers.ILogPrinter;
2726
import nsusbloader.NSLDataTypes.EMsgType;
@@ -69,7 +68,7 @@ class GoldLeaf_07 extends TransferModule {
6968
// For using in CMD_SelectFile with SPEC:/ prefix
7069
private File selectedFile;
7170

72-
GoldLeaf_07(DeviceHandle handler, LinkedHashMap<String, File> nspMap, INSTask task, ILogPrinter logPrinter, boolean nspFilter){
71+
GoldLeaf_07(DeviceHandle handler, LinkedHashMap<String, File> nspMap, Runnable task, ILogPrinter logPrinter, boolean nspFilter){
7372
super(handler, nspMap, task, logPrinter);
7473

7574
final byte CMD_GetDriveCount = 0x00;
@@ -993,7 +992,7 @@ private byte[] readGL(){
993992

994993
int result;
995994

996-
while (! task.isCancelled()) {
995+
while (! Thread.interrupted()) {
997996
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
998997

999998
switch (result) {
@@ -1023,7 +1022,7 @@ private byte[] readGL_file(){
10231022

10241023
int result;
10251024

1026-
while (! task.isCancelled()) {
1025+
while (! Thread.interrupted()) {
10271026
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
10281027

10291028
switch (result) {
@@ -1083,7 +1082,7 @@ private boolean writeToUsb(byte[] message){
10831082
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
10841083
int result;
10851084

1086-
while (! task.isCancelled()) {
1085+
while (! Thread.interrupted()) {
10871086
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint OUT = 0x01
10881087

10891088
switch (result){

src/main/java/nsusbloader/COM/USB/GoldLeaf_08.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import javafx.application.Platform;
2222
import javafx.stage.FileChooser;
23-
import nsusbloader.COM.INSTask;
2423
import nsusbloader.MediatorControl;
2524
import nsusbloader.ModelControllers.ILogPrinter;
2625
import nsusbloader.NSLDataTypes.EMsgType;
@@ -69,7 +68,7 @@ class GoldLeaf_08 extends TransferModule {
6968
// For using in CMD_SelectFile with SPEC:/ prefix
7069
private File selectedFile;
7170

72-
GoldLeaf_08(DeviceHandle handler, LinkedHashMap<String, File> nspMap, INSTask task, ILogPrinter logPrinter, boolean nspFilter){
71+
GoldLeaf_08(DeviceHandle handler, LinkedHashMap<String, File> nspMap, Runnable task, ILogPrinter logPrinter, boolean nspFilter){
7372
super(handler, nspMap, task, logPrinter);
7473

7574
final byte CMD_GetDriveCount = 1;
@@ -1012,7 +1011,7 @@ private byte[] readGL(){
10121011

10131012
int result;
10141013

1015-
while (! task.isCancelled()) {
1014+
while (! Thread.interrupted()) {
10161015
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
10171016

10181017
switch (result) {
@@ -1042,7 +1041,7 @@ private byte[] readGL_file(){
10421041

10431042
int result;
10441043

1045-
while (! task.isCancelled()) {
1044+
while (! Thread.interrupted() ) {
10461045
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
10471046

10481047
switch (result) {
@@ -1102,7 +1101,7 @@ private boolean writeToUsb(byte[] message){
11021101
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
11031102
int result;
11041103

1105-
while (! task.isCancelled()) {
1104+
while (! Thread.interrupted()) {
11061105
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint OUT = 0x01
11071106

11081107
switch (result){

src/main/java/nsusbloader/COM/USB/TinFoil.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
*/
1919
package nsusbloader.COM.USB;
2020

21-
import nsusbloader.COM.INSTask;
2221
import nsusbloader.ModelControllers.ILogPrinter;
2322
import nsusbloader.NSLDataTypes.EFileStatus;
2423
import nsusbloader.NSLDataTypes.EMsgType;
@@ -48,7 +47,7 @@ class TinFoil extends TransferModule {
4847
/* byte[] magic = new byte[4];
4948
ByteBuffer bb = StandardCharsets.UTF_8.encode("TUC0").rewind().get(magic); // Let's rephrase this 'string' */
5049

51-
TinFoil(DeviceHandle handler, LinkedHashMap<String, File> nspMap, INSTask task, ILogPrinter logPrinter){
50+
TinFoil(DeviceHandle handler, LinkedHashMap<String, File> nspMap, Runnable task, ILogPrinter logPrinter){
5251
super(handler, nspMap, task, logPrinter);
5352
logPrinter.print("============= Tinfoil =============", EMsgType.INFO);
5453

@@ -305,7 +304,7 @@ private boolean writeUsb(byte[] message) {
305304
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
306305
int result;
307306
//int varVar = 0; //todo:remove
308-
while (! task.isCancelled()) {
307+
while (! Thread.interrupted() ) {
309308
/*
310309
if (varVar != 0)
311310
logPrinter.print("writeUsb() retry cnt: "+varVar, EMsgType.INFO); //NOTE: DEBUG
@@ -345,7 +344,7 @@ private byte[] readUsb() throws Exception{
345344
// We can limit it to 32 bytes, but there is a non-zero chance to got OVERFLOW from libusb.
346345
IntBuffer readBufTransferred = IntBuffer.allocate(1);
347346
int result;
348-
while (! task.isCancelled()) {
347+
while (! Thread.interrupted()) {
349348
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
350349

351350
switch (result) {

0 commit comments

Comments
 (0)