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

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
+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 не мешает прочтению сообщений.
}
}