Skip to content

Commit

Permalink
Fix token handling
Browse files Browse the repository at this point in the history
  • Loading branch information
RetGal committed Jan 13, 2025
1 parent cd6a052 commit 59d61b3
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 53 deletions.
33 changes: 20 additions & 13 deletions src/main/java/mpo/dayon/assistant/gui/Assistant.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public class Assistant implements ClipboardOwner {

private static final String PORT_PARAM = "?port=%s";
private static final String WHATSMYIP_SERVER_URL = "https://fensterkitt.ch/dayon/whatismyip.php";
private final String tokenServerUrl;
private String tokenServerUrl;

private final NetworkAssistantEngine networkEngine;

Expand Down Expand Up @@ -105,18 +105,7 @@ public class Assistant implements ClipboardOwner {

public Assistant(String tokenServerUrl, String language) {
networkConfiguration = new NetworkAssistantEngineConfiguration();

if (tokenServerUrl != null) {
this.tokenServerUrl = tokenServerUrl + PORT_PARAM;
} else if (!networkConfiguration.getTokenServerUrl().isEmpty()) {
this.tokenServerUrl = networkConfiguration.getTokenServerUrl() + PORT_PARAM;
} else {
this.tokenServerUrl = DEFAULT_TOKEN_SERVER_URL + PORT_PARAM;
}

if (!this.tokenServerUrl.startsWith(DEFAULT_TOKEN_SERVER_URL)) {
System.setProperty("dayon.custom.tokenServer", this.tokenServerUrl);
}
updateTokenServerUrl(tokenServerUrl);

this.configuration = new AssistantConfiguration();
// has not been overridden by command line
Expand Down Expand Up @@ -146,6 +135,22 @@ public Assistant(String tokenServerUrl, String language) {
initGui();
}

private void updateTokenServerUrl(String tokenServerUrl) {
if (tokenServerUrl != null && !tokenServerUrl.trim().isEmpty()) {
this.tokenServerUrl = tokenServerUrl + PORT_PARAM;
} else if (!networkConfiguration.getTokenServerUrl().isEmpty()) {
this.tokenServerUrl = networkConfiguration.getTokenServerUrl() + PORT_PARAM;
} else {
this.tokenServerUrl = DEFAULT_TOKEN_SERVER_URL + PORT_PARAM;
}

if (!this.tokenServerUrl.startsWith(DEFAULT_TOKEN_SERVER_URL)) {
System.setProperty("dayon.custom.tokenServer", this.tokenServerUrl.substring(0, this.tokenServerUrl.indexOf('?')));
} else {
System.clearProperty("dayon.custom.tokenServer");
}
}

private void initGui() {
createCounters();
if (frame != null) {
Expand Down Expand Up @@ -582,6 +587,7 @@ public void actionPerformed(ActionEvent ev) {
}

private void requestToken() throws IOException, InterruptedException {
Log.debug("Requesting token using: " + tokenServerUrl);
// HttpClient doesn't implement AutoCloseable nor close before Java 21!
@java.lang.SuppressWarnings("squid:S2095")
HttpClient client = HttpClient.newBuilder().build();
Expand Down Expand Up @@ -907,6 +913,7 @@ public void onIOError(IOException error) {
@Override
public void onReconfigured(NetworkAssistantEngineConfiguration networkEngineConfiguration) {
networkConfiguration = networkEngineConfiguration;
updateTokenServerUrl(networkConfiguration.getTokenServerUrl());
clearToken();
}
}
Expand Down
57 changes: 38 additions & 19 deletions src/main/java/mpo/dayon/assisted/gui/Assisted.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class Assisted implements Subscriber, ClipboardOwner {

private static final String TOKEN_PARAM = "?token=%s";

private final String tokenServerUrl;
private String tokenServerUrl;

private AssistedFrame frame;

Expand All @@ -68,8 +68,18 @@ public class Assisted implements Subscriber, ClipboardOwner {

public Assisted(String tokenServerUrl) {
networkConfiguration = new NetworkAssistedEngineConfiguration();
updateTokenServerUrl(tokenServerUrl);

if (tokenServerUrl != null) {
final String lnf = getDefaultLookAndFeel();
try {
UIManager.setLookAndFeel(lnf);
} catch (Exception ex) {
Log.warn(format("Could not set the L&F [%s]", lnf), ex);
}
}

private void updateTokenServerUrl(String tokenServerUrl) {
if (tokenServerUrl != null && !tokenServerUrl.trim().isEmpty()) {
this.tokenServerUrl = tokenServerUrl + TOKEN_PARAM;
} else if (!networkConfiguration.getTokenServerUrl().isEmpty()) {
this.tokenServerUrl = networkConfiguration.getTokenServerUrl() + TOKEN_PARAM;
Expand All @@ -78,29 +88,16 @@ public Assisted(String tokenServerUrl) {
}

if (!this.tokenServerUrl.startsWith(DEFAULT_TOKEN_SERVER_URL)) {
System.setProperty("dayon.custom.tokenServer", this.tokenServerUrl);
}

final String lnf = getDefaultLookAndFeel();
try {
UIManager.setLookAndFeel(lnf);
} catch (Exception ex) {
Log.warn(format("Could not set the L&F [%s]", lnf), ex);
System.setProperty("dayon.custom.tokenServer", this.tokenServerUrl.substring(0, this.tokenServerUrl.indexOf('?')));
} else {
System.clearProperty("dayon.custom.tokenServer");
}
}

/**
* Returns true if we have a valid configuration
*/
public boolean start(String serverName, String portNumber, boolean autoConnect) {
if (frame == null) {
frame = new AssistedFrame(createStartAction(), createStopAction(), createToggleMultiScreenAction());
FatalErrorHandler.attachFrame(frame);
KeyboardErrorHandler.attachFrame(frame);
frame.setVisible(true);
Log.info("Assisted start");
}

// these should not block as they are called from the network incoming message thread (!)
final NetworkCaptureConfigurationMessageHandler captureConfigurationHandler = this::onCaptureEngineConfigured;
final NetworkCompressorConfigurationMessageHandler compressorConfigurationHandler = this::onCompressorEngineConfigured;
Expand All @@ -113,6 +110,14 @@ public boolean start(String serverName, String portNumber, boolean autoConnect)
controlHandler, clipboardRequestHandler, screenshotRequestHandler, this);
networkEngine.addListener(new MyNetworkAssistedEngineListener());

if (frame == null) {
frame = new AssistedFrame(createStartAction(), createStopAction(), createToggleMultiScreenAction(), networkEngine);
FatalErrorHandler.attachFrame(frame);
KeyboardErrorHandler.attachFrame(frame);
frame.setVisible(true);
Log.info("Assisted start");
}

return configureConnection(serverName, portNumber, autoConnect);
}

Expand Down Expand Up @@ -191,12 +196,13 @@ private void applyConnectionSettings(ConnectionSettingsDialog connectionSettings
CompletableFuture.supplyAsync(() -> {
final NetworkAssistedEngineConfiguration newConfiguration;
String tokenString = connectionSettingsDialog.getToken().trim();
if (!tokenString.isEmpty()) {
if (!tokenString.isEmpty() && !tokenString.equals(this.token)) {
this.token = tokenString;
final Cursor cursor = frame.getCursor();
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
String connectionParams = null;
try {
Log.debug("Resolving token using: " + tokenServerUrl);
connectionParams = resolveToken(tokenServerUrl, token);
} catch (IOException | InterruptedException ex) {
Log.warn("Could not resolve token " + token);
Expand All @@ -206,10 +212,17 @@ private void applyConnectionSettings(ConnectionSettingsDialog connectionSettings
}
Log.debug("Connection params " + connectionParams);
newConfiguration = extractConfiguration(connectionParams);
if (newConfiguration == null) {
// expired or wrong token server
Log.warn("Invalid token " + token);
JOptionPane.showMessageDialog(frame, translate("connection.settings.invalidToken"), translate("connection.settings.token"), JOptionPane.ERROR_MESSAGE);
this.token = null;
}
frame.setCursor(cursor);
} else {
newConfiguration = new NetworkAssistedEngineConfiguration(connectionSettingsDialog.getIpAddress().trim(),
Integer.parseInt(connectionSettingsDialog.getPortNumber().trim()));
this.token = null;
}
return newConfiguration;
}).thenAcceptAsync(newConfiguration -> {
Expand Down Expand Up @@ -461,6 +474,12 @@ public void onIOError(IOException error) {
frame.onDisconnecting();
}

@Override
public void onReconfigured(NetworkAssistedEngineConfiguration configuration) {
networkConfiguration = configuration;
updateTokenServerUrl(configuration.getTokenServerUrl());
}

private void capsOff() {
if (Toolkit.getDefaultToolkit().getLockingKeyState(VK_CAPS_LOCK)) {
Log.info("Caps Lock is on, turning it off");
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/mpo/dayon/assisted/gui/AssistedFrame.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package mpo.dayon.assisted.gui;

import mpo.dayon.assisted.network.NetworkAssistedEngine;
import mpo.dayon.assisted.utils.ScreenUtilities;
import mpo.dayon.common.gui.common.BaseFrame;
import mpo.dayon.common.gui.common.FrameType;
import mpo.dayon.common.gui.common.ImageNames;
import mpo.dayon.common.gui.common.ImageUtilities;
import mpo.dayon.common.gui.statusbar.StatusBar;
import mpo.dayon.common.gui.toolbar.ToolBar;
import mpo.dayon.assisted.utils.ScreenUtilities;
import mpo.dayon.common.log.Log;

import javax.swing.*;
Expand All @@ -27,13 +28,13 @@ class AssistedFrame extends BaseFrame {
private final Cursor mouseCursor = this.getCursor();
private boolean connected;

AssistedFrame(Action startAction, Action stopAction, Action toggleMultiScreenCaptureAction) {
AssistedFrame(Action startAction, Action stopAction, Action toggleMultiScreenCaptureAction, NetworkAssistedEngine networkEngine) {
super.setFrameType(FrameType.ASSISTED);
this.stopAction = stopAction;
this.startAction = startAction;
this.startButton = createButton(this.startAction);
this.stopButton = createButton(this.stopAction, false);
this.connectionSettingsButton = createButton(createAssistedConnectionSettingsAction());
this.connectionSettingsButton = createButton(createAssistedConnectionSettingsAction(networkEngine));
this.toggleMultiScreenCaptureAction = toggleMultiScreenCaptureAction;
setupToolBar(createToolBar());
setupStatusBar(createStatusBar());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import mpo.dayon.assisted.mouse.MouseEngineListener;
import mpo.dayon.common.buffer.MemByteBuffer;
import mpo.dayon.common.concurrent.RunnableEx;
import mpo.dayon.common.configuration.Configurable;
import mpo.dayon.common.configuration.ReConfigurable;
import mpo.dayon.common.error.FatalErrorHandler;
import mpo.dayon.common.event.Listeners;
import mpo.dayon.common.log.Log;
Expand All @@ -30,7 +30,7 @@
import static java.lang.String.format;

public class NetworkAssistedEngine extends NetworkEngine
implements Configurable<NetworkAssistedEngineConfiguration>, CompressorEngineListener, MouseEngineListener {
implements ReConfigurable<NetworkAssistedEngineConfiguration>, CompressorEngineListener, MouseEngineListener {
private NetworkAssistedEngineConfiguration configuration;

private final NetworkCaptureConfigurationMessageHandler captureConfigurationHandler;
Expand Down Expand Up @@ -88,6 +88,12 @@ public void configure(NetworkAssistedEngineConfiguration configuration) {
this.configuration = configuration;
}

@Override
public void reconfigure(NetworkAssistedEngineConfiguration configuration) {
this.configuration = configuration;
fireOnReconfigured(configuration);
}

public void addListener(NetworkAssistedEngineListener listener) {
listeners.add(listener);
}
Expand Down Expand Up @@ -287,4 +293,8 @@ protected void fireOnIOError(IOException ex) {
listeners.getListeners().forEach(listener -> listener.onIOError(ex));
}

private void fireOnReconfigured(NetworkAssistedEngineConfiguration configuration) {
listeners.getListeners().forEach(listener -> listener.onReconfigured(configuration));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ public interface NetworkAssistedEngineListener extends Listener {
*/
void onIOError(IOException error);

void onReconfigured(NetworkAssistedEngineConfiguration configuration);

}
25 changes: 9 additions & 16 deletions src/main/java/mpo/dayon/common/gui/common/BaseFrame.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.dosse.upnp.UPnP;
import mpo.dayon.assistant.network.NetworkAssistantEngine;
import mpo.dayon.assistant.network.NetworkAssistantEngineConfiguration;
import mpo.dayon.assisted.network.NetworkAssistedEngine;
import mpo.dayon.assisted.network.NetworkAssistedEngineConfiguration;
import mpo.dayon.common.gui.statusbar.StatusBar;
import mpo.dayon.common.gui.toolbar.ToolBar;
Expand Down Expand Up @@ -288,15 +289,15 @@ public void actionPerformed(ActionEvent ev) {
return showSystemInfo;
}

protected Action createAssistedConnectionSettingsAction() {
return createConnectionSettingsAction(CompletableFuture.completedFuture(false), null);
protected Action createAssistedConnectionSettingsAction(NetworkAssistedEngine networkEngine) {
return createConnectionSettingsAction(CompletableFuture.completedFuture(false), null, networkEngine);
}

protected Action createAssistantConnectionSettingsAction(CompletableFuture<Boolean> isUpnpEnabled, NetworkAssistantEngine networkEngine) {
return createConnectionSettingsAction(isUpnpEnabled, networkEngine);
return createConnectionSettingsAction(isUpnpEnabled, networkEngine, null);
}

protected Action createConnectionSettingsAction(CompletableFuture<Boolean> isUpnpEnabled, NetworkAssistantEngine networkEngine) {
protected Action createConnectionSettingsAction(CompletableFuture<Boolean> isUpnpEnabled, NetworkAssistantEngine networkAssistantEngine, NetworkAssistedEngine networkAssistedEngine) {
final Action conf = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ev) {
Expand All @@ -316,11 +317,10 @@ public void actionPerformed(ActionEvent ev) {
if (ok) {
final String newTokenServerUrl = tokenRadioGroup.getSelection().getActionCommand().equals(CUSTOM) &&
isValidUrl(customTokenTextField.getText().trim()) ? customTokenTextField.getText() : "";
updateSystemProperty(newTokenServerUrl);
if (ASSISTED.equals(frameType)) {
updateAssistedNetworkConfiguration(addressTextField, portNumberTextField, autoConnectCheckBox, newTokenServerUrl);
updateAssistedNetworkConfiguration(addressTextField, portNumberTextField, autoConnectCheckBox, newTokenServerUrl, networkAssistedEngine);
} else {
updateAssistantNetworkConfiguration(portNumberTextField, newTokenServerUrl, networkEngine);
updateAssistantNetworkConfiguration(portNumberTextField, newTokenServerUrl, networkAssistantEngine);
}
}
}
Expand Down Expand Up @@ -449,12 +449,13 @@ private String validateInputFields(JTextField addressTextField, JTextField portN
return null;
}

private static void updateAssistedNetworkConfiguration(JTextField addressTextField, JTextField portNumberTextField, JCheckBox autoConnectCheckBox, String newTokenServerUrl) {
private static void updateAssistedNetworkConfiguration(JTextField addressTextField, JTextField portNumberTextField, JCheckBox autoConnectCheckBox, String newTokenServerUrl, NetworkAssistedEngine networkEngine) {
final NetworkAssistedEngineConfiguration newConfig = new NetworkAssistedEngineConfiguration(
addressTextField.getText().trim(), Integer.parseInt(portNumberTextField.getText()), autoConnectCheckBox.isSelected(), newTokenServerUrl);

if (!newConfig.equals(new NetworkAssistedEngineConfiguration())) {
newConfig.persist();
networkEngine.reconfigure(newConfig);
}
}

Expand All @@ -470,14 +471,6 @@ private static void updateAssistantNetworkConfiguration(JTextField portNumberTex
}
}

private static void updateSystemProperty(String newTokenServerUrl) {
if (newTokenServerUrl.isEmpty()) {
System.clearProperty("dayon.custom.tokenServer");
return;
}
System.setProperty("dayon.custom.tokenServer", newTokenServerUrl);
}

private static GridBagConstraints createGridBagConstraints(int gridy) {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = HORIZONTAL;
Expand Down

0 comments on commit 59d61b3

Please sign in to comment.