Skip to content

Commit

Permalink
Terminate comet client after too makny handshake failures
Browse files Browse the repository at this point in the history
  • Loading branch information
CDrummond committed Aug 22, 2024
1 parent 9383287 commit 97557eb
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,21 @@ public void handleMessage(@NonNull Message msg) {
String[] vals = (String[])msg.obj;
Utils.debug("Set notification player name " + vals[1] + ", id:" + vals[0]);
srv.notificationBuilder.setContentTitle(vals[1]);
srv.cometClient.setPlayer(vals[0]);
if (FULL_NOTIFICATION.equals(srv.notificationType) && null!=srv.cometClient) {
srv.cometClient.setPlayer(vals[0]);
if (!srv.cometClient.isConnected()) {
srv.cometClient.connect();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(srv.getApplicationContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
return;
}
srv.updateNotification();
} else if (msg.what == PLAYER_REFRESH && null!=srv.notificationBuilder && null!=srv.notificationManager) {
if (FULL_NOTIFICATION.equals(srv.notificationType) && null!=srv.cometClient && !srv.cometClient.isConnected()) {
Utils.debug("Connect comet client");
srv.cometClient.connect();
}
srv.createNotification();
} else if (msg.what == CHECK_COMET_CONNECTION && null!=srv.cometClient && FULL_NOTIFICATION.equals(srv.notificationType)) {
srv.cometClient.reconnectIfChanged();
Expand Down Expand Up @@ -436,8 +445,7 @@ public void onSeekTo(long pos) {
@Override
public void onCustomAction(String action, Bundle extras) {
if (ACTION_QUIT.equals(action)) {
stopForegroundService();
System.exit(0);
quit();
} else if (ACTION_POWER.equals(action)) {
sendCommand(POWER_COMMAND);
}
Expand Down Expand Up @@ -494,6 +502,11 @@ public void onAdjustVolume(int direction) {
return null;
}

public void quit() {
stopForegroundService();
System.exit(0);
}

private void fetchCover(MediaMetadataCompat.Builder metaBuilder) {
currentCover = null;
Utils.debug(lastStatus.cover);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,12 @@ public class MainActivity extends AppCompatActivity {
public static String activePlayer = null;
public static String activePlayerName = null;
private static boolean isCurrentActivity = false;
private static Date pausedDate = null;

/**
* @return true if activity is active
*/
public static boolean isActive() {
if (isCurrentActivity) {
return true;
}
if (null!=pausedDate) {
return (new Date().getTime() - pausedDate.getTime())<5000;
}
return false;
return isCurrentActivity;
}

private Messenger controlServiceMessenger;
Expand Down Expand Up @@ -285,6 +278,7 @@ private String getConfiguredUrl() {
builder.appendQueryParameter("nativePlayer", "1");
builder.appendQueryParameter("nativeTheme", "1");
builder.appendQueryParameter("nativeTextColor", "1");
builder.appendQueryParameter("nativeConnectionStatus", "1");
if (sharedPreferences.getBoolean(SettingsActivity.PLAYER_START_MENU_ITEM_PREF_KEY, false)) {
builder.appendQueryParameter("nativePlayerPower", "1");
}
Expand Down Expand Up @@ -838,6 +832,14 @@ private void setTheme() {
setTheme(/*isDark ?*/ R.style.AppTheme /*: R.style.AppTheme_Light*/);
}

@JavascriptInterface
public void updateConnectionStatus(boolean connected) {
Utils.debug(""+connected);
if (ControlService.isActive() && connected) {
refreshControlService();
}
}

@JavascriptInterface
public void cancelDownload(String str) {
Utils.debug(str);
Expand Down Expand Up @@ -897,7 +899,6 @@ protected void onPause() {
webView.pauseTimers();
super.onPause();
isCurrentActivity = false;
pausedDate = new Date();
}

private static boolean deleteDir(File path, Set<String> ignore) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.android.volley.Response;
import com.craigd.lmsmaterial.app.ControlService;
import com.craigd.lmsmaterial.app.JsonRpc;
import com.craigd.lmsmaterial.app.MainActivity;
import com.craigd.lmsmaterial.app.ServerDiscovery;
import com.craigd.lmsmaterial.app.SettingsActivity;
import com.craigd.lmsmaterial.app.Utils;
Expand Down Expand Up @@ -61,7 +62,9 @@ public class CometClient {
private ControlService service;
private JsonRpc rpc;
private Response.Listener<JSONObject> rpcResponse;
private int handShakeFailures = 0;

private static final int MAX_HANDSHAKE_FAILURES = 5;
private static final String DEFAULT_RADIO_COVER = "/material/html/images/noradio.png";
private static final String DEFAULT_COVER = "/material/html/images/nocover.png";
private static final String DEFAULT_WORKS_COVER = "/material/html/images/nowork.png";
Expand Down Expand Up @@ -159,6 +162,10 @@ public synchronized void reconnectIfChanged() {
}
}

public synchronized boolean isConnected() {
return connectionState.isConnected() && null!=bayeuxClient;
}

public synchronized void connect() {
Utils.debug("");
connectionState.setConnectionState(ConnectionState.State.CONNECTION_STARTED);
Expand Down Expand Up @@ -196,10 +203,32 @@ protected void customize(org.eclipse.jetty.client.api.Request request) {
bayeuxClient.addExtension(new BayeuxExtension());
backgroundHandler.sendEmptyMessageDelayed(MSG_HANDSHAKE_TIMEOUT, HANDSHAKE_TIMEOUT);
bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener) (channel, message) -> {
Utils.debug("Handshake OK? " + message.isSuccessful() + " , canRehandshake? " + connectionState.canRehandshake());
handShakeFailures = message.isSuccessful() ? 0 : (handShakeFailures+1);
Utils.debug("Handshake OK: " + message.isSuccessful() + ", canRehandshake: " + connectionState.canRehandshake() + ", failures:" +handShakeFailures);
if (message.isSuccessful()) {
onConnected();
} else if (handShakeFailures>=MAX_HANDSHAKE_FAILURES && Utils.isNetworkConnected(service)) {
Utils.error("Too many handshake errors, aborting");
handShakeFailures = 0;
try {
clientTransport.abort();
try {
httpClient.stop();
} catch (Exception e) {
Utils.error("Failed to stop HTTP client", e);
}
bayeuxClient.stop();
bayeuxClient = null;
if (!MainActivity.isActive() && !SettingsActivity.isVisible()) {
Utils.debug("UI is not visible, so terminate");
service.quit();
}
} catch (Exception e) {
Utils.error("Aborting", e);
}
connectionState.setConnectionState(ConnectionState.State.DISCONNECTED);
} else if (!connectionState.canRehandshake()) {
handShakeFailures = 0;
Map<String, Object> failure = getRecord(message, "failure");
Message failedMessage = (failure != null) ? (Message) failure.get("message") : message;
// Advices are handled internally by the bayeux protocol, so skip these here
Expand Down Expand Up @@ -256,8 +285,8 @@ public void disconnect() {
}

private void disconnect(boolean andReconnect) {
Utils.debug("");
if (bayeuxClient != null) {
Utils.debug("connected:"+connectionState.isConnected());
if (bayeuxClient != null && connectionState.isConnected()) {
backgroundHandler.sendEmptyMessage(andReconnect ? MSG_RECONNECT : MSG_DISCONNECT);
}
connectionState.setConnectionState(ConnectionState.State.DISCONNECTED);
Expand All @@ -266,7 +295,7 @@ private void disconnect(boolean andReconnect) {
private synchronized void disconnectFromServer() {
if (bayeuxClient != null) {
String[] channels = new String[]{Channel.META_HANDSHAKE, Channel.META_CONNECT};
for (String channelId: channels) {
for (String channelId : channels) {
ClientSessionChannel channel = bayeuxClient.getChannel(channelId);
for (ClientSessionChannel.ClientSessionChannelListener listener : channel.getListeners()) {
channel.removeListener(listener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,9 @@ private boolean isConnected() {
}

public void connect(String host, int port) throws IOException {
if (_aborted) {
throw new IOException("Aborted");
}
Socket session = new Socket();

synchronized (this) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ public class SlimClient extends BayeuxClient {
this.connectionState = connectionState;
}

public void stop() {
this.terminate();
}

@Override
public void onSending(List<? extends Message> messages) {
super.onSending(messages);
Expand Down

0 comments on commit 97557eb

Please sign in to comment.