Allow configuring local network

Can disable/enable local network and set port
This commit is contained in:
Arnaud Vergnet 2021-01-27 11:19:25 +01:00
parent 60fa5adfe4
commit 298e01d09c
9 changed files with 137 additions and 51 deletions

View file

@ -1,11 +1,15 @@
{ {
"serveur": { "serveur": {
"actif": 1, "actif": 0,
"uri": "localhost", "uri": "localhost",
"type": "INSA", "type": "INSA",
"ports": { "ports": {
"presence": 35650, "presence": 35650,
"proxy": 35750 "proxy": 35750
} }
},
"local": {
"actif": 1,
"port": 31590
} }
} }

View file

@ -8,10 +8,13 @@ import org.json.JSONObject;
public class Config { public class Config {
private ServerConfig serverConfig; private ServerConfig serverConfig;
private LocalConfig localConfig;
private final String SERVER_KEY = "serveur"; private final String SERVER_KEY = "serveur";
private final String LOCAL_KEY = "local";
public Config() { public Config() {
serverConfig = new ServerConfig(); serverConfig = new ServerConfig();
localConfig = new LocalConfig();
} }
public Config(JSONObject obj) { public Config(JSONObject obj) {
@ -19,14 +22,22 @@ public class Config {
if (obj.has(SERVER_KEY)) { if (obj.has(SERVER_KEY)) {
this.serverConfig = new ServerConfig(obj.getJSONObject(SERVER_KEY)); this.serverConfig = new ServerConfig(obj.getJSONObject(SERVER_KEY));
} }
if (obj.has(LOCAL_KEY)) {
this.localConfig = new LocalConfig(obj.getJSONObject(LOCAL_KEY));
}
} }
public ServerConfig getServerConfig() { public ServerConfig getServerConfig() {
return serverConfig; return serverConfig;
} }
public LocalConfig getLocalConfig() {
return localConfig;
}
@SuppressWarnings("FieldCanBeLocal") @SuppressWarnings("FieldCanBeLocal")
public static class ServerConfig { public static class ServerConfig {
public static final int DEFAULT_PRESENCE_PORT = 35650;
public static final int DEFAULT_PROXY_PORT = 35750;
private JSONObject obj; private JSONObject obj;
@ -114,8 +125,8 @@ public class Config {
presencePort = portsObj.getInt(PORT_PRESENCE_KEY); presencePort = portsObj.getInt(PORT_PRESENCE_KEY);
proxyPort = portsObj.getInt(PORT_PROXY_KEY); proxyPort = portsObj.getInt(PORT_PROXY_KEY);
} catch (JSONException e) { } catch (JSONException e) {
presencePort = 30000; // TODO set default ports presencePort = DEFAULT_PRESENCE_PORT;
proxyPort = 300001; proxyPort = DEFAULT_PROXY_PORT;
} }
} }
@ -145,4 +156,73 @@ public class Config {
return proxyPort; return proxyPort;
} }
} }
@SuppressWarnings("FieldCanBeLocal")
public static class LocalConfig {
public static final int DEFAULT_TCP_PORT = 31598;
private JSONObject obj;
private boolean enabled;
private int port;
private final String ENABLED_KEY = "actif";
private final String PORT_KEY = "port";
/**
* Basic constructor setting the default local configuration
*/
public LocalConfig() {
enabled = true;
port = DEFAULT_TCP_PORT;
}
/**
* Tries to read the given JSON object to extract custom user configuration
*
* @param obj THe JSON object to read config from
*/
public LocalConfig(JSONObject obj) {
this();
this.obj = obj;
readEnabled();
if (enabled) {
readServerPort();
}
}
/**
* Reads if local mode is enabled.
* Uses true by default.
*/
private void readEnabled() {
try {
enabled = obj.getInt(ENABLED_KEY) == 1;
} catch (JSONException e) {
enabled = true;
}
}
private void readServerPort() {
try {
port = obj.getInt(PORT_KEY);
} catch (JSONException e) {
port = DEFAULT_TCP_PORT;
}
}
/**
* Checks if the local mode is enabled.
* If this returns false, all other data returned by this object can be ignored.
*
* @return True if enabled, false otherwise.
*/
public boolean isEnabled() {
return enabled;
}
public int getPort() {
return port;
}
}
} }

View file

