SHA256
34 lines
1.9 KiB
JavaScript
34 lines
1.9 KiB
JavaScript
// Один 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 не мешает прочтению сообщений.
|
|
}
|
|
}
|