import { formatDate, formatTime } from '../i18n/format.js'; // Настройки личных чатов на этом устройстве: «без звука» (навсегда или до срока) и «закреплён». // Сервер про них не знает: хранятся в localStorage отдельно для каждого аккаунта. // Список «без звука» дублируется в Cache Storage, чтобы его видел service worker: // push о новом сообщении от такого собеседника не показывается, пока приложение закрыто. import { normalizeDmChatId, state } from '../state.js'; const STORAGE_PREFIX = 'shine-dm-chat-prefs-v1:'; const SW_CACHE_NAME = 'shine-dm-prefs'; const SW_CACHE_URL = '/__shine/dm-muted.json'; export const DM_CHAT_PREFS_EVENT = 'shine-dm-chat-prefs-updated'; function ownerLogin() { return String(state.session?.login || '').trim().toLowerCase(); } // muted – список собеседников; mutedUntil – срок (мс) для тех, у кого звук выключен на время. // Нет срока – «без звука» навсегда (так же понимают список и прежние версии приложения). function parsePrefs(raw) { const untilRaw = raw?.mutedUntil && typeof raw.mutedUntil === 'object' ? raw.mutedUntil : {}; // Без прототипа: логин вроде «constructor» не должен находить чужие свойства. const mutedUntil = Object.create(null); Object.entries(untilRaw).forEach(([id, until]) => { if (Number(until) > 0) mutedUntil[id] = Number(until); }); return { muted: Array.isArray(raw?.muted) ? raw.muted.map(String) : [], pinned: Array.isArray(raw?.pinned) ? raw.pinned.map(String) : [], mutedUntil, }; } function readPrefs() { const owner = ownerLogin(); if (!owner) return parsePrefs(null); try { return parsePrefs(JSON.parse(localStorage.getItem(STORAGE_PREFIX + owner) || '{}')); } catch { return parsePrefs(null); } } // Чей срок «без звука» ещё не вышел: { собеседник: срок, 0 – навсегда }. function activeMutes(prefs, now = Date.now()) { const result = Object.create(null); prefs.muted.forEach((id) => { const until = Number(prefs.mutedUntil[id] || 0); if (!until || until > now) result[id] = until; }); return result; } function writePrefs(prefs) { const owner = ownerLogin(); if (!owner) return; // Истёкшие сроки при записи убираются, чтобы список не копился. const active = activeMutes(prefs); const next = { muted: prefs.muted.filter((id) => id in active), pinned: prefs.pinned, mutedUntil: Object.fromEntries(Object.entries(active).filter(([, until]) => until > 0)), }; try { localStorage.setItem(STORAGE_PREFIX + owner, JSON.stringify(next)); } catch { // Приватный режим или переполненное хранилище: настройка проживёт до перезагрузки вкладки. } void syncMutedForServiceWorker(); scheduleExpiry(next); window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT)); } // Когда срок «без звука» выходит, пока приложение открыто, списки и шапка чата узнают об этом // тем же событием, что и о ручном включении звука. let expiryTimer = 0; function scheduleExpiry(prefs = readPrefs()) { if (expiryTimer) window.clearTimeout(expiryTimer); expiryTimer = 0; const now = Date.now(); const nearest = Math.min(...Object.values(activeMutes(prefs, now)).filter((until) => until > now)); if (!Number.isFinite(nearest)) return; expiryTimer = window.setTimeout(() => { expiryTimer = 0; void syncMutedForServiceWorker(); window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT)); scheduleExpiry(); }, Math.min(nearest - now + 250, 2 ** 31 - 1)); } function ensureExpiryScheduled(prefs) { if (!expiryTimer) scheduleExpiry(prefs); } // Все аккаунты этого устройства: push приходит с toLogin, и worker сверяет пару «кому – от кого». // Формат для worker: { владелец: { собеседник: срок в мс, 0 – навсегда } }. async function syncMutedForServiceWorker() { try { if (!globalThis.caches) return; const muted = {}; const now = Date.now(); for (let i = 0; i < localStorage.length; i += 1) { const key = localStorage.key(i) || ''; if (!key.startsWith(STORAGE_PREFIX)) continue; const active = activeMutes(parsePrefs(JSON.parse(localStorage.getItem(key) || '{}')), now); if (Object.keys(active).length) muted[key.slice(STORAGE_PREFIX.length)] = active; } const cache = await caches.open(SW_CACHE_NAME); await cache.put(SW_CACHE_URL, new Response(JSON.stringify(muted), { headers: { 'Content-Type': 'application/json' } })); } catch { // Без Cache Storage «без звука» действует только пока приложение открыто. } } function toggleIn(listName, chatId, enabled) { const id = normalizeDmChatId(chatId); if (!id) return; const prefs = readPrefs(); const rest = prefs[listName].filter((x) => x !== id); prefs[listName] = enabled ? [id, ...rest] : rest; return { id, prefs }; } export function isDmChatMuted(chatId) { const prefs = readPrefs(); ensureExpiryScheduled(prefs); return normalizeDmChatId(chatId) in activeMutes(prefs); } // Срок «без звука»: null – звук включён, 0 – выключен навсегда, иначе время (мс), когда включится. export function getDmChatMutedUntil(chatId) { const active = activeMutes(readPrefs()); const id = normalizeDmChatId(chatId); return id in active ? active[id] : null; } // untilMs – когда звук включится сам; 0 – «навсегда». export function setDmChatMuted(chatId, muted, { untilMs = 0 } = {}) { const result = toggleIn('muted', chatId, muted); if (!result) return; const { id, prefs } = result; if (muted && Number(untilMs) > Date.now()) prefs.mutedUntil[id] = Number(untilMs); else delete prefs.mutedUntil[id]; writePrefs(prefs); } export function isDmChatPinned(chatId) { return readPrefs().pinned.includes(normalizeDmChatId(chatId)); } export function setDmChatPinned(chatId, pinned) { const result = toggleIn('pinned', chatId, pinned); if (result) writePrefs(result.prefs); } // Порядок закреплённых: последний закреплённый – выше всех. export function getPinnedDmChats() { return readPrefs().pinned; } // Чаты «без звука» – для списка в настройках уведомлений: [{ chatId, until }], until 0 – навсегда. export function getMutedDmChats() { const prefs = readPrefs(); ensureExpiryScheduled(prefs); return Object.entries(activeMutes(prefs)).map(([chatId, until]) => ({ chatId, until })); } // «до 14:30», «до завтра, 9:00», «до 20 октября, 9:00»; для «навсегда» – пустая строка. export function formatDmMuteUntil(until, now = new Date()) { const value = Number(until || 0); if (!value) return ''; const date = new Date(value); const time = formatTime(date, { hour: 'numeric', minute: '2-digit' }); const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); const days = Math.round((startOfDay(date) - startOfDay(now)) / 86400000); if (days <= 0) return `до ${time}`; if (days === 1) return `до завтра, ${time}`; return `до ${formatDate(date, { day: 'numeric', month: 'long' })}, ${time}`; }