SHA256
39 lines
2.0 KiB
JavaScript
39 lines
2.0 KiB
JavaScript
import { getLanguage, t } from '../i18n/index.js';
|
|
|
|
// Один 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));
|
|
if (getLanguage() === 'en') {
|
|
return t(n === 1 ? 'notifications.dm_unread_one' : 'notifications.dm_unread_many', { count: n });
|
|
}
|
|
const lastTwo = n % 100;
|
|
const last = n % 10;
|
|
if (!(lastTwo >= 11 && lastTwo <= 14) && last === 1) return t('notifications.dm_unread_one', { count: n });
|
|
if (!(lastTwo >= 11 && lastTwo <= 14) && last >= 2 && last <= 4) return t('notifications.dm_unread_few', { count: n });
|
|
return t('notifications.dm_unread_many', { count: 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 не мешает прочтению сообщений.
|
|
}
|
|
}
|