@ -15,12 +15,13 @@ public class PeerHandshake {
private TcpConnection connection; private TcpConnection connection;
private UserInformation userInformation; private UserInformation userInformation;
public void createConnection(InetAddress ipAddr, UserConnectedCallback callback, ErrorCallback errorCallback) { public void createConnection(InetAddress ipAddr, int port, UserConnectedCallback callback, ErrorCallback errorCallback) {
closeConnection(); closeConnection();
Log.v(this.getClass().getSimpleName(), "Creating new TCP connection "); Log.v(this.getClass().getSimpleName(), "Creating new TCP connection ");
connection = new TcpConnection( connection = new TcpConnection(
ipAddr, ipAddr,
port,
(thisConnection) -> init(thisConnection, (thisConnection) -> init(thisConnection,
false, false,
callback, callback,

View file

@ -56,6 +56,11 @@ public class MainController implements Initializable {
private Presence presenceServer; private Presence presenceServer;
private boolean online; private boolean online;
private final int DEFAULT_PORT = 31598;
private int port = DEFAULT_PORT;
private boolean localEnabled = true;
public MainController() { public MainController() {
online = false; online = false;
currentUser = CurrentUser.getInstance(); currentUser = CurrentUser.getInstance();
@ -168,8 +173,10 @@ public class MainController implements Initializable {
* If any error happens, disconnect the user from chat and ask for reconnection. * If any error happens, disconnect the user from chat and ask for reconnection.
*/ */
private void discoverActiveUsers() { private void discoverActiveUsers() {
if (userList != null && online) { if (userList != null && online && localEnabled) {
userList.discoverActiveUsers((e) -> { userList.discoverActiveUsers(
port,
(e) -> {
Log.e(this.getClass().getSimpleName(), "Error discovering users", e); Log.e(this.getClass().getSimpleName(), "Error discovering users", e);
CurrentUser.getInstance().setState(CurrentUser.State.INVALID); CurrentUser.getInstance().setState(CurrentUser.State.INVALID);
}); });
@ -181,9 +188,11 @@ public class MainController implements Initializable {
* If any error happens, disconnect the user from chat and ask for reconnection. * If any error happens, disconnect the user from chat and ask for reconnection.
*/ */
private void startListening() { private void startListening() {
if (userList != null) { if (userList != null && online && localEnabled) {
userList.startDiscoveryListening(); userList.startDiscoveryListening();
userList.startUserListening((e) -> { userList.startUserListening(
port,
(e) -> {
Log.e(this.getClass().getSimpleName(), "Error listening to users", e); Log.e(this.getClass().getSimpleName(), "Error listening to users", e);
CurrentUser.getInstance().setState(CurrentUser.State.INVALID); CurrentUser.getInstance().setState(CurrentUser.State.INVALID);
}); });
@ -268,22 +277,34 @@ public class MainController implements Initializable {
*/ */
private void initBackend() { private void initBackend() {
ConfigLoader.load( ConfigLoader.load(
(Config config) -> new DatabaseController().initTables( (Config config) -> {
() -> userList.retrievedPreviousUsers( initLocalNetwork(config.getLocalConfig());
() -> currentUser.init( new DatabaseController().initTables(
() -> initPresenceServer(config), () -> userList.retrievedPreviousUsers(
this::onInitError), () -> currentUser.init(
this::onInitError () -> initPresenceServer(config.getServerConfig()),
), this::onInitError)); this::onInitError),
this::onInitError
), this::onInitError);
});
}
private void initLocalNetwork(Config.LocalConfig localConfig) {
port = localConfig.getPort();
localEnabled = localConfig.isEnabled();
if (localEnabled) {
Log.v(getClass().getSimpleName(), "Local network support enabled on port: " + port);
} else {
Log.v(getClass().getSimpleName(), "Local network support disabled");
}
} }
/** /**
* Initializes the presence server based on user config * Initializes the presence server based on user config
* *
* @param config The user config * @param serverConfig The server config
*/ */
public void initPresenceServer(Config config) { private void initPresenceServer(Config.ServerConfig serverConfig) {
final Config.ServerConfig serverConfig = config.getServerConfig();
if (serverConfig.isEnabled()) { if (serverConfig.isEnabled()) {
try { try {
final PresenceType type = serverConfig.getType(); final PresenceType type = serverConfig.getType();

View file

@ -38,11 +38,12 @@ public class UserList {
* *
* @param errorCallback The function to call on error * @param errorCallback The function to call on error
*/ */
public void discoverActiveUsers(ErrorCallback errorCallback) { public void discoverActiveUsers(int port, ErrorCallback errorCallback) {
netDiscoverer.discoverActiveUsers("CLAVARDATOR_BROADCAST", (ipAddr, data) -> { netDiscoverer.discoverActiveUsers("CLAVARDATOR_BROADCAST", (ipAddr, data) -> {
Log.v(this.getClass().getSimpleName(), "Discovered new user: " + data); Log.v(this.getClass().getSimpleName(), "Discovered new user: " + data);
new PeerHandshake().createConnection( new PeerHandshake().createConnection(
ipAddr, ipAddr,
port,
this::onUserConnectionSuccess, this::onUserConnectionSuccess,
errorCallback); errorCallback);
}, errorCallback); }, errorCallback);
@ -111,8 +112,9 @@ public class UserList {
* *
* @param errorCallback Callback on error * @param errorCallback Callback on error
*/ */
public void startUserListening(ErrorCallback errorCallback) { public void startUserListening(int port, ErrorCallback errorCallback) {
tcpListener.acceptConnection( tcpListener.acceptConnection(
port,
(clientSocket) -> { (clientSocket) -> {
Log.v(this.getClass().getSimpleName(), Log.v(this.getClass().getSimpleName(),
"new connection from user at address: " + clientSocket.getInetAddress().toString()); "new connection from user at address: " + clientSocket.getInetAddress().toString());

View file

@ -13,7 +13,6 @@ import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
public class TcpConnection { public class TcpConnection {
public static final int TCP_PORT = 31598;
private Socket socket; private Socket socket;
private ObjectOutputStream outputStream; private ObjectOutputStream outputStream;
@ -22,17 +21,6 @@ public class TcpConnection {
private final int port; private final int port;
private final Object outputStreamGuard = new Object(); private final Object outputStreamGuard = new Object();
/**
* Creates a new connection, and connects to the peer
*
* @param ipAddr The IP address of the peer
* @param callback The function to call when connected
* @param errorCallback The function to call on error
*/
public TcpConnection(InetAddress ipAddr, SocketConnectedCallback callback, ErrorCallback errorCallback) {
this(ipAddr, TCP_PORT, callback, errorCallback);
}
/** /**
* Creates a new connection, and connects to the peer * Creates a new connection, and connects to the peer
* *

View file

@ -6,27 +6,13 @@ import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import static fr.insa.clavardator.lib.network.TcpConnection.TCP_PORT;
public class TcpListener { public class TcpListener {
Acceptor acceptor = null; Acceptor acceptor = null;
int port = TCP_PORT;
public TcpListener() { public TcpListener() {
} }
public TcpListener(int port) { public void acceptConnection(int port, NewConnectionCallback callback, ErrorCallback errorCallback) {
this.port = port;
}
/**
* Start accepting incoming connections
*
* @param callback The function to call when a user connects
* @param errorCallback The function to call on error
*/
public void acceptConnection(NewConnectionCallback callback, ErrorCallback errorCallback) {
if (acceptor != null) { if (acceptor != null) {
acceptor.stopAccepting(); acceptor.stopAccepting();
} }

View file

@ -22,8 +22,10 @@ public class Presence {
private final TcpListener presenceListener; private final TcpListener presenceListener;
public Presence() { public Presence() {
presenceListener = new TcpListener(PRESENCE_PORT); presenceListener = new TcpListener();
presenceListener.acceptConnection(this::subscribe, presenceListener.acceptConnection(
PRESENCE_PORT,
this::subscribe,
e -> Log.e(getClass().getSimpleName(), "Error while registering a user", e)); e -> Log.e(getClass().getSimpleName(), "Error while registering a user", e));
} }

View file

@ -17,8 +17,10 @@ public class Proxy {
private final TcpListener proxyListener; private final TcpListener proxyListener;
public Proxy() { public Proxy() {
proxyListener = new TcpListener(PROXY_PORT); proxyListener = new TcpListener();
proxyListener.acceptConnection(clientSocket -> { proxyListener.acceptConnection(
PROXY_PORT,
clientSocket -> {
Log.v(getClass().getSimpleName(), "Accepting a new user"); Log.v(getClass().getSimpleName(), "Accepting a new user");
TcpConnection connection = new TcpConnection(clientSocket); TcpConnection connection = new TcpConnection(clientSocket);