Files
SHiNE-server/shine-UI/firebase-messaging-sw.js
T

389 lines
14 KiB
JavaScript

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));
}
});
async function broadcastToClients(payload) {
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
clients.forEach((client) => {
client.postMessage({
type: 'SHINE_WEB_PUSH_EVENT',
payload,
});
});
}
async function broadcastCallActionToClients(action, payload) {
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
clients.forEach((client) => {
client.postMessage({
type: 'SHINE_CALL_PUSH_ACTION',
action,
payload,
});
});
}
function rememberStoppedCall(callId, sentAtMs = 0) {
if (!callId) return;
const now = Date.now();
const markAtMs = Number.isFinite(Number(sentAtMs)) ? Number(sentAtMs) : now;
self.__shineStoppedCalls.set(callId, Math.max(now, markAtMs));
const cutoff = now - 10 * 60 * 1000;
for (const [id, ts] of self.__shineStoppedCalls.entries()) {
if (Number(ts || 0) < cutoff) self.__shineStoppedCalls.delete(id);
}
}
function isCallStopped(callId, sentAtMs = 0) {
if (!callId) return false;
const stoppedAt = Number(self.__shineStoppedCalls.get(callId) || 0);
if (!stoppedAt) return false;
const incomingAt = Number.isFinite(Number(sentAtMs)) ? Number(sentAtMs) : 0;
return incomingAt <= 0 || incomingAt <= stoppedAt;
}
async function closeCallNotification(callId) {
if (!callId) return;
const list = await self.registration.getNotifications({ tag: callId });
list.forEach((n) => {
try { n.close(); } catch {}
});
}
function decodePushJson(rawText) {
try {
if (!rawText) return {};
return JSON.parse(rawText);
} catch {
return {};
}
}
function encodeCallPushPayloadForUrl(payload) {
try {
return encodeURIComponent(JSON.stringify(payload || {}));
} catch {
return '';
}
}
// Чаты «без звука» (пишет приложение, см. js/services/dm-chat-prefs.js):
// { владелец: { собеседник: срок в мс, 0 – навсегда } }; прежний формат – { владелец: [собеседники] }.
async function isMutedDirectMessage(toLogin, fromLogin) {
try {
const owner = String(toLogin || '').trim().toLowerCase();
const peer = String(fromLogin || '').trim().toLowerCase();
if (!peer) return false;
const cache = await caches.open('shine-dm-prefs');
const response = await cache.match('/__shine/dm-muted.json');
if (!response) return false;
const muted = await response.json();
// Сервер сейчас не кладёт в push получателя: тогда смотрим списки всех аккаунтов этого устройства.
const lists = owner ? [muted?.[owner]] : Object.values(muted || {});
const now = Date.now();
return lists.some((list) => {
if (Array.isArray(list)) return list.includes(peer);
if (!list || typeof list !== 'object' || !Object.prototype.hasOwnProperty.call(list, peer)) return false;
const until = Number(list[peer] || 0);
return !until || until > now;
});
} catch {
return false;
}
}
// Идентификатор совпадает с 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 = '';
let kind = '';
let fromLogin = '';
let title = '';
try {
if (event.data) {
const text = event.data.text();
rawText = text || '';
const json = decodePushJson(rawText);
kind = String(json.kind || '');
title = String(json.title || '');
body = String(json.text || '');
fromLogin = String(json.fromLogin || '');
if (!kind && rawText) {
body = rawText || '';
}
}
} catch {
// ignore
}
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();
const toLogin = String(json.toLogin || '').trim();
const reason = String(json.reason || '').trim();
const sentAtMs = Number(json.sentAtMs || 0);
const expiresAtMs = Number(json.expiresAtMs || 0);
const nowMs = Date.now();
if (kind === 'stop_call' && callId) {
rememberStoppedCall(callId, sentAtMs || nowMs);
}
const isExpiredIncomingCall = kind === 'incoming_call'
&& Number.isFinite(expiresAtMs)
&& expiresAtMs > 0
&& nowMs > expiresAtMs;
const isIncomingCallAlreadyStopped = kind === 'incoming_call' && callId && isCallStopped(callId, sentAtMs || nowMs);
const shouldNotify = (
kind === 'test_push'
|| (kind === 'incoming_call' && !isExpiredIncomingCall && !isIncomingCallAlreadyStopped)
|| (!kind && body)
);
const notificationTitle = kind === 'test_push'
? (title || 'SHiNE: тестовый push')
: (kind === 'incoming_call'
? 'SHiNE: входящий звонок'
: 'SHiNE: входящее сообщение');
const notifyPromise = shouldNotify
? self.registration.showNotification(notificationTitle, {
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
renotify: true,
requireInteraction: kind === 'incoming_call',
data: {
kind,
callId,
fromLogin,
fromSessionId,
targetSessionId,
toLogin,
sentAtMs,
expiresAtMs,
reason,
},
actions: kind === 'incoming_call'
? [
{ action: 'accept', title: 'Ответить' },
{ action: 'decline', title: 'Сбросить' },
]
: [],
})
: Promise.resolve();
const closeOnStopPromise = kind === 'stop_call' && callId
? closeCallNotification(callId)
: Promise.resolve();
event.waitUntil(Promise.all([
notifyPromise,
closeOnStopPromise,
broadcastToClients({
kind,
body,
fromLogin,
fromSessionId,
targetSessionId,
toLogin,
callId,
sentAtMs,
expiresAtMs,
reason,
stale: isExpiredIncomingCall || isIncomingCallAlreadyStopped,
rawText,
receivedAt: nowMs,
}),
]));
});
self.addEventListener('notificationclick', (event) => {
event.notification?.close();
const action = String(event?.action || '').trim().toLowerCase();
const data = event?.notification?.data || {};
const payload = {
kind: String(data.kind || '').trim(),
callId: String(data.callId || '').trim(),
fromLogin: String(data.fromLogin || '').trim(),
fromSessionId: String(data.fromSessionId || '').trim(),
targetSessionId: String(data.targetSessionId || '').trim(),
toLogin: String(data.toLogin || '').trim(),
sentAtMs: Number(data.sentAtMs || 0),
expiresAtMs: Number(data.expiresAtMs || 0),
reason: String(data.reason || '').trim(),
};
event.waitUntil((async () => {
if ((action === 'accept' || action === 'decline') && payload.callId) {
await broadcastCallActionToClients(action, payload);
}
const allClients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
const existing = allClients[0] || null;
const openUrlBase = './index.html';
const encodedPayload = encodeCallPushPayloadForUrl(payload);
const openUrl = (action === 'accept' || action === 'decline')
? `${openUrlBase}?callPushAction=${encodeURIComponent(action)}&callPushPayload=${encodedPayload}`
: `${openUrlBase}?pushOpenPayload=${encodedPayload}`;
if (existing) {
try {
if (action === 'accept' || action === 'decline') {
existing.postMessage({
type: 'SHINE_CALL_PUSH_ACTION',
action,
payload,
});
} else {
existing.postMessage({
type: 'SHINE_NOTIFICATION_CLICK',
payload,
});
}
} catch {}
await existing.focus();
return;
}
await self.clients.openWindow(openUrl);
})());
});