Поправил пуши для личных сообщений

This commit is contained in:
AidarKC
2026-10-21 11:47:27 +03:00
parent aa5addb5d9
commit 7a6ab3b35a
22 changed files with 723 additions and 678 deletions
@@ -1,5 +1,6 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.MsgSubType;
import shine.db.entities.SignedMessageEntry;
@@ -17,6 +18,7 @@ import java.util.Map;
public final class DmDialogStateDAO {
private static volatile DmDialogStateDAO instance;
private final DbController db = DbController.getInstance();
private DmDialogStateDAO() {}
@@ -129,6 +131,26 @@ public final class DmDialogStateDAO {
return out;
}
/** Снимок счётчика после записи DM. Используется только сервером для push/WS, не отдаёт текст сообщения. */
public NotificationState getNotificationState(String ownerLogin, String peerLogin) throws SQLException {
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT unread_count, updated_at_ms
FROM dm_dialog_state
WHERE LOWER(owner_login) = LOWER(?) AND LOWER(peer_login) = LOWER(?)
LIMIT 1
""")) {
ps.setString(1, normalize(ownerLogin));
ps.setString(2, normalize(peerLogin));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
return new NotificationState(Math.max(0, rs.getInt("unread_count")), rs.getLong("updated_at_ms"));
}
}
}
public record NotificationState(int unreadCount, long versionMs) {}
public void refreshFromEntry(Connection c, SignedMessageEntry entry) throws SQLException {
if (entry == null) return;
refreshConversationPair(c, entry.getFromLogin(), entry.getToLogin());
@@ -274,7 +296,7 @@ public final class DmDialogStateDAO {
last_message_time_ms = EXCLUDED.last_message_time_ms,
unread_count = EXCLUDED.unread_count,
last_read_receipt_time_ms = EXCLUDED.last_read_receipt_time_ms,
updated_at_ms = EXCLUDED.updated_at_ms
updated_at_ms = GREATEST(dm_dialog_state.updated_at_ms + 1, EXCLUDED.updated_at_ms)
""")) {
ps.setString(1, summary.ownerLogin());
ps.setString(2, summary.peerLogin());
@@ -9,6 +9,7 @@ import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.push.WebPushSender;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.dao.DmDialogStateDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.SignedMessageEntry;
@@ -49,6 +50,9 @@ public final class SignedMessagesRealtime {
DeliveryCounters counters = new DeliveryCounters();
long now = System.currentTimeMillis();
for (String targetLogin : targetLoginsForMessage(message)) {
boolean incomingNotification = shouldPushNewIncomingMessage(targetLogin, message, block);
DmDialogStateDAO.NotificationState notificationState = incomingNotification
? loadNotificationState(targetLogin, message.getFromLogin()) : null;
List<ActiveSessionEntry> sessions = ActiveSessionsDAO.getInstance().getByLogin(targetLogin);
List<String> sessionIdsToTrack = new ArrayList<>();
for (ActiveSessionEntry s : sessions) {
@@ -64,13 +68,13 @@ public final class SignedMessagesRealtime {
if (excludeSessionId != null && excludeSessionId.equals(sessionId)) {
continue;
}
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false);
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false, notificationState);
if (deliveredOnline) {
counters.wsDelivered++;
continue;
}
if (shouldPushNewIncomingMessage(targetLogin, message, block)) {
boolean pushed = pushNewMessageNotification(s, message);
if (incomingNotification) {
boolean pushed = pushNewMessageNotification(s, message, notificationState);
if (pushed) counters.pushDelivered++;
}
}
@@ -100,7 +104,7 @@ public final class SignedMessagesRealtime {
List<SignedMessageEntry> pending = SignedMessagesDAO.getInstance()
.listPendingForSession(login, sessionId);
for (SignedMessageEntry e : pending) {
sendEventToSessionIfOnline(sessionId, login, e, true);
sendEventToSessionIfOnline(sessionId, login, e, true, null);
}
} catch (Exception e) {
log.warn("Failed to dispatch pending messages for sessionId={}", sessionId, e);
@@ -111,7 +115,8 @@ public final class SignedMessagesRealtime {
String sessionId,
String actualTargetLogin,
SignedMessageEntry message,
boolean backlog
boolean backlog,
DmDialogStateDAO.NotificationState notificationState
) {
ConnectionContext targetCtx = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
if (targetCtx == null) return false;
@@ -128,6 +133,10 @@ public final class SignedMessagesRealtime {
payload.put("nonce", message.getNonce());
payload.put("blobB64", blobB64);
payload.put("backlog", backlog);
if (message.getMessageType() == SignedMessageBlock.TYPE_INCOMING_TEXT && notificationState != null) {
payload.put("unreadCount", notificationState.unreadCount());
payload.put("notificationVersionMs", notificationState.versionMs());
}
if (message.getReceiptRefBaseKey() != null) {
payload.put("receiptRefBaseKey", message.getReceiptRefBaseKey());
}
@@ -141,21 +150,41 @@ public final class SignedMessagesRealtime {
return block.revisionTimeMs == 0;
}
private static boolean pushNewMessageNotification(ActiveSessionEntry session, SignedMessageEntry message) {
private static DmDialogStateDAO.NotificationState loadNotificationState(String ownerLogin, String peerLogin) {
try {
return DmDialogStateDAO.getInstance().getNotificationState(ownerLogin, peerLogin);
} catch (Exception e) {
log.warn("Не удалось получить счётчик непрочитанных DM для {} / {}", ownerLogin, peerLogin, e);
return null;
}
}
private static boolean pushNewMessageNotification(
ActiveSessionEntry session, SignedMessageEntry message, DmDialogStateDAO.NotificationState notificationState
) {
try {
if (session == null) return false;
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
return false;
}
String text = "Новое сообщение от " + message.getFromLogin();
String payload = "{\"kind\":\"new_message\",\"fromLogin\":\"" + jsonEscape(message.getFromLogin()) + "\",\"text\":\"" + jsonEscape(text) + "\"}";
ObjectNode payload = MAPPER.createObjectNode();
payload.put("kind", "new_message");
payload.put("toLogin", session.getLogin());
payload.put("fromLogin", message.getFromLogin());
payload.put("messageKey", message.getMessageKey());
payload.put("text", "Новое сообщение от " + message.getFromLogin());
if (notificationState != null) {
payload.put("unreadCount", notificationState.unreadCount());
payload.put("notificationVersionMs", notificationState.versionMs());
}
return WebPushSender.sendBase64Payload(
session.getPushEndpoint(),
session.getPushP256dhKey(),
session.getPushAuthKey(),
payload
payload.toString()
);
} catch (Exception e) {
log.warn("Не удалось подготовить Web Push для DM {}", message.getMessageKey(), e);
return false;
}
}
@@ -182,21 +211,6 @@ public final class SignedMessagesRealtime {
return s == null ? "" : s.trim().toLowerCase();
}
private static String jsonEscape(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') out.append("\\\\");
else if (c == '"') out.append("\\\"");
else if (c == '\n') out.append("\\n");
else if (c == '\r') out.append("\\r");
else if (c == '\t') out.append("\\t");
else out.append(c);
}
return out.toString();
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.19.36
server.version=1.15.0
client.version=1.19.37
server.version=1.15.1
@@ -324,10 +324,16 @@ signed-блока проверяется всегда. Официальный UI
"timeMs": 1774700000123,
"nonce": 123456789,
"blobB64": "BASE64_SIGNED_BLOCK",
"backlog": false
"backlog": false,
"unreadCount": 3,
"notificationVersionMs": 1774700000456
}
```
`unreadCount` и `notificationVersionMs` добавляются только для нового входящего type=1 при обычной realtime-доставке. Это серверный снимок `dm_dialog_state`; для backlog, read-receipts и других типов эти поля могут отсутствовать. `notificationVersionMs` монотонно увеличивается при обновлении состояния конкретной переписки; формат подписанного блока не меняется.
При отсутствии активного WebSocket сервер отправляет Web Push с полями `kind=new_message`, `toLogin`, `fromLogin`, `messageKey`, `unreadCount`, `notificationVersionMs`. Push не содержит расшифрованного текста. Service Worker показывает по одной карточке на пару (получатель, отправитель), обновляя счётчик с запросом нового звукового оповещения для каждого нового сообщения.
Если это новая ревизия того же письма, `messageKey` остаётся тем же, а `revisionTimeMs` меняется внутри бинарного блока.
Для типов `5/6/7/8` событие тоже приходит в таком же конверте, но логика применения определяется `messageType` и бинарным `blobB64`.
@@ -288,3 +288,14 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
`reencryptedAtMs=0` означает обычную исходную копию. При входе rotation в `MESSAGE_MIGRATION` её `updatedAtMs` фиксирует cutoff текущей миграции. Старые локальные копии, сохранённые до cutoff, получают `reencryptedAtMs=cutoff`. Следующая ротация использует уже свой новый cutoff.
Правило подписи `type=1` зависит от `reencryptedAtMs`: исходная входящая копия (`0`) подписана отправителем; локально перешифрованная входящая копия (`>0`) подписывается новым client key получателя. `type=2` остаётся подписанным владельцем исходящей локальной копии (`fromLogin`). Перешифрованная копия предназначена для локального восстановления содержимого новым client key и не считается сохранением первоначальной подписи отправителя.
## Push личных сообщений (19.10.2026)
- Уведомления не содержат расшифрованный DM-текст и приватные ключи. Шифрование `SHiNE_DM` не меняется.
- Для нового входящего type=1 сервер включает в Web Push `kind=new_message`, `toLogin`, `fromLogin`, `messageKey`, `unreadCount` и `notificationVersionMs` (состояние диалога после записи). Транспортный Web Push шифруется отдельно браузерным механизмом.
- Если сессия находится в активном WebSocket, событие `SignedMessageArrived` для type=1 также несёт `unreadCount` и `notificationVersionMs`; при backlog серверный счётчик не добавляется, а повторная доставка не генерирует новое уведомление.
- `unreadCount` читается из `dm_dialog_state` и не требует отдельного публичного метода или изменения схемы таблиц.
- Клиент и Service Worker используют один tag `shine-dm:<toLogin>:<fromLogin>`. Разные отправители не перезаписывают друг друга; следующие сообщения обновляют карточку. `renotify=true` запрашивает оповещение на каждое сообщение (фактический звук контролируется браузером и ОС).
- Открытие диалога и локальное `markChatRead` закрывают уведомление этого диалога на текущем устройстве. Service Worker хранит локальную границу прочтения и историю недавно показанных `messageKey`, чтобы снизить вероятность старого или дублированного уведомления.
- Чаты «без звука» по-прежнему не генерируют системные уведомления, но сообщения и серверный unread-счётчик продолжают поступать.
- События удалений, редактирований, read-receipts и повторные backlog-события не инициируют новые уведомления.
@@ -405,3 +405,14 @@ UI-примечание (байтовый формат не меняет): ра
- `type=2`: подпись проверяется по `clientKey` `fromLogin`; при миграции ciphertext локальной исходящей копии также шифруется на новый client key владельца.
При перешифровке сохраняются `fromLogin`, `toLogin`, `timeMs`, `nonce`, `messageType` и `revisionTimeMs`; меняются encrypted body, подпись и `reencryptedAtMs`.
## Push личных сообщений (19.10.2026)
- Уведомления не содержат расшифрованный DM-текст и приватные ключи. Шифрование `SHiNE_DM` не меняется.
- Для нового входящего type=1 сервер включает в Web Push `kind=new_message`, `toLogin`, `fromLogin`, `messageKey`, `unreadCount` и `notificationVersionMs` (состояние диалога после записи). Транспортный Web Push шифруется отдельно браузерным механизмом.
- Если сессия находится в активном WebSocket, событие `SignedMessageArrived` для type=1 также несёт `unreadCount` и `notificationVersionMs`; при backlog серверный счётчик не добавляется, а повторная доставка не генерирует новое уведомление.
- `unreadCount` читается из `dm_dialog_state` и не требует отдельного публичного метода или изменения схемы таблиц.
- Клиент и Service Worker используют один tag `shine-dm:<toLogin>:<fromLogin>`. Разные отправители не перезаписывают друг друга; следующие сообщения обновляют карточку. `renotify=true` запрашивает оповещение на каждое сообщение (фактический звук контролируется браузером и ОС).
- Открытие диалога и локальное `markChatRead` закрывают уведомление этого диалога на текущем устройстве. Service Worker хранит локальную границу прочтения и историю недавно показанных `messageKey`, чтобы снизить вероятность старого или дублированного уведомления.
- Чаты «без звука» по-прежнему не генерируют системные уведомления, но сообщения и серверный unread-счётчик продолжают поступать.
- События удалений, редактирований, read-receipts и повторные backlog-события не инициируют новые уведомления.
+133 -4
View File
@@ -1,11 +1,14 @@
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
self.__shineStoppedCalls = self.__shineStoppedCalls || new Map();
self.__shineDmPushQueues = self.__shineDmPushQueues || new Map();
self.addEventListener('message', (event) => {
const data = event?.data || {};
if (data.type === 'SKIP_WAITING') {
self.skipWaiting();
} else if (data.type === 'SHINE_DM_READ') {
event.waitUntil(clearDirectMessageNotification(data.toLogin, data.fromLogin, data.latestSeenVersionMs));
}
});
@@ -99,6 +102,125 @@ async function isMutedDirectMessage(toLogin, fromLogin) {
}
}
// Идентификатор совпадает с UI, включая профиль получателя.
function dmNotificationTag(toLogin, fromLogin) {
return `shine-dm:${encodeURIComponent(String(toLogin || '').trim().toLowerCase())}:${encodeURIComponent(String(fromLogin || '').trim().toLowerCase())}`;
}
function dmUnreadLabel(count) {
const n = Math.max(1, Math.trunc(Number(count) || 1));
const lastTwo = n % 100;
const last = n % 10;
if (!(lastTwo >= 11 && lastTwo <= 14) && last === 1) return `${n} непрочитанное сообщение`;
if (!(lastTwo >= 11 && lastTwo <= 14) && last >= 2 && last <= 4) return `${n} непрочитанных сообщения`;
return `${n} непрочитанных сообщений`;
}
function queueDmAction(tag, task) {
const preceding = self.__shineDmPushQueues.get(tag) || Promise.resolve();
const next = preceding.catch(() => {}).then(task);
self.__shineDmPushQueues.set(tag, next);
void next.finally(() => {
if (self.__shineDmPushQueues.get(tag) === next) self.__shineDmPushQueues.delete(tag);
}).catch(() => {});
return next;
}
const DM_PUSH_CACHE = 'shine-dm-notification-state-v1';
async function getDmPushState(tag) {
try {
const cache = await caches.open(DM_PUSH_CACHE);
const key = new URL(`./__shine/dm-push-state?tag=${encodeURIComponent(tag)}`, self.registration.scope).toString();
const response = await cache.match(key);
const state = response ? await response.json() : {};
return { cache, key, state };
} catch {
// При запрете Cache Storage не теряем само уведомление.
return { cache: null, key: null, state: {} };
}
}
async function saveDmPushState(cache, key, state) {
if (!cache || !key) return;
try {
await cache.put(key, new Response(JSON.stringify(state), {
headers: { 'Content-Type': 'application/json' },
}));
} catch {
// Best effort: уведомление уже показано, отказ кэша не должен ломать push.
}
}
async function clearDirectMessageNotification(toLogin, fromLogin, latestSeenVersionMs = 0) {
if (!toLogin || !fromLogin) return;
const tag = dmNotificationTag(toLogin, fromLogin);
await queueDmAction(tag, async () => {
const { cache, key, state } = await getDmPushState(tag);
state.lastReadVersionMs = Math.max(
Number(state.lastReadVersionMs || 0), Number(state.versionMs || 0), Number(latestSeenVersionMs || 0),
);
state.unreadCount = 0;
await saveDmPushState(cache, key, state);
const shown = await self.registration.getNotifications({ tag });
shown.forEach((notification) => notification.close());
});
}
async function showDirectMessageNotification(json) {
const toLogin = String(json.toLogin || '').trim();
const fromLogin = String(json.fromLogin || '').trim();
if (!fromLogin) return;
if (await isMutedDirectMessage(toLogin, fromLogin)) return;
const tag = dmNotificationTag(toLogin, fromLogin);
await queueDmAction(tag, async () => {
const { cache, key, state } = await getDmPushState(tag);
const messageKey = String(json.messageKey || '').trim();
const version = Math.max(0, Number(json.notificationVersionMs || 0));
// Уведомление могло быть создано клиентом по живому WS, а не этим Service Worker.
const shown = await self.registration.getNotifications({ tag });
const visible = shown.reduce((latest, row) => Number(row.data?.notificationVersionMs || 0) >= Number(latest?.data?.notificationVersionMs || 0)
? row : latest, null);
const visibleVersion = Number(visible?.data?.notificationVersionMs || 0);
if (visibleVersion > Number(state.versionMs || 0)) {
state.versionMs = visibleVersion;
state.unreadCount = Number(visible?.data?.unreadCount || state.unreadCount || 0);
}
const previouslySeen = Array.isArray(state.seenMessageKeys) ? state.seenMessageKeys : [];
if (messageKey && previouslySeen.includes(messageKey)) return;
// Запоздавший push после прочтения не должен заново открывать уже закрытое уведомление.
if (version && Number(state.lastReadVersionMs || 0) >= version) return;
const remoteCount = Number(json.unreadCount);
const validCount = Number.isInteger(remoteCount) && remoteCount >= 0;
const latestVersion = Number(state.versionMs || 0);
let count = validCount ? remoteCount : Math.max(1, Number(state.unreadCount || 0) + 1);
if (version && latestVersion > version) count = Number(state.unreadCount || count);
if (count <= 0) return;
// Ранние пуши иногда доставляются позже новых: число на карточке не должно уменьшаться.
if (!version && Number(state.unreadCount || 0) > count) count = Number(state.unreadCount);
await self.registration.showNotification(`Сообщение от ${fromLogin}`, {
body: dmUnreadLabel(count),
tag,
renotify: true, // каждое новое сообщение запрашивает повторный системный звук
silent: false,
data: {
kind: 'new_message',
fromLogin,
toLogin,
messageKey,
unreadCount: count,
notificationVersionMs: version,
},
});
state.unreadCount = count;
state.versionMs = Math.max(latestVersion, version);
state.seenMessageKeys = messageKey
? [...previouslySeen, messageKey].slice(-64)
: previouslySeen;
await saveDmPushState(cache, key, state);
});
}
self.addEventListener('push', (event) => {
let body = '';
let rawText = '';
@@ -123,6 +245,14 @@ self.addEventListener('push', (event) => {
}
const json = decodePushJson(rawText);
// DM обрабатывается отдельно от звонков: персональный tag, серверный unreadCount и защита от повтора.
if (kind === 'new_message') {
event.waitUntil(Promise.all([
showDirectMessageNotification(json),
broadcastToClients({ ...json, receivedAt: Date.now() }),
]));
return;
}
const callId = String(json.callId || '').trim();
const fromSessionId = String(json.fromSessionId || '').trim();
const targetSessionId = String(json.targetSessionId || '').trim();
@@ -143,8 +273,7 @@ self.addEventListener('push', (event) => {
const isIncomingCallAlreadyStopped = kind === 'incoming_call' && callId && isCallStopped(callId, sentAtMs || nowMs);
const shouldNotify = (
kind === 'new_message'
|| kind === 'test_push'
kind === 'test_push'
|| (kind === 'incoming_call' && !isExpiredIncomingCall && !isIncomingCallAlreadyStopped)
|| (!kind && body)
);
@@ -155,7 +284,7 @@ self.addEventListener('push', (event) => {
: 'SHiNE: входящее сообщение');
const notifyPromise = shouldNotify
? (kind === 'new_message' ? isMutedDirectMessage(toLogin, fromLogin) : Promise.resolve(false)).then((muted) => (muted ? undefined : self.registration.showNotification(notificationTitle, {
? self.registration.showNotification(notificationTitle, {
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
renotify: true,
@@ -177,7 +306,7 @@ self.addEventListener('push', (event) => {
{ action: 'decline', title: 'Сбросить' },
]
: [],
})))
})
: Promise.resolve();
const closeOnStopPromise = kind === 'stop_call' && callId
+20 -8
View File
@@ -15,6 +15,7 @@ import {
import { attachScrollToBottomButton } from './components/scroll-to-bottom-button.js';
import { initPwaInstallPromptHandling } from './services/pwa-install-service.js';
import { initPwaPush } from './services/pwa-push-service.js';
import { dmNotificationTag, dmUnreadLabel } from './services/dm-push-notifications.js';
import { initCallUiOverlay } from './services/call-ui-service.js';
import { showToast } from './services/channels-ux.js';
import { toUserMessage } from './services/ui-error-texts.js';
@@ -49,6 +50,7 @@ import {
deleteConversationMessagesBefore,
deleteSignedMessageByBaseKey,
markIncomingReadByBaseKey,
getChatMessages,
markOutgoingDeliveryState,
markOutgoingReadByBaseKey,
normalizeDmChatId,
@@ -718,19 +720,24 @@ async function tryLockPortraitOrientation() {
}
}
async function notifyHiddenIncomingMessage(fromLogin, text) {
const body = String(text || '').trim() || `Вам пришло сообщение от ${fromLogin}`;
async function notifyHiddenIncomingMessage(fromLogin, toLogin, unreadCount, messageKey, notificationVersionMs) {
const title = `Сообщение от ${fromLogin}`;
const body = dmUnreadLabel(unreadCount);
try {
const registration = await navigator.serviceWorker?.getRegistration?.();
if (registration?.showNotification) {
await registration.showNotification(title, {
body,
tag: `shine-hidden-dm-${String(fromLogin || '').trim().toLowerCase() || 'unknown'}`,
renotify: true,
tag: dmNotificationTag(toLogin, fromLogin),
renotify: true, // каждое новое DM — отдельный сигнал, но одна карточка на собеседника
silent: false,
data: {
kind: 'new_message',
fromLogin,
toLogin,
messageKey,
unreadCount,
notificationVersionMs,
},
});
} else {
@@ -1849,14 +1856,19 @@ async function init() {
// Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления.
if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) {
const parsedText = parseDmTechBlocks(text);
const displayText = String(parsedText.displayText || '');
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
const toLogin = String(state.session.login || payload.toLogin || '').trim();
const serverUnread = Number(payload.unreadCount);
const localUnread = getChatMessages(chatId)
.filter((row) => row?.from === 'in' && row?.unread && Number(row?.messageType) === 1).length;
const unreadCount = Number.isFinite(serverUnread) && serverUnread > 0
? serverUnread : Math.max(1, localUnread);
if (document.visibilityState === 'visible') {
void playDmSignal({ extended: false });
} else if (Notification.permission === 'granted' && !suppressHiddenNotification) {
try {
void notifyHiddenIncomingMessage(fromLogin, displayText || '');
} catch {}
void notifyHiddenIncomingMessage(
fromLogin, toLogin, unreadCount, messageKey, Number(payload.notificationVersionMs || 0),
);
} else if (!suppressHiddenNotification) {
void playDmSignal({ extended: true });
}
+6 -6
View File
@@ -10,11 +10,10 @@ function normLogin(value) {
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
function relationTypeFromRelation(relation) {
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
const role = relation?.role;
if (FAMILY_ROLES.includes(role)) return 'family';
if (role === 'friend') return 'friend';
// Тип отношения выбирает владелец рассматриваемого графа.
const ownType = String(relation?.relationType || '').trim().toLowerCase();
if (ownType === 'close_friend' || ownType === 'friend') return ownType;
if (relation?.role === 'friend') return 'friend';
return 'contact';
}
@@ -24,7 +23,7 @@ function relationTypeFromRelation(relation) {
// - взаимные дружеские связи ближе односторонних.
function deriveStrength(relation) {
if (relation.isRelative) return 0.9;
if (relation?.mark?.relationType === 'close_friend') return 0.9;
if (relation?.relationType === 'close_friend') return 0.9;
if (relation.role === 'contact') return 0.4;
if (relation.forward && relation.backward) return 0.8;
return 0.55;
@@ -69,6 +68,7 @@ export function engineModelFromGraphModel(graphModel) {
shining: Boolean(r?.mark?.shine),
official: Boolean(r?.mark?.official),
tier: 1,
mutual: Boolean(r?.forward && r?.backward),
};
})
.filter(Boolean);
@@ -716,6 +716,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
node.dotOnly = spec.dotOnly;
node.strength = strength;
node.relationType = src.relationType;
node.mutual = src.mutual !== false;
node.shining = Boolean(src.shining);
node.official = Boolean(src.official);
node.isHistoryCenter = Boolean(src.isHistoryCenter);
@@ -940,6 +941,28 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
n.dotRadius = full ? 12 : 5; // радиус для расчёта концов линий связей
}
// Четыре части одной дуги: толстый штрих → короткий штрих → точечки у адресата.
// Используется и обычным force-графом, и историей / «друзьями друзей».
function directedFriendEdgePaths(x1, y1, cx, cy, x2, y2, color, opacity, width = 1.2) {
const at = (t) => ({
x: (1 - t) ** 2 * x1 + 2 * t * (1 - t) * cx + t ** 2 * x2,
y: (1 - t) ** 2 * y1 + 2 * t * (1 - t) * cy + t ** 2 * y2,
});
const sections = [[20, 3], [12, 4], [6, 4], [1, 5]];
return sections.map(([dash, gap], index) => {
const start = index / sections.length;
const finish = (index + 1) / sections.length;
const a = at(start);
const b = at(finish);
const control = {
x: a.x + (finish - start) * ((1 - start) * (cx - x1) + start * (x2 - cx)),
y: a.y + (finish - start) * ((1 - start) * (cy - y1) + start * (y2 - cy)),
};
const d = `M${a.x.toFixed(1)} ${a.y.toFixed(1)} Q${control.x.toFixed(1)} ${control.y.toFixed(1)} ${b.x.toFixed(1)} ${b.y.toFixed(1)}`;
return `<path d="${d}" fill="none" stroke="${color}" stroke-width="${width}" stroke-linecap="round" stroke-dasharray="${dash} ${gap}" opacity="${opacity.toFixed(3)}" />`;
});
}
function renderHistoryEdges() {
const Z = zoom;
const parts = [];
@@ -990,6 +1013,10 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const opacity = Math.min(childOpacity, parentOpacity);
const shine = Boolean(parent.shining && n.shining) && !n.hidden;
if (ref?.mutual === false) {
parts.push(...directedFriendEdgePaths(x1, y1, cpx, cpy, x2, y2, relationColor(relationType), opacity * 0.82));
continue;
}
if (shine) {
const pnx = -uy;
const pny = ux;
@@ -1112,6 +1139,11 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
dashAttr = ` stroke-dasharray="${L.toFixed(1)}" stroke-dashoffset="${(L * (1 - growP)).toFixed(1)}"`;
}
const pe = n.alwaysVisible ? 1 : (parent.expandP || 0); // X2 виден сразу; старые deep-ветки — по раскрытию
if (n.mutual === false) {
const opacity = nodeOpacity * sp * (n.tier > 1 ? pe : 1) * 0.82;
if (opacity > 0.02) parts.push(...directedFriendEdgePaths(x1, y1, cpx, cpy, x2, y2, relationColor(n.relationType), opacity));
continue;
}
if (n.tier >= 3) {
// 3-й уровень: тонкая нить В ЦВЕТЕ СВЯЗИ (видна при раскрытии). Сияющая — светится (ореол+ядро).
if (pe > 0.02) {
@@ -1,5 +1,6 @@
import { createTopBar } from '../../components/topbar.js';
import { authService, state } from '../../state.js';
import { getConnectionsGraphCached as loadSharedGraph, cachedConnectionsGraph as getCachedSharedGraph, CONNECTIONS_GRAPH_CHANGED, CONNECTIONS_GRAPH_TTL_MS } from '../../services/connections-graph-cache.js';
import { makeProfileRoute } from '../../services/shine-routes.js';
import { makeProfileLinksRoute } from '../../services/shine-routes.js';
import { createForceGraph } from './force-graph.js';
@@ -136,66 +137,29 @@ function getRelativeGenderMap(graph) {
function buildGraphModel(graph, centerLogin) {
const login = normalizeLogin(graph?.login || centerLogin || state.session.login);
const outFriends = toSet(graph?.outFriends);
const inFriends = toSet(graph?.inFriends);
const outCloseFriends = toSet(graph?.outCloseFriends);
const inFriends = toSet(graph?.inFriends);
const inCloseFriends = toSet(graph?.inCloseFriends);
const outParents = toSet(graph?.outParents);
const inParents = toSet(graph?.inParents);
const outChildren = toSet(graph?.outChildren);
const inChildren = toSet(graph?.inChildren);
const outSiblings = toSet(graph?.outSiblings);
const inSiblings = toSet(graph?.inSiblings);
const outSpouses = toSet(graph?.outSpouses);
const inSpouses = toSet(graph?.inSpouses);
// контакты/подписки/знакомые — для слоя «Все контакты» (Фаза 3)
const outContacts = toSet(graph?.outContacts);
const inContacts = toSet(graph?.inContacts);
const outFollows = toSet(graph?.outFollows);
const inFollows = toSet(graph?.inFollows);
const outOfficial = toSet(graph?.outOfficialAccounts);
const inOfficial = toSet(graph?.inOfficialAccounts);
const relativesGender = getRelativeGenderMap(graph);
const allMarks = getMarkByLogin(graph?.allUsers);
// Граф показывает только тех, кого владелец сам выбрал другом.
// Входящие друзья нужны лишь для проверки взаимности, контакты и подписки исключены.
const allLogins = uniqueLogins([
...(graph?.outFriends || []),
...(graph?.inFriends || []),
...(graph?.outCloseFriends || []),
...(graph?.inCloseFriends || []),
...(graph?.outContacts || []),
...(graph?.inContacts || []),
...(graph?.outFollows || []),
...(graph?.inFollows || []),
...(graph?.outOfficialAccounts || []),
...(graph?.inOfficialAccounts || []),
...(graph?.outFriends || []),
]).filter((entry) => normKey(entry) !== normKey(login));
const relations = allLogins.map((targetLogin) => {
const friendOut = hasLogin(outFriends, targetLogin);
const friendIn = hasLogin(inFriends, targetLogin);
const closeFriendOut = hasLogin(outCloseFriends, targetLogin);
const closeFriendIn = hasLogin(inCloseFriends, targetLogin);
const contactOut = hasLogin(outContacts, targetLogin) || hasLogin(outFollows, targetLogin) || hasLogin(outOfficial, targetLogin);
const contactIn = hasLogin(inContacts, targetLogin) || hasLogin(inFollows, targetLogin) || hasLogin(inOfficial, targetLogin);
let role = 'contact';
if (closeFriendOut || closeFriendIn || friendOut || friendIn) role = 'friend';
let forward = role === 'friend' ? (closeFriendOut || friendOut) : contactOut;
let backward = role === 'friend' ? (closeFriendIn || friendIn) : contactIn;
return {
login: targetLogin,
key: normKey(targetLogin),
role,
isRelative: false,
gender: normalizeGender(relativesGender.get(normKey(targetLogin))),
forward: Boolean(forward),
backward: Boolean(backward),
mark: allMarks.get(normKey(targetLogin)) || null,
};
});
const relations = allLogins.map((targetLogin) => ({
login: targetLogin,
key: normKey(targetLogin),
role: 'friend',
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
isRelative: false,
gender: GENDER_UNKNOWN,
forward: true,
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
mark: allMarks.get(normKey(targetLogin)) || null,
}));
return {
centerLogin: login,
@@ -296,6 +260,7 @@ function relationEdge(parentId, node) {
return {
id: normKey(parentId),
relationType: String(node?.relationType || 'contact'),
mutual: node?.mutual !== false,
strength: Math.max(0, Math.min(1, Number(node?.strength) || 0.5)),
};
}
@@ -412,48 +377,7 @@ async function buildSecondLevelEngineModel(baseModel, getGraph) {
return { ...baseModel, nodes: [...byKey.values()] };
}
const NETWORK_GRAPH_CACHE_TTL_MS = 2 * 60 * 1000;
const NETWORK_GRAPH_CACHE_MAX = 240;
const networkGraphCache = new Map();
const networkGraphInflight = new Map();
async function getConnectionsGraphCached(login, { force = false, retries = 0 } = {}) {
const clean = normalizeLogin(login);
const key = normKey(clean);
if (!key) throw new Error('LOGIN_REQUIRED');
const now = Date.now();
const cached = networkGraphCache.get(key);
if (!force && cached && now - cached.savedAt < NETWORK_GRAPH_CACHE_TTL_MS) return cached.graph;
if (!force && networkGraphInflight.has(key)) return networkGraphInflight.get(key);
const request = (async () => {
let lastError = null;
for (let attempt = 0; attempt <= Math.max(0, retries); attempt += 1) {
try {
const graph = await authService.getUserConnectionsGraph(clean);
networkGraphCache.delete(key);
networkGraphCache.set(key, { graph, savedAt: Date.now() });
while (networkGraphCache.size > NETWORK_GRAPH_CACHE_MAX) {
const oldestKey = networkGraphCache.keys().next().value;
if (!oldestKey) break;
networkGraphCache.delete(oldestKey);
}
return graph;
} catch (error) {
lastError = error;
if (attempt < retries) await new Promise((resolve) => window.setTimeout(resolve, 120 * (attempt + 1)));
}
}
throw lastError || new Error('GRAPH_LOAD_FAILED');
})();
networkGraphInflight.set(key, request);
try {
return await request;
} finally {
if (networkGraphInflight.get(key) === request) networkGraphInflight.delete(key);
}
}
const getConnectionsGraphCached = (login, options) => loadSharedGraph(authService, login, options);
function historyNodeClearance(node) {
return (Number(node?.tier) || 1) >= 2 ? HISTORY_TIER2_CLEARANCE : HISTORY_NODE_CLEARANCE;
@@ -738,6 +662,7 @@ function buildStableHistoryEngineModel(history, historyDepth = HISTORY_MAX_PREVI
parent: parentKey,
child: key,
relationType: String(ref?.relationType || rawNode?.relationType || 'contact'),
mutual: ref?.mutual !== false,
strength: Math.max(0, Math.min(1, Number(ref?.strength) || Number(rawNode?.strength) || 0.5)),
});
});
@@ -753,7 +678,7 @@ function buildStableHistoryEngineModel(history, historyDepth = HISTORY_MAX_PREVI
if (!nodeMap.has(edge.parent) || !nodeMap.has(edge.child)) continue;
const list = edgeParentsByChild.get(edge.child) || [];
if (!list.some((row) => normKey(row?.id) === edge.parent)) {
list.push({ id: edge.parent, relationType: edge.relationType, strength: edge.strength });
list.push({ id: edge.parent, relationType: edge.relationType, mutual: edge.mutual, strength: edge.strength });
}
edgeParentsByChild.set(edge.child, list);
}
@@ -1302,8 +1227,21 @@ export function render({ navigate, route, chrome } = {}) {
],
});
function refreshConnectionsView() {
if (!centerLogin) return;
// После записи полностью пересобираем историю/X2 из общего кэша, сохраняя по возможности позиции.
void load(centerLogin, { pushHistory: false });
}
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
const graphRefreshTimer = window.setInterval(() => {
if (engine && !document.hidden) refreshConnectionsView();
}, CONNECTIONS_GRAPH_TTL_MS);
// Ресайз и перерисовку рёбер движок обрабатывает сам (window resize + ResizeObserver внутри).
screen.cleanup = () => {
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
window.clearInterval(graphRefreshTimer);
loadSeq += 1;
if (engine) engine.destroy();
engine = null;
};
+53 -171
View File
@@ -13,6 +13,7 @@ import { renderUserAvatar } from '../components/avatar-image.js';
import { createErrorState, createSpinner, createStateMessage } from '../components/feedback.js';
import { createListSection, createPersonRow } from '../components/person-row.js';
import { authService, state } from '../state.js';
import { getConnectionsGraphCached as loadSharedGraph, cachedConnectionsGraph as getCachedSharedGraph, CONNECTIONS_GRAPH_CHANGED, CONNECTIONS_GRAPH_TTL_MS } from '../services/connections-graph-cache.js';
import { openHistoryLayer } from '../router.js';
import { makeProfileRoute, makeProfileLinksRoute, makeShineChannelRootRoute } from '../services/shine-routes.js';
import { userDisplayName } from '../services/user-display.js';
@@ -30,7 +31,7 @@ import {
updateCompanySnapshots,
} from './network/companies-store.js';
import {
PEOPLE_DATA_FRESH_MS, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
PEOPLE_DATA_FRESH_MS, peopleDataGeneration, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
} from './network/people-data-store.js';
import {
clearManualLayout, getAutoLayoutMode, getLayoutMode, getManualBase, getManualLayout, getViewSetting, hasManualLayout,
@@ -119,52 +120,28 @@ function normalizeAvatar(row) {
function buildGraphModel(graph, centerLogin) {
const login = normalizeLogin(graph?.login || centerLogin || state.session.login);
const outFriends = toSet(graph?.outFriends);
const inFriends = toSet(graph?.inFriends);
const outCloseFriends = toSet(graph?.outCloseFriends);
const inFriends = toSet(graph?.inFriends);
const inCloseFriends = toSet(graph?.inCloseFriends);
const outContacts = toSet(graph?.outContacts);
const inContacts = toSet(graph?.inContacts);
const outFollows = toSet(graph?.outFollows);
const inFollows = toSet(graph?.inFollows);
const outOfficial = toSet(graph?.outOfficialAccounts);
const inOfficial = toSet(graph?.inOfficialAccounts);
const allMarks = getMarkByLogin(graph?.allUsers);
// Родственные связи сервер хранит, но в интерфейсе они пока скрыты.
// Граф показывает только тех, кого владелец сам выбрал другом.
// Входящие друзья нужны лишь для проверки взаимности, контакты и подписки исключены.
const allLogins = uniqueLogins([
...(graph?.outFriends || []),
...(graph?.inFriends || []),
...(graph?.outCloseFriends || []),
...(graph?.inCloseFriends || []),
...(graph?.outContacts || []),
...(graph?.inContacts || []),
...(graph?.outFollows || []),
...(graph?.inFollows || []),
...(graph?.outOfficialAccounts || []),
...(graph?.inOfficialAccounts || []),
...(graph?.outFriends || []),
]).filter((entry) => normKey(entry) !== normKey(login));
const relations = allLogins.map((targetLogin) => {
const friendOut = hasLogin(outFriends, targetLogin);
const friendIn = hasLogin(inFriends, targetLogin);
const closeFriendOut = hasLogin(outCloseFriends, targetLogin);
const closeFriendIn = hasLogin(inCloseFriends, targetLogin);
const contactOut = hasLogin(outContacts, targetLogin) || hasLogin(outFollows, targetLogin) || hasLogin(outOfficial, targetLogin);
const contactIn = hasLogin(inContacts, targetLogin) || hasLogin(inFollows, targetLogin) || hasLogin(inOfficial, targetLogin);
const role = closeFriendOut || closeFriendIn || friendOut || friendIn ? 'friend' : 'contact';
// Взаимность – по любой связи с той стороны: «друг» в ответ на «контакт» – тоже ответ.
const forward = closeFriendOut || friendOut || contactOut;
const backward = closeFriendIn || friendIn || contactIn;
return {
login: targetLogin,
key: normKey(targetLogin),
role,
isRelative: false,
forward,
backward,
mark: allMarks.get(normKey(targetLogin)) || null,
};
});
const relations = allLogins.map((targetLogin) => ({
login: targetLogin,
key: normKey(targetLogin),
role: 'friend',
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
isRelative: false,
forward: true,
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
mark: allMarks.get(normKey(targetLogin)) || null,
}));
return {
centerLogin: login,
@@ -188,52 +165,8 @@ async function mapWithConcurrency(items, concurrency, worker) {
return out;
}
const NETWORK_GRAPH_CACHE_TTL_MS = 2 * 60 * 1000;
const NETWORK_GRAPH_CACHE_MAX = 240;
const networkGraphCache = new Map();
const networkGraphInflight = new Map();
function cachedGraph(login) {
const cached = networkGraphCache.get(normKey(login));
return cached && Date.now() - cached.savedAt < NETWORK_GRAPH_CACHE_TTL_MS ? cached.graph : null;
}
async function getConnectionsGraphCached(login, { force = false, retries = 0 } = {}) {
const clean = normalizeLogin(login);
const key = normKey(clean);
if (!key) throw new Error('LOGIN_REQUIRED');
const fresh = force ? null : cachedGraph(clean);
if (fresh) return fresh;
if (!force && networkGraphInflight.has(key)) return networkGraphInflight.get(key);
const request = (async () => {
let lastError = null;
for (let attempt = 0; attempt <= Math.max(0, retries); attempt += 1) {
try {
const graph = await authService.getUserConnectionsGraph(clean);
networkGraphCache.delete(key);
networkGraphCache.set(key, { graph, savedAt: Date.now() });
while (networkGraphCache.size > NETWORK_GRAPH_CACHE_MAX) {
const oldestKey = networkGraphCache.keys().next().value;
if (!oldestKey) break;
networkGraphCache.delete(oldestKey);
}
return graph;
} catch (error) {
lastError = error;
if (attempt < retries) await new Promise((resolve) => window.setTimeout(resolve, 120 * (attempt + 1)));
}
}
throw lastError || new Error('GRAPH_LOAD_FAILED');
})();
networkGraphInflight.set(key, request);
try {
return await request;
} finally {
if (networkGraphInflight.get(key) === request) networkGraphInflight.delete(key);
}
}
const cachedGraph = (login) => getCachedSharedGraph(authService, login);
const getConnectionsGraphCached = (login, options) => loadSharedGraph(authService, login, options);
// Поиск без учёта регистра и «ё».
function searchText(value) {
@@ -247,24 +180,19 @@ const MAX_NODES = 400; // предел карты: дальше раскры
const RELATION_RANK = { close_friend: 0, family: 1, friend: 2, contact: 3 };
const FRIEND_TYPES = new Set(['close_friend', 'friend', 'family']);
const RELATION_LABEL = { close_friend: 'Близкий друг', friend: 'Друг', family: 'Семья', contact: 'Контакт' };
// Связь только с той стороны: другу – «хочет дружить», контакту – «вас добавили».
// Строгая взаимность дружбы. Чисто входящие пользователи на карте отсутствуют.
function directionLabel(node) {
if (node.direction === 'out') return 'без ответа';
if (node.direction === 'in') return FRIEND_TYPES.has(node.relationType) ? 'хочет дружить' : 'вас добавили';
return 'взаимно';
return node.direction === 'out' ? 'без ответа' : 'взаимно';
}
// Переживает уход с экрана: возврат по «Связям» из профиля показывает ту же карту.
const persisted = { centerLogin: '', expanded: [], filter: 'all', friendsOfFriends: false, interest: '', view: null, listScroll: 0 };
// Фильтр – один выбранный. Тип связи и «добавили вас» – только про прямые связи центра,
// «сияющие» и «с заметкой» – про всех на карте.
// Фильтры относятся только к исходящему кругу друзей, а также раскрытым друзьям друзей.
const FILTERS = [
{ id: 'all', label: 'Все', pred: null },
{ id: 'close', label: 'Близкие', direct: true, pred: (node) => node.relationType === 'close_friend' || node.relationType === 'family' },
{ id: 'friends', label: 'Друзья', direct: true, pred: (node) => node.relationType === 'friend' },
{ id: 'contacts', label: 'Контакты', direct: true, pred: (node) => node.relationType === 'contact' },
{ id: 'incoming', label: 'Добавили вас', direct: true, selfOnly: true, pred: (node) => node.direction === 'in' },
{ id: 'shining', label: 'Сияющие', pred: (node) => Boolean(node.shining) },
{ id: 'notes', label: 'С заметкой', pred: (node) => Boolean(node.mark || node.hasNote) },
];
@@ -396,7 +324,6 @@ export function render({ navigate, route, chrome } = {}) {
let noteSheet = null;
let legendSheet = null;
let search = null; // { query, topbar, layer, remote: { seq, query, items, loading, failed } }
let waitingExpanded = false; // «Добавили вас» в списке: сначала несколько, по кнопке – все
let groupsModel = null; // острова «Компаний» / «Интересов»: { lens, groups, byId, byPerson }
let selectedGroupId = '';
let groupSheet = null;
@@ -905,16 +832,6 @@ export function render({ navigate, route, chrome } = {}) {
actions.append(cardAction('edit', 'Заметка', () => openNoteEditor(node)));
}
card.append(actions);
if (canAnswerBack(node)) {
const answer = document.createElement('button');
answer.type = 'button';
answer.className = 'primary-btn net-card__answer';
const busy = answering.has(node.id);
answer.disabled = busy;
answer.textContent = busy ? 'Сохраняю…' : answerBackLabel(node);
answer.addEventListener('click', () => { void answerBack(node); });
card.append(answer);
}
if (node.hiddenCount > 0) {
const more = document.createElement('p');
more.className = 'net-card__hint';
@@ -925,40 +842,6 @@ export function render({ navigate, route, chrome } = {}) {
placeOverlays();
}
// --- ответ взаимностью ---
// «Добавили вас»: ответить в одно касание – другом на дружбу, контактом на контакт
// (другой вид связи можно выбрать в профиле человека).
const answering = new Set();
function canAnswerBack(node) {
return Boolean(node) && node.id !== map?.focusId && node.tier === 1 && node.direction === 'in' && isSelfCenter();
}
function answerBackLabel(node) {
return FRIEND_TYPES.has(node.relationType) ? 'Дружить в ответ' : 'Добавить в ответ';
}
async function answerBack(node) {
if (!node || answering.has(node.id)) return;
const kind = FRIEND_TYPES.has(node.relationType) ? 'friend' : 'contact';
answering.add(node.id);
renderCard();
if (viewMode === 'list') renderList();
let done = false;
try {
await authService.setUserRelation({
login: state.session.login, toLogin: node.login, kind, enabled: true, storagePwd: state.session.storagePwdInMemory,
});
done = true;
if (!disposed) showToast(kind === 'friend' ? 'Теперь вы друзья' : 'Добавлено в контакты');
const graph = await getConnectionsGraphCached(selfLogin, { force: true });
if (!disposed) graphs.set(selfKey, buildGraphModel(graph, selfLogin));
} catch (error) {
// Связь сохранена, но карта не перечиталась – она обновится при следующем открытии.
if (!done && !disposed) showToast(actionErrorText('Не удалось ответить', error), { kind: 'error' });
} finally {
answering.delete(node.id);
if (!disposed) renderMap();
}
}
// --- заметка ---
function openNoteEditor(node) {
noteSheet?.close();
@@ -984,8 +867,7 @@ export function render({ navigate, route, chrome } = {}) {
const rows = [
['line', 'close_friend', 'Близкий друг'],
['line', 'friend', 'Друг'],
['line', 'contact', 'Контакт'],
['dash', 'friend', 'Пунктир – связь только с одной стороны'],
['dash', 'friend', 'Пунктир → точки – вы добавили друга, ответа пока нет'],
['aura', '', 'Свечение вокруг – сияющий'],
['badge', '', 'Синяя галочка – официальный аккаунт'],
['mark', '', 'Цветная точка – ваша заметка или метка'],
@@ -1005,7 +887,7 @@ export function render({ navigate, route, chrome } = {}) {
const tips = document.createElement('ul');
tips.className = 'net-legend__tips';
for (const tip of [
'«По близости»: ближе к центру – близкие, дальше – друзья, снаружи – контакты. Знакомые между собой стоят рядом.',
'«По близости»: ближе к центру – близкие друзья, дальше – друзья. Знакомые между собой стоят рядом.',
'«Компании» (в меню «•••») собирают вместе тех, кто знаком между собой: школа, работа, друзья по увлечению. Нить между компаниями – сколько в них знакомых друг с другом. Нажмите на название компании – откроется её карточка, там её можно назвать.',
'Человека можно перетащить в другую компанию – он останется в ней. Или нажмите «Перенести…» в его карточке.',
'«Интересы» собирают людей у каналов, которые они читают; нажмите на канал – подсветятся все его читатели. «Города» – кто где живёт (по полю «Город» в профиле). Знакомства, подписки и города узнаются один раз и хранятся на этом устройстве.',
@@ -1226,6 +1108,7 @@ export function render({ navigate, route, chrome } = {}) {
async function loadPeopleData(kind, { quiet = false, force = false } = {}) {
if (disposed || !map) return false;
const centerKey = normKey(centerLogin);
const generationAtStart = peopleDataGeneration();
const jobKey = `${kind}|${centerKey}`;
if (lensLoads.has(jobKey) || (!force && (lensBlockedUntil.get(jobKey) || 0) > Date.now())) return false;
const people = directPeople().slice(0, PEOPLE_DATA_LIMIT);
@@ -1259,7 +1142,7 @@ export function render({ navigate, route, chrome } = {}) {
const near = new Map();
for (const relation of buildGraphModel(graph, node.login).relations) {
if (relation.key === node.id || !directIds.has(relation.key)) continue;
near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.forward && relation.backward });
if (relation.forward) near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.backward });
}
entry.people.set(node.id, near);
} else if (kind === 'subs') {
@@ -1277,7 +1160,9 @@ export function render({ navigate, route, chrome } = {}) {
job.done += 1;
if (job.foreground && !disposed) syncLensProgress();
});
lensLoads.delete(jobKey);
if (lensLoads.get(jobKey) === job) lensLoads.delete(jobKey);
// Прежняя пачка данных могла закончиться уже после изменения дружбы.
if (disposed || generationAtStart !== peopleDataGeneration()) return false;
if (failed) lensBlockedUntil.set(jobKey, Date.now() + 60 * 1000);
else lensBlockedUntil.delete(jobKey);
// Освежили всех – отметка времени; если большинство не ответило, попробуем в следующий раз.
@@ -1486,19 +1371,17 @@ export function render({ navigate, route, chrome } = {}) {
persist();
}
// Состав по близости: «3 близких, 8 друзей, 15 контактов».
// Состав по близости: здесь считаются только друзья.
function compositionText(members) {
const counts = { close: 0, friend: 0, contact: 0 };
const counts = { close: 0, friend: 0 };
members.forEach((id) => {
const type = map?.byId.get(id)?.relationType;
if (type === 'close_friend' || type === 'family') counts.close += 1;
else if (type === 'friend') counts.friend += 1;
else counts.contact += 1;
});
const parts = [];
if (counts.close) parts.push(`${counts.close} ${pluralRu(counts.close, 'близкий', 'близких', 'близких')}`);
if (counts.friend) parts.push(`${counts.friend} ${pluralRu(counts.friend, 'друг', 'друга', 'друзей')}`);
if (counts.contact) parts.push(`${counts.contact} ${pluralRu(counts.contact, 'контакт', 'контакта', 'контактов')}`);
return parts.join(', ');
}
@@ -1922,11 +1805,9 @@ export function render({ navigate, route, chrome } = {}) {
ensureLensData();
}
// --- фильтры: «Все / Близкие / Друзья / Контакты» – тем же переключателем, что в чатах;
// реже нужное («Добавили вас», «Сияющие», «С заметкой», «Друзья друзей») – в «Ещё».
const PRIMARY_FILTERS = ['all', 'close', 'friends', 'contacts'];
// Дружеский круг: все, близкие, друзья; остальные условия – в меню «Ещё».
const PRIMARY_FILTERS = ['all', 'close', 'friends'];
const EXTRA_FILTERS = [
{ id: 'incoming', short: 'Добавили', icon: 'user-plus' },
{ id: 'shining', short: 'Сияющие', icon: 'sparkle' },
{ id: 'notes', short: 'С заметкой', icon: 'edit' },
];
@@ -2204,15 +2085,12 @@ export function render({ navigate, route, chrome } = {}) {
note: note?.text?.trim() ? note.text.trim().split('\n')[0] : '',
markColor: note?.mark || (note?.text?.trim() ? 'note' : ''),
ring: node.shining ? 'shining' : (node.relationType === 'close_friend' && node.tier === 1 ? 'close' : ''),
tag: node.tier === 1 && node.direction === 'in' && isSelfCenter() ? directionLabel(node) : '',
tag: '',
onClick: onOpen || (() => {
if (search) closeSearch();
navigate(profileRoute(node.login));
}),
actions: [
canAnswerBack(node)
? { icon: 'user-plus', label: answerBackLabel(node), primary: true, busy: answering.has(node.id), onClick: () => { void answerBack(node); } }
: null,
{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(node.login)}`) },
{ icon: 'more', label: 'Ещё', onClick: (event, button) => openRowMenu(node, button) },
],
@@ -2254,13 +2132,10 @@ export function render({ navigate, route, chrome } = {}) {
].filter((section) => section.items.length);
}
const direct = people.filter((node) => node.tier === 1);
const waiting = isSelfCenter() ? direct.filter((node) => node.direction === 'in') : [];
const rest = direct.filter((node) => !waiting.includes(node));
const rest = direct;
return [
{ title: 'Добавили вас', items: waiting.sort(byName), waiting: true },
{ title: 'Близкие', items: rest.filter((node) => node.relationType === 'close_friend' || node.relationType === 'family').sort(byName) },
{ title: 'Друзья', items: rest.filter((node) => node.relationType === 'friend').sort(byName) },
{ title: 'Контакты', items: rest.filter((node) => node.relationType === 'contact').sort(byName) },
{ title: 'Друзья друзей', items: people.filter((node) => node.tier > 1).sort(byName) },
].filter((group) => group.items.length);
}
@@ -2285,18 +2160,7 @@ export function render({ navigate, route, chrome } = {}) {
section.prepend(groupDot(group.group));
}
frag.append(section);
// Длинный «Добавили вас» не должен закрывать собой весь список: сначала трое.
const collapsed = group.waiting && !waitingExpanded && !query && group.items.length > 4;
const shown = collapsed ? group.items.slice(0, 3) : group.items;
shown.forEach((node) => frag.append(personRow(node, { withType })));
if (collapsed) {
const more = document.createElement('button');
more.type = 'button';
more.className = 'list-more';
more.innerHTML = `${iconHtml('chevron-down')}<span>Показать всех · ${group.items.length}</span>`;
more.addEventListener('click', () => { waitingExpanded = true; renderList(); });
frag.append(more);
}
group.items.forEach((node) => frag.append(personRow(node, { withType })));
}
if (query) appendRemoteResults(frag, new Set(people.map((node) => node.id)));
if (!people.length && map.nodes.length > 1 && !(query && search?.remote?.items?.length)) {
@@ -2490,6 +2354,22 @@ export function render({ navigate, route, chrome } = {}) {
overlayObserver?.observe(stage);
overlayObserver?.observe(filterBar);
function refreshConnectionsView() {
if (disposed || !centerLogin) return;
// Полный сброс отображаемых графов; запросы заново заполняют общий кэш.
graphs.clear();
lensLoads.clear();
lensBlockedUntil.clear();
groupsModel = null;
if (map) restoreView = engine.getView();
void load(centerLogin);
}
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
const graphRefreshTimer = window.setInterval(() => {
// TTL сам по себе не перерисовывает уже открытую карту — обновляем её при активности вкладки.
if (!disposed && !document.hidden) refreshConnectionsView();
}, CONNECTIONS_GRAPH_TTL_MS);
screen.cleanup = () => {
if (disposed) return;
disposed = true;
@@ -2505,6 +2385,8 @@ export function render({ navigate, route, chrome } = {}) {
window.cancelAnimationFrame(listFrame);
window.clearTimeout(remoteTimer);
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
window.clearInterval(graphRefreshTimer);
document.removeEventListener('keydown', onKeydown);
noteSheet?.close();
legendSheet?.close();
+5 -6
View File
@@ -12,11 +12,10 @@ function normKey(value) {
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
export function relationTypeFromRelation(relation) {
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
const role = relation?.role;
if (FAMILY_ROLES.includes(role)) return 'family';
if (role === 'friend') return 'friend';
// Тип отношения выбирает владелец рассматриваемого графа.
const ownType = String(relation?.relationType || '').trim().toLowerCase();
if (ownType === 'close_friend' || ownType === 'friend') return ownType;
if (relation?.role === 'friend') return 'friend';
return 'contact';
}
@@ -45,7 +44,7 @@ export function peopleFromGraphModel(graphModel) {
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
const login = normLogin(relation?.login);
const key = normKey(login);
if (!login || seen.has(key)) continue;
if (!login || seen.has(key) || !relation?.forward) continue;
seen.add(key);
const forward = Boolean(relation?.forward);
const backward = Boolean(relation?.backward);
+36 -6
View File
@@ -1604,6 +1604,20 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
return !edge.tie;
}
// Подотрезок квадратичной Безье по параметру t (направление: добавивший → добавленный).
function quadraticPart(g, from, to) {
const point = (t) => ({
x: (1 - t) ** 2 * g.x1 + 2 * t * (1 - t) * g.cx + t ** 2 * g.x2,
y: (1 - t) ** 2 * g.y1 + 2 * t * (1 - t) * g.cy + t ** 2 * g.y2,
});
const first = point(from);
const last = point(to);
const dx = 2 * ((1 - from) * (g.cx - g.x1) + from * (g.x2 - g.cx));
const dy = 2 * ((1 - from) * (g.cy - g.y1) + from * (g.y2 - g.cy));
const dt = (to - from) / 2;
return { first, ctrl: { x: first.x + dx * dt, y: first.y + dy * dt }, last };
}
// Нити рисуются пачками одного вида: сотни отдельных штрихов со сменой пунктира – это
// и была главная цена кадра на «друзьях друзей».
function drawEdges(inView, widthScale) {
@@ -1660,13 +1674,29 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
for (const batch of ordered) {
ctx.strokeStyle = rgba(colors.edge[batch.type], batch.alpha);
ctx.lineWidth = EDGE_WIDTH[batch.type] * widthScale * (batch.incident ? 1.5 : 1);
ctx.setLineDash(batch.mutual ? [] : [5 * widthScale, 4 * widthScale]);
ctx.beginPath();
for (const g of batch.list) {
ctx.moveTo(g.x1, g.y1);
ctx.quadraticCurveTo(g.cx, g.cy, g.x2, g.y2);
if (batch.mutual) {
ctx.setLineDash([]);
ctx.beginPath();
for (const g of batch.list) {
ctx.moveTo(g.x1, g.y1);
ctx.quadraticCurveTo(g.cx, g.cy, g.x2, g.y2);
}
ctx.stroke();
} else {
// От инициатора дружбы линия почти сплошная; возле адресата превращается в точки.
// Делим кривую, сохраняя геометрию и пакетную отрисовку внутри каждого сегмента.
const patterns = [[20, 3], [12, 4], [6, 4], [1, 5]];
patterns.forEach(([dash, gap], section) => {
ctx.setLineDash([dash * widthScale, gap * widthScale]);
ctx.beginPath();
for (const g of batch.list) {
const part = quadraticPart(g, section / 4, (section + 1) / 4);
ctx.moveTo(part.first.x, part.first.y);
ctx.quadraticCurveTo(part.ctrl.x, part.ctrl.y, part.last.x, part.last.y);
}
ctx.stroke();
});
}
ctx.stroke();
}
ctx.setLineDash([]);
}
+16 -1
View File
@@ -5,14 +5,29 @@
// Сервер не трогаем: знакомства – из графа связей каждого человека, подписки – из списка
// «Подписки» его профиля (публичные каналы), город – из параметра city его профиля.
import { state } from '../../state.js';
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
const PREFIX = { ties: 'shine-network-ties-v1:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
const PREFIX = { ties: 'shine-network-ties-v2:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
export const PEOPLE_DATA_FRESH_MS = 12 * 60 * 60 * 1000; // старше – освежаются в фоне
const TYPE_CODE = { close_friend: 3, family: 3, friend: 2, contact: 1 };
const CODE_TYPE = { 3: 'close_friend', 2: 'friend', 1: 'contact' };
const memory = new Map(); // `${kind}|${owner}|${center}` → запись
let peopleGeneration = 0;
export function peopleDataGeneration() { return peopleGeneration; }
export function invalidatePeopleData() {
peopleGeneration += 1;
memory.clear();
const owner = ownerLogin();
if (!owner) return;
for (const prefix of Object.values(PREFIX)) {
try { localStorage.removeItem(prefix + owner); } catch { /* хранилище может быть недоступно */ }
}
}
if (typeof window !== 'undefined') window.addEventListener(CONNECTIONS_GRAPH_CHANGED, invalidatePeopleData);
function ownerLogin() {
return String(state.session?.login || '').trim().toLowerCase();
}
+2 -352
View File
@@ -1,6 +1,5 @@
import { createTopBar } from '../components/topbar.js';
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
import { confirmDialog } from '../components/confirm-dialog.js';
import { showToast } from '../services/channels-ux.js';
import { profile } from '../mock-data.js';
import { authService, state } from '../state.js';
@@ -18,7 +17,7 @@ import {
saveProfileParamBlock,
saveProfileStatus,
} from '../services/user-profile-params.js';
import { buildIdentityLines, loadUserProfileCard } from '../services/user-connections.js';
import { buildIdentityLines } from '../services/user-connections.js';
import { openAvatarWizard } from '../components/avatar-wizard.js';
import { renderUserAvatar } from '../components/avatar-image.js';
@@ -55,45 +54,6 @@ const GENDER_OPTIONS = Object.freeze([
{ value: PROFILE_GENDER_UNKNOWN, label: 'Не указан' },
]);
// Родственные типы сохранены в протоколе, но пока намеренно скрыты из UI.
const RELATIVE_RELATION_OPTIONS = Object.freeze([
{ value: 'friend', label: 'Друг' },
{ value: 'close_friend', label: 'Близкий друг' },
]);
function normalizeGender(value) {
const v = String(value || '').trim().toLowerCase();
if (v === PROFILE_GENDER_MALE) return PROFILE_GENDER_MALE;
if (v === PROFILE_GENDER_FEMALE) return PROFILE_GENDER_FEMALE;
return PROFILE_GENDER_UNKNOWN;
}
function relationAccusativeLabel(type, targetGender) {
const gender = normalizeGender(targetGender);
if (type === 'parent') {
if (gender === PROFILE_GENDER_MALE) return 'отца';
if (gender === PROFILE_GENDER_FEMALE) return 'мать';
return 'родителя';
}
if (type === 'child') {
if (gender === PROFILE_GENDER_MALE) return 'сына';
if (gender === PROFILE_GENDER_FEMALE) return 'дочь';
return 'ребёнка';
}
if (type === 'sibling') {
if (gender === PROFILE_GENDER_MALE) return 'брата';
if (gender === PROFILE_GENDER_FEMALE) return 'сестру';
return 'брата/сестру';
}
if (type === 'spouse') {
if (gender === PROFILE_GENDER_MALE) return 'мужа';
if (gender === PROFILE_GENDER_FEMALE) return 'жену';
return 'жену/мужа';
}
if (type === 'friend') return 'друга';
return 'близкого друга';
}
function escapeHtml(text) {
return String(text || '')
.replaceAll('&', '&amp;')
@@ -147,18 +107,9 @@ export function render({ navigate, chrome }) {
const listWrap = document.createElement('div');
listWrap.className = 'nav-list profile-param-list';
const relativesCard = document.createElement('div');
relativesCard.className = 'card stack';
relativesCard.innerHTML = `
<div class="profile-param-value"><b>Друзья</b></div>
<div class="meta-muted">Добавьте человека в друзья или в близкие друзья.</div>
<button class="secondary-btn" type="button" data-add-relative="true">Добавить друга</button>
`;
const reloadBtn = topRow.querySelector('[data-reload="true"]');
const accountRoleBtn = badgesRow.querySelector('[data-status="account_role"]');
const shineBtn = badgesRow.querySelector('[data-status="shine"]');
const addRelativeBtn = relativesCard.querySelector('[data-add-relative="true"]');
const avatarActionEl = topRow.querySelector('[data-change-avatar="true"]');
let currentFields = [];
@@ -363,224 +314,6 @@ export function render({ navigate, chrome }) {
});
}
function openAddRelativeModal({ contacts = [] } = {}) {
const root = document.getElementById('modal-root');
if (!root) return Promise.resolve(null);
const preparedContacts = Array.isArray(contacts)
? contacts
.map((item) => String(item || '').trim())
.filter(Boolean)
: [];
const uniqueContacts = Array.from(new Set(preparedContacts.map((item) => item.toLowerCase())))
.map((key) => preparedContacts.find((item) => item.toLowerCase() === key))
.filter(Boolean);
root.innerHTML = `
<div class="modal" id="profile-add-relative-modal">
<div class="modal-card stack">
<h3 class="modal-title">Добавить связь</h3>
<label class="meta-muted" for="profile-relative-kind">Какой тип связи вы хотите добавить?</label>
<select class="input profile-relation-select" id="profile-relative-kind">
${RELATIVE_RELATION_OPTIONS.map((item) => (
`<option value="${item.value}">${item.label}</option>`
)).join('')}
</select>
<label class="meta-muted" for="profile-relative-login">Логин пользователя</label>
<input
class="input"
id="profile-relative-login"
type="text"
maxlength="30"
placeholder="Введите логин пользователя"
/>
<div class="meta-muted profile-relative-search-meta" id="profile-relative-search-meta">
Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.
</div>
<div class="profile-relative-search-suggest" id="profile-relative-search-suggest" hidden></div>
<div class="meta-muted inline-error" id="profile-relative-error"></div>
<div class="form-actions-grid">
<button class="secondary-btn" id="profile-relative-cancel" type="button">Отмена</button>
<button class="primary-btn" id="profile-relative-submit" type="button">Продолжить</button>
</div>
</div>
</div>
`;
return new Promise((resolve) => {
const modal = root.querySelector('#profile-add-relative-modal');
const kindEl = root.querySelector('#profile-relative-kind');
const loginEl = root.querySelector('#profile-relative-login');
const submitEl = root.querySelector('#profile-relative-submit');
const cancelEl = root.querySelector('#profile-relative-cancel');
const errorEl = root.querySelector('#profile-relative-error');
const searchMetaEl = root.querySelector('#profile-relative-search-meta');
const suggestEl = root.querySelector('#profile-relative-search-suggest');
if (!(modal instanceof HTMLElement) || !(kindEl instanceof HTMLSelectElement) || !(loginEl instanceof HTMLInputElement)) {
root.innerHTML = '';
resolve(null);
return;
}
let closed = false;
let searchTimerId = 0;
let searchSeq = 0;
const clearSearchTimer = () => {
if (!searchTimerId) return;
window.clearTimeout(searchTimerId);
searchTimerId = 0;
};
const uniqueCaseInsensitive = (list) => {
const out = [];
const seen = new Set();
(Array.isArray(list) ? list : []).forEach((item) => {
const value = String(item || '').trim();
if (!value) return;
const key = value.toLowerCase();
if (seen.has(key)) return;
seen.add(key);
out.push(value);
});
return out;
};
const renderSuggestions = (list) => {
if (!(suggestEl instanceof HTMLElement)) return;
const values = uniqueCaseInsensitive(list).slice(0, 5);
if (!values.length) {
suggestEl.hidden = true;
suggestEl.innerHTML = '';
return;
}
suggestEl.hidden = false;
suggestEl.innerHTML = values.map((value) => (
`<button type="button" class="ui-button profile-relative-suggest-item" data-login="${escapeHtml(value)}">${escapeHtml(value)}</button>`
)).join('');
};
const searchContactsFallback = (prefix) => {
const query = String(prefix || '').trim().toLowerCase();
if (!query) return [];
return uniqueContacts
.filter((entry) => entry.toLowerCase().startsWith(query))
.slice(0, 5);
};
const runSearch = async ({ withErrorMessage = false } = {}) => {
const prefix = String(loginEl.value || '').trim();
if (!prefix) {
renderSuggestions([]);
if (searchMetaEl) {
searchMetaEl.textContent = 'Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.';
}
return;
}
if (searchMetaEl) searchMetaEl.textContent = `Поиск пользователей по префиксу «${prefix}»...`;
const reqId = ++searchSeq;
let found = [];
let searchFailed = false;
try {
const payload = await authService.searchUsers(prefix);
found = Array.isArray(payload) ? payload : [];
} catch {
searchFailed = true;
found = [];
}
if (closed || reqId !== searchSeq) return;
const query = prefix.toLowerCase();
const candidateList = uniqueCaseInsensitive([
...found,
...searchContactsFallback(prefix),
])
.filter((entry) => entry.toLowerCase().startsWith(query))
.slice(0, 5);
renderSuggestions(candidateList);
if (candidateList.length > 0) {
if (searchMetaEl) searchMetaEl.textContent = `Найдено ${candidateList.length} пользователей. Выберите пользователя из списка.`;
return;
}
if (searchFailed) {
if (searchMetaEl) searchMetaEl.textContent = 'Не удалось получить список пользователей. Уточните логин вручную.';
if (withErrorMessage && errorEl) errorEl.textContent = 'Ошибка поиска пользователей.';
return;
}
if (searchMetaEl) searchMetaEl.textContent = 'Пользователи с таким префиксом не найдены.';
};
const close = (payload = null) => {
closed = true;
clearSearchTimer();
root.innerHTML = '';
resolve(payload);
};
const submit = () => {
const relationType = String(kindEl.value || '').trim();
const toLogin = String(loginEl.value || '').trim();
if (!relationType) {
if (errorEl) errorEl.textContent = 'Выберите тип связи.';
return;
}
if (!toLogin) {
if (errorEl) errorEl.textContent = 'Введите логин пользователя.';
return;
}
close({ relationType, toLogin });
};
modal.addEventListener('click', (event) => {
if (event.target === modal) close(null);
});
cancelEl?.addEventListener('click', () => close(null));
submitEl?.addEventListener('click', submit);
suggestEl?.addEventListener('click', (event) => {
const target = event.target;
if (!(target instanceof HTMLElement)) return;
const button = target.closest('[data-login]');
if (!(button instanceof HTMLElement)) return;
const pickedLogin = String(button.dataset.login || '').trim();
if (!pickedLogin) return;
loginEl.value = pickedLogin;
if (errorEl) errorEl.textContent = '';
if (searchMetaEl) searchMetaEl.textContent = `Выбран пользователь «${pickedLogin}». Нажмите «Продолжить».`;
renderSuggestions([]);
});
loginEl.addEventListener('input', () => {
if (errorEl) errorEl.textContent = '';
clearSearchTimer();
const value = String(loginEl.value || '').trim();
if (!value) {
renderSuggestions([]);
if (searchMetaEl) {
searchMetaEl.textContent = 'Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.';
}
return;
}
if (searchMetaEl) searchMetaEl.textContent = 'Ожидание паузы 2 секунды для поиска...';
searchTimerId = window.setTimeout(() => {
runSearch({ withErrorMessage: false });
}, 2000);
});
loginEl.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
clearSearchTimer();
runSearch({ withErrorMessage: true });
}
});
window.setTimeout(() => loginEl.focus(), 0);
});
}
function renderFields(fields) {
listWrap.innerHTML = '';
fields.forEach((field) => {
@@ -611,7 +344,6 @@ export function render({ navigate, chrome }) {
reloadBtn.disabled = true;
accountRoleBtn.disabled = true;
shineBtn.disabled = true;
if (addRelativeBtn instanceof HTMLButtonElement) addRelativeBtn.disabled = true;
try {
const snapshot = await loadProfileSnapshot(login);
@@ -637,7 +369,6 @@ export function render({ navigate, chrome }) {
reloadBtn.disabled = false;
accountRoleBtn.disabled = false;
shineBtn.disabled = false;
if (addRelativeBtn instanceof HTMLButtonElement) addRelativeBtn.disabled = false;
}
}
@@ -750,86 +481,6 @@ export function render({ navigate, chrome }) {
}
}
async function onAddRelativeClick() {
const sessionLogin = String(login || '').trim();
if (!sessionLogin) {
showToast('Для добавления связи нужен вход в аккаунт.', { kind: 'error' });
return;
}
status.className = 'status-line';
status.textContent = 'Подготовка окна добавления связи...';
let contacts = [];
try {
const payload = await authService.listContacts();
contacts = Array.isArray(payload?.contacts) ? payload.contacts : [];
} catch {
contacts = [];
}
const picked = await openAddRelativeModal({ contacts });
if (!picked) {
status.className = 'status-line is-available';
status.textContent = 'Добавление связи отменено.';
return;
}
const relationType = String(picked.relationType || '').trim().toLowerCase();
const inputLogin = String(picked.toLogin || '').trim();
if (!relationType || !inputLogin) return;
if (inputLogin.toLowerCase() === sessionLogin.toLowerCase()) {
status.className = 'status-line is-unavailable';
status.textContent = 'Нельзя добавить связь с самим собой.';
return;
}
status.className = 'status-line';
status.textContent = 'Проверка пользователя...';
let targetCard;
try {
targetCard = await loadUserProfileCard(inputLogin);
} catch (error) {
status.className = 'status-line is-unavailable';
status.textContent = actionErrorText('Не удалось найти пользователя', error);
showLocalErrorAlert('Не удалось выбрать пользователя', error);
return;
}
const targetLogin = String(targetCard?.login || inputLogin).trim();
const targetGender = normalizeGender(targetCard?.gender || PROFILE_GENDER_UNKNOWN);
const relationLabel = relationAccusativeLabel(relationType, targetGender);
const confirmed = await confirmDialog({
title: 'Добавить связь?',
text: `Добавить ${targetLogin} как ${relationLabel}?`,
confirmLabel: 'Добавить',
});
if (!confirmed) return;
status.className = 'status-line';
status.textContent = 'Сохранение связи...';
try {
if (!state.session.storagePwdInMemory) {
throw new Error('Нет storagePwd в памяти сессии. Выполните вход заново.');
}
await authService.setUserRelation({
login: sessionLogin,
toLogin: targetLogin,
kind: relationType,
enabled: true,
storagePwd: state.session.storagePwdInMemory,
});
status.className = 'status-line is-available';
status.textContent = `Связь добавлена: ${targetLogin} как ${relationLabel}.`;
} catch (error) {
status.className = 'status-line is-unavailable';
status.textContent = actionErrorText('Не удалось добавить связь', error);
showLocalErrorAlert('Не удалось добавить связь', error);
}
}
listWrap.addEventListener('click', (event) => {
const target = event.target;
if (!(target instanceof HTMLElement)) return;
@@ -847,10 +498,9 @@ export function render({ navigate, chrome }) {
reloadBtn.addEventListener('click', refreshProfileSnapshot);
accountRoleBtn.addEventListener('click', () => onStatusClick('account_role'));
shineBtn.addEventListener('click', () => onStatusClick('shine'));
addRelativeBtn?.addEventListener('click', onAddRelativeClick);
avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); });
card.append(topRow, badgesRow, status, listWrap, relativesCard);
card.append(topRow, badgesRow, status, listWrap);
screen.append(card);
updateAvatarUi();
+4 -1
View File
@@ -1,4 +1,5 @@
import { WsJsonClient } from './ws-client.js';
import { invalidateConnectionsGraphCache } from './connections-graph-cache.js';
import {
base64ToBytes,
bytesToBase64,
@@ -3368,7 +3369,9 @@ export class AuthService {
const kinds = CONNECTION_SUBTYPES[cleanKind];
if (!kinds) throw new Error(`Неподдерживаемый тип связи: ${kind}`);
const subType = enabled ? kinds.on : kinds.off;
return this.addBlockConnection({ login, toLogin, subType, storagePwd });
const result = await this.addBlockConnection({ login, toLogin, subType, storagePwd });
invalidateConnectionsGraphCache();
return result;
}
async addBlockUserParam({ login, param, value, storagePwd }) {
@@ -0,0 +1,74 @@
// Единый кэш графов для обеих версий экрана «Связи».
// Через две минуты запись устаревает; пока экран открыт, он сам перечитывает граф.
// После любого подтверждённого изменения отношения кэш целиком сбрасывается.
export const CONNECTIONS_GRAPH_CHANGED = 'shine:connections-graph-changed';
export const CONNECTIONS_GRAPH_TTL_MS = 2 * 60 * 1000;
const CACHE_LIMIT = 240;
const cache = new Map();
const inflight = new Map();
let generation = 0;
function cacheKey(service, login) {
const server = String(service?.serverUrl || '').trim().toLowerCase();
return `${server}|${String(login || '').trim().toLowerCase()}`;
}
export function cachedConnectionsGraph(service, login) {
const entry = cache.get(cacheKey(service, login));
return entry && Date.now() - entry.savedAt < CONNECTIONS_GRAPH_TTL_MS ? entry.graph : null;
}
// invalidate делается после подтверждения записи, но до любого повторного запроса графа.
// generation не даёт устаревшему ответу незавершённого запроса вернуться в кэш.
export function invalidateConnectionsGraphCache() {
generation += 1;
cache.clear();
inflight.clear();
// Сбрасываем и локальные снимки дополнительного слоя (12 ч), даже если Modern UI
// ещё не открывали в этой вкладке. Старые versions удаляются одновременно.
try {
for (let index = localStorage.length - 1; index >= 0; index -= 1) {
const key = localStorage.key(index);
if (/^shine-network-(ties|subs|cities)-v\d+:/.test(key)) localStorage.removeItem(key);
}
} catch { /* storage может быть недоступен */ }
if (typeof window !== 'undefined') window.dispatchEvent(new Event(CONNECTIONS_GRAPH_CHANGED));
}
export async function getConnectionsGraphCached(service, login, { force = false, retries = 0 } = {}) {
const clean = String(login || '').trim();
if (!clean) throw new Error('LOGIN_REQUIRED');
const key = cacheKey(service, clean);
if (!force) {
const graph = cachedConnectionsGraph(service, clean);
if (graph) return graph;
}
// Включая принудительную загрузку: не запускаем параллельных запросов одного графа.
if (inflight.has(key)) return inflight.get(key);
const startedAtGeneration = generation;
const request = (async () => {
let lastError = null;
for (let attempt = 0; attempt <= Math.max(0, retries); attempt += 1) {
try {
const graph = await service.getUserConnectionsGraph(clean);
if (startedAtGeneration !== generation) {
// Запись произошла во время запроса: нельзя возвращать старый снимок.
return getConnectionsGraphCached(service, clean, { force: true, retries });
}
cache.delete(key);
cache.set(key, { graph, savedAt: Date.now() });
while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
return graph;
} catch (error) {
lastError = error;
if (attempt < retries) await new Promise((resolve) => setTimeout(resolve, 120 * (attempt + 1)));
}
}
throw lastError || new Error('GRAPH_LOAD_FAILED');
})();
inflight.set(key, request);
try { return await request; }
finally { if (inflight.get(key) === request) inflight.delete(key); }
}
@@ -0,0 +1,33 @@
// Один tag на пару (получатель, отправитель); одинаковый для фонового WS и Web Push.
export function dmNotificationTag(toLogin, fromLogin) {
const to = encodeURIComponent(String(toLogin || '').trim().toLowerCase());
const from = encodeURIComponent(String(fromLogin || '').trim().toLowerCase());
return `shine-dm:${to}:${from}`;
}
export function dmUnreadLabel(count) {
const n = Math.max(1, Math.trunc(Number(count) || 1));
const lastTwo = n % 100;
const last = n % 10;
if (!(lastTwo >= 11 && lastTwo <= 14) && last === 1) return `${n} непрочитанное сообщение`;
if (!(lastTwo >= 11 && lastTwo <= 14) && last >= 2 && last <= 4) return `${n} непрочитанных сообщения`;
return `${n} непрочитанных сообщений`;
}
// Локальное прочтение: закрываем notification и сообщаем SW, чтобы старый push его не вернул.
export async function closeDmNotification(toLogin, fromLogin) {
if (!toLogin || !fromLogin || !('serviceWorker' in navigator)) return;
try {
const registration = await navigator.serviceWorker.getRegistration();
if (!registration) return;
const tag = dmNotificationTag(toLogin, fromLogin);
const notifications = await registration.getNotifications({ tag });
const latestSeenVersionMs = notifications.reduce((latest, notification) =>
Math.max(latest, Number(notification.data?.notificationVersionMs || 0)), 0);
notifications.forEach((notification) => notification.close());
const worker = navigator.serviceWorker.controller || registration.active;
worker?.postMessage({ type: 'SHINE_DM_READ', toLogin, fromLogin, latestSeenVersionMs });
} catch {
// Недоступность браузерного API не мешает прочтению сообщений.
}
}
+6
View File
@@ -1,4 +1,5 @@
import { AuthService } from './services/auth-service.js';
import { closeDmNotification } from './services/dm-push-notifications.js';
import { listStoredMessages, putStoredMessage, deleteStoredMessage, clearStoredMessages } from './services/message-store.js';
import { rpcEndpointFromShineHttp, setSolanaCluster } from './services/solana-rpc-gateway.js';
import {
@@ -956,6 +957,11 @@ export function markChatRead(chatId) {
changed += 1;
}
});
// Вызывается только когда чат действительно просматривается; даже если локальный счётчик уже 0,
// надо снять системное уведомление, полученное до открытия страницы.
if (state.session?.login && normalizedChatId) {
void closeDmNotification(state.session.login, normalizedChatId);
}
return changed;
}
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
getConnectionsGraphCached,
cachedConnectionsGraph,
invalidateConnectionsGraphCache,
CONNECTIONS_GRAPH_CHANGED,
} from '../js/services/connections-graph-cache.js';
import { peopleFromGraphModel } from '../js/pages/network/adapter.js';
import { engineModelFromGraphModel } from '../js/pages/network-legacy/adapter.js';
const screenPaths = ['../js/pages/network-view.js', '../js/pages/network-legacy/network-view.js'];
// Исполняем саму функцию построения модели из каждого экрана в минимальном окружении.
// Это проверяет реальные реализации, не требуя браузерного DOM для огромных экранов.
function graphModelBuilder(relativePath) {
const code = readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8');
const functionSource = code.slice(code.indexOf('function buildGraphModel('));
const stop = functionSource.indexOf('\n}\n');
assert.ok(stop > 0, `${relativePath}: buildGraphModel не найдена`);
const normalizeLogin = (value) => String(value || '').trim();
const normKey = (value) => normalizeLogin(value).toLowerCase();
const uniqueLogins = (values) => [...new Map(values.map((value) => [normKey(value), normalizeLogin(value)])).values()];
const toSet = (values) => new Set(uniqueLogins(values || []).map(normKey));
const hasLogin = (set, value) => set.has(normKey(value));
const getMarkByLogin = (rows) => new Map((rows || []).map((row) => [normKey(row.login), row]));
const state = { session: { login: 'alice' } };
const body = `${functionSource.slice(0, stop + 2)}\nreturn buildGraphModel;`;
return new Function('normalizeLogin', 'normKey', 'uniqueLogins', 'toSet', 'hasLogin', 'getMarkByLogin', 'state', 'GENDER_UNKNOWN', body)(
normalizeLogin, normKey, uniqueLogins, toSet, hasLogin, getMarkByLogin, state, 'unknown',
);
}
for (const path of screenPaths) {
test(`граф ${path}: только исходящие друзья и строгая взаимность`, () => {
const build = graphModelBuilder(path);
const graph = {
login: 'alice',
outFriends: ['Bob', 'Jill'],
outCloseFriends: ['Cara'],
inFriends: ['BOB', 'Nope'],
inCloseFriends: ['Lisa'],
outContacts: ['Contact'],
inContacts: ['Jill', 'IncomingContact'],
outFollows: ['Follow'],
};
const result = build(graph, 'alice');
assert.deepEqual(result.relations.map((r) => r.login), ['Cara', 'Bob', 'Jill']);
assert.equal(result.relations.find((r) => r.login === 'Cara').relationType, 'close_friend');
assert.equal(result.relations.find((r) => r.login === 'Bob').backward, true);
assert.equal(result.relations.find((r) => r.login === 'Jill').backward, false,
'Контакт в ответ не превращает одностороннюю дружбу во взаимную');
assert.equal(result.relations.find((r) => r.login === 'Cara').backward, false);
assert.deepEqual(build({ login: 'alice', inFriends: ['OnlyIncoming'], outContacts: ['OnlyContact'] }, 'alice').relations, []);
});
}
test('адаптеры обеих версий получают одинаковую взаимность и тип дружбы', () => {
const model = graphModelBuilder(screenPaths[0])({
login: 'alice', outFriends: ['bob'], outCloseFriends: ['cara'], inFriends: ['cara'],
}, 'alice');
const modern = peopleFromGraphModel(model).peers;
const legacy = engineModelFromGraphModel(model).nodes.slice(1);
assert.deepEqual(modern.map((peer) => [peer.person.login, peer.relationType, peer.mutual]),
[['cara', 'close_friend', true], ['bob', 'friend', false]]);
assert.deepEqual(legacy.map((peer) => [peer.login, peer.relationType, peer.mutual]),
[['cara', 'close_friend', true], ['bob', 'friend', false]]);
});
test('TTL графа — 2 минуты: до истечения повторный запрос не нужен', async () => {
const originalNow = Date.now;
let now = 10_000_000;
Date.now = () => now;
try {
invalidateConnectionsGraphCache();
let queries = 0;
const service = { serverUrl: 'wss://ttl.test', async getUserConnectionsGraph() { return { queries: ++queries }; } };
await getConnectionsGraphCached(service, 'alice');
now += 119_999;
assert.equal((await getConnectionsGraphCached(service, 'alice')).queries, 1);
now += 1;
assert.equal((await getConnectionsGraphCached(service, 'alice')).queries, 2);
} finally { Date.now = originalNow; }
});
test('общий кэш: два экрана / серверы / инвалидация / изменение в незавершённом запросе', async () => {
const previousWindow = globalThis.window;
const windowMock = new EventTarget();
globalThis.window = windowMock;
try {
let seen = 0;
windowMock.addEventListener(CONNECTIONS_GRAPH_CHANGED, () => { seen += 1; });
let queries = 0;
const service = { serverUrl: 'wss://first.test', async getUserConnectionsGraph() { return { version: ++queries }; } };
const first = await getConnectionsGraphCached(service, 'Alice');
const second = await getConnectionsGraphCached(service, 'ALICE');
assert.strictEqual(first, second);
assert.equal(queries, 1);
assert.strictEqual(cachedConnectionsGraph(service, 'alice'), first);
const secondServer = { serverUrl: 'wss://second.test', async getUserConnectionsGraph() { return { version: 77 }; } };
assert.equal((await getConnectionsGraphCached(secondServer, 'alice')).version, 77);
invalidateConnectionsGraphCache();
assert.equal(seen, 1);
assert.equal(cachedConnectionsGraph(service, 'alice'), null);
assert.equal((await getConnectionsGraphCached(service, 'alice')).version, 2);
let releaseOld;
let current = 0;
const pendingService = { serverUrl: 'wss://pending.test', getUserConnectionsGraph() {
current += 1;
return current === 1 ? new Promise((resolve) => { releaseOld = resolve; }) : Promise.resolve({ version: 'new' });
} };
const pending = getConnectionsGraphCached(pendingService, 'alice', { force: true });
invalidateConnectionsGraphCache();
releaseOld({ version: 'old' });
assert.equal((await pending).version, 'new', 'ответ старого запроса не должен воскресить устаревший снимок');
assert.equal(cachedConnectionsGraph(pendingService, 'alice').version, 'new');
} finally {
globalThis.window = previousWindow;
}
});
+54
View File
@@ -0,0 +1,54 @@
const fs=require('fs');
const path=require('path');
const vm=require('vm');
const assert=require('assert');
const registrations=[];
const events={};
const stateDb=new Map();
const notifications=new Map();
const cacheObj={
async match(key){return stateDb.get(key)?.clone() || null},
async put(key, response){stateDb.set(key, response)},
};
const context={
self:{
__shineStoppedCalls:new Map(),
registration:{scope:'https://shineup.me/',
async showNotification(title, options){ registrations.push({title,options}); if(options.tag) notifications.set(options.tag,{data:options.data, close(){ notifications.delete(options.tag) }}) },
async getNotifications({tag}){return notifications.get(tag)?[notifications.get(tag)]:[]},
},
clients:{async matchAll(){return []}},
addEventListener(name, handler){events[name]=handler},
skipWaiting(){},
},
caches:{async open(){return cacheObj}},
Response, URL, Promise, Date, Number, String, Math, Map, Object, JSON, encodeURIComponent,
};
vm.createContext(context);
vm.runInContext(fs.readFileSync(path.resolve(__dirname, '../firebase-messaging-sw.js'),'utf8'), context);
async function push(data){const pending=[];events.push({data:{text(){return JSON.stringify(data)}}, waitUntil(p){pending.push(p)}});await Promise.all(pending)}
async function read(to,from){const pending=[];events.message({data:{type:'SHINE_DM_READ',toLogin:to,fromLogin:from},waitUntil(p){pending.push(p)}});await Promise.all(pending)}
(async()=>{
for(let i=1;i<=5;i++){
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:`m${i}`,unreadCount:i,notificationVersionMs:1000+i});
}
assert.strictEqual(registrations.length,5,'every new message renotifies');
assert(registrations.every(x=>x.options.renotify===true && x.options.silent===false));
assert.strictEqual(notifications.size,1,'one tag per conversation');
assert.strictEqual(registrations.at(-1).options.body,'5 непрочитанных сообщений');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Kolya',messageKey:'k1',unreadCount:2,notificationVersionMs:2000});
assert.strictEqual(notifications.size,2);
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m5',unreadCount:5,notificationVersionMs:1005});
assert.strictEqual(registrations.length,6,'duplicate push ignored');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m6',unreadCount:4,notificationVersionMs:1003});
assert.strictEqual(registrations.at(-1).options.body,'5 непрочитанных сообщений','late push cannot downgrade unread count');
await read('AnNa','Vasya');
assert.strictEqual(notifications.size,1,'read closes only Vasya notification');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m7',unreadCount:4,notificationVersionMs:1004});
assert.strictEqual(notifications.size,1,'old push after read suppressed');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m8',unreadCount:1,notificationVersionMs:1008});
assert.strictEqual(notifications.size,2,'new push after read can notify');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'MashA',messageKey:'z1',unreadCount:21,notificationVersionMs:3000});
assert.strictEqual(registrations.at(-1).options.body,'21 непрочитанное сообщение');
console.log('PASS: 5 alerts, tags per conversation, counter, replay suppression, late-push ordering, read close and newer-push delivery');
})().catch(e=>{console.error(e);process.exitCode=1});