Доработать UI и счётчики

This commit is contained in:
AidarKC
2026-09-08 22:33:06 +04:00
parent 1f70d36e74
commit ae2f2fac41
18 changed files with 378 additions and 105 deletions
@@ -80,6 +80,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handle
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListGroupChats200_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListSubscriptionsFeed_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetUserCounters_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelsCounters_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetGroupDialog_Request;
@@ -87,6 +88,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageTh
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetPersonalDiary_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Request;
import server.logic.ws_protocol.JSON.handlers.connections.Net_GetUserConnectionsGraph_Handler;
import server.logic.ws_protocol.JSON.handlers.profile.Net_ListUserProfileRelations_Handler;
import server.logic.ws_protocol.JSON.handlers.profile.Net_ListUserProfileChannels_Handler;
@@ -211,6 +213,7 @@ public final class JsonHandlerRegistry {
Map.entry("GetGroupDialog", new Net_GetGroupDialog_Handler()),
Map.entry("ListGroupChats200", new Net_ListGroupChats200_Handler()),
Map.entry("GetChannelsCounters", new Net_GetChannelsCounters_Handler()),
Map.entry("GetUserCounters", new Net_GetUserCounters_Handler()),
Map.entry("ListContacts", new Net_ListContacts_Handler()),
Map.entry("GetUserConnectionsGraph", new Net_GetUserConnectionsGraph_Handler()),
Map.entry("ListUserProfileRelations", new Net_ListUserProfileRelations_Handler()),
@@ -302,6 +305,7 @@ public final class JsonHandlerRegistry {
Map.entry("GetGroupDialog", Net_GetGroupDialog_Request.class),
Map.entry("ListGroupChats200", Net_ListGroupChats200_Request.class),
Map.entry("GetChannelsCounters", Net_GetChannelsCounters_Request.class),
Map.entry("GetUserCounters", Net_GetUserCounters_Request.class),
Map.entry("ListContacts", Net_ListContacts_Request.class),
Map.entry("GetUserConnectionsGraph", Net_GetUserConnectionsGraph_Request.class),
Map.entry("ListUserProfileRelations", Net_ListUserProfileRelations_Request.class),
@@ -0,0 +1,46 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.DbController;
import java.sql.Connection;
public class Net_GetUserCounters_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetUserCounters_Handler.class);
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetUserCounters_Request req = (Net_GetUserCounters_Request) baseRequest;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Требуется авторизация");
}
String login = ctx.getLogin().trim();
try (Connection c = DbController.getInstance().getConnection()) {
UserCountersSupport.Snapshot s = UserCountersSupport.calculate(c, login);
Net_GetUserCounters_Response r = new Net_GetUserCounters_Response();
r.setOp(req.getOp());
r.setRequestId(req.getRequestId());
r.setStatus(WireCodes.Status.OK);
r.setLogin(login);
r.setDmUnreadCount(s.dmUnreadCount());
r.setChannelsUnreadCount(s.channelsUnreadCount());
r.setNotificationsUnreadCount(s.notificationsUnreadCount());
r.setNotificationRepliesUnreadCount(s.repliesUnreadCount());
r.setNotificationConnectionsUnreadCount(s.connectionsUnreadCount());
r.setNotificationEventsUnreadCount(s.eventsUnreadCount());
return r;
} catch (Exception e) {
log.error("GetUserCounters failed for {}", login, e);
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR, "internal_error", "Не удалось получить счётчики");
}
}
}
@@ -0,0 +1,116 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import shine.db.DbController;
import shine.db.MsgSubType;
import shine.db.dao.UserNotificationSeenStateDAO;
import shine.db.dao.UserNotificationsStateDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Temporary calculator behind the stable GetUserCounters/UserCountersChanged contract.
* It intentionally uses current DB state today; later it can read one materialized row/cache
* without changing API or UI.
*/
public final class UserCountersSupport {
private static final ObjectMapper MAPPER = new ObjectMapper();
private UserCountersSupport() {}
public record Snapshot(long dmUnreadCount, long channelsUnreadCount, long repliesUnreadCount,
long connectionsUnreadCount, long eventsUnreadCount) {
public long notificationsUnreadCount() {
return repliesUnreadCount + connectionsUnreadCount + eventsUnreadCount;
}
}
public static Snapshot calculate(Connection c, String login) throws Exception {
long dm = countDmUnread(c, login);
long channels = countChannelsUnread(c, login);
UserNotificationSeenStateDAO seen = UserNotificationSeenStateDAO.getInstance();
UserNotificationsStateDAO notifications = UserNotificationsStateDAO.getInstance();
long repliesSeen = seen.getSeenAt(c, login, "replies");
long connectionsSeen = seen.getSeenAt(c, login, "connections");
long eventsSeen = seen.getSeenAt(c, login, "events");
long replies = notifications.countUnseen(c, login, "reply", repliesSeen);
long connections = notifications.countUnseen(c, login, "connection", connectionsSeen);
long events = notifications.countUnseen(c, login, "event", eventsSeen);
return new Snapshot(dm, channels, replies, connections, events);
}
public static Snapshot calculate(String login) throws Exception {
try (Connection c = DbController.getInstance().getConnection()) {
return calculate(c, login);
}
}
public static void pushChanged(String login) {
if (login == null || login.isBlank()) return;
try {
Snapshot s = calculate(login);
ObjectNode payload = toPayload(login, s);
String eventId = "user-counters-" + System.currentTimeMillis();
for (ConnectionContext ctx : ActiveConnectionsRegistry.getInstance().getByLogin(login)) {
WsEventSender.sendEvent(ctx, "UserCountersChanged", eventId, payload);
}
} catch (Exception ignored) {
// Counter push is best-effort. The client can always recover with GetUserCounters.
}
}
public static ObjectNode toPayload(String login, Snapshot s) {
ObjectNode p = MAPPER.createObjectNode();
p.put("login", login);
p.put("dmUnreadCount", s.dmUnreadCount());
p.put("channelsUnreadCount", s.channelsUnreadCount());
p.put("notificationsUnreadCount", s.notificationsUnreadCount());
ObjectNode n = p.putObject("notifications");
n.put("replies", s.repliesUnreadCount());
n.put("connections", s.connectionsUnreadCount());
n.put("events", s.eventsUnreadCount());
return p;
}
private static long countDmUnread(Connection c, String login) throws Exception {
String sql = "SELECT COALESCE(SUM(unread_count),0) FROM dm_dialog_state WHERE LOWER(owner_login)=LOWER(?)";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? Math.max(0L, rs.getLong(1)) : 0L;
}
}
}
private static long countChannelsUnread(Connection c, String login) throws Exception {
String sql = """
SELECT cs.to_bch_name, COALESCE(cs.to_block_number,0) AS root_number
FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=?
""";
long total = 0L;
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setInt(2, MsgSubType.CONNECTION_FOLLOW);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String ownerBch = rs.getString("to_bch_name");
int rootNumber = rs.getInt("root_number");
if (ownerBch == null || ownerBch.isBlank()) continue;
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, ownerBch, rootNumber);
if (meta == null || meta.channelName == null || meta.channelName.isBlank()) continue;
if (meta.channelTypeCode == 0 || "stories".equalsIgnoreCase(meta.channelName)) continue;
int messages = ChannelsReadSupport.countPosts(c, ownerBch, rootNumber);
total += Math.max(0, ChannelsReadSupport.countUnreadMessages(c, login, ownerBch, meta.channelName, messages));
}
}
}
return total;
}
}
@@ -0,0 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Lightweight authenticated request for bottom-toolbar counters. */
public class Net_GetUserCounters_Request extends Net_Request {
}
@@ -0,0 +1,29 @@
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
/** Stable UI contract. Server-side calculation may be replaced by materialized counters later. */
public class Net_GetUserCounters_Response extends Net_Response {
private String login;
private long dmUnreadCount;
private long channelsUnreadCount;
private long notificationsUnreadCount;
private long notificationRepliesUnreadCount;
private long notificationConnectionsUnreadCount;
private long notificationEventsUnreadCount;
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public long getDmUnreadCount() { return dmUnreadCount; }
public void setDmUnreadCount(long value) { this.dmUnreadCount = value; }
public long getChannelsUnreadCount() { return channelsUnreadCount; }
public void setChannelsUnreadCount(long value) { this.channelsUnreadCount = value; }
public long getNotificationsUnreadCount() { return notificationsUnreadCount; }
public void setNotificationsUnreadCount(long value) { this.notificationsUnreadCount = value; }
public long getNotificationRepliesUnreadCount() { return notificationRepliesUnreadCount; }
public void setNotificationRepliesUnreadCount(long value) { this.notificationRepliesUnreadCount = value; }
public long getNotificationConnectionsUnreadCount() { return notificationConnectionsUnreadCount; }
public void setNotificationConnectionsUnreadCount(long value) { this.notificationConnectionsUnreadCount = value; }
public long getNotificationEventsUnreadCount() { return notificationEventsUnreadCount; }
public void setNotificationEventsUnreadCount(long value) { this.notificationEventsUnreadCount = value; }
}
@@ -5,6 +5,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.notifications.entyties.*;
import server.logic.ws_protocol.JSON.handlers.channels.UserCountersSupport;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.DbController;
@@ -23,7 +24,7 @@ public final class Net_SetNotificationState_Handler implements JsonMessageHandle
byte[] pub=Ed25519Util.keyFromBase64(ctx.getCurrentUser().getClientKey()); if(!Ed25519Util.verify(p.signedBody,p.signature64,pub)) return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"BAD_SIGNATURE","Некорректная подпись clientKey");
long now=System.currentTimeMillis(); if(p.timeMs>now+5*60_000L) return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"BAD_TIME","Некорректное время подписи");
long actual; try(Connection c=DbController.getInstance().getConnection()){ actual=UserNotificationSeenStateDAO.getInstance().advance(c,login,p.categoryName(),p.seenAtMs,p.timeMs,raw); }
Net_SetNotificationState_Response r=new Net_SetNotificationState_Response(); r.setOp(req.getOp()); r.setRequestId(req.getRequestId()); r.setStatus(WireCodes.Status.OK); r.setCategory(p.categoryName()); r.setSeenAtMs(actual); return r;
Net_SetNotificationState_Response r=new Net_SetNotificationState_Response(); r.setOp(req.getOp()); r.setRequestId(req.getRequestId()); r.setStatus(WireCodes.Status.OK); r.setCategory(p.categoryName()); r.setSeenAtMs(actual); UserCountersSupport.pushChanged(login); return r;
}catch(Exception e){ return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"BAD_NOTIFICATION_STATE",e.getMessage()==null?"Некорректное состояние уведомлений":e.getMessage()); }
}
}
@@ -9,6 +9,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.userSettings.entyties.Net_UpsertUserSetting_Request;
import server.logic.ws_protocol.JSON.handlers.userSettings.entyties.Net_UpsertUserSetting_Response;
import server.logic.ws_protocol.JSON.handlers.channels.UserCountersSupport;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.DbController;
@@ -100,6 +101,9 @@ public class Net_UpsertUserSetting_Handler implements JsonMessageHandler {
resp.setSetting_type(settingType);
resp.setSetting_key(settingKey);
resp.setTime_ms(timeMs);
if (settingType == 1) {
UserCountersSupport.pushChanged(login);
}
return resp;
}
} catch (SQLException e) {
@@ -4,6 +4,7 @@ import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.channels.UserCountersSupport;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
@@ -59,6 +60,8 @@ public class Net_ReceiveIncomingMessage_Handler implements JsonMessageHandler {
SignedMessagesRealtime.DeliveryCounters counters = new SignedMessagesRealtime.DeliveryCounters();
if (status.applied()) {
counters = SignedMessagesRealtime.deliverToRelevantSessions(entry, incoming);
UserCountersSupport.pushChanged(incoming.toLogin);
UserCountersSupport.pushChanged(incoming.fromLogin);
}
if (status == SignedMessagesDAO.ApplyStatus.BLOCKED_BY_CONVERSATION_TOMBSTONE) {
bounceConversationDeleteIfKnown(incoming.fromLogin, incoming.toLogin);
@@ -4,6 +4,7 @@ import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.channels.UserCountersSupport;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendMessagePair_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendMessagePair_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
@@ -78,6 +79,14 @@ public class Net_SendMessagePair_Handler implements JsonMessageHandler {
SignedMessagesRealtime.DeliveryCounters outCounters = new SignedMessagesRealtime.DeliveryCounters();
if (pairStatus.applied()) {
outCounters = SignedMessagesRealtime.deliverToRelevantSessions(outgoingEntry, outgoing, excludeSessionId);
// SendMessagePair is also the local-server delivery path. Without this push,
// a recipient on the same access server receives the DM but the toolbar
// counter stays stale until the next explicit GetUserCounters refresh.
UserCountersSupport.pushChanged(incoming.toLogin);
if (!incoming.fromLogin.equalsIgnoreCase(incoming.toLogin)) {
UserCountersSupport.pushChanged(incoming.fromLogin);
}
}
if (pairStatus == SignedMessagesDAO.ApplyStatus.BLOCKED_BY_CONVERSATION_TOMBSTONE) {