Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc918e7664 | ||
|
|
aba3930417 | ||
|
|
4476f41aa6 | ||
|
|
5122683761 | ||
|
|
924835dd55 |
@@ -4,6 +4,7 @@ import android.util.Base64;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -14,16 +15,22 @@ import java.util.Arrays;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
final class AppEventSocketClient {
|
||||
private static final long HEARTBEAT_INTERVAL_MS = 15000L;
|
||||
private static final int SOCKET_CONNECT_TIMEOUT_MS = 10000;
|
||||
private static final int SOCKET_READ_TIMEOUT_MS = 45000;
|
||||
|
||||
interface Listener {
|
||||
void onMessage(String text);
|
||||
void onClosed();
|
||||
}
|
||||
|
||||
private final Listener listener;
|
||||
private final Object writeLock = new Object();
|
||||
private Socket socket;
|
||||
private BufferedInputStream input;
|
||||
private BufferedOutputStream output;
|
||||
private volatile boolean closed;
|
||||
private Thread heartbeatThread;
|
||||
|
||||
AppEventSocketClient(Listener listener) {
|
||||
this.listener = listener;
|
||||
@@ -40,12 +47,11 @@ final class AppEventSocketClient {
|
||||
sendFrame(8, new byte[0]);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
if (socket != null) {
|
||||
socket.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
closeSocketQuietly();
|
||||
}
|
||||
|
||||
boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
private void run(String baseUrl) {
|
||||
@@ -55,6 +61,7 @@ final class AppEventSocketClient {
|
||||
input = new BufferedInputStream(socket.getInputStream());
|
||||
output = new BufferedOutputStream(socket.getOutputStream());
|
||||
handshake(uri);
|
||||
startHeartbeat();
|
||||
while (!closed) {
|
||||
Frame frame = readFrame();
|
||||
if (frame.opcode == 1) {
|
||||
@@ -69,12 +76,7 @@ final class AppEventSocketClient {
|
||||
} finally {
|
||||
closed = true;
|
||||
listener.onClosed();
|
||||
try {
|
||||
if (socket != null) {
|
||||
socket.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
closeSocketQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,10 +93,39 @@ final class AppEventSocketClient {
|
||||
if (port == -1) {
|
||||
port = "wss".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
|
||||
}
|
||||
Socket raw = new Socket();
|
||||
raw.connect(new InetSocketAddress(uri.getHost(), port), SOCKET_CONNECT_TIMEOUT_MS);
|
||||
Socket connected;
|
||||
if ("wss".equalsIgnoreCase(uri.getScheme())) {
|
||||
return SSLSocketFactory.getDefault().createSocket(uri.getHost(), port);
|
||||
connected = ((SSLSocketFactory) SSLSocketFactory.getDefault())
|
||||
.createSocket(raw, uri.getHost(), port, true);
|
||||
} else {
|
||||
connected = raw;
|
||||
}
|
||||
return new Socket(uri.getHost(), port);
|
||||
connected.setKeepAlive(true);
|
||||
connected.setTcpNoDelay(true);
|
||||
connected.setSoTimeout(SOCKET_READ_TIMEOUT_MS);
|
||||
return connected;
|
||||
}
|
||||
|
||||
private void startHeartbeat() {
|
||||
heartbeatThread = new Thread(() -> {
|
||||
while (!closed) {
|
||||
try {
|
||||
Thread.sleep(HEARTBEAT_INTERVAL_MS);
|
||||
if (!closed) {
|
||||
sendFrame(9, new byte[0]);
|
||||
}
|
||||
} catch (InterruptedException ignored) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
} catch (Exception error) {
|
||||
closeSocketQuietly();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, "app-events-ws-heartbeat");
|
||||
heartbeatThread.start();
|
||||
}
|
||||
|
||||
private void handshake(URI uri) throws Exception {
|
||||
@@ -181,6 +212,7 @@ final class AppEventSocketClient {
|
||||
}
|
||||
|
||||
private void sendFrame(int opcode, byte[] payload) throws Exception {
|
||||
synchronized (writeLock) {
|
||||
if (output == null) {
|
||||
return;
|
||||
}
|
||||
@@ -208,6 +240,20 @@ final class AppEventSocketClient {
|
||||
output.write(masked);
|
||||
output.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private void closeSocketQuietly() {
|
||||
if (heartbeatThread != null) {
|
||||
heartbeatThread.interrupt();
|
||||
heartbeatThread = null;
|
||||
}
|
||||
try {
|
||||
if (socket != null) {
|
||||
socket.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Frame {
|
||||
final int opcode;
|
||||
|
||||
@@ -18,6 +18,8 @@ import android.graphics.drawable.StateListDrawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.provider.Settings;
|
||||
import android.text.TextUtils;
|
||||
import android.text.InputType;
|
||||
@@ -46,7 +48,9 @@ import org.json.JSONObject;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -60,12 +64,13 @@ public final class MainActivity extends Activity {
|
||||
private static final int MAX_TERMINAL_COLS = 140;
|
||||
private static final int MIN_TERMINAL_ROWS = 8;
|
||||
private static final int MAX_TERMINAL_ROWS = 80;
|
||||
private static final int TERMINAL_KEYS_HEIGHT_DP = 76;
|
||||
private static final int TERMINAL_KEYS_HEIGHT_DP = 64;
|
||||
private static final int STATUS_NORMAL = 0;
|
||||
private static final int STATUS_BUSY = 1;
|
||||
private static final int STATUS_SUCCESS = 2;
|
||||
private static final int STATUS_ERROR = 3;
|
||||
private static final long TERMINAL_RENDER_INTERVAL_MS = 80L;
|
||||
private static final long[] SOCKET_RECONNECT_DELAYS_MS = {1000L, 2000L, 4000L, 8000L, 15000L};
|
||||
private static final int COLOR_APP_BG = Color.rgb(9, 11, 13);
|
||||
private static final int COLOR_BAR = Color.rgb(15, 18, 21);
|
||||
private static final int COLOR_PANEL = Color.rgb(22, 26, 30);
|
||||
@@ -92,7 +97,7 @@ public final class MainActivity extends Activity {
|
||||
private static final String PAGE_TOOLS = "Tools";
|
||||
private static final String PAGE_UPDATE = "Update";
|
||||
private static final String PAGE_ABOUT = "About";
|
||||
private static final String TERMINAL_ENTER = "\n";
|
||||
private static final String TERMINAL_ENTER = "\r";
|
||||
private static final String[] SERVER_PROFILES = {
|
||||
"http://100.89.0.116:3000",
|
||||
"http://100.89.0.2:3000",
|
||||
@@ -102,6 +107,7 @@ public final class MainActivity extends Activity {
|
||||
};
|
||||
|
||||
private final ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private SharedPreferences prefs;
|
||||
private UpdateManager updateManager;
|
||||
private SessionApiClient api;
|
||||
@@ -129,10 +135,18 @@ public final class MainActivity extends Activity {
|
||||
private TerminalScreenBuffer terminalScreen = new TerminalScreenBuffer(DEFAULT_TERMINAL_COLS, DEFAULT_TERMINAL_ROWS);
|
||||
private final StringBuilder queuedTerminalInput = new StringBuilder();
|
||||
private boolean terminalConnected;
|
||||
private boolean terminalConnecting;
|
||||
private boolean terminalRenderPending;
|
||||
private boolean terminalSelectionEnabled;
|
||||
private boolean terminalFollowOutput = true;
|
||||
private int terminalKeyPage;
|
||||
private int terminalReconnectAttempt;
|
||||
private int terminalConnectionGeneration;
|
||||
private int eventReconnectAttempt;
|
||||
private int eventConnectionGeneration;
|
||||
private boolean activityDestroyed;
|
||||
private Runnable terminalReconnectTask;
|
||||
private Runnable eventReconnectTask;
|
||||
private long lastTerminalRenderMs;
|
||||
private int terminalCols = DEFAULT_TERMINAL_COLS;
|
||||
private int terminalRows = DEFAULT_TERMINAL_ROWS;
|
||||
@@ -1146,7 +1160,7 @@ public final class MainActivity extends Activity {
|
||||
terminalText.setLineSpacing(0, 1.05f);
|
||||
terminalText.setGravity(Gravity.BOTTOM | Gravity.START);
|
||||
terminalText.setTextIsSelectable(terminalSelectionEnabled);
|
||||
terminalText.setPadding(dp(10), dp(10), dp(10), dp(10));
|
||||
terminalText.setPadding(dp(2), dp(8), dp(2), dp(8));
|
||||
terminalText.setBackgroundColor(COLOR_TERMINAL_BG);
|
||||
terminalScroll.addView(terminalText, new ScrollView.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
@@ -1320,9 +1334,10 @@ public final class MainActivity extends Activity {
|
||||
JSONObject rootObject = new JSONObject(text == null || text.isEmpty() ? "{}" : text);
|
||||
JSONArray projects = rootObject.optJSONArray("projects");
|
||||
if (projects == null) {
|
||||
terminalGroupRow.addView(groupLabel("no group"));
|
||||
renderUngroupedTerminalSessions(sessionName, null);
|
||||
return;
|
||||
}
|
||||
Set<String> groupedSessions = collectGroupedSessions(projects);
|
||||
for (int projectIndex = 0; projectIndex < projects.length(); projectIndex++) {
|
||||
JSONObject project = projects.optJSONObject(projectIndex);
|
||||
if (project == null) {
|
||||
@@ -1342,12 +1357,62 @@ public final class MainActivity extends Activity {
|
||||
}
|
||||
return;
|
||||
}
|
||||
terminalGroupRow.addView(groupLabel("no group"));
|
||||
renderUngroupedTerminalSessions(sessionName, groupedSessions);
|
||||
} catch (Exception error) {
|
||||
terminalGroupRow.addView(groupLabel("group parse"));
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> collectGroupedSessions(JSONArray projects) {
|
||||
Set<String> names = new HashSet<>();
|
||||
for (int projectIndex = 0; projectIndex < projects.length(); projectIndex++) {
|
||||
JSONObject project = projects.optJSONObject(projectIndex);
|
||||
JSONArray agents = project == null ? null : project.optJSONArray("agents");
|
||||
for (int agentIndex = 0; agents != null && agentIndex < agents.length(); agentIndex++) {
|
||||
String sessionName = agentSessionName(agents.optJSONObject(agentIndex));
|
||||
if (!sessionName.isEmpty()) {
|
||||
names.add(sessionName);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private void renderUngroupedTerminalSessions(String sessionName, Set<String> groupedSessions) {
|
||||
terminalGroupRow.addView(groupLabel("ungrouped..."));
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
List<SessionSummary> sessions = api.getSessions();
|
||||
runOnUiThread(() -> {
|
||||
if (!sessionName.equals(activeSessionName) || terminalGroupRow == null) {
|
||||
return;
|
||||
}
|
||||
terminalGroupRow.removeAllViews();
|
||||
terminalGroupRow.addView(groupLabel("ungrouped"));
|
||||
int count = 0;
|
||||
for (SessionSummary session : sessions) {
|
||||
if (groupedSessions != null && groupedSessions.contains(session.name)) {
|
||||
continue;
|
||||
}
|
||||
terminalGroupRow.addView(groupSessionButton(session.name, session.name.equals(sessionName)));
|
||||
count++;
|
||||
}
|
||||
if (count == 0) {
|
||||
terminalGroupRow.removeAllViews();
|
||||
terminalGroupRow.addView(groupLabel("no group"));
|
||||
}
|
||||
});
|
||||
} catch (Exception error) {
|
||||
runOnUiThread(() -> {
|
||||
if (sessionName.equals(activeSessionName) && terminalGroupRow != null) {
|
||||
terminalGroupRow.removeAllViews();
|
||||
terminalGroupRow.addView(groupLabel("ungrouped failed"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean projectContainsSession(JSONArray agents, String sessionName) {
|
||||
if (agents == null) {
|
||||
return false;
|
||||
@@ -1543,10 +1608,10 @@ public final class MainActivity extends Activity {
|
||||
|
||||
terminalKeyPageButton = terminalPageButton();
|
||||
LinearLayout.LayoutParams pageParams = new LinearLayout.LayoutParams(
|
||||
dp(70),
|
||||
dp(48)
|
||||
dp(62),
|
||||
dp(42)
|
||||
);
|
||||
pageParams.rightMargin = dp(6);
|
||||
pageParams.rightMargin = dp(4);
|
||||
row.addView(terminalKeyPageButton, pageParams);
|
||||
|
||||
inputField = new EditText(this);
|
||||
@@ -1555,7 +1620,7 @@ public final class MainActivity extends Activity {
|
||||
inputField.setHint("type, edit, paste");
|
||||
inputField.setSingleLine(false);
|
||||
inputField.setMinLines(1);
|
||||
inputField.setMaxLines(3);
|
||||
inputField.setMaxLines(2);
|
||||
inputField.setCursorVisible(true);
|
||||
inputField.setFocusableInTouchMode(true);
|
||||
inputField.setGravity(Gravity.TOP | Gravity.START);
|
||||
@@ -1581,13 +1646,9 @@ public final class MainActivity extends Activity {
|
||||
return false;
|
||||
});
|
||||
row.addView(inputField, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
|
||||
row.addView(toolbarButton("Type", view -> sendTypedText()), new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
dp(48)
|
||||
));
|
||||
row.addView(toolbarButton("Send", view -> sendLine()), new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
dp(48)
|
||||
dp(42)
|
||||
));
|
||||
bar.addView(row, matchWrap());
|
||||
return bar;
|
||||
@@ -2258,9 +2319,22 @@ public final class MainActivity extends Activity {
|
||||
}
|
||||
|
||||
private void connectTerminal(String sessionName) {
|
||||
closeTerminalSocket();
|
||||
queuedTerminalInput.setLength(0);
|
||||
terminalReconnectAttempt = 0;
|
||||
terminalConnectionGeneration++;
|
||||
cancelTerminalReconnect();
|
||||
closeTerminalSocket(false);
|
||||
connectTerminalSocket(sessionName, terminalConnectionGeneration);
|
||||
}
|
||||
|
||||
private void connectTerminalSocket(String sessionName, int generation) {
|
||||
if (activityDestroyed
|
||||
|| activeSessionName == null
|
||||
|| !sessionName.equals(activeSessionName)
|
||||
|| generation != terminalConnectionGeneration) {
|
||||
return;
|
||||
}
|
||||
terminalConnected = false;
|
||||
terminalConnecting = true;
|
||||
terminalSocketStatus = "terminal connecting";
|
||||
updateTerminalMeta();
|
||||
setStatus("Connecting " + sessionName);
|
||||
@@ -2270,7 +2344,12 @@ public final class MainActivity extends Activity {
|
||||
@Override
|
||||
public void onConnected() {
|
||||
runOnUiThread(() -> {
|
||||
if (!isCurrentTerminalConnection(sessionName, generation)) {
|
||||
return;
|
||||
}
|
||||
terminalConnected = true;
|
||||
terminalConnecting = false;
|
||||
terminalReconnectAttempt = 0;
|
||||
terminalSocketStatus = "terminal connected";
|
||||
updateTerminalMeta();
|
||||
setStatus("Connected " + sessionName);
|
||||
@@ -2281,12 +2360,20 @@ public final class MainActivity extends Activity {
|
||||
|
||||
@Override
|
||||
public void onOutput(String data) {
|
||||
runOnUiThread(() -> appendTerminal(data));
|
||||
runOnUiThread(() -> {
|
||||
if (isCurrentTerminalConnection(sessionName, generation)) {
|
||||
appendTerminal(data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(String message) {
|
||||
runOnUiThread(() -> {
|
||||
if (!isCurrentTerminalConnection(sessionName, generation)) {
|
||||
return;
|
||||
}
|
||||
terminalConnecting = false;
|
||||
appendTerminal("\r\n[error] " + message + "\r\n");
|
||||
terminalSocketStatus = "terminal error";
|
||||
updateTerminalMeta();
|
||||
@@ -2297,10 +2384,15 @@ public final class MainActivity extends Activity {
|
||||
@Override
|
||||
public void onClosed() {
|
||||
runOnUiThread(() -> {
|
||||
if (!isCurrentTerminalConnection(sessionName, generation)) {
|
||||
return;
|
||||
}
|
||||
terminalConnected = false;
|
||||
terminalConnecting = false;
|
||||
terminalSocketStatus = "terminal disconnected";
|
||||
updateTerminalMeta();
|
||||
setStatus("Disconnected " + sessionName);
|
||||
scheduleTerminalReconnect(sessionName, generation);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -2326,7 +2418,8 @@ public final class MainActivity extends Activity {
|
||||
if (lineHeight <= 0) {
|
||||
lineHeight = dp(16);
|
||||
}
|
||||
int cols = clamp((int) Math.floor((width - horizontalPadding) / charWidth) - 1, MIN_TERMINAL_COLS, MAX_TERMINAL_COLS);
|
||||
int usableWidth = Math.max(1, width - horizontalPadding);
|
||||
int cols = clamp((int) Math.floor(usableWidth / charWidth), MIN_TERMINAL_COLS, MAX_TERMINAL_COLS);
|
||||
int rows = clamp((height - verticalPadding) / lineHeight, MIN_TERMINAL_ROWS, MAX_TERMINAL_ROWS);
|
||||
if (cols == terminalCols && rows == terminalRows && !forceSend) {
|
||||
return;
|
||||
@@ -2360,23 +2453,9 @@ public final class MainActivity extends Activity {
|
||||
setStatus("Sent " + text.length() + " chars");
|
||||
}
|
||||
|
||||
private void sendTypedText() {
|
||||
if (inputField == null) {
|
||||
return;
|
||||
}
|
||||
String text = inputField.getText().toString();
|
||||
if (text.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String normalized = text.replace("\r\n", "\n").replace('\r', '\n');
|
||||
terminalFollowOutput = true;
|
||||
sendTerminalInput(normalized);
|
||||
inputField.setText("");
|
||||
setStatus("Typed " + text.length() + " chars");
|
||||
}
|
||||
|
||||
private void sendTerminalInput(String data) {
|
||||
if (activeSessionName == null) {
|
||||
String sessionName = activeSessionName;
|
||||
if (sessionName == null) {
|
||||
return;
|
||||
}
|
||||
TerminalSocketClient socket = terminalSocket;
|
||||
@@ -2385,7 +2464,7 @@ public final class MainActivity extends Activity {
|
||||
setStatus("Sent input");
|
||||
return;
|
||||
}
|
||||
if (socket != null && !socket.isClosed()) {
|
||||
if ((socket != null && !socket.isClosed()) || terminalConnecting || terminalReconnectTask != null) {
|
||||
queuedTerminalInput.append(data);
|
||||
setStatus("Queued input until terminal connects");
|
||||
return;
|
||||
@@ -2393,7 +2472,7 @@ public final class MainActivity extends Activity {
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
for (int i = 0; i < data.length(); i += 200) {
|
||||
api.sendInput(activeSessionName, data.substring(i, Math.min(i + 200, data.length())));
|
||||
api.sendInput(sessionName, data.substring(i, Math.min(i + 200, data.length())));
|
||||
}
|
||||
runOnUiThread(() -> setStatus("Sent input"));
|
||||
} catch (Exception error) {
|
||||
@@ -2673,9 +2752,9 @@ public final class MainActivity extends Activity {
|
||||
private Button terminalPageButton() {
|
||||
Button button = toolbarButton("", view -> setTerminalKeyPage(terminalKeyPage + 1));
|
||||
button.setTextSize(10);
|
||||
button.setPadding(dp(5), 0, dp(5), 0);
|
||||
button.setMinWidth(dp(70));
|
||||
button.setMinimumWidth(dp(70));
|
||||
button.setPadding(dp(4), 0, dp(4), 0);
|
||||
button.setMinWidth(dp(62));
|
||||
button.setMinimumWidth(dp(62));
|
||||
button.setOnLongClickListener(view -> {
|
||||
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
|
||||
setTerminalKeyPage(terminalKeyPage - 1);
|
||||
@@ -2691,7 +2770,7 @@ public final class MainActivity extends Activity {
|
||||
|
||||
private void updateTerminalPageButton(Button button) {
|
||||
if (button != null) {
|
||||
button.setText("‹ " + accessoryPageName() + " ›");
|
||||
button.setText(accessoryPageName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2708,7 +2787,7 @@ public final class MainActivity extends Activity {
|
||||
input.setTextColor(COLOR_TEXT);
|
||||
input.setHintTextColor(COLOR_TEXT_DIM);
|
||||
input.setTextSize(14);
|
||||
input.setPadding(dp(10), dp(8), dp(10), dp(8));
|
||||
input.setPadding(dp(9), dp(6), dp(9), dp(6));
|
||||
input.setBackground(inputBackground());
|
||||
}
|
||||
|
||||
@@ -2770,18 +2849,18 @@ public final class MainActivity extends Activity {
|
||||
|
||||
private void addSoftButton(LinearLayout row, String label, View.OnClickListener listener) {
|
||||
Button button = toolbarButton(label, listener);
|
||||
button.setTextSize(isArrowLabel(label) ? 17 : 10);
|
||||
button.setPadding(dp(5), 0, dp(5), 0);
|
||||
int width = "Space".equals(label) ? 64 : (isArrowLabel(label) ? 38 : 44);
|
||||
button.setTextSize(isArrowLabel(label) ? 15 : 9);
|
||||
button.setPadding(dp(4), 0, dp(4), 0);
|
||||
int width = "Space".equals(label) ? 56 : (isArrowLabel(label) ? 32 : 38);
|
||||
button.setMinWidth(dp(width));
|
||||
button.setMinimumWidth(dp(width));
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
dp(27)
|
||||
);
|
||||
params.leftMargin = dp(2);
|
||||
params.rightMargin = dp(2);
|
||||
params.topMargin = dp(1);
|
||||
params.leftMargin = dp(1);
|
||||
params.rightMargin = dp(1);
|
||||
params.topMargin = dp(2);
|
||||
params.bottomMargin = dp(1);
|
||||
row.addView(button, params);
|
||||
}
|
||||
@@ -2914,9 +2993,53 @@ public final class MainActivity extends Activity {
|
||||
return Math.round(value * getResources().getDisplayMetrics().density);
|
||||
}
|
||||
|
||||
private boolean isCurrentTerminalConnection(String sessionName, int generation) {
|
||||
return !activityDestroyed
|
||||
&& generation == terminalConnectionGeneration
|
||||
&& sessionName.equals(activeSessionName);
|
||||
}
|
||||
|
||||
private void scheduleTerminalReconnect(String sessionName, int generation) {
|
||||
if (!isCurrentTerminalConnection(sessionName, generation) || terminalReconnectTask != null) {
|
||||
return;
|
||||
}
|
||||
long delay = reconnectDelay(terminalReconnectAttempt++);
|
||||
terminalSocketStatus = "retry in " + Math.max(1L, delay / 1000L) + "s";
|
||||
updateTerminalMeta();
|
||||
setStatus("Terminal reconnecting in " + Math.max(1L, delay / 1000L) + "s");
|
||||
terminalReconnectTask = () -> {
|
||||
terminalReconnectTask = null;
|
||||
if (isCurrentTerminalConnection(sessionName, generation)) {
|
||||
connectTerminalSocket(sessionName, generation);
|
||||
}
|
||||
};
|
||||
mainHandler.postDelayed(terminalReconnectTask, delay);
|
||||
}
|
||||
|
||||
private void cancelTerminalReconnect() {
|
||||
if (terminalReconnectTask != null) {
|
||||
mainHandler.removeCallbacks(terminalReconnectTask);
|
||||
terminalReconnectTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
private long reconnectDelay(int attempt) {
|
||||
return SOCKET_RECONNECT_DELAYS_MS[Math.min(attempt, SOCKET_RECONNECT_DELAYS_MS.length - 1)];
|
||||
}
|
||||
|
||||
private void closeTerminalSocket() {
|
||||
terminalConnected = false;
|
||||
closeTerminalSocket(true);
|
||||
}
|
||||
|
||||
private void closeTerminalSocket(boolean invalidateConnection) {
|
||||
if (invalidateConnection) {
|
||||
terminalConnectionGeneration++;
|
||||
terminalReconnectAttempt = 0;
|
||||
cancelTerminalReconnect();
|
||||
queuedTerminalInput.setLength(0);
|
||||
}
|
||||
terminalConnected = false;
|
||||
terminalConnecting = false;
|
||||
terminalRenderPending = false;
|
||||
if (terminalSocket != null) {
|
||||
terminalSocket.close();
|
||||
@@ -2925,25 +3048,69 @@ public final class MainActivity extends Activity {
|
||||
}
|
||||
|
||||
private void connectAppEvents() {
|
||||
eventReconnectAttempt = 0;
|
||||
eventConnectionGeneration++;
|
||||
cancelEventReconnect();
|
||||
if (eventSocket != null) {
|
||||
eventSocket.close();
|
||||
eventSocket = null;
|
||||
}
|
||||
connectAppEventSocket(api.getBaseUrl(), eventConnectionGeneration);
|
||||
}
|
||||
|
||||
private void connectAppEventSocket(String baseUrl, int generation) {
|
||||
if (activityDestroyed || generation != eventConnectionGeneration) {
|
||||
return;
|
||||
}
|
||||
eventSocket = new AppEventSocketClient(new AppEventSocketClient.Listener() {
|
||||
@Override
|
||||
public void onMessage(String text) {
|
||||
runOnUiThread(() -> handleAppEvent(text));
|
||||
runOnUiThread(() -> {
|
||||
if (generation == eventConnectionGeneration && !activityDestroyed) {
|
||||
handleAppEvent(text);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosed() {
|
||||
runOnUiThread(() -> {
|
||||
if (generation != eventConnectionGeneration || activityDestroyed) {
|
||||
return;
|
||||
}
|
||||
terminalEventStatus = "events disconnected";
|
||||
updateTerminalMeta();
|
||||
setStatus("Event stream disconnected");
|
||||
scheduleEventReconnect(baseUrl, generation);
|
||||
});
|
||||
}
|
||||
});
|
||||
eventSocket.connect(api.getBaseUrl());
|
||||
eventSocket.connect(baseUrl);
|
||||
}
|
||||
|
||||
private void scheduleEventReconnect(String baseUrl, int generation) {
|
||||
if (activityDestroyed
|
||||
|| generation != eventConnectionGeneration
|
||||
|| eventReconnectTask != null) {
|
||||
return;
|
||||
}
|
||||
long delay = reconnectDelay(eventReconnectAttempt++);
|
||||
terminalEventStatus = "events retry in " + Math.max(1L, delay / 1000L) + "s";
|
||||
updateTerminalMeta();
|
||||
eventReconnectTask = () -> {
|
||||
eventReconnectTask = null;
|
||||
if (!activityDestroyed && generation == eventConnectionGeneration) {
|
||||
connectAppEventSocket(baseUrl, generation);
|
||||
}
|
||||
};
|
||||
mainHandler.postDelayed(eventReconnectTask, delay);
|
||||
}
|
||||
|
||||
private void cancelEventReconnect() {
|
||||
if (eventReconnectTask != null) {
|
||||
mainHandler.removeCallbacks(eventReconnectTask);
|
||||
eventReconnectTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAppEvent(String text) {
|
||||
@@ -2951,6 +3118,7 @@ public final class MainActivity extends Activity {
|
||||
JSONObject event = new JSONObject(text);
|
||||
String type = event.optString("type", "");
|
||||
if ("hello".equals(type)) {
|
||||
eventReconnectAttempt = 0;
|
||||
terminalEventStatus = "events connected";
|
||||
updateTerminalMeta();
|
||||
setStatus("Event stream connected");
|
||||
@@ -3043,11 +3211,23 @@ public final class MainActivity extends Activity {
|
||||
if (updateManager != null) {
|
||||
updateManager.resumePendingInstall();
|
||||
}
|
||||
if (activeSessionName != null
|
||||
&& !terminalConnected
|
||||
&& !terminalConnecting
|
||||
&& terminalReconnectTask == null) {
|
||||
scheduleTerminalReconnect(activeSessionName, terminalConnectionGeneration);
|
||||
}
|
||||
if ((eventSocket == null || eventSocket.isClosed()) && eventReconnectTask == null) {
|
||||
connectAppEvents();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
activityDestroyed = true;
|
||||
closeTerminalSocket();
|
||||
eventConnectionGeneration++;
|
||||
cancelEventReconnect();
|
||||
if (eventSocket != null) {
|
||||
eventSocket.close();
|
||||
eventSocket = null;
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -19,6 +20,10 @@ import java.util.concurrent.RejectedExecutionException;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
final class TerminalSocketClient {
|
||||
private static final long HEARTBEAT_INTERVAL_MS = 15000L;
|
||||
private static final int SOCKET_CONNECT_TIMEOUT_MS = 10000;
|
||||
private static final int SOCKET_READ_TIMEOUT_MS = 45000;
|
||||
|
||||
interface Listener {
|
||||
void onConnected();
|
||||
void onOutput(String data);
|
||||
@@ -35,6 +40,7 @@ final class TerminalSocketClient {
|
||||
private BufferedOutputStream output;
|
||||
private volatile boolean closed;
|
||||
private Thread thread;
|
||||
private Thread heartbeatThread;
|
||||
|
||||
TerminalSocketClient(Listener listener) {
|
||||
this.listener = listener;
|
||||
@@ -97,6 +103,7 @@ final class TerminalSocketClient {
|
||||
"rows", rows
|
||||
);
|
||||
listener.onConnected();
|
||||
startHeartbeat();
|
||||
readLoop();
|
||||
} catch (Exception error) {
|
||||
if (!closed) {
|
||||
@@ -123,10 +130,39 @@ final class TerminalSocketClient {
|
||||
if (port == -1) {
|
||||
port = "wss".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
|
||||
}
|
||||
Socket raw = new Socket();
|
||||
raw.connect(new InetSocketAddress(uri.getHost(), port), SOCKET_CONNECT_TIMEOUT_MS);
|
||||
Socket connected;
|
||||
if ("wss".equalsIgnoreCase(uri.getScheme())) {
|
||||
return SSLSocketFactory.getDefault().createSocket(uri.getHost(), port);
|
||||
connected = ((SSLSocketFactory) SSLSocketFactory.getDefault())
|
||||
.createSocket(raw, uri.getHost(), port, true);
|
||||
} else {
|
||||
connected = raw;
|
||||
}
|
||||
return new Socket(uri.getHost(), port);
|
||||
connected.setKeepAlive(true);
|
||||
connected.setTcpNoDelay(true);
|
||||
connected.setSoTimeout(SOCKET_READ_TIMEOUT_MS);
|
||||
return connected;
|
||||
}
|
||||
|
||||
private void startHeartbeat() {
|
||||
heartbeatThread = new Thread(() -> {
|
||||
while (!closed) {
|
||||
try {
|
||||
Thread.sleep(HEARTBEAT_INTERVAL_MS);
|
||||
if (!closed) {
|
||||
sendFrame(9, new byte[0]);
|
||||
}
|
||||
} catch (InterruptedException ignored) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
} catch (Exception error) {
|
||||
closeSocketQuietly();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, "terminal-ws-heartbeat");
|
||||
heartbeatThread.start();
|
||||
}
|
||||
|
||||
private void handshake(URI uri) throws Exception {
|
||||
@@ -279,6 +315,10 @@ final class TerminalSocketClient {
|
||||
}
|
||||
|
||||
private void closeSocketQuietly() {
|
||||
if (heartbeatThread != null) {
|
||||
heartbeatThread.interrupt();
|
||||
heartbeatThread = null;
|
||||
}
|
||||
try {
|
||||
if (socket != null) {
|
||||
socket.close();
|
||||
|
||||
Reference in New Issue
Block a user