Перевести звонки на SendSignal с client key

This commit is contained in:
AidarKC
2026-08-09 20:09:54 +04:00
parent 5c38f8f0d8
commit c511910b8f
11 changed files with 556 additions and 43 deletions
@@ -26,6 +26,7 @@ import java.util.Set;
public class Net_CallInviteBroadcast_Handler implements JsonMessageHandler {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final int TYPE_INVITE = 100;
private static final int TYPE_CONNECT_START = 170;
private static final long PUSH_CALL_TTL_MS = 10_000L;
@Override
@@ -38,8 +39,11 @@ public class Net_CallInviteBroadcast_Handler implements JsonMessageHandler {
String toRequest = req.getToLogin() == null ? "" : req.getToLogin().trim();
String callId = req.getCallId() == null ? "" : req.getCallId().trim();
int type = req.getType() == null ? TYPE_INVITE : req.getType();
if (toRequest.isBlank() || callId.isBlank() || type != TYPE_INVITE) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "toLogin/callId/type=100 обязательны");
String data = req.getData() == null ? "" : req.getData().trim();
boolean isInvite = type == TYPE_INVITE;
boolean isConnectStart = type == TYPE_CONNECT_START;
if (toRequest.isBlank() || callId.isBlank() || (!isInvite && !isConnectStart)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "toLogin/callId/type=100|170 обязательны");
}
CurrentUserEntry targetUser = CurrentUsersDAO.getInstance().getByLogin(toRequest);
@@ -69,13 +73,28 @@ public class Net_CallInviteBroadcast_Handler implements JsonMessageHandler {
payload.put("fromSessionId", ctx.getSessionId());
payload.put("toLogin", to);
payload.put("callId", callId);
payload.put("type", TYPE_INVITE);
payload.put("type", type);
payload.put("timeMs", timeMs);
if (!data.isBlank()) {
payload.put("data", data);
}
boolean sent = WsEventSender.sendEvent(targetCtx, "IncomingCallInvite", eventId, payload);
if (sent) wsDelivered++;
}
if (isConnectStart) {
Net_CallInviteBroadcast_Response resp = new Net_CallInviteBroadcast_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setCallId(callId);
resp.setDeliveredWsSessions(wsDelivered);
resp.setDeliveredFcmSessions(0);
resp.setDeliveredWebPushSessions(0);
return resp;
}
for (ActiveSessionEntry session : allTargetSessions) {
String sessionId = String.valueOf(session.getSessionId() == null ? "" : session.getSessionId()).trim();
if (!sessionId.isBlank() && activeSessionIds.contains(sessionId)) {
@@ -12,10 +12,12 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendSignal_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendSignal_Response;
import server.logic.ws_protocol.JSON.push.WebPushSender;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import server.logic.ws_protocol.JSON.utils.AuthKeyUtils;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.CurrentUserEntry;
@@ -34,6 +36,13 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
private static final String TARGET_MODE_SINGLE = "single_session";
private static final String TARGET_MODE_ALL = "all_sessions";
private static final long ALLOWED_SKEW_MS = 30_000L;
private static final long PUSH_CALL_TTL_MS = 10_000L;
private static final String SIGNAL_CALL_INVITE = "call_invite";
private static final String SIGNAL_CALL_ACCEPT = "call_accept";
private static final String SIGNAL_CALL_DECLINE_BUSY = "call_decline_busy";
private static final String SIGNAL_CALL_TIMEOUT = "call_timeout";
private static final String SIGNAL_CALL_HANGUP = "call_hangup";
private static final String SIGNAL_CALL_CONNECT_START = "call_connect_start";
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) throws Exception {
@@ -99,6 +108,10 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_SESSION_SIGNATURE", "Некорректная подпись session key");
}
if (isCallSignalType(signalType) && clientSignatureB64.isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "CLIENT_SIGNATURE_REQUIRED", "Для call_* сигналов обязательна подпись client key");
}
if (!clientSignatureB64.isBlank()) {
String clientPreimage = buildClientPreimage(fromLogin, fromSessionId, toLogin, targetMode, targetSessionId, signalType, signalRequestId, timeMs, digestB64);
if (!verifySignature(senderUser.getClientKey(), clientPreimage, clientSignatureB64, "clientKey")) {
@@ -107,7 +120,13 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
}
List<ConnectionContext> targets = resolveTargets(targetMode, toLogin, targetSessionId);
if (targets.isEmpty()) {
boolean isCallInviteAllSessions = TARGET_MODE_ALL.equals(targetMode) && SIGNAL_CALL_INVITE.equals(signalType);
boolean isCallAcceptSingleSession = TARGET_MODE_SINGLE.equals(targetMode) && SIGNAL_CALL_ACCEPT.equals(signalType);
boolean isCallTerminalSingleSession = TARGET_MODE_SINGLE.equals(targetMode)
&& (SIGNAL_CALL_DECLINE_BUSY.equals(signalType)
|| SIGNAL_CALL_TIMEOUT.equals(signalType)
|| SIGNAL_CALL_HANGUP.equals(signalType));
if (targets.isEmpty() && !isCallInviteAllSessions) {
String code = TARGET_MODE_SINGLE.equals(targetMode) ? "SESSION_NOT_FOUND" : "NO_TARGET_SESSIONS";
String msg = TARGET_MODE_SINGLE.equals(targetMode) ? "Целевая сессия не найдена" : "Нет активных сессий для доставки сигнала";
return NetExceptionResponseFactory.error(req, 404, code, msg);
@@ -135,16 +154,62 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
}
}
if (deliveredSessionIds.isEmpty()) {
int webPushDelivered = 0;
if (isCallInviteAllSessions) {
webPushDelivered = sendIncomingCallPushToOfflineSessions(
toLogin,
fromLogin,
fromSessionId,
signalRequestId,
deliveredSessionIds
);
}
if (deliveredSessionIds.isEmpty() && webPushDelivered <= 0) {
return NetExceptionResponseFactory.error(req, 404, "DELIVERY_FAILED", "Не удалось доставить сигнал ни в одну целевую сессию");
}
if (isCallAcceptSingleSession) {
notifyStopOnOtherSessions(
fromLogin,
fromSessionId,
fromLogin,
fromSessionId,
signalRequestId,
"accepted_on_other_device"
);
}
if (isCallTerminalSingleSession) {
String deliveredTargetSessionId = deliveredSessionIds.isEmpty() ? targetSessionId : deliveredSessionIds.get(0);
String reason = "terminal_call_signal_" + signalType;
notifyStopOnOtherSessions(
fromLogin,
fromSessionId,
fromLogin,
fromSessionId,
signalRequestId,
reason
);
notifyStopOnOtherSessions(
toLogin,
deliveredTargetSessionId,
fromLogin,
fromSessionId,
signalRequestId,
reason
);
}
Net_SendSignal_Response resp = new Net_SendSignal_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setDeliveredCount(deliveredSessionIds.size());
resp.setDeliveredCount(deliveredSessionIds.size() + webPushDelivered);
resp.setDeliveredSessionIds(deliveredSessionIds);
resp.setDeliveredWsSessions(deliveredSessionIds.size());
resp.setDeliveredFcmSessions(webPushDelivered);
resp.setDeliveredWebPushSessions(webPushDelivered);
return resp;
}
@@ -190,6 +255,19 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
+ dataSha256B64;
}
private static boolean isCallSignalType(String signalType) {
return SIGNAL_CALL_INVITE.equals(signalType)
|| "call_ringing".equals(signalType)
|| SIGNAL_CALL_ACCEPT.equals(signalType)
|| SIGNAL_CALL_DECLINE_BUSY.equals(signalType)
|| SIGNAL_CALL_TIMEOUT.equals(signalType)
|| SIGNAL_CALL_HANGUP.equals(signalType)
|| SIGNAL_CALL_CONNECT_START.equals(signalType)
|| "call_offer".equals(signalType)
|| "call_answer".equals(signalType)
|| "call_ice".equals(signalType);
}
private static boolean verifySignature(String publicKeyValue, String preimage, String signatureB64, String fieldName) throws Exception {
byte[] publicKey32 = AuthKeyUtils.parseEd25519PublicKey(publicKeyValue, fieldName);
byte[] signature64 = Base64Ws.decodeLen(signatureB64, 64, "signatureB64");
@@ -214,7 +292,130 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
return targets;
}
private int sendIncomingCallPushToOfflineSessions(
String toLogin,
String fromLogin,
String fromSessionId,
String callId,
List<String> deliveredOnlineSessionIds
) throws Exception {
List<ActiveSessionEntry> persistedSessions = ActiveSessionsDAO.getInstance().getByLogin(toLogin);
long sentAtMs = System.currentTimeMillis();
long expiresAtMs = sentAtMs + PUSH_CALL_TTL_MS;
int delivered = 0;
for (ActiveSessionEntry session : persistedSessions) {
String sessionId = safe(session.getSessionId());
if (!sessionId.isBlank() && deliveredOnlineSessionIds.contains(sessionId)) {
continue;
}
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
continue;
}
String payload = "{\"kind\":\"incoming_call\""
+ ",\"title\":\"SHiNE: входящий звонок\""
+ ",\"text\":\"Вам звонит " + jsonEscape(fromLogin) + "\""
+ ",\"fromLogin\":\"" + jsonEscape(fromLogin) + "\""
+ ",\"fromSessionId\":\"" + jsonEscape(fromSessionId) + "\""
+ ",\"targetSessionId\":\"" + jsonEscape(sessionId) + "\""
+ ",\"toLogin\":\"" + jsonEscape(toLogin) + "\""
+ ",\"callId\":\"" + jsonEscape(callId) + "\""
+ ",\"sentAtMs\":" + sentAtMs
+ ",\"expiresAtMs\":" + expiresAtMs
+ "}";
boolean pushed = WebPushSender.sendBase64Payload(
session.getPushEndpoint(),
session.getPushP256dhKey(),
session.getPushAuthKey(),
payload
);
if (pushed) {
delivered++;
}
}
return delivered;
}
private void notifyStopOnOtherSessions(
String targetLogin,
String excludeSessionId,
String fromLogin,
String fromSessionId,
String callId,
String reason
) throws Exception {
if (isBlank(targetLogin) || isBlank(callId)) {
return;
}
Set<String> onlineSessionIds = new java.util.HashSet<>();
Set<ConnectionContext> sameUserSessions = ActiveConnectionsRegistry.getInstance().getByLogin(targetLogin);
for (ConnectionContext siblingCtx : sameUserSessions) {
if (siblingCtx == null || siblingCtx.getWsSession() == null || !siblingCtx.getWsSession().isOpen()) continue;
onlineSessionIds.add(safe(siblingCtx.getSessionId()));
if (!isBlank(excludeSessionId) && excludeSessionId.equals(siblingCtx.getSessionId())) continue;
String siblingEventId = server.logic.ws_protocol.JSON.utils.NetIdGenerator.eventId("evt");
ObjectNode siblingPayload = MAPPER.createObjectNode();
siblingPayload.put("eventId", siblingEventId);
siblingPayload.put("fromLogin", fromLogin);
siblingPayload.put("fromSessionId", fromSessionId);
siblingPayload.put("toLogin", targetLogin);
siblingPayload.put("targetMode", TARGET_MODE_SINGLE);
siblingPayload.put("targetSessionId", safe(siblingCtx.getSessionId()));
siblingPayload.put("signalType", SIGNAL_CALL_HANGUP);
siblingPayload.put("signalRequestId", callId);
siblingPayload.put("data", "{\"callId\":\"" + jsonEscape(callId) + "\",\"type\":150,\"data\":\"" + jsonEscape(reason) + "\"}");
siblingPayload.put("timeMs", System.currentTimeMillis());
WsEventSender.sendEvent(siblingCtx, "IncomingSignal", siblingEventId, siblingPayload);
}
List<ActiveSessionEntry> persistedSessions = ActiveSessionsDAO.getInstance().getByLogin(targetLogin);
long sentAtMs = System.currentTimeMillis();
for (ActiveSessionEntry session : persistedSessions) {
String sessionId = safe(session.getSessionId());
if (!isBlank(excludeSessionId) && excludeSessionId.equals(sessionId)) continue;
if (!sessionId.isBlank() && onlineSessionIds.contains(sessionId)) continue;
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
continue;
}
String pushPayload = "{\"kind\":\"stop_call\""
+ ",\"callId\":\"" + jsonEscape(callId) + "\""
+ ",\"reason\":\"" + jsonEscape(reason) + "\""
+ ",\"fromLogin\":\"" + jsonEscape(fromLogin) + "\""
+ ",\"fromSessionId\":\"" + jsonEscape(fromSessionId) + "\""
+ ",\"targetSessionId\":\"" + jsonEscape(sessionId) + "\""
+ ",\"toLogin\":\"" + jsonEscape(targetLogin) + "\""
+ ",\"sentAtMs\":" + sentAtMs
+ "}";
WebPushSender.sendBase64Payload(
session.getPushEndpoint(),
session.getPushP256dhKey(),
session.getPushAuthKey(),
pushPayload
);
}
}
private static String safe(String value) {
return value == null ? "" : value.trim();
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
private static String jsonEscape(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') out.append("\\\\");
else if (c == '"') out.append("\\\"");
else if (c == '\n') out.append("\\n");
else if (c == '\r') out.append("\\r");
else if (c == '\t') out.append("\\t");
else out.append(c);
}
return out.toString();
}
}
@@ -6,6 +6,7 @@ public class Net_CallInviteBroadcast_Request extends Net_Request {
private String toLogin;
private String callId;
private Integer type;
private String data;
public String getToLogin() { return toLogin; }
public void setToLogin(String toLogin) { this.toLogin = toLogin; }
@@ -15,4 +16,7 @@ public class Net_CallInviteBroadcast_Request extends Net_Request {
public Integer getType() { return type; }
public void setType(Integer type) { this.type = type; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
}
@@ -8,6 +8,9 @@ import java.util.List;
public class Net_SendSignal_Response extends Net_Response {
private int deliveredCount;
private List<String> deliveredSessionIds = new ArrayList<>();
private int deliveredWsSessions;
private int deliveredFcmSessions;
private int deliveredWebPushSessions;
public int getDeliveredCount() {
return deliveredCount;
@@ -24,4 +27,28 @@ public class Net_SendSignal_Response extends Net_Response {
public void setDeliveredSessionIds(List<String> deliveredSessionIds) {
this.deliveredSessionIds = deliveredSessionIds;
}
public int getDeliveredWsSessions() {
return deliveredWsSessions;
}
public void setDeliveredWsSessions(int deliveredWsSessions) {
this.deliveredWsSessions = deliveredWsSessions;
}
public int getDeliveredFcmSessions() {
return deliveredFcmSessions;
}
public void setDeliveredFcmSessions(int deliveredFcmSessions) {
this.deliveredFcmSessions = deliveredFcmSessions;
}
public int getDeliveredWebPushSessions() {
return deliveredWebPushSessions;
}
public void setDeliveredWebPushSessions(int deliveredWebPushSessions) {
this.deliveredWebPushSessions = deliveredWebPushSessions;
}
}