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

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
+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