SHA256
Compare commits
4
Commits
0c5089fa79
...
e0295eebde
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
e0295eebde | ||
|
|
ebc9143593 | ||
|
|
e7c8fd748c | ||
|
|
aff601f61a |
@@ -36,6 +36,7 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_17 = 17;
|
||||
public static final int SCHEMA_VERSION_18 = 18;
|
||||
public static final int SCHEMA_VERSION_19 = 19;
|
||||
public static final int SCHEMA_VERSION_20 = 20;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V2_RESOURCE = "postgres/migration_v2.sql";
|
||||
public static final String POSTGRES_MIGRATION_V3_RESOURCE = "postgres/migration_v3.sql";
|
||||
@@ -55,6 +56,7 @@ public final class DatabaseInitializer {
|
||||
public static final String POSTGRES_MIGRATION_V17_RESOURCE = "postgres/migration_v17.sql";
|
||||
public static final String POSTGRES_MIGRATION_V18_RESOURCE = "postgres/migration_v18.sql";
|
||||
public static final String POSTGRES_MIGRATION_V19_RESOURCE = "postgres/migration_v19.sql";
|
||||
public static final String POSTGRES_MIGRATION_V20_RESOURCE = "postgres/migration_v20.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -200,6 +202,10 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V19_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_19;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_20) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V20_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_20;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,16 +77,18 @@ public final class DmDialogStateDAO {
|
||||
ps.setString(1, cleanOwner);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
long lastMessageTimeMs = rs.getLong("last_message_time_ms");
|
||||
int unreadCount = rs.getInt("unread_count");
|
||||
DialogSummary row = new DialogSummary(
|
||||
rs.getString("owner_login"),
|
||||
rs.getString("peer_login"),
|
||||
normalizeRelationFlag(rs.getString("relation_flag")),
|
||||
rs.getString("last_message_blob_b64"),
|
||||
rs.getLong("last_message_time_ms"),
|
||||
rs.getInt("unread_count"),
|
||||
lastMessageTimeMs,
|
||||
unreadCount,
|
||||
rs.getLong("last_read_receipt_time_ms"),
|
||||
rs.getLong("updated_at_ms"),
|
||||
true
|
||||
lastMessageTimeMs > 0 || unreadCount > 0
|
||||
);
|
||||
byPeer.put(normKey(row.peerLogin()), row);
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
public final class UserNotificationSeenStateDAO {
|
||||
private static final UserNotificationSeenStateDAO INSTANCE = new UserNotificationSeenStateDAO();
|
||||
private UserNotificationSeenStateDAO() {}
|
||||
public static UserNotificationSeenStateDAO getInstance() { return INSTANCE; }
|
||||
|
||||
public long getSeenAt(Connection c, String login, String category) throws Exception {
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT seen_at_ms FROM user_notification_seen_state WHERE owner_login=? AND category=?")) {
|
||||
ps.setString(1, login); ps.setString(2, category);
|
||||
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
|
||||
}
|
||||
}
|
||||
|
||||
public long advance(Connection c, String login, String category, long seenAtMs, long signedAtMs, byte[] signedBlob) throws Exception {
|
||||
String sql = """
|
||||
INSERT INTO user_notification_seen_state(owner_login, category, seen_at_ms, signed_blob, signed_at_ms, updated_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(owner_login, category) DO UPDATE SET
|
||||
seen_at_ms=EXCLUDED.seen_at_ms, signed_blob=EXCLUDED.signed_blob,
|
||||
signed_at_ms=EXCLUDED.signed_at_ms, updated_at_ms=EXCLUDED.updated_at_ms
|
||||
WHERE user_notification_seen_state.seen_at_ms < EXCLUDED.seen_at_ms
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, login); ps.setString(2, category); ps.setLong(3, seenAtMs);
|
||||
ps.setBytes(4, signedBlob); ps.setLong(5, signedAtMs); ps.setLong(6, System.currentTimeMillis());
|
||||
ps.executeUpdate();
|
||||
}
|
||||
return getSeenAt(c, login, category);
|
||||
}
|
||||
}
|
||||
+27
@@ -84,6 +84,33 @@ public final class UserNotificationsStateDAO {
|
||||
return out;
|
||||
}
|
||||
|
||||
public List<UserNotificationEntry> listVisible(Connection c, String ownerLogin, String kind, long seenAtMs, long cutoffMs) throws SQLException {
|
||||
String sql = """
|
||||
SELECT owner_login, notification_kind, created_at_ms, source_login, source_bch_name,
|
||||
source_block_number, source_block_hash, target_login, target_bch_name,
|
||||
target_block_number, target_block_hash, source_msg_sub_type, source_text
|
||||
FROM user_notifications_state
|
||||
WHERE owner_login = ? AND notification_kind = ?
|
||||
AND (created_at_ms > ? OR created_at_ms >= ?)
|
||||
ORDER BY created_at_ms DESC, source_block_number DESC
|
||||
""";
|
||||
List<UserNotificationEntry> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
ps.setLong(4, Math.max(0, cutoffMs));
|
||||
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException {
|
||||
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
|
||||
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
|
||||
}
|
||||
}
|
||||
|
||||
private static UserNotificationEntry mapRow(ResultSet rs) throws SQLException {
|
||||
UserNotificationEntry e = new UserNotificationEntry();
|
||||
e.setOwnerLogin(rs.getString("owner_login"));
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Notifications v2: three categories + signed seen watermarks.
|
||||
|
||||
ALTER TABLE user_notifications_state
|
||||
DROP CONSTRAINT IF EXISTS user_notifications_state_notification_kind_check;
|
||||
ALTER TABLE user_notifications_state
|
||||
ADD CONSTRAINT user_notifications_state_notification_kind_check
|
||||
CHECK (notification_kind IN ('reply', 'connection', 'event'));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_notification_seen_state (
|
||||
owner_login VARCHAR(60) NOT NULL,
|
||||
category TEXT NOT NULL CHECK (category IN ('replies', 'connections', 'events')),
|
||||
seen_at_ms BIGINT NOT NULL DEFAULT 0,
|
||||
signed_blob BYTEA NOT NULL,
|
||||
signed_at_ms BIGINT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL,
|
||||
PRIMARY KEY (owner_login, category)
|
||||
);
|
||||
|
||||
UPDATE db_schema_version SET schema_version = 20 WHERE id = 1;
|
||||
@@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS db_schema_version (
|
||||
);
|
||||
|
||||
INSERT INTO db_schema_version (id, schema_version, updated_at_ms)
|
||||
VALUES (1, 18, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
|
||||
VALUES (1, 20, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
schema_version = EXCLUDED.schema_version,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms;
|
||||
@@ -765,7 +765,7 @@ CREATE INDEX IF NOT EXISTS idx_signed_message_delivery_session
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_notifications_state (
|
||||
owner_login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login),
|
||||
notification_kind TEXT NOT NULL CHECK (notification_kind IN ('reply', 'connection')),
|
||||
notification_kind TEXT NOT NULL CHECK (notification_kind IN ('reply', 'connection', 'event')),
|
||||
created_at_ms BIGINT NOT NULL,
|
||||
source_login TEXT NOT NULL,
|
||||
source_bch_name TEXT NOT NULL,
|
||||
@@ -1997,8 +1997,20 @@ UPDATE message_stats ms SET
|
||||
AND rs.to_login=ms.to_login AND rs.to_bch_name=ms.to_bch_name AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash
|
||||
AND shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login));
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_notification_seen_state (
|
||||
owner_login VARCHAR(60) NOT NULL,
|
||||
category TEXT NOT NULL CHECK (category IN ('replies', 'connections', 'events')),
|
||||
seen_at_ms BIGINT NOT NULL DEFAULT 0,
|
||||
signed_blob BYTEA NOT NULL,
|
||||
signed_at_ms BIGINT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL,
|
||||
PRIMARY KEY (owner_login, category)
|
||||
);
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms)
|
||||
VALUES(1,18,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
VALUES(1,20,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
|
||||
COMMIT;
|
||||
|
||||
|
||||
+4
@@ -95,10 +95,12 @@ import server.logic.ws_protocol.JSON.handlers.profile.entyties.Net_ListUserProfi
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.Net_AddCloseFriend_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.Net_ListContacts_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.Net_GetNotifications_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.Net_SetNotificationState_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_GetUserConnectionsGraph_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_AddCloseFriend_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_ListContacts_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.entyties.Net_GetNotifications_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.entyties.Net_SetNotificationState_Request;
|
||||
import server.logic.ws_protocol.JSON.messages.Net_AckSessionDelivery_Handler;
|
||||
import server.logic.ws_protocol.JSON.messages.Net_CallInviteBroadcast_Handler;
|
||||
import server.logic.ws_protocol.JSON.messages.Net_CallSignalToSession_Handler;
|
||||
@@ -215,6 +217,7 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("ListUserProfileChannels", new Net_ListUserProfileChannels_Handler()),
|
||||
Map.entry("AddCloseFriend", new Net_AddCloseFriend_Handler()),
|
||||
Map.entry("GetNotifications", new Net_GetNotifications_Handler()),
|
||||
Map.entry("SetNotificationState", new Net_SetNotificationState_Handler()),
|
||||
|
||||
// --- direct messages / push ---
|
||||
Map.entry("UpsertPushToken", new Net_UpsertPushToken_Handler()),
|
||||
@@ -305,6 +308,7 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("ListUserProfileChannels", Net_ListUserProfileChannels_Request.class),
|
||||
Map.entry("AddCloseFriend", Net_AddCloseFriend_Request.class),
|
||||
Map.entry("GetNotifications", Net_GetNotifications_Request.class),
|
||||
Map.entry("SetNotificationState", Net_SetNotificationState_Request.class),
|
||||
|
||||
// --- direct messages / push ---
|
||||
Map.entry("UpsertPushToken", Net_UpsertPushToken_Request.class),
|
||||
|
||||
+17
-10
@@ -916,16 +916,23 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
return entry;
|
||||
}
|
||||
|
||||
// Connection notifications are intentionally modeled as a generic kind.
|
||||
// Current UI surfaces FRIEND and CLOSE_FRIEND here; other reserved relation types stay silent.
|
||||
if (msgType == 3
|
||||
&& (msgSubType == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_FRIEND & 0xFFFF))
|
||||
&& block.body instanceof ConnectionBody) {
|
||||
UserNotificationEntry entry = baseNotificationEntry(storedEntry, ownerLogin, createdAtMs, msgSubType);
|
||||
entry.setNotificationKind("connection");
|
||||
entry.setSourceText("");
|
||||
return entry;
|
||||
if (msgType == 3 && block.body instanceof ConnectionBody) {
|
||||
boolean personalConnection = msgSubType == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_UNCLOSE_FRIEND & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_FRIEND & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_UNFRIEND & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_SHINE_UNCONFIRMED & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
|
||||
boolean channelEvent = msgSubType == (MsgSubType.CONNECTION_FOLLOW & 0xFFFF)
|
||||
|| msgSubType == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF);
|
||||
if (personalConnection || channelEvent) {
|
||||
UserNotificationEntry entry = baseNotificationEntry(storedEntry, ownerLogin, createdAtMs, msgSubType);
|
||||
entry.setNotificationKind(channelEvent ? "event" : "connection");
|
||||
entry.setSourceText("");
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
+22
-89
@@ -1,94 +1,27 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.notifications;
|
||||
|
||||
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.notifications.entyties.Net_GetNotifications_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.entyties.Net_GetNotifications_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
import shine.db.dao.UserNotificationsStateDAO;
|
||||
import shine.db.entities.UserNotificationEntry;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext; import server.logic.ws_protocol.JSON.entyties.*; import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.notifications.entyties.*; import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory; import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController; import shine.db.dao.*; import shine.db.entities.UserNotificationEntry;
|
||||
import java.sql.Connection; import java.util.*;
|
||||
|
||||
public final class Net_GetNotifications_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetNotifications_Handler.class);
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_GetNotifications_Request req = (Net_GetNotifications_Request) baseRequest;
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getCurrentUser() == null) {
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.UNVERIFIED,
|
||||
"NOT_AUTHENTICATED",
|
||||
"Операция доступна только для авторизованных пользователей"
|
||||
);
|
||||
}
|
||||
|
||||
String login = String.valueOf(ctx.getCurrentUser().getLogin() == null ? "" : ctx.getCurrentUser().getLogin()).trim();
|
||||
if (login.isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Не удалось определить авторизованного пользователя");
|
||||
}
|
||||
|
||||
int limit = req.getLimit() == null ? 50 : Math.max(1, Math.min(200, req.getLimit()));
|
||||
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
List<UserNotificationEntry> replyRows = UserNotificationsStateDAO.getInstance().listByOwnerAndKind(c, login, "reply", limit);
|
||||
List<UserNotificationEntry> eventRows = UserNotificationsStateDAO.getInstance().listByOwnerAndKind(c, login, "connection", limit);
|
||||
|
||||
Net_GetNotifications_Response resp = new Net_GetNotifications_Response();
|
||||
resp.setOp(req.getOp());
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
resp.setLogin(login);
|
||||
resp.setReplies(mapRows(replyRows));
|
||||
resp.setEvents(mapRows(eventRows));
|
||||
return resp;
|
||||
} catch (Exception e) {
|
||||
log.error("GetNotifications failed", e);
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR, "internal_error", "Внутренняя ошибка сервера");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Net_GetNotifications_Response.NotificationItem> mapRows(List<UserNotificationEntry> rows) {
|
||||
List<Net_GetNotifications_Response.NotificationItem> out = new ArrayList<>();
|
||||
for (UserNotificationEntry row : rows) {
|
||||
Net_GetNotifications_Response.NotificationItem item = new Net_GetNotifications_Response.NotificationItem();
|
||||
item.setKind(row.getNotificationKind());
|
||||
item.setCreatedAtMs(row.getCreatedAtMs());
|
||||
item.setSourceLogin(row.getSourceLogin());
|
||||
item.setSourceBlockchainName(row.getSourceBchName());
|
||||
item.setSourceBlockNumber(row.getSourceBlockNumber());
|
||||
item.setSourceBlockHash(bytesToHex(row.getSourceBlockHash()));
|
||||
item.setSourceMsgSubType(row.getSourceMsgSubType());
|
||||
item.setConnectionTypeCode("connection".equals(row.getNotificationKind()) ? row.getSourceMsgSubType() : null);
|
||||
item.setSourceText(row.getSourceText());
|
||||
item.setTargetLogin(row.getTargetLogin());
|
||||
item.setTargetBlockchainName(row.getTargetBchName());
|
||||
item.setTargetBlockNumber(row.getTargetBlockNumber());
|
||||
item.setTargetBlockHash(bytesToHex(row.getTargetBlockHash()));
|
||||
out.add(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
if (bytes == null) return null;
|
||||
char[] HEX = "0123456789abcdef".toCharArray();
|
||||
char[] out = new char[bytes.length * 2];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int v = bytes[i] & 0xff;
|
||||
out[i * 2] = HEX[v >>> 4];
|
||||
out[i * 2 + 1] = HEX[v & 0x0f];
|
||||
}
|
||||
return new String(out);
|
||||
}
|
||||
private static final Logger log=LoggerFactory.getLogger(Net_GetNotifications_Handler.class); private static final long HISTORY_MS=60L*24*60*60*1000;
|
||||
public Net_Response handle(Net_Request base, ConnectionContext ctx){
|
||||
Net_GetNotifications_Request req=(Net_GetNotifications_Request)base; if(ctx==null||!ctx.isAuthenticatedUser()||ctx.getCurrentUser()==null) return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"NOT_AUTHENTICATED","Операция доступна только для авторизованных пользователей");
|
||||
String login=String.valueOf(ctx.getCurrentUser().getLogin()).trim();
|
||||
try(Connection c=DbController.getInstance().getConnection()){
|
||||
UserNotificationSeenStateDAO sd=UserNotificationSeenStateDAO.getInstance(); UserNotificationsStateDAO nd=UserNotificationsStateDAO.getInstance(); long cutoff=System.currentTimeMillis()-HISTORY_MS;
|
||||
long rs=sd.getSeenAt(c,login,"replies"), cs=sd.getSeenAt(c,login,"connections"), es=sd.getSeenAt(c,login,"events");
|
||||
Net_GetNotifications_Response r=new Net_GetNotifications_Response(); r.setOp(req.getOp());r.setRequestId(req.getRequestId());r.setStatus(WireCodes.Status.OK);r.setLogin(login);
|
||||
if (!Boolean.TRUE.equals(req.getCountsOnly())) {
|
||||
r.setReplies(map(nd.listVisible(c,login,"reply",rs,cutoff))); r.setConnections(map(nd.listVisible(c,login,"connection",cs,cutoff))); r.setEvents(map(nd.listVisible(c,login,"event",es,cutoff)));
|
||||
}
|
||||
r.setRepliesSeenAtMs(rs);r.setConnectionsSeenAtMs(cs);r.setEventsSeenAtMs(es); r.setRepliesUnseenCount(nd.countUnseen(c,login,"reply",rs)); r.setConnectionsUnseenCount(nd.countUnseen(c,login,"connection",cs)); r.setEventsUnseenCount(nd.countUnseen(c,login,"event",es));
|
||||
return r;
|
||||
}catch(Exception e){log.error("GetNotifications failed",e);return NetExceptionResponseFactory.error(req,WireCodes.Status.INTERNAL_ERROR,"internal_error","Внутренняя ошибка сервера");}
|
||||
}
|
||||
private List<Net_GetNotifications_Response.NotificationItem> map(List<UserNotificationEntry> rows){ List<Net_GetNotifications_Response.NotificationItem> out=new ArrayList<>(); for(UserNotificationEntry x:rows){ Net_GetNotifications_Response.NotificationItem i=new Net_GetNotifications_Response.NotificationItem(); i.setKind(x.getNotificationKind());i.setCreatedAtMs(x.getCreatedAtMs());i.setSourceLogin(x.getSourceLogin());i.setSourceBlockchainName(x.getSourceBchName());i.setSourceBlockNumber(x.getSourceBlockNumber());i.setSourceBlockHash(hex(x.getSourceBlockHash()));i.setSourceMsgSubType(x.getSourceMsgSubType());i.setConnectionTypeCode("connection".equals(x.getNotificationKind())?x.getSourceMsgSubType():null);i.setSourceText(x.getSourceText());i.setTargetLogin(x.getTargetLogin());i.setTargetBlockchainName(x.getTargetBchName());i.setTargetBlockNumber(x.getTargetBlockNumber());i.setTargetBlockHash(hex(x.getTargetBlockHash()));out.add(i);} return out; }
|
||||
private static String hex(byte[] b){if(b==null)return null;StringBuilder s=new StringBuilder();for(byte x:b)s.append(String.format("%02x",x));return s.toString();}
|
||||
}
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.notifications;
|
||||
|
||||
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.notifications.entyties.*;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
import shine.db.dao.UserNotificationSeenStateDAO;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import java.sql.Connection;
|
||||
import java.util.Base64;
|
||||
|
||||
public final class Net_SetNotificationState_Handler implements JsonMessageHandler {
|
||||
public Net_Response handle(Net_Request base, ConnectionContext ctx){
|
||||
Net_SetNotificationState_Request req=(Net_SetNotificationState_Request)base;
|
||||
if(ctx==null||!ctx.isAuthenticatedUser()||ctx.getCurrentUser()==null) return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"NOT_AUTHENTICATED","Требуется авторизация");
|
||||
try{
|
||||
byte[] raw=Base64.getDecoder().decode(String.valueOf(req.getBlobB64()).trim()); NotificationStatePacket p=NotificationStatePacket.parse(raw);
|
||||
String login=String.valueOf(ctx.getCurrentUser().getLogin()).trim(); if(!login.equalsIgnoreCase(p.login)) return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"LOGIN_MISMATCH","Подпись принадлежит другому пользователю");
|
||||
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;
|
||||
}catch(Exception e){ return NetExceptionResponseFactory.error(req,WireCodes.Status.UNVERIFIED,"BAD_NOTIFICATION_STATE",e.getMessage()==null?"Некорректное состояние уведомлений":e.getMessage()); }
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.notifications;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
final class NotificationStatePacket {
|
||||
static final byte[] PREFIX = "SHiNE_NTF".getBytes(StandardCharsets.US_ASCII);
|
||||
static final int STATE_SEEN_WATERMARK = 1;
|
||||
static final int CATEGORY_REPLIES = 1;
|
||||
static final int CATEGORY_CONNECTIONS = 2;
|
||||
static final int CATEGORY_EVENTS = 3;
|
||||
|
||||
final String login; final long timeMs; final long nonce; final int stateType; final int category; final long seenAtMs;
|
||||
final byte[] signedBody; final byte[] signature64; final byte[] rawPacket;
|
||||
private NotificationStatePacket(String login,long timeMs,long nonce,int stateType,int category,long seenAtMs,byte[] signedBody,byte[] signature64,byte[] rawPacket){
|
||||
this.login=login;this.timeMs=timeMs;this.nonce=nonce;this.stateType=stateType;this.category=category;this.seenAtMs=seenAtMs;this.signedBody=signedBody;this.signature64=signature64;this.rawPacket=rawPacket;
|
||||
}
|
||||
static NotificationStatePacket parse(byte[] raw) {
|
||||
if(raw==null||raw.length<PREFIX.length+2+1+1+8+4+1+1+8+64) throw new IllegalArgumentException("BAD_LEN");
|
||||
for(int i=0;i<PREFIX.length;i++) if(raw[i]!=PREFIX[i]) throw new IllegalArgumentException("BAD_PREFIX");
|
||||
ByteBuffer bb=ByteBuffer.wrap(raw).order(ByteOrder.BIG_ENDIAN); bb.position(PREFIX.length);
|
||||
int major=Byte.toUnsignedInt(bb.get()), minor=Byte.toUnsignedInt(bb.get());
|
||||
if(major!=1||minor!=0) throw new IllegalArgumentException("BAD_FORMAT_VERSION");
|
||||
int len=Byte.toUnsignedInt(bb.get()); if(len<1||len>60||bb.remaining()<len+8+4+1+1+8+64) throw new IllegalArgumentException("BAD_LOGIN");
|
||||
byte[] lb=new byte[len]; bb.get(lb); for(byte b:lb) if(b<0x20||b>0x7e) throw new IllegalArgumentException("BAD_LOGIN");
|
||||
String login=new String(lb,StandardCharsets.US_ASCII); long timeMs=bb.getLong(); if(timeMs<0) throw new IllegalArgumentException("BAD_TIME");
|
||||
long nonce=Integer.toUnsignedLong(bb.getInt()); int stateType=Byte.toUnsignedInt(bb.get()); if(stateType!=STATE_SEEN_WATERMARK) throw new IllegalArgumentException("BAD_STATE_TYPE");
|
||||
int category=Byte.toUnsignedInt(bb.get()); if(category<1||category>3) throw new IllegalArgumentException("BAD_CATEGORY");
|
||||
long seenAtMs=bb.getLong(); if(seenAtMs<0||bb.remaining()!=64) throw new IllegalArgumentException("BAD_SEEN_TIME");
|
||||
byte[] sig=new byte[64]; bb.get(sig); return new NotificationStatePacket(login,timeMs,nonce,stateType,category,seenAtMs,Arrays.copyOf(raw,raw.length-64),sig,raw);
|
||||
}
|
||||
String categoryName(){ return category==CATEGORY_REPLIES?"replies":category==CATEGORY_CONNECTIONS?"connections":"events"; }
|
||||
}
|
||||
+4
-2
@@ -3,8 +3,10 @@ package server.logic.ws_protocol.JSON.handlers.notifications.entyties;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
public class Net_GetNotifications_Request extends Net_Request {
|
||||
private Integer limit;
|
||||
|
||||
private Integer limit; // legacy: поле принимается для совместимости, но в v2 не ограничивает выдачу
|
||||
private Boolean countsOnly;
|
||||
public Integer getLimit() { return limit; }
|
||||
public void setLimit(Integer limit) { this.limit = limit; }
|
||||
public Boolean getCountsOnly() { return countsOnly; }
|
||||
public void setCountsOnly(Boolean countsOnly) { this.countsOnly = countsOnly; }
|
||||
}
|
||||
|
||||
+11
@@ -8,12 +8,23 @@ import java.util.List;
|
||||
public class Net_GetNotifications_Response extends Net_Response {
|
||||
private String login;
|
||||
private List<NotificationItem> replies = new ArrayList<>();
|
||||
private List<NotificationItem> connections = new ArrayList<>();
|
||||
private List<NotificationItem> events = new ArrayList<>();
|
||||
private long repliesSeenAtMs, connectionsSeenAtMs, eventsSeenAtMs;
|
||||
private long repliesUnseenCount, connectionsUnseenCount, eventsUnseenCount;
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
public List<NotificationItem> getReplies() { return replies; }
|
||||
public void setReplies(List<NotificationItem> replies) { this.replies = replies; }
|
||||
public List<NotificationItem> getConnections() { return connections; }
|
||||
public void setConnections(List<NotificationItem> v) { connections = v; }
|
||||
public long getRepliesSeenAtMs(){return repliesSeenAtMs;} public void setRepliesSeenAtMs(long v){repliesSeenAtMs=v;}
|
||||
public long getConnectionsSeenAtMs(){return connectionsSeenAtMs;} public void setConnectionsSeenAtMs(long v){connectionsSeenAtMs=v;}
|
||||
public long getEventsSeenAtMs(){return eventsSeenAtMs;} public void setEventsSeenAtMs(long v){eventsSeenAtMs=v;}
|
||||
public long getRepliesUnseenCount(){return repliesUnseenCount;} public void setRepliesUnseenCount(long v){repliesUnseenCount=v;}
|
||||
public long getConnectionsUnseenCount(){return connectionsUnseenCount;} public void setConnectionsUnseenCount(long v){connectionsUnseenCount=v;}
|
||||
public long getEventsUnseenCount(){return eventsUnseenCount;} public void setEventsUnseenCount(long v){eventsUnseenCount=v;}
|
||||
public List<NotificationItem> getEvents() { return events; }
|
||||
public void setEvents(List<NotificationItem> events) { this.events = events; }
|
||||
|
||||
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.notifications.entyties;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
public class Net_SetNotificationState_Request extends Net_Request { private String blobB64; public String getBlobB64(){return blobB64;} public void setBlobB64(String v){blobB64=v;} }
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.notifications.entyties;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
public class Net_SetNotificationState_Response extends Net_Response { private String category; private long seenAtMs; public String getCategory(){return category;} public void setCategory(String v){category=v;} public long getSeenAtMs(){return seenAtMs;} public void setSeenAtMs(long v){seenAtMs=v;} }
|
||||
Executable
+300
@@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# Build an offline-ready source bundle ZIP.
|
||||
# In addition to the normal source tree, this variant can attach a local
|
||||
# Gradle distribution zip and a helper script that rewrites wrapper URLs to
|
||||
# that local file so the bundle can be used without internet access.
|
||||
#
|
||||
# Usage:
|
||||
# ./bundle-offline.sh
|
||||
# ./bundle-offline.sh path/to/output.zip
|
||||
#
|
||||
# Expected local asset:
|
||||
# offline/gradle-offline.zip
|
||||
# or a custom path via BUNDLE_OFFLINE_GRADLE_ZIP
|
||||
|
||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
OUT="${1:-SHiNE-bundle-offline-$(date +%Y%m%d-%H%M%S).zip}"
|
||||
case "$OUT" in
|
||||
/*) ;;
|
||||
*) OUT="$ROOT/$OUT" ;;
|
||||
esac
|
||||
|
||||
if ! command -v zip >/dev/null 2>&1; then
|
||||
echo "ERROR: 'zip' is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TMP="$(mktemp -d)"
|
||||
LIST="$TMP/files.txt"
|
||||
SAFE_LIST="$TMP/safe-files.txt"
|
||||
STAGE="$TMP/stage"
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
|
||||
mkdir -p "$STAGE"
|
||||
|
||||
# Paths / filenames that must never be bundled.
|
||||
is_denied_path() {
|
||||
local p="/$1"
|
||||
|
||||
case "$p" in
|
||||
*/.git/*|*/.git|\
|
||||
*/.gradle/*|*/.gradle|\
|
||||
*/.gradle-home/*|*/.gradle-home|\
|
||||
*/.idea/*|*/.idea|\
|
||||
*/.vscode/*|*/.vscode|\
|
||||
*/node_modules/*|*/node_modules|\
|
||||
*/target/*|*/target|\
|
||||
*/build/*|*/build|\
|
||||
*/out/*|*/out|\
|
||||
*/bin/*|*/bin|\
|
||||
*/logs/*|*/logs|\
|
||||
*/data/*|*/data|\
|
||||
*/test-ledger/*|*/test-ledger|\
|
||||
*/.anchor/*|*/.anchor|\
|
||||
*/.yarn/*|*/.yarn|\
|
||||
*/.vendor/*|*/.vendor|\
|
||||
*/.agents/*|*/.agents|\
|
||||
*/.codex/*|*/.codex|\
|
||||
*/.claude/*|*/.claude|\
|
||||
*/deploy/backup/archive/*|\
|
||||
*/scripts/*/runs/*|\
|
||||
*/scripts/*/keypairs/*|\
|
||||
*/keys/*|\
|
||||
*/.git-local-backup/*|\
|
||||
*/SHiNE-bundle-*.zip|\
|
||||
*/bundle-offline*.zip)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
local base="${p##*/}"
|
||||
local lower
|
||||
lower="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]')"
|
||||
|
||||
case "$lower" in
|
||||
.env|.env.*|\
|
||||
.debug-token|\
|
||||
.npmrc|.pypirc|.netrc|\
|
||||
credentials|credentials.*|\
|
||||
secrets|secrets.*|\
|
||||
secret|secret.*|\
|
||||
id_rsa|id_dsa|id_ecdsa|id_ed25519|\
|
||||
*.pem|*.key|*.p12|*.pfx|*.jks|*.keystore|\
|
||||
*keypair*.json|\
|
||||
service-account*.json|\
|
||||
firebase-adminsdk*.json|\
|
||||
google-services.json|\
|
||||
validator.log)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$lower" in
|
||||
*.class|*.jar|*.war|*.ear|*.o|*.a|*.so|*.dll|*.dylib|\
|
||||
*.elf|*.map|*.uf2|*.bin|*.merged.bin|\
|
||||
*.log|*.bak|*.bak.png|*.tmp|*.swp|*.swo|\
|
||||
.ds_store)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
find_offline_gradle_zip() {
|
||||
local candidate="${BUNDLE_OFFLINE_GRADLE_ZIP:-}"
|
||||
if [[ -n "$candidate" && -f "$candidate" ]]; then
|
||||
printf '%s\n' "$candidate"
|
||||
return 0
|
||||
fi
|
||||
|
||||
for candidate in \
|
||||
"$ROOT/offline/gradle-offline.zip" \
|
||||
"$ROOT/offline/gradle-8.14-bin.zip" \
|
||||
"$ROOT/offline/gradle.zip"
|
||||
do
|
||||
if [[ -f "$candidate" ]]; then
|
||||
printf '%s\n' "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
create_offline_helper() {
|
||||
local zip_name="$1"
|
||||
local helper="$STAGE/offline/prepare-local-gradle.sh"
|
||||
local readme="$STAGE/offline/README.txt"
|
||||
|
||||
mkdir -p "$STAGE/offline"
|
||||
|
||||
cat > "$helper" <<EOF
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
|
||||
ZIP_PATH="\${1:-\$ROOT/offline/$zip_name}"
|
||||
|
||||
if [[ ! -f "\$ZIP_PATH" ]]; then
|
||||
echo "ERROR: offline Gradle zip not found: \$ZIP_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ABS_ZIP="\$(cd -- "\$(dirname -- "\$ZIP_PATH")" && pwd -P)/\$(basename -- "\$ZIP_PATH")"
|
||||
ESCAPED_ABS_ZIP="\${ABS_ZIP//\\\\/\\\\\\\\}"
|
||||
ESCAPED_ABS_ZIP="\${ESCAPED_ABS_ZIP//&/\\\\&}"
|
||||
ESCAPED_ABS_ZIP="\${ESCAPED_ABS_ZIP//|/\\\\|}"
|
||||
|
||||
while IFS= read -r props; do
|
||||
[[ -f "\$props" ]] || continue
|
||||
cp -p "\$props" "\$props.bak"
|
||||
sed -i -e "s|^distributionUrl=.*\$|distributionUrl=file://\$ESCAPED_ABS_ZIP|" "\$props"
|
||||
done < <(find "\$ROOT" -path '*/gradle/wrapper/gradle-wrapper.properties' -type f | sort)
|
||||
|
||||
cat <<'MSG'
|
||||
Gradle wrapper URLs rewritten to the local offline zip.
|
||||
Run now:
|
||||
./gradlew --offline test
|
||||
MSG
|
||||
EOF
|
||||
chmod +x "$helper"
|
||||
|
||||
cat > "$readme" <<EOF
|
||||
Offline Gradle helper
|
||||
|
||||
Included archive:
|
||||
offline/$zip_name
|
||||
|
||||
Helper:
|
||||
offline/prepare-local-gradle.sh
|
||||
|
||||
What it does:
|
||||
- backs up each gradle-wrapper.properties as .bak
|
||||
- rewrites wrapper distributionUrl to the local zip in this bundle
|
||||
|
||||
Recommended flow after unpacking:
|
||||
1. cd into the unpacked bundle root
|
||||
2. run ./offline/prepare-local-gradle.sh
|
||||
3. run ./gradlew --offline test
|
||||
|
||||
This bundle is intended for local, network-free verification.
|
||||
EOF
|
||||
}
|
||||
|
||||
# Collect files. Prefer Git because it naturally avoids most ignored local files.
|
||||
if command -v git >/dev/null 2>&1 && git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
git -C "$ROOT" ls-files -co --exclude-standard -z > "$TMP/files.z"
|
||||
else
|
||||
find "$ROOT" -type f -print0 > "$TMP/files.z"
|
||||
fi
|
||||
|
||||
# Convert to project-relative paths and enforce hard deny rules.
|
||||
: > "$LIST"
|
||||
while IFS= read -r -d '' f; do
|
||||
if [[ "$f" = /* ]]; then
|
||||
rel="${f#"$ROOT"/}"
|
||||
else
|
||||
rel="$f"
|
||||
fi
|
||||
|
||||
[[ "$rel" == "$OUT" ]] && continue
|
||||
[[ -z "$rel" ]] && continue
|
||||
|
||||
if is_denied_path "$rel"; then
|
||||
continue
|
||||
fi
|
||||
|
||||
printf '%s\n' "$rel" >> "$LIST"
|
||||
done < "$TMP/files.z"
|
||||
|
||||
sort -u "$LIST" -o "$LIST"
|
||||
|
||||
# Always include Gradle wrapper bootstrap, even though generic JARs are denied.
|
||||
for wrapper_jar in \
|
||||
'SHiNE-server/gradle/wrapper/gradle-wrapper.jar' \
|
||||
'SHiNE-browser-plugin-wallet/gradle/wrapper/gradle-wrapper.jar'
|
||||
do
|
||||
if [[ -f "$ROOT/$wrapper_jar" ]] && ! grep -Fxq "$wrapper_jar" "$LIST"; then
|
||||
printf '%s\n' "$wrapper_jar" >> "$LIST"
|
||||
fi
|
||||
done
|
||||
|
||||
sort -u "$LIST" -o "$LIST"
|
||||
|
||||
# Content scan: fail closed on common credential/private-key patterns.
|
||||
# We scan only text-ish files; grep -I skips binary data.
|
||||
SECRET_RE='-----BEGIN ([A-Z0-9 ]+ )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|(^|[^A-Za-z0-9])(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key)[[:space:]]*[:=][[:space:]]*["'\'']?[^${[:space:]]{][^[:space:]]{7,}'
|
||||
|
||||
: > "$SAFE_LIST"
|
||||
found_secret=0
|
||||
|
||||
while IFS= read -r rel; do
|
||||
[[ -f "$ROOT/$rel" ]] || continue
|
||||
|
||||
# Files that contain examples/templates can legitimately mention secret keys
|
||||
# with placeholders. They are scanned too, but placeholder-looking values
|
||||
# are less likely to match the regex above.
|
||||
if LC_ALL=C grep -IEnq "$SECRET_RE" "$ROOT/$rel" 2>/dev/null; then
|
||||
echo "BLOCKED: possible secret in $rel" >&2
|
||||
LC_ALL=C grep -IEn "$SECRET_RE" "$ROOT/$rel" 2>/dev/null \
|
||||
| sed -E 's/(:[[:space:]]*).*/\1[REDACTED]/' \
|
||||
| head -n 3 >&2 || true
|
||||
found_secret=1
|
||||
continue
|
||||
fi
|
||||
|
||||
printf '%s\n' "$rel" >> "$SAFE_LIST"
|
||||
done < "$LIST"
|
||||
|
||||
if (( found_secret != 0 )); then
|
||||
echo >&2
|
||||
echo "Bundle NOT created because possible secrets were detected." >&2
|
||||
echo "Move secrets to ignored/local files or adjust the scanner only after review." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ ! -s "$SAFE_LIST" ]]; then
|
||||
echo "ERROR: no files left to bundle." >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
OFFLINE_ZIP_SRC=""
|
||||
OFFLINE_ZIP_NAME=""
|
||||
if OFFLINE_ZIP_SRC="$(find_offline_gradle_zip)"; then
|
||||
OFFLINE_ZIP_NAME="gradle-offline.zip"
|
||||
else
|
||||
echo "ERROR: offline Gradle zip not found." >&2
|
||||
echo "Place it at ./offline/gradle-offline.zip or set BUNDLE_OFFLINE_GRADLE_ZIP." >&2
|
||||
echo "The bundle is not created because this variant is meant to be offline-ready." >&2
|
||||
exit 4
|
||||
fi
|
||||
|
||||
rm -rf "$STAGE"
|
||||
mkdir -p "$STAGE"
|
||||
|
||||
while IFS= read -r rel; do
|
||||
src="$ROOT/$rel"
|
||||
dst="$STAGE/$rel"
|
||||
mkdir -p "$(dirname -- "$dst")"
|
||||
cp -p "$src" "$dst"
|
||||
done < "$SAFE_LIST"
|
||||
|
||||
mkdir -p "$STAGE/offline"
|
||||
cp -p "$OFFLINE_ZIP_SRC" "$STAGE/offline/$OFFLINE_ZIP_NAME"
|
||||
create_offline_helper "$OFFLINE_ZIP_NAME"
|
||||
|
||||
rm -f -- "$OUT"
|
||||
|
||||
(
|
||||
cd "$STAGE"
|
||||
find . -type f -print | sort | zip -q -9 "$OUT" -@
|
||||
)
|
||||
|
||||
echo "Created: $OUT"
|
||||
echo "Files: $(cd "$STAGE" && find . -type f | wc -l | tr -d ' ')"
|
||||
echo "Size: $(du -h "$OUT" | awk '{print $1}')"
|
||||
@@ -60,7 +60,8 @@
|
||||
| `ListContacts` | `11_Connections_API.md` | контакты текущего пользователя |
|
||||
| `GetUserConnectionsGraph` | `11_Connections_API.md` | граф связей пользователя |
|
||||
| `AddCloseFriend` | `11_Connections_API.md` | добавить близкого друга |
|
||||
| `GetNotifications` | `15_Notifications_API.md` | ответы и события уведомлений |
|
||||
| `GetNotifications` | `15_Notifications_API.md` | ответы, связи, события и unread-watermark |
|
||||
| `SetNotificationState` | `15_Notifications_API.md` | подписанное состояние просмотра уведомлений |
|
||||
| `UpsertPushToken` | `12_Direct_Messages_Push_Calls_API.md` | регистрация WebPush-токена |
|
||||
| `SendTestWebPush` | `12_Direct_Messages_Push_Calls_API.md` | тестовая push-доставка |
|
||||
| `SendMessagePair` | `12_Direct_Messages_Push_Calls_API.md` | отправка пары входящий/исходящий DM |
|
||||
|
||||
@@ -1,81 +1,42 @@
|
||||
# API для разработчиков: уведомления
|
||||
|
||||
Документ описывает чтение пользовательских уведомлений, которые сервер индексирует при `AddBlock`.
|
||||
Уведомления являются серверной проекцией событий блокчейна. Сервер возвращает все непросмотренные записи независимо от возраста и просмотренные записи не старше 60 дней. Пагинации нет: выдача содержит все непросмотренные и всю доступную 60-дневную просмотренную историю.
|
||||
|
||||
Текущая операция:
|
||||
## GetNotifications
|
||||
|
||||
- `GetNotifications`
|
||||
Авторизация обязательна. Обычно payload пустой. Legacy-поле `limit` принимается для совместимости, но в v2 игнорируется. Для обновления badge без загрузки карточек можно передать `{"countsOnly":true}`; тогда массивы лент остаются пустыми, но watermark и `*UnseenCount` возвращаются.
|
||||
|
||||
## 1. `GetNotifications`
|
||||
Ответ содержит три ленты: `replies`, `connections`, `events`, а также `*SeenAtMs` и `*UnseenCount` для каждой категории.
|
||||
|
||||
Метод читает уведомления текущего пользователя. В `payload.login` можно передать логин явно, но обычно клиент использует авторизованную сессию.
|
||||
- `replies`: TEXT_REPLY.
|
||||
- `connections`: friend/unfriend, close_friend/unclose_friend, shine confirmed/unconfirmed, official confirmed/unconfirmed. Контакты не создают уведомлений.
|
||||
- `events`: FOLLOW/UNFOLLOW каналов.
|
||||
|
||||
Возвращаются две отдельные ленты:
|
||||
Фильтр каждой категории: `created_at_ms > seenAtMs OR created_at_ms >= now - 60 days`.
|
||||
|
||||
- `replies` — ответы на сообщения пользователя в каналах и тредах;
|
||||
- `events` — события добавления в `close_friend`.
|
||||
## SetNotificationState
|
||||
|
||||
### Запрос
|
||||
Сохраняет подписанный watermark просмотра. Сервер принимает только монотонное движение `seenAtMs` вперёд.
|
||||
|
||||
Запрос:
|
||||
```json
|
||||
{
|
||||
"op": "GetNotifications",
|
||||
"requestId": "notif-001",
|
||||
"payload": {
|
||||
"login": "alice",
|
||||
"limit": 50
|
||||
}
|
||||
}
|
||||
{"op":"SetNotificationState","requestId":"ntf-seen-1","payload":{"blobB64":"..."}}
|
||||
```
|
||||
|
||||
### Успешный ответ
|
||||
Бинарный контейнер `SHiNE_NTF` v1.0 (big-endian):
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "GetNotifications",
|
||||
"requestId": "notif-001",
|
||||
"status": 200,
|
||||
"ok": true,
|
||||
"payload": {
|
||||
"login": "Alice",
|
||||
"replies": [
|
||||
{
|
||||
"kind": "reply",
|
||||
"createdAtMs": 1755673200000,
|
||||
"sourceLogin": "Bob",
|
||||
"sourceBlockchainName": "bob-001",
|
||||
"sourceBlockNumber": 42,
|
||||
"sourceBlockHash": "ab12...",
|
||||
"sourceMsgSubType": 20,
|
||||
"sourceText": "Спасибо!",
|
||||
"targetLogin": "Alice",
|
||||
"targetBlockchainName": "alice-001",
|
||||
"targetBlockNumber": 18,
|
||||
"targetBlockHash": "cd34..."
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"kind": "close_friend",
|
||||
"createdAtMs": 1755673300000,
|
||||
"sourceLogin": "Kate",
|
||||
"sourceBlockchainName": "kate-001",
|
||||
"sourceBlockNumber": 7,
|
||||
"sourceBlockHash": "ef56...",
|
||||
"sourceMsgSubType": 10,
|
||||
"sourceText": "close_friend",
|
||||
"targetLogin": "Alice",
|
||||
"targetBlockchainName": "alice-001",
|
||||
"targetBlockNumber": 0,
|
||||
"targetBlockHash": "0000..."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```text
|
||||
'SHiNE_NTF' 9 bytes ASCII
|
||||
formatVersionMajor u8 = 1
|
||||
formatVersionMinor u8 = 0
|
||||
loginLen u8
|
||||
login ASCII[loginLen]
|
||||
timeMs u64
|
||||
nonce u32
|
||||
stateType u8 = 1 (SEEN_WATERMARK)
|
||||
category u8 (1 replies, 2 connections, 3 events)
|
||||
seenAtMs u64
|
||||
signature Ed25519[64]
|
||||
```
|
||||
|
||||
### Примечание
|
||||
|
||||
- `replies` заполняется только для `TEXT_REPLY`.
|
||||
- `events` заполняется только для входящего `CONNECTION_FRIEND` / `close_friend`.
|
||||
- Другие типы связей в эту ленту не попадают.
|
||||
Подпись `clientKey` вычисляется над всеми байтами контейнера до `signature`, по тому же принципу, что подписанный контейнер `SHiNE_DM`. Сервер проверяет, что `login` совпадает с авторизованным пользователем, проверяет Ed25519-подпись и сохраняет также исходный signed blob для будущей переносимой синхронизации состояния.
|
||||
|
||||
@@ -203,3 +203,22 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
|
||||
- Доступные группы: «Все чаты», «Близкие друзья», «Контакты», «Новые».
|
||||
- Фильтрация использует уже существующий признак отношения диалога: `close_friend`, `contact`, `none`; формат DM и серверный протокол при этом не меняются.
|
||||
- Для недавних сообщений UI показывает относительное время (секунды, минуты, часы, дни). Для более старых сообщений текущего года используется формат `DD.MM, HH:MM`, для другого года — `DD.MM.YYYY` без времени.
|
||||
|
||||
## Мультипрофильный клиент (UI, 2026-09-03)
|
||||
- На одном устройстве клиент может хранить несколько авторизованных профилей, но одновременно использует только один активный runtime/WebSocket для DM.
|
||||
- При переключении профиля новая сохранённая сессия сначала проверяется отдельным временным соединением. Текущий профиль не заменяется, если проверка неуспешна.
|
||||
- Web Push может быть зарегистрирован для нескольких профилей на одном браузерном push endpoint. Поле `toLogin` определяет, какому профилю относится событие.
|
||||
- При клике по push-сообщению другого сохранённого профиля UI сначала спрашивает подтверждение переключения. Сам клик по системному уведомлению не является `read-receipt` и не помечает DM прочитанным.
|
||||
- Локальный IndexedDB-кэш DM логически разделён по `ownerLogin`, чтобы сообщения разных сохранённых профилей не смешивались.
|
||||
|
||||
## UI: видимость пустого диалога после DeleteConversation
|
||||
|
||||
`DeleteConversation` (`type=7/8`) остаётся техническим tombstone и сам по себе не считается пользовательским сообщением диалога.
|
||||
|
||||
Для списка личных чатов действует правило:
|
||||
|
||||
- если после очистки истории у пары нет обычных DM-сообщений и пользователь не находится в `contact`, `friend` или `close_friend`, строка диалога не показывается;
|
||||
- если связь `contact`, `friend` или `close_friend` сохраняется, пустой чат может оставаться в списке как чат существующей связи;
|
||||
- при удалении чата с `friend`/`close_friend` UI должен отдельно предупредить, что одна очистка истории не уберёт строку чата, и при подтверждении снять социальную связь и очистить историю.
|
||||
|
||||
Это правило не меняет wire/API-формат DM и не меняет байтовый формат tombstone.
|
||||
|
||||
@@ -356,3 +356,12 @@ ReadReceiptBody_v1_0
|
||||
|
||||
## Примечание UI списка чатов (2026-08-28)
|
||||
Это изменение не меняет байтовый формат DM. В списке чатов клиент может фильтровать уже полученные диалоги по `relationFlag` (`close_friend`, `contact`, `none`) и локально форматировать время последнего сообщения: относительное для недавних, `DD.MM, HH:MM` в текущем году и `DD.MM.YYYY` для прошлых лет.
|
||||
|
||||
## Примечание о мультипрофиле (2026-09-03)
|
||||
Мультипрофильность клиента не меняет байтовый формат DM v1 и не добавляет полей в подписанный DM-блок. Разделение профилей выполняется только на уровне клиентской сессии, push-маршрутизации по уже существующему `toLogin` и локального кэша сообщений (`ownerLogin`).
|
||||
|
||||
## UI-семантика `type=7/8` в списке диалогов
|
||||
|
||||
Контейнер `type=7/8` является служебным tombstone очистки истории. Его наличие без обычных сообщений `type=1/2` не должно само по себе означать, что у пары есть видимый пользовательский диалог.
|
||||
|
||||
Следствие для UI/агрегата диалогов: `hasDialog` определяется наличием пользовательского содержимого (или непрочитанных пользовательских сообщений), а не наличием служебной записи состояния/tombstone. Формат контейнера при этом не изменяется.
|
||||
|
||||
@@ -202,19 +202,13 @@ self.addEventListener('notificationclick', (event) => {
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
const existing = allClients.find((client) => {
|
||||
try {
|
||||
return client.url.includes('/index.html') || client.url.endsWith('/');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
const existing = allClients[0] || null;
|
||||
|
||||
const openUrlBase = './index.html';
|
||||
const encodedPayload = encodeCallPushPayloadForUrl(payload);
|
||||
const openUrl = (action === 'accept' || action === 'decline')
|
||||
? `${openUrlBase}?callPushAction=${encodeURIComponent(action)}&callPushPayload=${encodedPayload}`
|
||||
: openUrlBase;
|
||||
: `${openUrlBase}?pushOpenPayload=${encodedPayload}`;
|
||||
|
||||
if (existing) {
|
||||
try {
|
||||
@@ -224,6 +218,11 @@ self.addEventListener('notificationclick', (event) => {
|
||||
action,
|
||||
payload,
|
||||
});
|
||||
} else {
|
||||
existing.postMessage({
|
||||
type: 'SHINE_NOTIFICATION_CLICK',
|
||||
payload,
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
await existing.focus();
|
||||
|
||||
+101
-5
@@ -33,6 +33,9 @@ import {
|
||||
addAppLogEntry,
|
||||
authorizeSession,
|
||||
hydrateMessagesFromStore,
|
||||
getSavedProfiles,
|
||||
closeSavedProfile,
|
||||
switchToSavedProfile,
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
setSessionAuthorizedHandler,
|
||||
@@ -67,6 +70,7 @@ import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
|
||||
import * as profileView from './pages/profile-view.js?v=202607150910';
|
||||
import * as profileEditView from './pages/profile-edit-view.js';
|
||||
import * as profilesView from './pages/profiles-view.js';
|
||||
import * as walletView from './pages/wallet-view.js?v=202606281930';
|
||||
import * as settingsView from './pages/settings-view.js';
|
||||
import * as accessServersView from './pages/access-servers-view.js';
|
||||
@@ -132,6 +136,7 @@ const routes = {
|
||||
queue: publicSupportQueueView,
|
||||
'profile-view': profileView,
|
||||
'profile-edit-view': profileEditView,
|
||||
'profiles-view': profilesView,
|
||||
'wallet-view': walletView,
|
||||
'settings-view': settingsView,
|
||||
'access-servers-view': accessServersView,
|
||||
@@ -213,6 +218,7 @@ const SCROLL_TO_BOTTOM_PAGE_IDS = new Set([
|
||||
const FILLED_ACTION_BUTTON_PAGE_IDS = new Set([
|
||||
...PRE_AUTH_PAGES.filter((pageId) => pageId !== 'entry-settings-view'),
|
||||
'settings-view',
|
||||
'profiles-view',
|
||||
]);
|
||||
|
||||
const SETTINGS_BORDERED_ACTION_PAGE_IDS = new Set([
|
||||
@@ -745,6 +751,77 @@ function consumeCallPushActionFromUrlIfAny() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function pushTargetLogin(payload = {}) {
|
||||
return String(payload?.toLogin || '').trim();
|
||||
}
|
||||
|
||||
function pushTargetPath(payload = {}) {
|
||||
const kind = String(payload?.kind || '').trim();
|
||||
const fromLogin = String(payload?.fromLogin || '').trim();
|
||||
if (kind === 'new_message' && fromLogin) return `/chat/${encodeURIComponent(fromLogin)}`;
|
||||
return '/profile';
|
||||
}
|
||||
|
||||
function savedProfileExists(login) {
|
||||
const normalized = String(login || '').trim().toLowerCase();
|
||||
if (!normalized) return false;
|
||||
return getSavedProfiles().some((item) => String(item.login || '').trim().toLowerCase() === normalized);
|
||||
}
|
||||
|
||||
async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
const targetLogin = pushTargetLogin(payload);
|
||||
const currentLogin = String(state.session.login || '').trim();
|
||||
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
||||
if (!savedProfileExists(targetLogin)) {
|
||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const kind = String(payload?.kind || '').trim();
|
||||
const question = kind === 'incoming_call'
|
||||
? `Входящий звонок для профиля «${targetLogin}». Переключиться на этот профиль?`
|
||||
: `Это сообщение пришло профилю «${targetLogin}». Переключиться, чтобы открыть его?`;
|
||||
if (!window.confirm(question)) return false;
|
||||
|
||||
try {
|
||||
await switchToSavedProfile(targetLogin);
|
||||
if (action === 'accept' || action === 'decline') {
|
||||
savePendingCallPushAction(action, payload);
|
||||
window.location.assign(pushTargetPath(payload));
|
||||
} else {
|
||||
window.location.assign(pushTargetPath(payload));
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
showToast(`Не удалось переключить профиль: ${error?.message || 'unknown'}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNotificationClick(payload = {}) {
|
||||
const canOpen = await ensurePushTargetProfile(payload);
|
||||
if (!canOpen) return;
|
||||
const path = pushTargetPath(payload);
|
||||
navigate(path.replace(/^\//, ''));
|
||||
}
|
||||
|
||||
function consumeNotificationOpenFromUrlIfAny() {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search || '');
|
||||
const rawPayload = String(params.get('pushOpenPayload') || '');
|
||||
if (!rawPayload) return null;
|
||||
let payload = {};
|
||||
try { payload = JSON.parse(decodeURIComponent(rawPayload)); } catch {}
|
||||
params.delete('pushOpenPayload');
|
||||
const nextQuery = params.toString();
|
||||
window.history.replaceState({}, '', `${window.location.pathname}${nextQuery ? `?${nextQuery}` : ''}`);
|
||||
return payload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function processPendingCallPushActionIfPossible() {
|
||||
if (!state.session.isAuthorized) return;
|
||||
const pending = loadPendingCallPushAction();
|
||||
@@ -1197,7 +1274,8 @@ function renderApp() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.session.isAuthorized && PRE_AUTH_PAGES.includes(pageId)) {
|
||||
const addingProfile = state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
|
||||
if (state.session.isAuthorized && PRE_AUTH_PAGES.includes(pageId) && !addingProfile) {
|
||||
navigate('messages-list');
|
||||
return;
|
||||
}
|
||||
@@ -1286,6 +1364,11 @@ async function tryAutoLogin() {
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
if (isSessionInvalidError(error)) {
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
if (result?.nextProfile) {
|
||||
window.location.assign('/profile');
|
||||
return;
|
||||
}
|
||||
await terminateCurrentSession({
|
||||
infoMessage: 'Сессия на этом устройстве уже завершена. Выполните вход заново.',
|
||||
});
|
||||
@@ -1338,6 +1421,7 @@ async function ensureSessionRuntimeStarted() {
|
||||
|
||||
async function init() {
|
||||
consumeCallPushActionFromUrlIfAny();
|
||||
const initialNotificationOpenPayload = consumeNotificationOpenFromUrlIfAny();
|
||||
void tryLockPortraitOrientation();
|
||||
|
||||
if (state.session.isLocalDemo) {
|
||||
@@ -1373,12 +1457,20 @@ async function init() {
|
||||
const action = String(data.action || '').trim().toLowerCase();
|
||||
const payload = data.payload || {};
|
||||
if (action === 'accept' || action === 'decline') {
|
||||
if (!isCallPushTargetForCurrentSession(payload)) return;
|
||||
savePendingCallPushAction(action, payload);
|
||||
void processPendingCallPushActionIfPossible();
|
||||
void (async () => {
|
||||
const canHandle = await ensurePushTargetProfile(payload, { action });
|
||||
if (!canHandle) return;
|
||||
if (!isCallPushTargetForCurrentSession(payload)) return;
|
||||
savePendingCallPushAction(action, payload);
|
||||
await processPendingCallPushActionIfPossible();
|
||||
})();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (data.type === 'SHINE_NOTIFICATION_CLICK') {
|
||||
void handleNotificationClick(data.payload || {});
|
||||
return;
|
||||
}
|
||||
if (data.type !== 'SHINE_WEB_PUSH_EVENT') return;
|
||||
|
||||
const payload = data.payload || {};
|
||||
@@ -1411,7 +1503,8 @@ async function init() {
|
||||
}
|
||||
|
||||
authService.onEvent('SessionRevoked', async () => {
|
||||
await terminateCurrentSession({ infoMessage: 'Сессия закрыта с другого устройства.' });
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
window.location.assign(result?.nextProfile ? '/profile' : '/start');
|
||||
});
|
||||
|
||||
authService.onEvent('ForceUiReload', async (evt) => {
|
||||
@@ -1714,6 +1807,9 @@ async function init() {
|
||||
void (async () => {
|
||||
try {
|
||||
await tryAutoLogin();
|
||||
if (initialNotificationOpenPayload) {
|
||||
await handleNotificationClick(initialNotificationOpenPayload);
|
||||
}
|
||||
await hydrateMessagesFromStore();
|
||||
if (!state.session.isLocalDemo) {
|
||||
startConnectionMonitor();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { resolveToolbarActive } from '../router.js';
|
||||
import { state } from '../state.js';
|
||||
import { state, authService } from '../state.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from './shine-logo.js';
|
||||
|
||||
@@ -72,6 +72,8 @@ export function renderToolbar(currentPageId, navigate) {
|
||||
const isProfile = item.pageId === 'profile-view';
|
||||
const isMessages = item.pageId === 'messages-list';
|
||||
const isNetwork = item.pageId === 'network-view';
|
||||
const isNotifications = item.pageId === 'notifications-view';
|
||||
btn.dataset.toolbarPage = item.pageId;
|
||||
btn.className = `toolbar-btn${item.pageId === active ? ' active' : ''}${isProfile ? ' toolbar-btn-profile' : ''}${isMessages ? ' toolbar-btn-messages' : ''}${isNetwork ? ' toolbar-btn-network' : ''}${item.hero ? ' toolbar-btn-hero' : ''}`;
|
||||
if (isProfile) {
|
||||
btn.innerHTML = `
|
||||
@@ -97,6 +99,14 @@ export function renderToolbar(currentPageId, navigate) {
|
||||
badge.setAttribute('aria-label', `Непрочитанных сообщений: ${badge.textContent}`);
|
||||
btn.append(badge);
|
||||
}
|
||||
if (isNotifications && Number(state.notificationUnreadTotal || 0) > 0) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'toolbar-unread-badge notification-toolbar-badge';
|
||||
const n = Number(state.notificationUnreadTotal || 0);
|
||||
badge.textContent = n > 99 ? '99+' : String(n);
|
||||
badge.setAttribute('aria-label', `Новых уведомлений: ${n}`);
|
||||
btn.append(badge);
|
||||
}
|
||||
if (item.pageId === 'channels-list') {
|
||||
btn.addEventListener('click', () => navigate('channels-list'));
|
||||
} else {
|
||||
@@ -105,5 +115,19 @@ export function renderToolbar(currentPageId, navigate) {
|
||||
root.append(btn);
|
||||
});
|
||||
|
||||
if (state.session.isAuthorized && currentPageId !== 'notifications-view') {
|
||||
void authService.getNotifications(true).then((payload) => {
|
||||
const total = Number(payload?.repliesUnseenCount || 0) + Number(payload?.connectionsUnseenCount || 0) + Number(payload?.eventsUnseenCount || 0);
|
||||
state.notificationUnreadTotal = total;
|
||||
const btn = root.querySelector('[data-toolbar-page="notifications-view"]');
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
if (total <= 0) { badge?.remove(); return; }
|
||||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; btn.append(badge); }
|
||||
badge.textContent = total > 99 ? '99+' : String(total);
|
||||
badge.setAttribute('aria-label', `Новых уведомлений: ${total}`);
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
@@ -2266,9 +2266,12 @@ export function render({ navigate, route, chrome }) {
|
||||
leftAction: { label: '<', onClick: () => navigate('channels-list') },
|
||||
rightActions: [
|
||||
{ label: 'Оглавление', className: 'channel-header-entrypoint-btn', onClick: () => {} },
|
||||
{ label: '⋯', className: 'channel-header-more-btn', onClick: () => {} },
|
||||
],
|
||||
});
|
||||
header.classList.add('channel-view-topbar');
|
||||
const channelEntrypointButton = header.querySelector('.header-actions .channel-header-entrypoint-btn');
|
||||
const channelMoreButton = header.querySelector('.header-actions .channel-header-more-btn');
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
@@ -2544,6 +2547,36 @@ export function render({ navigate, route, chrome }) {
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
channelMoreButton.onclick = (event) => {
|
||||
event.stopPropagation();
|
||||
header.querySelector('.channel-header-more-menu')?.remove();
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'channel-header-more-menu';
|
||||
const about = document.createElement('button'); about.type='button'; about.textContent='О канале';
|
||||
about.onclick = () => {
|
||||
const aboutRoute = makeShineChannelAboutRoute({ ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '', channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? '', channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? '' });
|
||||
menu.remove(); if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
menu.append(about);
|
||||
if (apiData?.isSubscribed && !apiData?.isOwnChannel) {
|
||||
const unfollow = document.createElement('button'); unfollow.type='button'; unfollow.className='is-danger'; unfollow.textContent='Отписаться от канала';
|
||||
unfollow.onclick = async () => {
|
||||
menu.remove();
|
||||
try {
|
||||
const { login, storagePwd } = requireSigningSession();
|
||||
await authService.addBlockFollowChannel({ login, storagePwd, targetBlockchainName: apiData.selector.ownerBlockchainName, targetBlockNumber: apiData.selector.channelRootBlockNumber, targetBlockHashHex: apiData.selector.channelRootBlockHash, unfollow: true });
|
||||
const feed = await authService.listSubscriptionsFeed(login, 200); setChannelsFeed(feed, state.channelsIndex); showToast('Вы отписались от канала'); rerender();
|
||||
} catch (error) { showStatus(toUserMessage(error, 'Не удалось отписаться от канала.')); }
|
||||
};
|
||||
menu.append(unfollow);
|
||||
}
|
||||
header.append(menu);
|
||||
const close = (e) => { if (!menu.contains(e.target) && e.target !== channelMoreButton) { menu.remove(); document.removeEventListener('click', close, true); } };
|
||||
setTimeout(() => document.addEventListener('click', close, true), 0);
|
||||
};
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
|
||||
@@ -264,18 +264,30 @@ function openChatConfirmModal({
|
||||
});
|
||||
}
|
||||
|
||||
function openDeleteChatConfirmModal({ contactName = '', onConfirm }) {
|
||||
function openDeleteChatConfirmModal({ contactName = '', relationType = 'none', onConfirm }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
const relation = normalizeChatRelationType(relationType);
|
||||
const isCloseFriend = relation === 'close_friend';
|
||||
const isFriend = relation === 'friend';
|
||||
const isProtectedRelation = isCloseFriend || isFriend;
|
||||
const relationName = isCloseFriend ? 'близких друзей' : 'друзей';
|
||||
const safeName = String(contactName || '').trim() || 'этого пользователя';
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="chat-delete-chat-modal">
|
||||
<div class="modal-card stack dm-dialog-card">
|
||||
<h3 class="modal-title">Удалить чат?</h3>
|
||||
<p class="meta-muted">Удалить пользователя ${contactName} из контактов?</p>
|
||||
<label class="dm-confirm-check">
|
||||
<input type="checkbox" id="chat-delete-chat-history" checked />
|
||||
<span>Также удалить всю историю переписки</span>
|
||||
</label>
|
||||
${isProtectedRelation ? `
|
||||
<p class="meta-muted">Можно удалить содержимое переписки, но чат с ${isCloseFriend ? 'близким другом' : 'другом'} останется в списке.</p>
|
||||
<p class="meta-muted">Удалить ${safeName} из ${relationName} и удалить чат?</p>
|
||||
` : `
|
||||
<p class="meta-muted">Удалить пользователя ${safeName} из контактов?</p>
|
||||
<label class="dm-confirm-check">
|
||||
<input type="checkbox" id="chat-delete-chat-history" checked />
|
||||
<span>Также удалить всю историю переписки</span>
|
||||
</label>
|
||||
`}
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" id="chat-delete-chat-no">Нет</button>
|
||||
<button class="destructive-btn" type="button" id="chat-delete-chat-yes">Да</button>
|
||||
@@ -290,10 +302,12 @@ function openDeleteChatConfirmModal({ contactName = '', onConfirm }) {
|
||||
|
||||
root.querySelector('#chat-delete-chat-no')?.addEventListener('click', close);
|
||||
root.querySelector('#chat-delete-chat-yes')?.addEventListener('click', async () => {
|
||||
const deleteHistory = Boolean(root.querySelector('#chat-delete-chat-history')?.checked);
|
||||
const deleteHistory = isProtectedRelation
|
||||
? true
|
||||
: Boolean(root.querySelector('#chat-delete-chat-history')?.checked);
|
||||
close();
|
||||
if (typeof onConfirm === 'function') {
|
||||
await onConfirm({ deleteHistory });
|
||||
await onConfirm({ deleteHistory, removeRelation: isProtectedRelation });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1173,24 +1187,40 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
},
|
||||
onDeleteChat: async () => {
|
||||
const relationBeforeDelete = normalizeChatRelationType(peerRelationType);
|
||||
openDeleteChatConfirmModal({
|
||||
contactName: contact.name,
|
||||
relationType: relationBeforeDelete,
|
||||
onConfirm: async ({ deleteHistory }) => {
|
||||
try {
|
||||
if (deleteHistory) {
|
||||
await clearConversationHistory();
|
||||
}
|
||||
await authService.setUserRelation({
|
||||
login: state.session.login,
|
||||
toLogin: chatId,
|
||||
kind: 'contact',
|
||||
enabled: false,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
|
||||
// Друг/близкий друг может иметь одновременно и более слабые флаги связи.
|
||||
// Для настоящего «удалить чат» снимаем весь социальный стек, иначе пустой чат
|
||||
// закономерно останется в списке из-за действующей связи.
|
||||
const relationKinds = relationBeforeDelete === 'close_friend' || relationBeforeDelete === 'friend'
|
||||
? ['close_friend', 'friend', 'contact']
|
||||
: ['contact'];
|
||||
for (const kind of relationKinds) {
|
||||
await authService.setUserRelation({
|
||||
login: state.session.login,
|
||||
toLogin: chatId,
|
||||
kind,
|
||||
enabled: false,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
}
|
||||
|
||||
const contactsPayload = await authService.listContacts();
|
||||
setContacts(contactsPayload?.contacts || []);
|
||||
setContacts(
|
||||
contactsPayload?.contacts
|
||||
|| contactsPayload?.dialogs?.filter((x) => x?.relationFlag !== 'none').map((x) => x.peerLogin)
|
||||
|| [],
|
||||
);
|
||||
notifyUnreadStateUpdated();
|
||||
showToast('Чат удалён из контактов', { timeoutMs: 1200 });
|
||||
showToast('Чат удалён', { timeoutMs: 1200 });
|
||||
navigate('messages-list');
|
||||
} catch (error) {
|
||||
showToast(`Не удалось удалить чат: ${error?.message || 'unknown'}`, { kind: 'error', timeoutMs: 1600 });
|
||||
|
||||
@@ -2,6 +2,8 @@ import { renderHeader } from '../components/header.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
consumeAuthReturnPage,
|
||||
isAddingProfileLogin,
|
||||
clearAuthMessages,
|
||||
clearBrowserClientData,
|
||||
refreshSessions,
|
||||
@@ -205,10 +207,13 @@ export function render({ navigate }) {
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const session = await authService.createSessionFromImportedSecrets(scannedTransfer.login, scannedTransfer.keys);
|
||||
await terminateCurrentSession({ closeServerSession: true });
|
||||
await clearStoredMessages().catch(() => {});
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(session.login).catch(() => {});
|
||||
await saveEncryptedUserSecrets(session.login, session.storagePwd, scannedTransfer.keys);
|
||||
await authService.persistSessionMaterial(session.login, session.sessionMaterial);
|
||||
const resumed = await authService.resumeSession(session.login, session.sessionId);
|
||||
@@ -221,7 +226,7 @@ export function render({ navigate }) {
|
||||
state.loginDraft.password = '';
|
||||
await refreshSessions();
|
||||
setAuthInfo(`Вход по QR-коду выполнен для @${resumed.login || session.login}.`);
|
||||
navigate('profile-view');
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, 'Не удалось войти по QR-коду.');
|
||||
setAuthError(message);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
consumeAuthReturnPage,
|
||||
isAddingProfileLogin,
|
||||
clearAuthMessages,
|
||||
clearBrowserClientData,
|
||||
refreshSessions,
|
||||
@@ -182,10 +184,13 @@ export function render({ navigate }) {
|
||||
|
||||
const finalizeAuthorizedLogin = async (keys, login) => {
|
||||
const session = await authService.createSessionFromImportedSecrets(login, keys);
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
await clearStoredMessages().catch(() => {});
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(session.login).catch(() => {});
|
||||
await saveEncryptedUserSecrets(session.login, session.storagePwd, keys);
|
||||
await authService.persistSessionMaterial(session.login, session.sessionMaterial);
|
||||
const resumed = await authService.resumeSession(session.login, session.sessionId);
|
||||
@@ -199,7 +204,7 @@ export function render({ navigate }) {
|
||||
await refreshSessions();
|
||||
setAuthInfo(`Вход через другое устройство выполнен для @${resumed.login || session.login}.`);
|
||||
showToast(`Устройство подключено для @${resumed.login || session.login}`);
|
||||
navigate('profile-view');
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
};
|
||||
|
||||
const finalizeAuthorizedSessionAttach = async (payloadSession, login, requesterKeys) => {
|
||||
@@ -215,10 +220,13 @@ export function render({ navigate }) {
|
||||
sessionType: Number(payloadSession?.sessionType || 50) || 50,
|
||||
};
|
||||
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
await clearStoredMessages().catch(() => {});
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
const addingProfile = isAddingProfileLogin();
|
||||
if (!addingProfile) {
|
||||
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
||||
clearBrowserClientData();
|
||||
await clearClientAuthData().catch(() => {});
|
||||
}
|
||||
await clearStoredMessages(login).catch(() => {});
|
||||
await authService.persistSessionMaterial(login, sessionMaterial);
|
||||
const resumed = await authService.resumeSession(login, sessionId);
|
||||
authorizeSession({
|
||||
@@ -231,7 +239,7 @@ export function render({ navigate }) {
|
||||
await refreshSessions();
|
||||
setAuthInfo(`Session-only вход выполнен для @${resumed.login || login}.`);
|
||||
showToast(`Wallet-session подключена для @${resumed.login || login}`);
|
||||
navigate('profile-view');
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
};
|
||||
|
||||
const schedulePoll = () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import {
|
||||
authService,
|
||||
cancelAddProfileLogin,
|
||||
clearAuthMessages,
|
||||
setAuthBusy,
|
||||
setAuthError,
|
||||
@@ -155,7 +156,17 @@ export function render({ navigate }) {
|
||||
screen.append(
|
||||
renderHeader({
|
||||
title: '',
|
||||
leftAction: { label: '←', onClick: () => navigate('start-view') },
|
||||
leftAction: {
|
||||
label: '←',
|
||||
onClick: async () => {
|
||||
if (state.authReturnHash === '/profiles') {
|
||||
await cancelAddProfileLogin();
|
||||
navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
navigate('start-view');
|
||||
},
|
||||
},
|
||||
}),
|
||||
panel,
|
||||
);
|
||||
|
||||
@@ -448,6 +448,9 @@ function renderRow(item) {
|
||||
});
|
||||
|
||||
const rows = Array.from(byPeer.values())
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог.
|
||||
// Пустые друзья/контакты остаются, а пользователь без связи исчезает после очистки.
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog))
|
||||
.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter)
|
||||
.sort((a, b) => {
|
||||
const orderA = relationOrder(a.relationFlag);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
@@ -25,32 +27,6 @@ function createDebounced(fn, delayMs = 2000) {
|
||||
};
|
||||
}
|
||||
|
||||
function createHeaderSearchIcon() {
|
||||
const ns = 'http://www.w3.org/2000/svg';
|
||||
const svg = document.createElementNS(ns, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 24 24');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
svg.setAttribute('class', 'header-icon-svg header-icon-svg--search');
|
||||
|
||||
const circle = document.createElementNS(ns, 'circle');
|
||||
circle.setAttribute('cx', '11');
|
||||
circle.setAttribute('cy', '11');
|
||||
circle.setAttribute('r', '6.5');
|
||||
circle.setAttribute('fill', 'none');
|
||||
circle.setAttribute('stroke', 'currentColor');
|
||||
circle.setAttribute('stroke-width', '2');
|
||||
|
||||
const handle = document.createElementNS(ns, 'path');
|
||||
handle.setAttribute('d', 'M16 16l4.5 4.5');
|
||||
handle.setAttribute('fill', 'none');
|
||||
handle.setAttribute('stroke', 'currentColor');
|
||||
handle.setAttribute('stroke-width', '2');
|
||||
handle.setAttribute('stroke-linecap', 'round');
|
||||
|
||||
svg.append(circle, handle);
|
||||
return svg;
|
||||
}
|
||||
|
||||
function normKey(value) {
|
||||
return normalizeLogin(value).toLowerCase();
|
||||
}
|
||||
@@ -290,7 +266,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
<div class="modal" id="network-search-modal">
|
||||
<div class="modal-card stack">
|
||||
<button class="icon-btn" type="button" id="network-search-close" style="justify-self:end;">✕</button>
|
||||
<h3 class="modal-title">Найти человека</h3>
|
||||
<h3 class="modal-title">Найти пользователя</h3>
|
||||
<div class="row" style="gap:8px;">
|
||||
<input class="input" id="network-search-input" type="text" maxlength="30" placeholder="Введите логин" />
|
||||
<button class="primary-btn" type="button" id="network-search-run">Искать</button>
|
||||
@@ -462,17 +438,32 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
title: 'Связи',
|
||||
rightActions: [
|
||||
{
|
||||
iconNode: createHeaderSearchIcon(),
|
||||
title: 'Найти пользователя',
|
||||
ariaLabel: 'Найти пользователя',
|
||||
className: 'chat-header-icon-btn',
|
||||
onClick: openSearchModal,
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню связей',
|
||||
ariaLabel: 'Открыть меню связей',
|
||||
className: 'chat-header-icon-btn network-header-menu-btn',
|
||||
onClick: () => {},
|
||||
},
|
||||
],
|
||||
});
|
||||
const networkMenuButton = header.querySelector('.network-header-menu-btn');
|
||||
const searchIconHtml = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="11" cy="11" r="6.5"></circle>
|
||||
<path d="M16 16l4 4"></path>
|
||||
</svg>
|
||||
`;
|
||||
const networkMenu = createDropdownMenu({
|
||||
anchorEl: networkMenuButton,
|
||||
minWidth: 220,
|
||||
items: [
|
||||
{ label: 'Найти пользователя', iconHtml: searchIconHtml, action: openSearchModal },
|
||||
],
|
||||
});
|
||||
|
||||
// Ресайз и перерисовку рёбер движок обрабатывает сам (window resize + ResizeObserver внутри).
|
||||
screen.cleanup = () => {
|
||||
networkMenu.destroy();
|
||||
if (engine) engine.destroy();
|
||||
engine = null;
|
||||
appScreenEl?.classList.remove('network-scroll-lock');
|
||||
|
||||
@@ -5,18 +5,37 @@ import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
|
||||
const CONNECTION_CLOSE_FRIEND = 10;
|
||||
const CONNECTION_UNCLOSE_FRIEND = 11;
|
||||
const CONNECTION_FRIEND = 14;
|
||||
const CONNECTION_UNFRIEND = 15;
|
||||
const CONNECTION_FOLLOW = 30;
|
||||
const CONNECTION_UNFOLLOW = 31;
|
||||
const CONNECTION_SHINE_CONFIRMED = 70;
|
||||
const CONNECTION_SHINE_UNCONFIRMED = 71;
|
||||
const CONNECTION_OFFICIAL_CONFIRMED = 80;
|
||||
const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
||||
const profileSnapshotCache = new Map();
|
||||
const profileSnapshotPending = new Map();
|
||||
|
||||
function connectionTypeLabel(typeCode) {
|
||||
function connectionActionLabel(typeCode) {
|
||||
switch (Number(typeCode)) {
|
||||
case CONNECTION_CLOSE_FRIEND:
|
||||
return 'близкие друзья';
|
||||
default:
|
||||
return 'новую связь';
|
||||
case CONNECTION_CLOSE_FRIEND: return 'Добавил(а) вас в близкие друзья.';
|
||||
case CONNECTION_UNCLOSE_FRIEND: return 'Удалил(а) вас из близких друзей.';
|
||||
case CONNECTION_FRIEND: return 'Добавил(а) вас в друзья.';
|
||||
case CONNECTION_UNFRIEND: return 'Удалил(а) вас из друзей.';
|
||||
case CONNECTION_SHINE_CONFIRMED: return 'Подтвердил(а), что вы Сияющий.';
|
||||
case CONNECTION_SHINE_UNCONFIRMED: return 'Снял(а) подтверждение «Сияющий».';
|
||||
case CONNECTION_OFFICIAL_CONFIRMED: return 'Подтвердил(а) официальный статус аккаунта.';
|
||||
case CONNECTION_OFFICIAL_UNCONFIRMED: return 'Снял(а) подтверждение официального статуса.';
|
||||
default: return 'Изменил(а) связь с вами.';
|
||||
}
|
||||
}
|
||||
|
||||
function eventActionLabel(typeCode) {
|
||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return 'Отписался(-ась) от вашего канала.';
|
||||
return 'Подписался(-ась) на ваш канал.';
|
||||
}
|
||||
|
||||
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
|
||||
|
||||
function normalizeItem(item) {
|
||||
@@ -136,12 +155,10 @@ function renderEmpty(activeTab) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'card stack notification-empty-state';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : 'Пока нет ответов';
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = activeTab === 'events'
|
||||
? 'Когда кто-то добавит новую связь с вами, событие появится здесь.'
|
||||
: 'Когда кто-то ответит на ваше сообщение в канале или треде, ответ появится здесь.';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или треде, ответ появится здесь.';
|
||||
card.append(title, text);
|
||||
return card;
|
||||
}
|
||||
@@ -239,7 +256,7 @@ function renderEngagement(engagement) {
|
||||
}
|
||||
|
||||
function notificationRoute(item, activeTab) {
|
||||
if (activeTab === 'events') {
|
||||
if (activeTab === 'events' || activeTab === 'connections') {
|
||||
const login = String(item?.sourceLogin || '').trim();
|
||||
return login ? makeProfileRoute(login) : '';
|
||||
}
|
||||
@@ -278,8 +295,10 @@ function renderItem(item, activeTab, navigate) {
|
||||
|
||||
const action = document.createElement('p');
|
||||
action.className = 'notification-action';
|
||||
if (activeTab === 'events') {
|
||||
action.textContent = `Добавил(а) вас в ${connectionTypeLabel(item.connectionTypeCode)}.`;
|
||||
if (activeTab === 'connections') {
|
||||
action.textContent = connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType);
|
||||
} else if (activeTab === 'events') {
|
||||
action.textContent = eventActionLabel(item.sourceMsgSubType, item);
|
||||
} else {
|
||||
action.textContent = 'Ответил(а) на ваше сообщение.';
|
||||
}
|
||||
@@ -305,90 +324,98 @@ export function render({ navigate, chrome } = {}) {
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'notification-feed-tabs app-top-tabs';
|
||||
tabs.innerHTML = `
|
||||
<button
|
||||
type="button"
|
||||
class="fg-filter-chip notification-tab-btn ${state.notificationsTab === 'replies' ? 'is-active' : ''}"
|
||||
data-tab="replies"
|
||||
data-selected="${state.notificationsTab === 'replies' ? 'true' : 'false'}"
|
||||
aria-selected="${state.notificationsTab === 'replies' ? 'true' : 'false'}"
|
||||
>Ответы</button>
|
||||
<button
|
||||
type="button"
|
||||
class="fg-filter-chip notification-tab-btn ${state.notificationsTab === 'events' ? 'is-active' : ''}"
|
||||
data-tab="events"
|
||||
data-selected="${state.notificationsTab === 'events' ? 'true' : 'false'}"
|
||||
aria-selected="${state.notificationsTab === 'events' ? 'true' : 'false'}"
|
||||
>События</button>
|
||||
`;
|
||||
|
||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack notifications-list';
|
||||
|
||||
let payloadCache = null;
|
||||
let requestSeq = 0;
|
||||
let observer = null;
|
||||
const pendingSeenTimers = { replies: null, connections: null, events: null };
|
||||
const localSeen = { replies: 0, connections: 0, events: 0 };
|
||||
|
||||
async function load() {
|
||||
const seq = ++requestSeq;
|
||||
const activeTab = state.notificationsTab;
|
||||
list.replaceChildren(renderEmpty(activeTab));
|
||||
function countsFromPayload(payload) {
|
||||
return {
|
||||
replies: Number(payload?.repliesUnseenCount || 0),
|
||||
connections: Number(payload?.connectionsUnseenCount || 0),
|
||||
events: Number(payload?.eventsUnseenCount || 0),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await authService.getNotifications(50);
|
||||
if (seq !== requestSeq) return;
|
||||
const baseItems = (activeTab === 'events' ? payload.events : payload.replies)
|
||||
.map(normalizeItem);
|
||||
if (!baseItems.length) {
|
||||
list.replaceChildren(renderEmpty(activeTab));
|
||||
return;
|
||||
}
|
||||
function updateToolbarBadge(payload) {
|
||||
const c = countsFromPayload(payload);
|
||||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
if (state.notificationUnreadTotal <= 0) { badge?.remove(); return; }
|
||||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; btn.append(badge); }
|
||||
badge.textContent = state.notificationUnreadTotal > 99 ? '99+' : String(state.notificationUnreadTotal);
|
||||
}
|
||||
|
||||
const items = await Promise.all(baseItems.map((item) => enrichItem(item, activeTab)));
|
||||
if (seq !== requestSeq) return;
|
||||
list.replaceChildren(...items.map((item) => renderItem(item, activeTab, navigate)));
|
||||
} catch (error) {
|
||||
if (seq !== requestSeq) return;
|
||||
const card = document.createElement('article');
|
||||
card.className = 'card stack';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = 'Не удалось загрузить уведомления';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = error?.message || 'Ошибка запроса к серверу';
|
||||
card.append(title, text);
|
||||
list.replaceChildren(card);
|
||||
function renderTabs(payload) {
|
||||
const counts = countsFromPayload(payload);
|
||||
tabs.replaceChildren(...tabDefs.map(([key,label]) => {
|
||||
const b=document.createElement('button'); b.type='button'; b.className=`fg-filter-chip notification-tab-btn ${state.notificationsTab===key?'is-active':''}`; b.dataset.tab=key; b.setAttribute('aria-selected',state.notificationsTab===key?'true':'false');
|
||||
b.textContent = counts[key] > 0 ? `${label} ${counts[key]}` : label;
|
||||
b.addEventListener('click',()=>{ if(state.notificationsTab===key)return; state.notificationsTab=key; renderCurrent(); });
|
||||
return b;
|
||||
}));
|
||||
}
|
||||
|
||||
function categoryData(payload, tab) {
|
||||
if (tab === 'connections') return { items: payload?.connections || [], seenAt: Number(payload?.connectionsSeenAtMs || 0) };
|
||||
if (tab === 'events') return { items: payload?.events || [], seenAt: Number(payload?.eventsSeenAtMs || 0) };
|
||||
return { items: payload?.replies || [], seenAt: Number(payload?.repliesSeenAtMs || 0) };
|
||||
}
|
||||
|
||||
function scheduleSeen(category, seenAtMs) {
|
||||
if (seenAtMs <= Number(localSeen[category] || 0)) return;
|
||||
localSeen[category] = seenAtMs;
|
||||
clearTimeout(pendingSeenTimers[category]);
|
||||
pendingSeenTimers[category] = setTimeout(async () => {
|
||||
const target = Number(localSeen[category] || 0);
|
||||
try {
|
||||
await authService.setNotificationSeen({ login: state.session.login, category, seenAtMs: target, storagePwd: state.session.storagePwdInMemory });
|
||||
if (!payloadCache) return;
|
||||
const key = category === 'connections' ? 'connectionsSeenAtMs' : category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||||
const countKey = category === 'connections' ? 'connectionsUnseenCount' : category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||||
payloadCache[key] = Math.max(Number(payloadCache[key] || 0), target);
|
||||
payloadCache[countKey] = (payloadCache[category] || []).filter(x => Number(x?.createdAtMs || 0) > payloadCache[key]).length;
|
||||
renderTabs(payloadCache); updateToolbarBadge(payloadCache);
|
||||
} catch (e) { console.warn('Не удалось подписать watermark уведомлений', e); }
|
||||
}, 350);
|
||||
}
|
||||
|
||||
async function renderCurrent() {
|
||||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
||||
const tab=state.notificationsTab; const {items:raw,seenAt}=categoryData(payloadCache || {},tab); localSeen[tab]=Math.max(localSeen[tab]||0,seenAt);
|
||||
const base=raw.map(normalizeItem); if(!base.length){list.replaceChildren(renderEmpty(tab));return;}
|
||||
const items=await Promise.all(base.map(x=>enrichItem(x,tab)));
|
||||
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||||
const nodes=[];
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);nodes.push(n);});
|
||||
let divider=null;
|
||||
if(unread.length){divider=document.createElement('div');divider.className='notification-new-divider';divider.textContent=`НОВЫЕ · ${unread.length}`;nodes.push(divider);}
|
||||
old.forEach(x=>nodes.push(renderItem(x,tab,navigate))); list.replaceChildren(...nodes);
|
||||
if(unread.length && 'IntersectionObserver' in window){
|
||||
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
|
||||
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
|
||||
requestAnimationFrame(()=>divider?.scrollIntoView({block:'end'}));
|
||||
}
|
||||
}
|
||||
|
||||
function setActiveNotificationTab(nextTab) {
|
||||
const normalizedTab = nextTab === 'events' ? 'events' : 'replies';
|
||||
state.notificationsTab = normalizedTab;
|
||||
|
||||
tabs.querySelectorAll('.notification-tab-btn').forEach((node) => {
|
||||
const selected = node.dataset.tab === normalizedTab;
|
||||
node.classList.toggle('is-active', selected);
|
||||
node.dataset.selected = selected ? 'true' : 'false';
|
||||
node.setAttribute('aria-selected', selected ? 'true' : 'false');
|
||||
});
|
||||
async function load() {
|
||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
||||
catch(error){ if(seq!==requestSeq)return; const card=document.createElement('article');card.className='card stack';card.innerHTML='<strong>Не удалось загрузить уведомления</strong>';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);}
|
||||
}
|
||||
|
||||
// Активная кнопка остаётся визуально нажатой до выбора второй вкладки.
|
||||
// При переключении класс active и aria-selected синхронно переходят на новую кнопку.
|
||||
setActiveNotificationTab(state.notificationsTab);
|
||||
|
||||
tabs.querySelectorAll('.notification-tab-btn').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const nextTab = btn.dataset.tab === 'events' ? 'events' : 'replies';
|
||||
if (state.notificationsTab === nextTab) {
|
||||
setActiveNotificationTab(nextTab);
|
||||
return;
|
||||
}
|
||||
|
||||
setActiveNotificationTab(nextTab);
|
||||
void load();
|
||||
});
|
||||
});
|
||||
|
||||
screen.append(tabs, list);
|
||||
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||||
screen.cleanup = () => {
|
||||
observer?.disconnect();
|
||||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||||
};
|
||||
screen.append(tabs,list);
|
||||
void load();
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ export function render({ navigate, chrome }) {
|
||||
{ label: 'Редактировать профиль', iconSrc: '/assets/profile-icon-profile.svg', action: () => navigate('profile-edit-view') },
|
||||
{ label: 'Кошелёк', iconSrc: '/assets/profile-icon-wallet.svg', action: () => navigate('wallet-view') },
|
||||
{ label: 'Настройки', iconSrc: '/assets/profile-icon-settings.svg', action: () => navigate('settings-view') },
|
||||
{ label: 'Сменить профиль', action: () => navigate('profiles-view') },
|
||||
],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import {
|
||||
closeAllSavedProfiles,
|
||||
closeSavedProfile,
|
||||
getSavedProfiles,
|
||||
prepareAddProfileLogin,
|
||||
state,
|
||||
switchToSavedProfile,
|
||||
} from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'profiles-view', title: 'Профили' };
|
||||
|
||||
function reloadTo(path) {
|
||||
const clean = String(path || '/profile').trim() || '/profile';
|
||||
window.location.assign(clean.startsWith('/') ? clean : `/${clean}`);
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack profiles-screen';
|
||||
|
||||
screen.append(renderHeader({
|
||||
title: 'Профили',
|
||||
leftAction: { label: '←', onClick: () => navigate('profile-view') },
|
||||
}));
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'meta-muted profiles-summary';
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack profiles-list';
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line';
|
||||
status.hidden = true;
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'stack profiles-actions';
|
||||
|
||||
const addButton = document.createElement('button');
|
||||
addButton.type = 'button';
|
||||
addButton.className = 'secondary-btn';
|
||||
addButton.textContent = 'Добавить профиль';
|
||||
addButton.addEventListener('click', async () => {
|
||||
addButton.disabled = true;
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Подготавливаем вход в новый профиль…';
|
||||
try {
|
||||
await prepareAddProfileLogin();
|
||||
navigate('login-view');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось начать добавление профиля: ${error?.message || 'unknown'}`;
|
||||
addButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const closeAllButton = document.createElement('button');
|
||||
closeAllButton.type = 'button';
|
||||
closeAllButton.className = 'secondary-btn profiles-close-all';
|
||||
closeAllButton.textContent = 'Закрыть все профили';
|
||||
closeAllButton.addEventListener('click', async () => {
|
||||
const profiles = getSavedProfiles();
|
||||
if (!profiles.length) return;
|
||||
const confirmed = window.confirm('Закрыть все профили на этом устройстве? После этого откроется экран входа.');
|
||||
if (!confirmed) return;
|
||||
closeAllButton.disabled = true;
|
||||
status.hidden = false;
|
||||
status.textContent = 'Закрываем профили…';
|
||||
try {
|
||||
await closeAllSavedProfiles();
|
||||
reloadTo('/start');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось закрыть профили: ${error?.message || 'unknown'}`;
|
||||
closeAllButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
actions.append(addButton, closeAllButton);
|
||||
screen.append(intro, list, status, actions);
|
||||
|
||||
const renderList = () => {
|
||||
const profiles = getSavedProfiles();
|
||||
const active = profiles.find((item) => item.isActive);
|
||||
intro.textContent = profiles.length
|
||||
? `Профилей на устройстве: ${profiles.length}. Активен: ${active?.login || state.session.login || '—'}`
|
||||
: 'На устройстве нет сохранённых профилей.';
|
||||
closeAllButton.disabled = profiles.length === 0;
|
||||
list.innerHTML = '';
|
||||
|
||||
profiles.forEach((profile) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = `card profiles-row${profile.isActive ? ' is-active' : ''}`;
|
||||
|
||||
const select = document.createElement('button');
|
||||
select.type = 'button';
|
||||
select.className = 'profiles-select';
|
||||
select.innerHTML = `<span class="profiles-login">${profile.login}</span>${profile.isActive ? '<span class="badge">Активный</span>' : ''}`;
|
||||
select.disabled = profile.isActive;
|
||||
select.addEventListener('click', async () => {
|
||||
if (profile.isActive) return;
|
||||
const confirmed = window.confirm(`Переключиться на профиль «${profile.login}»?`);
|
||||
if (!confirmed) return;
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = `Подключаем профиль ${profile.login}…`;
|
||||
try {
|
||||
await switchToSavedProfile(profile.login);
|
||||
reloadTo('/profile');
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось переключить профиль: ${error?.message || 'unknown'}`;
|
||||
}
|
||||
});
|
||||
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'profiles-close';
|
||||
close.setAttribute('aria-label', `Закрыть профиль ${profile.login}`);
|
||||
close.textContent = '×';
|
||||
close.addEventListener('click', async () => {
|
||||
const others = profiles.filter((item) => item.login.toLowerCase() !== profile.login.toLowerCase());
|
||||
const message = profile.isActive
|
||||
? (others.length
|
||||
? `Закрыть текущий профиль «${profile.login}»? После закрытия приложение переключится на следующий сохранённый профиль.`
|
||||
: `Закрыть текущий профиль «${profile.login}»? После закрытия откроется экран входа.`)
|
||||
: `Закрыть профиль «${profile.login}» на этом устройстве?`;
|
||||
if (!window.confirm(message)) return;
|
||||
|
||||
status.hidden = false;
|
||||
status.className = 'status-line';
|
||||
status.textContent = `Закрываем профиль ${profile.login}…`;
|
||||
try {
|
||||
const result = await closeSavedProfile(profile.login);
|
||||
if (profile.isActive) {
|
||||
reloadTo(result.nextProfile ? '/profile' : '/start');
|
||||
return;
|
||||
}
|
||||
status.hidden = true;
|
||||
renderList();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось закрыть профиль: ${error?.message || 'unknown'}`;
|
||||
}
|
||||
});
|
||||
|
||||
row.append(select, close);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
|
||||
renderList();
|
||||
return screen;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import {
|
||||
authService,
|
||||
cancelAddProfileLogin,
|
||||
consumeAuthReturnPage,
|
||||
authorizeSession,
|
||||
refreshSessions,
|
||||
resetRegistrationFlow,
|
||||
@@ -103,7 +105,12 @@ export function render({ navigate }) {
|
||||
cancelButton.className = 'ghost-btn';
|
||||
cancelButton.type = 'button';
|
||||
cancelButton.textContent = 'Отмена';
|
||||
cancelButton.addEventListener('click', () => {
|
||||
cancelButton.addEventListener('click', async () => {
|
||||
if (state.authReturnHash === '/profiles') {
|
||||
await cancelAddProfileLogin();
|
||||
navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
resetRegistrationFlow();
|
||||
navigate('start-view');
|
||||
});
|
||||
@@ -143,7 +150,7 @@ export function render({ navigate }) {
|
||||
state.registrationDraft.pendingKeyBundle.blockchainPair = null;
|
||||
}
|
||||
|
||||
await clearStoredMessages().catch(() => {});
|
||||
await clearStoredMessages(state.registrationDraft.login).catch(() => {});
|
||||
|
||||
authorizeSession({
|
||||
login: state.registrationDraft.login,
|
||||
@@ -174,13 +181,7 @@ export function render({ navigate }) {
|
||||
setAuthInfo(isLoginFlow
|
||||
? `Ключи сохранены. Вы вошли как @${state.registrationDraft.login}. Далее откройте вкладку «Каналы».`
|
||||
: `Ключи сохранены. Регистрация завершена для @${state.registrationDraft.login}. Далее откройте вкладку «Каналы».`);
|
||||
const nextHash = String(state.authReturnHash || '').trim();
|
||||
state.authReturnHash = '';
|
||||
if (nextHash.startsWith('/')) {
|
||||
navigate(nextHash.slice(1));
|
||||
} else {
|
||||
navigate('profile-view');
|
||||
}
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
const message = toUserMessage(error, 'Не удалось сохранить ключи на устройстве.');
|
||||
setAuthError(message);
|
||||
@@ -196,7 +197,12 @@ export function render({ navigate }) {
|
||||
title: 'Сохранение ключей',
|
||||
leftAction: {
|
||||
label: '←',
|
||||
onClick: () => {
|
||||
onClick: async () => {
|
||||
if (state.authReturnHash === '/profiles') {
|
||||
await cancelAddProfileLogin();
|
||||
navigate('profiles-view');
|
||||
return;
|
||||
}
|
||||
resetRegistrationFlow();
|
||||
navigate('start-view');
|
||||
},
|
||||
|
||||
@@ -107,7 +107,7 @@ async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
},
|
||||
);
|
||||
await authService.persistSessionMaterial(result.login, result.sessionMaterial);
|
||||
await clearStoredMessages().catch(() => {});
|
||||
await clearStoredMessages(state.registrationDraft.login).catch(() => {});
|
||||
|
||||
const resumed = await authService.resumeSession(result.login, result.sessionId);
|
||||
const resumedLogin = resumed.login || result.login;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import { addAppLogEntry, authService, closeCurrentSessionAndSignOut } from '../state.js';
|
||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
||||
|
||||
@@ -77,7 +77,7 @@ export function render({ navigate }) {
|
||||
const signOutBtn = card.querySelector('#settings-signout');
|
||||
signOutBtn.addEventListener('click', async () => {
|
||||
const confirmed = window.confirm(
|
||||
'Завершить текущую сессию на сервере, отключиться, очистить локальные данные и перейти на стартовый экран?'
|
||||
'Завершить текущий профиль на этом устройстве? Если есть другие сохранённые профили, приложение переключится на следующий.'
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
@@ -88,9 +88,8 @@ export function render({ navigate }) {
|
||||
source: 'session',
|
||||
message: 'Запрошено завершение текущей сессии',
|
||||
});
|
||||
await closeCurrentSessionAndSignOut({
|
||||
infoMessage: 'Сеанс завершён. Выполните вход заново.',
|
||||
});
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
window.location.assign(result?.nextProfile ? '/profile' : '/start');
|
||||
} finally {
|
||||
signOutBtn.disabled = false;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ const PRETTY_PATHS = new Map([
|
||||
['key-storage-view', 'key-storage'],
|
||||
['profile-view', 'profile'],
|
||||
['profile-edit-view', 'profile/edit'],
|
||||
['profiles-view', 'profiles'],
|
||||
['messages-list', 'messages'],
|
||||
['contact-search-view', 'contacts'],
|
||||
['chat-view', 'chat'],
|
||||
@@ -248,6 +249,10 @@ export function parseRouteFromPath(pathname = '') {
|
||||
return { pageId: 'profile-view', params: {} };
|
||||
}
|
||||
|
||||
if (pageId === 'profiles') {
|
||||
return { pageId: 'profiles-view', params: {} };
|
||||
}
|
||||
|
||||
if (pageId === 'messages') {
|
||||
return { pageId: 'messages-list', params: {} };
|
||||
}
|
||||
@@ -437,6 +442,7 @@ export function resolveToolbarActive(pageId) {
|
||||
) return pageId;
|
||||
if (
|
||||
pageId === 'profile-edit-view' ||
|
||||
pageId === 'profiles-view' ||
|
||||
pageId === 'wallet-view' ||
|
||||
pageId === 'settings-view' ||
|
||||
pageId === 'access-servers-view' ||
|
||||
|
||||
@@ -249,6 +249,11 @@ function uint8Bytes(value) {
|
||||
}
|
||||
|
||||
const DM_PREFIX_V1 = utf8Bytes('SHiNE_DM');
|
||||
const NTF_PREFIX_V1 = utf8Bytes('SHiNE_NTF');
|
||||
const NTF_FORMAT_VERSION_MAJOR = 1;
|
||||
const NTF_FORMAT_VERSION_MINOR = 0;
|
||||
const NTF_STATE_SEEN_WATERMARK = 1;
|
||||
const NTF_CATEGORY = { replies: 1, connections: 2, events: 3 };
|
||||
const DM_TYPE_INCOMING = 1;
|
||||
const DM_TYPE_OUTGOING_COPY = 2;
|
||||
const DM_TYPE_READ_INCOMING = 3;
|
||||
@@ -994,6 +999,8 @@ export class AuthService {
|
||||
constructor(serverUrl) {
|
||||
this.serverUrl = normalizeServerUrl(serverUrl);
|
||||
this.ws = new WsJsonClient(this.serverUrl);
|
||||
this.eventListeners = new Map();
|
||||
this.wsEventUnsubscribers = new Map();
|
||||
this.headerHashCache = new Map();
|
||||
this.writeLocks = new Map();
|
||||
this.passwordKeyBundleCache = new Map();
|
||||
@@ -1003,14 +1010,39 @@ export class AuthService {
|
||||
this.remoteAddBlockSessionId = '';
|
||||
}
|
||||
|
||||
async reconnect(serverUrl) {
|
||||
bindRegisteredEventsToCurrentWs() {
|
||||
this.wsEventUnsubscribers.forEach((unsubscribe) => {
|
||||
try { unsubscribe?.(); } catch {}
|
||||
});
|
||||
this.wsEventUnsubscribers.clear();
|
||||
|
||||
this.eventListeners.forEach((_handlers, op) => {
|
||||
const unsubscribe = this.ws.onEvent(op, (data) => {
|
||||
const handlers = this.eventListeners.get(op);
|
||||
if (!handlers) return;
|
||||
handlers.forEach((handler) => {
|
||||
try { handler(data); } catch {}
|
||||
});
|
||||
});
|
||||
this.wsEventUnsubscribers.set(op, unsubscribe);
|
||||
});
|
||||
}
|
||||
|
||||
resetConnection(serverUrl = this.serverUrl, { clearSessionContext = true } = {}) {
|
||||
const normalized = normalizeServerUrl(serverUrl);
|
||||
if (normalized === this.serverUrl) return;
|
||||
this.ws.close();
|
||||
try { this.ws?.close(); } catch {}
|
||||
this.serverUrl = normalized;
|
||||
this.ws = new WsJsonClient(this.serverUrl);
|
||||
this.headerHashCache = new Map();
|
||||
this.writeLocks.clear();
|
||||
this.bindRegisteredEventsToCurrentWs();
|
||||
if (clearSessionContext) this.clearActiveSessionContext();
|
||||
}
|
||||
|
||||
async reconnect(serverUrl) {
|
||||
const normalized = normalizeServerUrl(serverUrl);
|
||||
if (normalized === this.serverUrl) return;
|
||||
this.resetConnection(normalized, { clearSessionContext: false });
|
||||
}
|
||||
|
||||
setActiveSessionContext({ login = '', sessionId = '' } = {}) {
|
||||
@@ -2509,7 +2541,28 @@ export class AuthService {
|
||||
|
||||
|
||||
onEvent(op, handler) {
|
||||
return this.ws.onEvent(op, handler);
|
||||
if (!op || typeof handler !== 'function') return () => {};
|
||||
if (!this.eventListeners.has(op)) {
|
||||
this.eventListeners.set(op, new Set());
|
||||
const unsubscribe = this.ws.onEvent(op, (data) => {
|
||||
const handlers = this.eventListeners.get(op);
|
||||
if (!handlers) return;
|
||||
handlers.forEach((callback) => {
|
||||
try { callback(data); } catch {}
|
||||
});
|
||||
});
|
||||
this.wsEventUnsubscribers.set(op, unsubscribe);
|
||||
}
|
||||
const handlers = this.eventListeners.get(op);
|
||||
handlers.add(handler);
|
||||
return () => {
|
||||
handlers.delete(handler);
|
||||
if (handlers.size) return;
|
||||
this.eventListeners.delete(op);
|
||||
const unsubscribe = this.wsEventUnsubscribers.get(op);
|
||||
try { unsubscribe?.(); } catch {}
|
||||
this.wsEventUnsubscribers.delete(op);
|
||||
};
|
||||
}
|
||||
|
||||
async upsertPushToken({ endpoint, p256dhKey, authKey, sessionId, platform = 'web', userAgent = navigator.userAgent || '' }) {
|
||||
@@ -2891,14 +2944,40 @@ export class AuthService {
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getNotifications(limit = 50) {
|
||||
const payload = {};
|
||||
if (Number.isFinite(Number(limit))) payload.limit = Math.max(1, Math.min(200, Number(limit)));
|
||||
const response = await this.ws.request('GetNotifications', payload);
|
||||
async getNotifications(countsOnly = false) {
|
||||
const response = await this.ws.request('GetNotifications', countsOnly ? { countsOnly: true } : {});
|
||||
if (response.status !== 200) throw opError('GetNotifications', response);
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async setNotificationSeen({ login, category, seenAtMs, storagePwd }) {
|
||||
const cleanLogin = this.normalizeDmLogin(login);
|
||||
const cleanCategory = String(category || '').trim().toLowerCase();
|
||||
const categoryCode = NTF_CATEGORY[cleanCategory];
|
||||
if (!cleanLogin || !categoryCode) throw new Error('Некорректный login/category уведомлений');
|
||||
if (!storagePwd) throw new Error('Не передан storagePwd для подписи состояния уведомлений');
|
||||
const normalizedSeenAtMs = Math.max(0, Math.trunc(Number(seenAtMs || 0)));
|
||||
const timeMs = Date.now();
|
||||
const nonce = Math.floor(Math.random() * 0x100000000);
|
||||
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
|
||||
const clientPriv = secrets?.clientKey;
|
||||
if (!clientPriv) throw new Error('Не найден приватный clientKey');
|
||||
const privateKey = await importPkcs8Ed25519(clientPriv);
|
||||
const loginBytes = ensureAsciiBytes(cleanLogin, 'login');
|
||||
const preimage = concatBytes(
|
||||
NTF_PREFIX_V1,
|
||||
uint8Bytes(NTF_FORMAT_VERSION_MAJOR), uint8Bytes(NTF_FORMAT_VERSION_MINOR),
|
||||
uint8Bytes(loginBytes.length), loginBytes,
|
||||
uint64Bytes(timeMs), uint32Bytes(nonce),
|
||||
uint8Bytes(NTF_STATE_SEEN_WATERMARK), uint8Bytes(categoryCode),
|
||||
uint64Bytes(normalizedSeenAtMs),
|
||||
);
|
||||
const signature = await signBytes(privateKey, preimage);
|
||||
const response = await this.ws.request('SetNotificationState', { blobB64: bytesToBase64(concatBytes(preimage, signature)) });
|
||||
if (response.status !== 200) throw opError('SetNotificationState', response);
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async getUserConnectionsGraph(login) {
|
||||
const response = await this.ws.request('GetUserConnectionsGraph', { login });
|
||||
if (response.status !== 200) throw opError('GetUserConnectionsGraph', response);
|
||||
|
||||
@@ -1,16 +1,67 @@
|
||||
const DB_NAME = 'shine-ui-messages-v1';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_MESSAGES = 'messages';
|
||||
const DB_VERSION = 3;
|
||||
const STORE_MESSAGES = 'messages_by_profile';
|
||||
const LEGACY_STORE_MESSAGES = 'messages';
|
||||
const ACTIVE_PROFILE_STORAGE_KEY = 'shine-ui-active-profile-v1';
|
||||
const LEGACY_SESSION_STORAGE_KEY = 'shine-ui-current-session-v1';
|
||||
|
||||
function normalizeOwnerLogin(value) {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function storageKey(ownerLogin, messageKey) {
|
||||
const owner = normalizeOwnerLogin(ownerLogin);
|
||||
const key = String(messageKey || '').trim();
|
||||
return owner && key ? `${owner}|${key}` : '';
|
||||
}
|
||||
|
||||
function migrationOwnerLogin() {
|
||||
try {
|
||||
const active = normalizeOwnerLogin(localStorage.getItem(ACTIVE_PROFILE_STORAGE_KEY));
|
||||
if (active) return active;
|
||||
const legacy = JSON.parse(localStorage.getItem(LEGACY_SESSION_STORAGE_KEY) || '{}');
|
||||
return normalizeOwnerLogin(legacy?.login);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function ensureIndexes(store) {
|
||||
if (!store.indexNames.contains('by_chat')) store.createIndex('by_chat', 'chatId', { unique: false });
|
||||
if (!store.indexNames.contains('by_ts')) store.createIndex('by_ts', 'ts', { unique: false });
|
||||
if (!store.indexNames.contains('by_owner')) store.createIndex('by_owner', 'ownerLogin', { unique: false });
|
||||
}
|
||||
|
||||
function openDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
let store;
|
||||
if (!db.objectStoreNames.contains(STORE_MESSAGES)) {
|
||||
const store = db.createObjectStore(STORE_MESSAGES, { keyPath: 'messageKey' });
|
||||
store.createIndex('by_chat', 'chatId', { unique: false });
|
||||
store.createIndex('by_ts', 'ts', { unique: false });
|
||||
store = db.createObjectStore(STORE_MESSAGES, { keyPath: 'storageKey' });
|
||||
} else {
|
||||
store = request.transaction.objectStore(STORE_MESSAGES);
|
||||
}
|
||||
ensureIndexes(store);
|
||||
|
||||
// Однократная миграция старого single-profile кэша в пространство текущего профиля.
|
||||
if (db.objectStoreNames.contains(LEGACY_STORE_MESSAGES)) {
|
||||
const owner = migrationOwnerLogin();
|
||||
if (owner) {
|
||||
const legacy = request.transaction.objectStore(LEGACY_STORE_MESSAGES);
|
||||
const cursorReq = legacy.openCursor();
|
||||
cursorReq.onsuccess = () => {
|
||||
const cursor = cursorReq.result;
|
||||
if (!cursor) return;
|
||||
const row = cursor.value || {};
|
||||
const messageKey = String(row.messageKey || '').trim();
|
||||
const rowOwner = normalizeOwnerLogin(row.ownerLogin) || owner;
|
||||
const key = storageKey(rowOwner, messageKey);
|
||||
if (key) store.put({ ...row, ownerLogin: rowOwner, storageKey: key });
|
||||
cursor.continue();
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
@@ -36,31 +87,55 @@ async function withStore(mode, callback) {
|
||||
|
||||
export async function putStoredMessage(record) {
|
||||
if (!record || !record.messageKey) return;
|
||||
const ownerLogin = normalizeOwnerLogin(record.ownerLogin);
|
||||
const key = storageKey(ownerLogin, record.messageKey);
|
||||
if (!key) return;
|
||||
await withStore('readwrite', (store) => {
|
||||
store.put(record);
|
||||
store.put({ ...record, ownerLogin, storageKey: key });
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteStoredMessage(messageKey) {
|
||||
if (!messageKey) return;
|
||||
export async function deleteStoredMessage(messageKey, ownerLogin = '') {
|
||||
const key = storageKey(ownerLogin, messageKey);
|
||||
if (!key) return;
|
||||
await withStore('readwrite', (store) => {
|
||||
store.delete(messageKey);
|
||||
store.delete(key);
|
||||
});
|
||||
}
|
||||
|
||||
export async function listStoredMessages() {
|
||||
export async function listStoredMessages(ownerLogin = '') {
|
||||
const owner = normalizeOwnerLogin(ownerLogin);
|
||||
if (!owner) return [];
|
||||
return withStore('readonly', (store) => new Promise((resolve, reject) => {
|
||||
const req = store.getAll();
|
||||
const req = store.index('by_owner').getAll(owner);
|
||||
req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
|
||||
req.onerror = () => reject(req.error || new Error('IndexedDB getAll failed'));
|
||||
req.onerror = () => reject(req.error || new Error('IndexedDB getAll by owner failed'));
|
||||
}));
|
||||
}
|
||||
|
||||
export async function clearStoredMessages() {
|
||||
await new Promise((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase(DB_NAME);
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error || new Error('IndexedDB delete failed'));
|
||||
request.onblocked = () => reject(new Error('IndexedDB delete blocked'));
|
||||
});
|
||||
export async function clearStoredMessages(ownerLogin = '') {
|
||||
const owner = normalizeOwnerLogin(ownerLogin);
|
||||
if (!owner) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase(DB_NAME);
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error || new Error('IndexedDB delete failed'));
|
||||
request.onblocked = () => reject(new Error('IndexedDB delete blocked'));
|
||||
});
|
||||
return;
|
||||
}
|
||||
await withStore('readwrite', (store) => new Promise((resolve, reject) => {
|
||||
const index = store.index('by_owner');
|
||||
const req = index.openKeyCursor(IDBKeyRange.only(owner));
|
||||
req.onsuccess = () => {
|
||||
const cursor = req.result;
|
||||
if (!cursor) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
store.delete(cursor.primaryKey);
|
||||
cursor.continue();
|
||||
};
|
||||
req.onerror = () => reject(req.error || new Error('IndexedDB clear by owner failed'));
|
||||
}));
|
||||
}
|
||||
|
||||
+350
-3
@@ -11,6 +11,8 @@ import { emptyPasswordWords } from './services/password-words.js';
|
||||
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||||
const SESSION_STORAGE_KEY = 'shine-ui-current-session-v1';
|
||||
const PROFILES_STORAGE_KEY = 'shine-ui-profiles-v1';
|
||||
const ACTIVE_PROFILE_STORAGE_KEY = 'shine-ui-active-profile-v1';
|
||||
const REACTIONS_STORAGE_KEY = 'shine-ui-message-reactions-v2';
|
||||
const WEB_PUSH_SUBSCRIPTION_KEY = 'shine-ui-webpush-subscription-v1';
|
||||
const ENTRY_SETTINGS_STORAGE_KEY = 'shine-ui-entry-settings-v1';
|
||||
@@ -122,7 +124,121 @@ function normalizeToolsSettings(rawTools) {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function normalizeProfileLogin(value) {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function loadProfileStoreRaw() {
|
||||
try {
|
||||
const raw = localStorage.getItem(PROFILES_STORAGE_KEY);
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item) => item && normalizeProfileLogin(item.login) && String(item.sessionId || '').trim());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function persistProfileStoreRaw(items) {
|
||||
try {
|
||||
localStorage.setItem(PROFILES_STORAGE_KEY, JSON.stringify(Array.isArray(items) ? items : []));
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveProfileLoginRaw() {
|
||||
try {
|
||||
return normalizeProfileLogin(localStorage.getItem(ACTIVE_PROFILE_STORAGE_KEY));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function setActiveProfileLoginRaw(login) {
|
||||
const normalized = normalizeProfileLogin(login);
|
||||
try {
|
||||
if (normalized) localStorage.setItem(ACTIVE_PROFILE_STORAGE_KEY, normalized);
|
||||
else localStorage.removeItem(ACTIVE_PROFILE_STORAGE_KEY);
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function profileEntrySettingsSnapshot(settings = {}) {
|
||||
return {
|
||||
solanaServer: String(settings.solanaServer || ''),
|
||||
shineServer: String(settings.shineServer || ''),
|
||||
shineServerLogin: String(settings.shineServerLogin || ''),
|
||||
shineServerHttp: String(settings.shineServerHttp || ''),
|
||||
arweaveServer: String(settings.arweaveServer || ''),
|
||||
callPreflightTimeoutMs: Number(settings.callPreflightTimeoutMs || DEFAULT_CALL_PREFLIGHT_TIMEOUT_MS),
|
||||
remoteAddBlockSessionId: String(settings.remoteAddBlockSessionId || ''),
|
||||
};
|
||||
}
|
||||
|
||||
function upsertSavedProfileInternal({ login, sessionId, isLocalDemo = false, entrySettings = null } = {}) {
|
||||
const normalized = normalizeProfileLogin(login);
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
if (!normalized || !cleanSessionId) return;
|
||||
const items = loadProfileStoreRaw();
|
||||
const index = items.findIndex((item) => normalizeProfileLogin(item.login) === normalized);
|
||||
const previous = index >= 0 ? items[index] : {};
|
||||
const next = {
|
||||
...previous,
|
||||
login: String(login || '').trim(),
|
||||
sessionId: cleanSessionId,
|
||||
isLocalDemo: Boolean(isLocalDemo),
|
||||
entrySettings: entrySettings ? profileEntrySettingsSnapshot(entrySettings) : (previous.entrySettings || {}),
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
if (index >= 0) items[index] = next;
|
||||
else items.push(next);
|
||||
persistProfileStoreRaw(items);
|
||||
setActiveProfileLoginRaw(normalized);
|
||||
}
|
||||
|
||||
function migrateLegacySessionToProfileStore() {
|
||||
const existing = loadProfileStoreRaw();
|
||||
if (existing.length) return;
|
||||
try {
|
||||
const raw = localStorage.getItem(SESSION_STORAGE_KEY);
|
||||
if (!raw) return;
|
||||
const legacy = JSON.parse(raw);
|
||||
if (!legacy?.login || !legacy?.sessionId) return;
|
||||
let entrySettings = {};
|
||||
try {
|
||||
entrySettings = JSON.parse(localStorage.getItem(ENTRY_SETTINGS_STORAGE_KEY) || '{}') || {};
|
||||
} catch {}
|
||||
upsertSavedProfileInternal({
|
||||
login: legacy.login,
|
||||
sessionId: legacy.sessionId,
|
||||
isLocalDemo: legacy.isLocalDemo,
|
||||
entrySettings,
|
||||
});
|
||||
} catch {
|
||||
// ignore migration errors
|
||||
}
|
||||
}
|
||||
|
||||
function loadStoredSession() {
|
||||
migrateLegacySessionToProfileStore();
|
||||
const profiles = loadProfileStoreRaw();
|
||||
if (profiles.length) {
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || profiles[0];
|
||||
if (active) {
|
||||
setActiveProfileLoginRaw(active.login);
|
||||
return {
|
||||
isAuthorized: false,
|
||||
isLocalDemo: Boolean(active.isLocalDemo),
|
||||
login: String(active.login || '').trim(),
|
||||
sessionId: String(active.sessionId || '').trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
try {
|
||||
const raw = localStorage.getItem(SESSION_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
@@ -169,6 +285,15 @@ function clearStoredSession() {
|
||||
}
|
||||
|
||||
function loadStoredEntrySettings() {
|
||||
migrateLegacySessionToProfileStore();
|
||||
const profiles = loadProfileStoreRaw();
|
||||
if (profiles.length) {
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
const active = profiles.find((item) => normalizeProfileLogin(item.login) === activeLogin) || profiles[0];
|
||||
if (active?.entrySettings && typeof active.entrySettings === 'object') {
|
||||
return active.entrySettings;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const raw = localStorage.getItem(ENTRY_SETTINGS_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
@@ -199,6 +324,19 @@ function persistEntrySettings(settings) {
|
||||
tools: normalizeToolsSettings(settings?.tools),
|
||||
};
|
||||
localStorage.setItem(ENTRY_SETTINGS_STORAGE_KEY, JSON.stringify(payload));
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
if (activeLogin) {
|
||||
const profiles = loadProfileStoreRaw();
|
||||
const index = profiles.findIndex((item) => normalizeProfileLogin(item.login) === activeLogin);
|
||||
if (index >= 0) {
|
||||
profiles[index] = {
|
||||
...profiles[index],
|
||||
entrySettings: profileEntrySettingsSnapshot(payload),
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
persistProfileStoreRaw(profiles);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
@@ -244,6 +382,7 @@ function createInitialState({ withStoredSession = true } = {}) {
|
||||
pendingIncomingReadByBaseKey: {},
|
||||
outgoingTempSeq: 1,
|
||||
notificationsTab: 'replies',
|
||||
notificationUnreadTotal: 0,
|
||||
pageLabelCollapsed: false,
|
||||
session: {
|
||||
isAuthorized: storedLocalDemo,
|
||||
@@ -401,6 +540,7 @@ function persistMessageRecord(chatId, row) {
|
||||
const resolvedTs = resolveChatMessageTimeMs(row);
|
||||
void putStoredMessage({
|
||||
messageKey: row.messageKey,
|
||||
ownerLogin: String(state.session.login || '').trim().toLowerCase(),
|
||||
chatId: normalizedChatId,
|
||||
from: row.from || 'in',
|
||||
text: String(row.text || ''),
|
||||
@@ -421,12 +561,12 @@ function persistMessageRecord(chatId, row) {
|
||||
|
||||
function removeStoredMessageRecord(messageKey) {
|
||||
if (!messageKey) return;
|
||||
void deleteStoredMessage(messageKey).catch(() => {});
|
||||
void deleteStoredMessage(messageKey, state.session.login).catch(() => {});
|
||||
}
|
||||
|
||||
export async function hydrateMessagesFromStore() {
|
||||
try {
|
||||
const rows = await listStoredMessages();
|
||||
const rows = await listStoredMessages(state.session.login);
|
||||
const touchedChats = new Set();
|
||||
rows
|
||||
.sort((a, b) => Number(a?.ts || 0) - Number(b?.ts || 0))
|
||||
@@ -927,6 +1067,7 @@ export function authorizeSession({
|
||||
login,
|
||||
sessionId,
|
||||
});
|
||||
upsertSavedProfileInternal({ login, sessionId, isLocalDemo: localDemo, entrySettings: state.entrySettings });
|
||||
authService.setActiveSessionContext({ login, sessionId });
|
||||
state.startHint = '';
|
||||
if (onSessionAuthorized) {
|
||||
@@ -1019,13 +1160,14 @@ async function tryCloseCurrentSessionOnServer() {
|
||||
}
|
||||
|
||||
export async function terminateCurrentSession({ infoMessage = '', closeServerSession = false, notifySessionReset = true } = {}) {
|
||||
const signedOutLogin = String(state.session.login || '').trim();
|
||||
if (closeServerSession) {
|
||||
await tryCloseCurrentSessionOnServer();
|
||||
}
|
||||
|
||||
clearStoredSession();
|
||||
resetStateForSignedOut();
|
||||
await clearStoredMessages().catch(() => {});
|
||||
await clearStoredMessages(signedOutLogin).catch(() => {});
|
||||
authService.close();
|
||||
authService.clearActiveSessionContext();
|
||||
if (infoMessage) {
|
||||
@@ -1045,6 +1187,211 @@ export async function closeCurrentSessionAndSignOut({ infoMessage = '' } = {}) {
|
||||
await terminateCurrentSession({ infoMessage, closeServerSession: true });
|
||||
}
|
||||
|
||||
|
||||
export function getSavedProfiles() {
|
||||
migrateLegacySessionToProfileStore();
|
||||
const activeLogin = getActiveProfileLoginRaw();
|
||||
return loadProfileStoreRaw().map((item) => ({
|
||||
login: String(item.login || '').trim(),
|
||||
sessionId: String(item.sessionId || '').trim(),
|
||||
isLocalDemo: Boolean(item.isLocalDemo),
|
||||
isActive: normalizeProfileLogin(item.login) === activeLogin,
|
||||
entrySettings: item.entrySettings || {},
|
||||
}));
|
||||
}
|
||||
|
||||
export async function switchToSavedProfile(login) {
|
||||
const targetLogin = normalizeProfileLogin(login);
|
||||
const target = loadProfileStoreRaw().find((item) => normalizeProfileLogin(item.login) === targetLogin);
|
||||
if (!target) throw new Error('Профиль не найден на этом устройстве');
|
||||
if (targetLogin === normalizeProfileLogin(state.session.login)) return target;
|
||||
|
||||
const origin = {
|
||||
login: String(state.session.login || '').trim(),
|
||||
sessionId: String(state.session.sessionId || '').trim(),
|
||||
isLocalDemo: Boolean(state.session.isLocalDemo),
|
||||
server: String(state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim(),
|
||||
};
|
||||
const targetServer = String(target?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
|
||||
|
||||
// В каждый момент времени держим только один WebSocket: сначала полностью
|
||||
// закрываем transport активного профиля, затем создаём новый для target.
|
||||
authService.resetConnection(targetServer, { clearSessionContext: true });
|
||||
try {
|
||||
const resumed = await authService.resumeSession(target.login, target.sessionId);
|
||||
target.login = resumed.login || target.login;
|
||||
target.sessionId = resumed.sessionId || target.sessionId;
|
||||
target.updatedAtMs = Date.now();
|
||||
authService.setActiveSessionContext({ login: target.login, sessionId: target.sessionId });
|
||||
persistProfileStoreRaw(loadProfileStoreRaw().map((item) => (
|
||||
normalizeProfileLogin(item.login) === targetLogin ? target : item
|
||||
)));
|
||||
setActiveProfileLoginRaw(target.login);
|
||||
persistSession({ isAuthorized: true, isLocalDemo: Boolean(target.isLocalDemo), login: target.login, sessionId: target.sessionId });
|
||||
if (target.entrySettings && typeof target.entrySettings === 'object') {
|
||||
persistEntrySettings({ ...state.entrySettings, ...target.entrySettings });
|
||||
}
|
||||
return target;
|
||||
} catch (switchError) {
|
||||
// Если новый профиль не поднялся — создаём новый socket обратно для старого.
|
||||
try {
|
||||
authService.resetConnection(origin.server, { clearSessionContext: true });
|
||||
if (origin.login && origin.sessionId && !origin.isLocalDemo) {
|
||||
const restored = await authService.resumeSession(origin.login, origin.sessionId);
|
||||
authService.setActiveSessionContext({
|
||||
login: restored?.login || origin.login,
|
||||
sessionId: restored?.sessionId || origin.sessionId,
|
||||
});
|
||||
} else if (origin.login) {
|
||||
authService.setActiveSessionContext({ login: origin.login, sessionId: origin.sessionId });
|
||||
}
|
||||
} catch (restoreError) {
|
||||
console.warn('[profiles] failed to restore previous profile connection after switch failure', restoreError);
|
||||
}
|
||||
throw switchError;
|
||||
}
|
||||
}
|
||||
|
||||
async function closeSavedProfileSessionBestEffort(profile) {
|
||||
if (!profile || profile.isLocalDemo) return;
|
||||
const cleanSessionId = String(profile.sessionId || '').trim();
|
||||
if (!cleanSessionId) return;
|
||||
const normalized = normalizeProfileLogin(profile.login);
|
||||
const activeNormalized = normalizeProfileLogin(state.session.login);
|
||||
if (normalized === activeNormalized && state.session.isAuthorized) {
|
||||
try { await authService.closeSession(cleanSessionId); } catch {}
|
||||
return;
|
||||
}
|
||||
|
||||
const origin = {
|
||||
login: String(state.session.login || '').trim(),
|
||||
sessionId: String(state.session.sessionId || '').trim(),
|
||||
isLocalDemo: Boolean(state.session.isLocalDemo),
|
||||
server: String(state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim(),
|
||||
};
|
||||
const targetServer = String(profile?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
|
||||
try {
|
||||
authService.resetConnection(targetServer, { clearSessionContext: true });
|
||||
await authService.resumeSession(profile.login, cleanSessionId);
|
||||
await authService.closeSession(cleanSessionId);
|
||||
} catch {
|
||||
// Закрытие профиля на устройстве не блокируем из-за недоступного сервера.
|
||||
} finally {
|
||||
try {
|
||||
authService.resetConnection(origin.server, { clearSessionContext: true });
|
||||
if (origin.login && origin.sessionId && !origin.isLocalDemo) {
|
||||
const restored = await authService.resumeSession(origin.login, origin.sessionId);
|
||||
authService.setActiveSessionContext({
|
||||
login: restored?.login || origin.login,
|
||||
sessionId: restored?.sessionId || origin.sessionId,
|
||||
});
|
||||
} else if (origin.login) {
|
||||
authService.setActiveSessionContext({ login: origin.login, sessionId: origin.sessionId });
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[profiles] failed to restore active profile after closing another profile', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function closeSavedProfile(login) {
|
||||
const normalized = normalizeProfileLogin(login);
|
||||
const items = loadProfileStoreRaw();
|
||||
const index = items.findIndex((item) => normalizeProfileLogin(item.login) === normalized);
|
||||
if (index < 0) return { closed: false, nextProfile: null };
|
||||
const target = items[index];
|
||||
await closeSavedProfileSessionBestEffort(target);
|
||||
await clearStoredMessages(target.login).catch(() => {});
|
||||
|
||||
const nextItems = items.filter((_, itemIndex) => itemIndex !== index);
|
||||
persistProfileStoreRaw(nextItems);
|
||||
const wasActive = normalized === getActiveProfileLoginRaw();
|
||||
if (!wasActive) return { closed: true, nextProfile: null };
|
||||
|
||||
const next = nextItems[index] || nextItems[index - 1] || nextItems[0] || null;
|
||||
if (!next) {
|
||||
setActiveProfileLoginRaw('');
|
||||
clearStoredSession();
|
||||
return { closed: true, nextProfile: null };
|
||||
}
|
||||
setActiveProfileLoginRaw(next.login);
|
||||
persistSession({ isAuthorized: true, isLocalDemo: Boolean(next.isLocalDemo), login: next.login, sessionId: next.sessionId });
|
||||
if (next.entrySettings && typeof next.entrySettings === 'object') {
|
||||
persistEntrySettings({ ...state.entrySettings, ...next.entrySettings });
|
||||
}
|
||||
return { closed: true, nextProfile: next };
|
||||
}
|
||||
|
||||
export async function closeAllSavedProfiles() {
|
||||
const items = loadProfileStoreRaw();
|
||||
for (const item of items) {
|
||||
await clearStoredMessages(item.login).catch(() => {});
|
||||
if (item.isLocalDemo || !String(item.sessionId || '').trim()) continue;
|
||||
const targetServer = String(item?.entrySettings?.shineServer || state.entrySettings.shineServer || DEFAULT_SHINE_SERVER).trim();
|
||||
try {
|
||||
authService.resetConnection(targetServer, { clearSessionContext: true });
|
||||
await authService.resumeSession(item.login, item.sessionId);
|
||||
await authService.closeSession(item.sessionId);
|
||||
} catch {
|
||||
// Все локальные профили всё равно закрываем, даже если один сервер недоступен.
|
||||
}
|
||||
}
|
||||
persistProfileStoreRaw([]);
|
||||
setActiveProfileLoginRaw('');
|
||||
clearStoredSession();
|
||||
authService.close();
|
||||
authService.clearActiveSessionContext();
|
||||
}
|
||||
|
||||
export function isAddingProfileLogin() {
|
||||
return state.session.isAuthorized && String(state.authReturnHash || '').trim() === '/profiles';
|
||||
}
|
||||
|
||||
export async function prepareAddProfileLogin() {
|
||||
state.loginDraft.login = '';
|
||||
state.loginDraft.password = '';
|
||||
clearAuthMessages();
|
||||
// While an existing profile stays authorized, PRE_AUTH login pages are normally
|
||||
// blocked by app.js. This return target also acts as an explicit add-profile mode.
|
||||
state.authReturnHash = '/profiles';
|
||||
|
||||
// Не пытаемся авторизовать второй login через уже authenticated socket.
|
||||
// Старую серверную сессию НЕ закрываем: закрываем только локальный transport.
|
||||
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||
}
|
||||
|
||||
export async function cancelAddProfileLogin() {
|
||||
const wasAddingProfile = isAddingProfileLogin();
|
||||
const shouldRestoreActiveConnection = wasAddingProfile
|
||||
&& state.session.isAuthorized
|
||||
&& Boolean(String(state.session.login || '').trim())
|
||||
&& Boolean(String(state.session.sessionId || '').trim());
|
||||
|
||||
state.authReturnHash = '';
|
||||
state.loginDraft.login = '';
|
||||
state.loginDraft.password = '';
|
||||
resetRegistrationFlow();
|
||||
clearAuthMessages();
|
||||
|
||||
if (shouldRestoreActiveConnection) {
|
||||
try {
|
||||
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||
await authService.resumeSession(state.session.login, state.session.sessionId);
|
||||
authService.setActiveSessionContext({ login: state.session.login, sessionId: state.session.sessionId });
|
||||
} catch (error) {
|
||||
console.warn('[profiles] failed to restore active profile connection after cancelling add-profile flow', error);
|
||||
}
|
||||
}
|
||||
return wasAddingProfile;
|
||||
}
|
||||
|
||||
export function consumeAuthReturnPage(fallback = 'profile-view') {
|
||||
const nextHash = String(state.authReturnHash || '').trim();
|
||||
state.authReturnHash = '';
|
||||
if (nextHash.startsWith('/')) return nextHash.slice(1) || fallback;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function refreshRegistrationBalance() {
|
||||
const next = (0.005 + Math.random() * 0.03).toFixed(4);
|
||||
state.registrationPayment.balanceSOL = next;
|
||||
|
||||
@@ -11676,3 +11676,49 @@ body.chat-topbar-overlay .page-header.app-topbar-shell .header-center {
|
||||
filter: blur(6px);
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
|
||||
/* Saved profiles */
|
||||
.profiles-screen { gap: 14px; }
|
||||
.profiles-summary { padding: 0 2px; }
|
||||
.profiles-list { gap: 10px; }
|
||||
.profiles-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 44px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 8px 8px 14px;
|
||||
}
|
||||
.profiles-row.is-active { border-color: rgba(255, 255, 255, 0.34); }
|
||||
.profiles-select {
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 0;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
}
|
||||
.profiles-select:not(:disabled) { cursor: pointer; }
|
||||
.profiles-login {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 650;
|
||||
}
|
||||
.profiles-close {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid rgba(255, 255, 255, 0.24);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: inherit;
|
||||
font-size: 27px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.profiles-actions { margin-top: 4px; }
|
||||
.profiles-close-all { margin-top: 4px; }
|
||||
|
||||
@@ -62,3 +62,14 @@ a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.notification-card--new { background: rgba(108, 92, 231, .10); border-color: rgba(143, 126, 255, .42); }
|
||||
.notification-card--new::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: currentColor; box-shadow: 0 0 10px currentColor; position: absolute; right: 12px; top: 12px; opacity: .9; }
|
||||
.notification-card { position: relative; }
|
||||
.notification-new-divider { text-align: center; font-size: 11px; letter-spacing: .12em; opacity: .72; padding: 6px 0; }
|
||||
|
||||
.channel-view-topbar { position: relative; }
|
||||
.channel-header-more-menu { position: absolute; right: 10px; top: calc(100% - 4px); z-index: 80; min-width: 190px; padding: 7px; border: 1px solid rgba(255,255,255,.16); border-radius: 14px; background: rgba(18,18,28,.96); backdrop-filter: blur(18px); box-shadow: 0 14px 34px rgba(0,0,0,.35); }
|
||||
.channel-header-more-menu button { width: 100%; border: 0; background: transparent; color: inherit; text-align: left; padding: 10px 12px; border-radius: 10px; }
|
||||
.channel-header-more-menu button:hover { background: rgba(255,255,255,.08); }
|
||||
.channel-header-more-menu button.is-danger { color: #ff8c9b; }
|
||||
|
||||
@@ -242,10 +242,9 @@
|
||||
.fg-node.is-pressed .node-dot { transform: none; }
|
||||
}
|
||||
|
||||
/* «Сияние» — мягкое живое свечение НА УЗЛЕ (аватарке), а не на линии связи.
|
||||
Многослойная анимированная box-shadow + размытый радиальный ореол (через внешний SVG-фильтр).
|
||||
Пульсация очень медленная и плавная (3.6с): радиус и прозрачность «дышат» 0.5 ↔ 1.0 —
|
||||
как мягкое свечение живого организма в темноте, а не «жирный маркер». */
|
||||
/* «Сияние» — постоянное живое свечение НА УЗЛЕ (аватарке), а не на линии связи.
|
||||
Пульсация остаётся мягкой, но нижняя точка теперь не проваливается почти в ноль:
|
||||
визуально сияющий пользователь всегда остаётся явно сияющим. */
|
||||
.fg-node.is-shine .node-dot {
|
||||
border-color: rgba(150, 240, 255, 0.62);
|
||||
animation: fg-shine-glow 3.6s ease-in-out infinite;
|
||||
@@ -268,9 +267,9 @@
|
||||
@keyframes fg-shine-glow {
|
||||
0%, 100% {
|
||||
box-shadow:
|
||||
0 0 5px rgba(125, 232, 255, 0.30),
|
||||
0 0 11px rgba(112, 226, 255, 0.18),
|
||||
0 0 20px rgba(100, 220, 255, 0.10);
|
||||
0 0 7px rgba(138, 239, 255, 0.48),
|
||||
0 0 15px rgba(118, 232, 255, 0.32),
|
||||
0 0 27px rgba(100, 220, 255, 0.19);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
@@ -282,7 +281,7 @@
|
||||
|
||||
/* ореол дышит размером и прозрачностью синхронно с тенью (мягко, без рывков) */
|
||||
@keyframes fg-shine-halo {
|
||||
0%, 100% { transform: scale(0.9); opacity: 0.5; }
|
||||
0%, 100% { transform: scale(0.98); opacity: 0.72; }
|
||||
50% { transform: scale(1.12); opacity: 1; }
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user