diff --git a/VERSION.properties b/VERSION.properties index ae0a1277..cb4690de 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.19.0 +client.version=1.19.1 server.version=1.15.0 diff --git a/docs/Personal_Messages/Протокол_DM_v1.md b/docs/Personal_Messages/Протокол_DM_v1.md index 75319d4d..6e3e5c0e 100644 --- a/docs/Personal_Messages/Протокол_DM_v1.md +++ b/docs/Personal_Messages/Протокол_DM_v1.md @@ -228,6 +228,15 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает Это правило не меняет wire/API-формат DM и не меняет байтовый формат tombstone. +## UI чата: поиск, переход к дате, «Медиа и файлы», «без звука», закрепление (12.10.2026) + +Всё ниже работает на клиенте и не меняет ни формат DM, ни серверный API. + +- Поиск по переписке и календарь «перейти к дате» работают по расшифрованным сообщениям на устройстве. Если история загружена не целиком, клиент сам долистывает её обычным `GetDirectMessages` (страницы по 50) до начала. Экран «Медиа и файлы» (`/chat//media`) делает то же самое и показывает фото и видео (`` до 20 МБ) сеткой, а остальные файлы списком. Голосовые в этот экран не попадают. +- При разборе страницы истории ключ `clientKey` достаётся из локального хранилища ключей один раз на страницу, а не для каждого сообщения. Сама расшифровка (X25519 + HKDF + AES-GCM) не меняется. +- «Без звука» и «закреплён» – настройки этого устройства. Они хранятся в `localStorage` отдельно для каждого `ownerLogin`, на сервер не передаются и с другими устройствами не синхронизируются. Для чата «без звука» входящее сообщение доставляется и считается непрочитанным как обычно, но клиент не проигрывает сигнал и не показывает системное уведомление. Список таких чатов дублируется в Cache Storage, чтобы service worker не показывал push `new_message` от этого собеседника. Если в push нет `toLogin`, проверяются списки всех профилей устройства. +- Закреплённые чаты показываются в списке выше остальных, независимо от фильтра по типу связи. Последний закреплённый показывается первым. + ## 15. Файлы в личных сообщениях diff --git a/shine-UI/firebase-messaging-sw.js b/shine-UI/firebase-messaging-sw.js index 47df1f1f..aae1aad2 100644 --- a/shine-UI/firebase-messaging-sw.js +++ b/shine-UI/firebase-messaging-sw.js @@ -74,6 +74,24 @@ function encodeCallPushPayloadForUrl(payload) { } } +// Чаты «без звука» (список пишет приложение, см. js/services/dm-chat-prefs.js): { владелец: [собеседники] }. +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 || {}); + return lists.some((list) => Array.isArray(list) && list.includes(peer)); + } catch { + return false; + } +} + self.addEventListener('push', (event) => { let body = ''; let rawText = ''; @@ -130,7 +148,7 @@ self.addEventListener('push', (event) => { : 'SHiNE: входящее сообщение'); const notifyPromise = shouldNotify - ? self.registration.showNotification(notificationTitle, { + ? (kind === 'new_message' ? isMutedDirectMessage(toLogin, fromLogin) : Promise.resolve(false)).then((muted) => (muted ? undefined : self.registration.showNotification(notificationTitle, { body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'), tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'), renotify: true, @@ -152,7 +170,7 @@ self.addEventListener('push', (event) => { { action: 'decline', title: 'Сбросить' }, ] : [], - }) + }))) : Promise.resolve(); const closeOnStopPromise = kind === 'stop_call' && callId diff --git a/shine-UI/index.html b/shine-UI/index.html index 093fcddc..d92467ec 100644 --- a/shine-UI/index.html +++ b/shine-UI/index.html @@ -39,21 +39,35 @@ }()); + diff --git a/shine-UI/js/app.js b/shine-UI/js/app.js index 3439dc31..38fa853a 100644 --- a/shine-UI/js/app.js +++ b/shine-UI/js/app.js @@ -103,6 +103,8 @@ import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js'; import * as messagesList from './pages/messages-list.js?v=202609260900'; import * as contactSearchView from './pages/contact-search-view.js'; import * as chatView from './pages/chat-view.js?v=202609260900'; +import * as chatMediaView from './pages/chat-media-view.js'; +import { isDmChatMuted } from './services/dm-chat-prefs.js'; import * as userProfileView from './pages/user-profile-view.js'; import * as userProfileListView from './pages/user-profile-list-view.js'; import * as userRelationManageView from './pages/user-relation-manage-view.js'; @@ -175,6 +177,7 @@ const routes = { 'messages-list': messagesList, 'contact-search-view': contactSearchView, 'chat-view': chatView, + 'chat-media-view': chatMediaView, user: userProfileView, 'user-profile-list-view': userProfileListView, 'user-relation-manage-view': userRelationManageView, @@ -1818,7 +1821,8 @@ async function init() { if (added && isIncomingForCurrent) { shouldRefreshToolbarUnread = true; } - if (added && isIncomingForCurrent && !payload.backlog) { + // Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления. + if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) { const parsedText = parseDmTechBlocks(text); const displayText = String(parsedText.displayText || ''); const suppressHiddenNotification = parsedText.callSummary?.status === 'completed'; diff --git a/shine-UI/js/components/dm-attachments.js b/shine-UI/js/components/dm-attachments.js new file mode 100644 index 00000000..1635db08 --- /dev/null +++ b/shine-UI/js/components/dm-attachments.js @@ -0,0 +1,95 @@ +// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать». +// Общие для ленты чата и экрана «Медиа и файлы». +import { decryptDmFileToBlob, downloadAndDecryptDmFile, formatDmFileSize } from '../services/dm-file-service.js'; +import { getAttachmentKind } from '../services/attachment-format.js'; +import { showToast } from '../services/channels-ux.js'; + +// Картинки и видео в личке показываются так же, как в каналах (карусель + просмотрщик), +// только файл сначала расшифровывается. Большие файлы остаются карточками со «Скачать», +// чтобы не тратить трафик на автозагрузку. +const DM_INLINE_MEDIA_MAX_BYTES = 20 * 1024 * 1024; +const DM_MEDIA_MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml', mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg' }; +const dmMediaBlobs = new Map(); +const DM_MEDIA_CACHE_LIMIT = 40; + +export function isDmInlineMedia(attachment) { + if (attachment?.kind === 'voice') return false; + const size = Number(attachment?.size || 0); + if (!(size > 0 && size <= DM_INLINE_MEDIA_MAX_BYTES)) return false; + const kind = getAttachmentKind(attachment); + return kind === 'image' || kind === 'video'; +} + +// Расшифрованный файл держим в памяти: лента перерисовывается на каждое новое сообщение, +// и без кэша картинка расшифровывалась бы и мигала заново. +export function resolveDmMediaUrl(attachment) { + const key = String(attachment?.id || attachment?.url || ''); + let pending = dmMediaBlobs.get(key); + if (!pending) { + const ext = String(attachment?.name || '').split('.').pop().toLowerCase(); + pending = decryptDmFileToBlob(attachment) + .then((blob) => new Blob([blob], { type: DM_MEDIA_MIME[ext] || blob.type || 'application/octet-stream' })); + pending.catch(() => dmMediaBlobs.delete(key)); + dmMediaBlobs.set(key, pending); + if (dmMediaBlobs.size > DM_MEDIA_CACHE_LIMIT) dmMediaBlobs.delete(dmMediaBlobs.keys().next().value); + } + return pending.then((blob) => ({ url: URL.createObjectURL(blob), objectUrl: true })); +} + +export function createDmFileAttachmentCard(attachment) { + const fileCard = document.createElement('div'); + fileCard.className = 'dm-file-card'; + + const fileIcon = document.createElement('span'); + fileIcon.className = 'dm-file-card__icon'; + fileIcon.textContent = '📎'; + + const fileCopy = document.createElement('span'); + fileCopy.className = 'dm-file-card__copy'; + const fileName = document.createElement('strong'); + fileName.className = 'dm-file-card__name'; + fileName.textContent = attachment.name || 'file'; + const fileMeta = document.createElement('span'); + fileMeta.className = 'dm-file-card__meta'; + const metaParts = [formatDmFileSize(attachment.size)]; + if (Number(attachment?.version || 1) >= 2) metaParts.push('BitTorrent v2'); + fileMeta.textContent = metaParts.join(' · '); + fileCopy.append(fileName, fileMeta); + + const downloadBtn = document.createElement('button'); + downloadBtn.type = 'button'; + downloadBtn.className = 'ui-button dm-file-card__download'; + downloadBtn.textContent = 'Скачать'; + downloadBtn.addEventListener('click', async (event) => { + event.stopPropagation(); + if (downloadBtn.disabled) return; + downloadBtn.disabled = true; + const previousLabel = downloadBtn.textContent; + downloadBtn.textContent = 'Скачивание…'; + try { + const result = await downloadAndDecryptDmFile(attachment, { + onProgress: ({ processedBytes, totalBytes }) => { + if (!totalBytes) return; + const percent = Math.min(100, Math.max(0, Math.round((processedBytes / totalBytes) * 100))); + downloadBtn.textContent = `${percent}%`; + }, + }); + if (!result?.cancelled) { + showToast( + result?.streamed + ? 'Файл расшифрован по частям и сохранён напрямую на диск' + : 'Файл расшифрован и передан браузеру для сохранения', + { timeoutMs: 1800 }, + ); + } + } catch (error) { + showToast(error?.message || 'Не удалось скачать файл', { kind: 'error', timeoutMs: 2800 }); + } finally { + downloadBtn.disabled = false; + downloadBtn.textContent = previousLabel; + } + }); + + fileCard.append(fileIcon, fileCopy, downloadBtn); + return fileCard; +} diff --git a/shine-UI/js/components/person-note-sheet.js b/shine-UI/js/components/person-note-sheet.js new file mode 100644 index 00000000..a5da4174 --- /dev/null +++ b/shine-UI/js/components/person-note-sheet.js @@ -0,0 +1,91 @@ +// Шторка «Заметка о человеке»: текст и цветная метка, видны только владельцу аккаунта. +// Открывается с карты связей и из профиля человека; хранение – services/people-notes.js. +import { openSheet } from './sheet.js'; +import { NOTE_MARKS, PERSON_NOTE_MAX_TEXT, getPersonNote, setPersonNote } from '../services/people-notes.js'; + +export function openPersonNoteSheet({ login, name = '', onClose = null } = {}) { + const current = getPersonNote(login); + let mark = current?.mark || ''; + return openSheet({ + title: `Заметка: ${name || login}`, + className: 'person-note-sheet', + onClose, + content: (sheet) => { + const wrap = document.createElement('div'); + wrap.className = 'stack person-note'; + const hint = document.createElement('p'); + hint.className = 'meta-muted person-note__hint'; + hint.textContent = 'Видна только вам. Пока хранится на этом устройстве.'; + const textarea = document.createElement('textarea'); + textarea.className = 'input person-note__text'; + textarea.rows = 5; + textarea.maxLength = PERSON_NOTE_MAX_TEXT; + textarea.placeholder = 'Кто это, откуда знакомы, о чём договорились…'; + textarea.value = current?.text || ''; + textarea.setAttribute('aria-label', 'Текст заметки'); + textarea.autofocus = true; + + const marksLabel = document.createElement('div'); + marksLabel.className = 'person-note__label'; + marksLabel.id = `person-note-marks-${Math.random().toString(36).slice(2, 8)}`; + marksLabel.textContent = 'Метка на карте связей'; + const marks = document.createElement('div'); + marks.className = 'person-note__marks'; + marks.setAttribute('role', 'radiogroup'); + marks.setAttribute('aria-labelledby', marksLabel.id); + const markButtons = []; + const syncMarks = () => markButtons.forEach((button) => button.setAttribute('aria-checked', String(button.dataset.mark === mark))); + for (const option of [{ id: '', label: 'Без метки' }, ...NOTE_MARKS]) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'person-note__mark'; + button.dataset.mark = option.id; + button.setAttribute('role', 'radio'); + button.setAttribute('aria-label', option.label); + button.title = option.label; + button.addEventListener('click', () => { mark = option.id; syncMarks(); }); + markButtons.push(button); + marks.append(button); + } + syncMarks(); + wrap.append(hint, textarea, marksLabel, marks); + + if (current) { + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'ghost-btn person-note__remove'; + remove.textContent = 'Удалить'; + remove.addEventListener('click', () => { + setPersonNote(login, { text: '', mark: '' }); + sheet.close(); + }); + sheet.footer.append(remove); + } + const save = document.createElement('button'); + save.type = 'button'; + save.className = 'primary-btn person-note__save'; + save.textContent = 'Сохранить'; + save.addEventListener('click', () => { + setPersonNote(login, { text: textarea.value, mark }); + sheet.close(); + }); + sheet.footer.append(save); + return wrap; + }, + }); +} + +// Готовый блок заметки (для карточки на карте и профиля); null, если заметки нет. +export function createPersonNotePreview(note, { className = '', onClick = null } = {}) { + if (!note) return null; + const el = document.createElement(onClick ? 'button' : 'div'); + if (onClick) { + el.type = 'button'; + el.title = 'Изменить заметку'; + el.addEventListener('click', onClick); + } + el.className = `person-note-preview${className ? ` ${className}` : ''}`; + if (note.mark) el.dataset.mark = note.mark; + el.textContent = note.text.trim() || 'Метка без текста'; + return el; +} diff --git a/shine-UI/js/components/ui-icon.js b/shine-UI/js/components/ui-icon.js index a5c829ab..be12e682 100644 --- a/shine-UI/js/components/ui-icon.js +++ b/shine-UI/js/components/ui-icon.js @@ -15,7 +15,8 @@ const paths = { emoji: '', send: '', mic: '', - image: '', + camera: '', + image: '', list: '', doc: '', close: '', @@ -35,6 +36,10 @@ const paths = { check: '', open: '', chevron: '', + 'chevron-up': '', + 'chevron-down': '', + calendar: '', + pin: '', back: '', down: '', edit: '', @@ -47,6 +52,9 @@ const paths = { repost: '', expand: '', clip: '', + minus: '', + fit: '', + focus: '', }; export function iconHtml(name, filled = false, className = '') { diff --git a/shine-UI/js/pages/chat-media-view.js b/shine-UI/js/pages/chat-media-view.js new file mode 100644 index 00000000..e729b57a --- /dev/null +++ b/shine-UI/js/pages/chat-media-view.js @@ -0,0 +1,244 @@ +// «Медиа и файлы» личной переписки: сетка фото и видео и список документов по месяцам. +// История догружается с сервера целиком; превью расшифровываются, только когда плитка видна. +import { createTopBar } from '../components/topbar.js'; +import { iconHtml } from '../components/ui-icon.js'; +import { openMediaViewer } from '../components/media-viewer.js'; +import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js'; +import { getAttachmentKind } from '../services/attachment-format.js'; +import { parseDmTechBlocks } from '../services/dm-tech-blocks.js'; +import { loadFullDmHistory, resolveMessageTimeMs } from '../services/dm-history.js'; +import { formatClockTime, formatDayLabel } from '../services/channels-ux.js'; +import { getChatMessages, getRememberedDmPeer, normalizeDmChatId } from '../state.js'; +import { navigateUp } from '../router.js'; + +export const pageMeta = { id: 'chat-media-view', title: 'Медиа и файлы' }; + +const monthTitle = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' }); + +// Все вложения переписки, от новых к старым. +function collectAttachments(chatId) { + const media = []; + const files = []; + for (const msg of getChatMessages(chatId)) { + if (msg?.deleted) continue; + const parsed = parseDmTechBlocks(String(msg?.text || '')); + const list = Array.isArray(parsed.fileAttachments) ? parsed.fileAttachments : (parsed.fileAttachment ? [parsed.fileAttachment] : []); + for (const attachment of list) { + if (attachment?.kind === 'voice') continue; + const entry = { attachment, timeMs: resolveMessageTimeMs(msg), from: msg?.from }; + (isDmInlineMedia(attachment) ? media : files).push(entry); + } + } + const newestFirst = (a, b) => b.timeMs - a.timeMs; + return { media: media.sort(newestFirst), files: files.sort(newestFirst) }; +} + +function groupByMonth(entries) { + const groups = []; + for (const entry of entries) { + const raw = entry.timeMs ? monthTitle.format(new Date(entry.timeMs)) : 'Без даты'; + const label = raw.charAt(0).toUpperCase() + raw.slice(1); + const last = groups[groups.length - 1]; + if (last?.label === label) last.items.push(entry); + else groups.push({ label, items: [entry] }); + } + return groups; +} + +export function render({ navigate, route, chrome }) { + const chatId = normalizeDmChatId(route?.params?.chatId); + const peer = getRememberedDmPeer(chatId); + const peerName = [peer?.firstName, peer?.lastName].map((x) => String(x || '').trim()).filter(Boolean).join(' ') || chatId; + const chatPath = `chat/${encodeURIComponent(chatId)}`; + + const screen = document.createElement('section'); + screen.className = 'stack chat-media-screen'; + let disposed = false; + let activeTab = 'media'; + let loading = true; + let loadFailed = false; + const objectUrls = new Set(); + const tileUrls = new Map(); // id файла → url для просмотрщика + const fileKey = (attachment) => String(attachment?.id || attachment?.url || ''); + + chrome?.setTopbar(createTopBar({ + title: 'Медиа и файлы', + back: { + onClick: () => navigateUp((r) => r.pageId === 'chat-view' && normalizeDmChatId(r.params?.chatId) === chatId, chatPath), + }, + })); + + const subtitle = document.createElement('p'); + subtitle.className = 'meta-muted chat-media-peer'; + subtitle.textContent = `Переписка с ${peerName}`; + + const tabs = document.createElement('div'); + tabs.className = 'tabs tabs--auto tabs--dense chat-media-tabs'; + tabs.setAttribute('role', 'radiogroup'); + tabs.setAttribute('aria-label', 'Что показать'); + const tabButtons = new Map(); + for (const [value, label] of [['media', 'Медиа'], ['files', 'Файлы']]) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'tab-btn'; + button.dataset.tab = value; + button.setAttribute('role', 'radio'); + button.addEventListener('click', () => { + if (activeTab === value) return; + activeTab = value; + renderBody(); + }); + tabButtons.set(value, { button, label }); + tabs.append(button); + } + + const status = document.createElement('div'); + status.className = 'chat-media-status'; + const body = document.createElement('div'); + body.className = 'stack chat-media-body'; + screen.append(subtitle, tabs, status, body); + + const thumbObserver = typeof IntersectionObserver === 'function' + ? new IntersectionObserver((entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + thumbObserver.unobserve(entry.target); + entry.target.__loadThumb?.(); + } + }, { rootMargin: '300px 0px' }) + : null; + + const createTile = (entry, openAt) => { + const { attachment } = entry; + const kind = getAttachmentKind(attachment); + const tile = document.createElement('button'); + tile.type = 'button'; + tile.className = `chat-media-tile is-loading${kind === 'video' ? ' chat-media-tile--video' : ''}`; + tile.setAttribute('aria-label', `${kind === 'video' ? 'Видео' : 'Фото'} ${attachment.name || ''}, ${formatDayLabel(entry.timeMs)}`); + tile.__loadThumb = () => { + resolveDmMediaUrl(attachment).then(({ url }) => { + objectUrls.add(url); + if (disposed) return; + tileUrls.set(fileKey(attachment), url); + const media = document.createElement(kind === 'video' ? 'video' : 'img'); + media.className = 'chat-media-tile__media'; + if (kind === 'video') { + media.muted = true; + media.preload = 'metadata'; + media.playsInline = true; + // Кадр чуть позже начала: первый часто чёрный. + media.src = `${url}#t=0.1`; + } else { + media.alt = ''; + media.decoding = 'async'; + media.src = url; + } + tile.prepend(media); + tile.classList.remove('is-loading'); + }).catch(() => { + if (!disposed) tile.classList.replace('is-loading', 'is-failed'); + }); + }; + if (kind === 'video') { + const badge = document.createElement('span'); + badge.className = 'chat-media-tile__badge'; + badge.innerHTML = iconHtml('video'); + tile.append(badge); + } + tile.addEventListener('click', () => openAt(attachment)); + if (thumbObserver) thumbObserver.observe(tile); + else tile.__loadThumb(); + return tile; + }; + + const openViewerAt = async (allMedia, attachment) => { + if (!tileUrls.has(fileKey(attachment))) { + try { + const { url } = await resolveDmMediaUrl(attachment); + objectUrls.add(url); + tileUrls.set(fileKey(attachment), url); + } catch { + return; + } + } + if (disposed) return; + // В просмотрщик – уже расшифрованные: остальные догрузятся, когда до них долистают в сетке. + const entries = allMedia + .filter((entry) => tileUrls.has(fileKey(entry.attachment))) + .map((entry) => ({ kind: getAttachmentKind(entry.attachment), url: tileUrls.get(fileKey(entry.attachment)), name: entry.attachment.name, attachment: entry.attachment })); + openMediaViewer(entries, Math.max(0, entries.findIndex((entry) => fileKey(entry.attachment) === fileKey(attachment)))); + }; + + const renderEmpty = (text) => { + const empty = document.createElement('p'); + empty.className = 'empty-note'; + empty.textContent = text; + body.append(empty); + }; + + function renderBody() { + if (disposed) return; + const { media, files } = collectAttachments(chatId); + for (const [value, { button, label }] of tabButtons) { + const count = value === 'media' ? media.length : files.length; + button.textContent = count ? `${label} · ${count}` : label; + button.setAttribute('aria-checked', String(value === activeTab)); + } + status.hidden = !loading && !loadFailed; + status.classList.toggle('is-error', loadFailed); + status.innerHTML = loadFailed + ? 'Не удалось загрузить всю историю – показано то, что уже есть на устройстве.' + : 'Загружаю историю переписки…'; + thumbObserver?.disconnect(); + body.replaceChildren(); + + const entries = activeTab === 'media' ? media : files; + if (!entries.length) { + if (!loading) renderEmpty(activeTab === 'media' ? 'В этой переписке пока нет фото и видео.' : 'В этой переписке пока нет файлов.'); + return; + } + for (const group of groupByMonth(entries)) { + const heading = document.createElement('h2'); + heading.className = 'chat-media-month'; + heading.textContent = group.label; + body.append(heading); + if (activeTab === 'media') { + const grid = document.createElement('div'); + grid.className = 'chat-media-grid'; + group.items.forEach((entry) => grid.append(createTile(entry, (attachment) => void openViewerAt(media, attachment)))); + body.append(grid); + } else { + const list = document.createElement('div'); + list.className = 'stack chat-media-files'; + for (const entry of group.items) { + const row = document.createElement('div'); + row.className = 'chat-media-file'; + const meta = document.createElement('span'); + meta.className = 'meta-muted chat-media-file__meta'; + meta.textContent = `${entry.from === 'out' ? 'Вы' : peerName} · ${formatDayLabel(entry.timeMs)}, ${formatClockTime(entry.timeMs)}`; + row.append(createDmFileAttachmentCard(entry.attachment), meta); + list.append(row); + } + body.append(list); + } + } + } + + renderBody(); + loadFullDmHistory(chatId) + .catch(() => { loadFailed = true; }) + .finally(() => { + loading = false; + renderBody(); + }); + + screen.cleanup = () => { + if (disposed) return; + disposed = true; + thumbObserver?.disconnect(); + // Просмотрщик мог остаться открытым поверх: его картинки живут, пока он не закрыт. + window.setTimeout(() => objectUrls.forEach((url) => URL.revokeObjectURL(url)), 60000); + }; + + return screen; +} diff --git a/shine-UI/js/pages/chat-view.js b/shine-UI/js/pages/chat-view.js index 459e49a3..6847dcdf 100644 --- a/shine-UI/js/pages/chat-view.js +++ b/shine-UI/js/pages/chat-view.js @@ -18,6 +18,8 @@ import { markReadReceiptSentByBaseKey, normalizeDmChatId, authService, + getRememberedDmPeer, + rememberDmPeer, setContacts, state, } from '../state.js'; @@ -35,13 +37,24 @@ import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitiz import { isDmFileTransferEnabled } from '../services/feature-settings.js'; import { decryptDmFileToBlob, - downloadAndDecryptDmFile, encryptAndUploadDmFile, - formatDmFileSize, DM_MAX_ATTACHMENTS_PER_MESSAGE, } from '../services/dm-file-service.js'; +import { createAttachmentCarouselElement } from '../services/attachment-format.js'; +import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js'; +import { + DM_HISTORY_PAGE_SIZE, + isDmHistoryFullyLoaded, + loadFullDmHistory, + markDmHistoryFullyLoaded, + mergeDirectMessagesPage, + parseBaseKey, + resolveMessageTimeMs, +} from '../services/dm-history.js'; +import { isDmChatMuted, isDmChatPinned, setDmChatMuted, setDmChatPinned } from '../services/dm-chat-prefs.js'; import { loadProfileSnapshot } from '../services/user-profile-params.js'; import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-routes.js'; +import { openHistoryLayer } from '../router.js'; export const pageMeta = { id: 'chat-view', @@ -96,6 +109,7 @@ function createChatHeaderParts(login, navigate) { avatar: null, relationType: 'none', }; + let muted = false; const identityButton = document.createElement('button'); identityButton.type = 'button'; @@ -119,6 +133,13 @@ function createChatHeaderParts(login, navigate) { const lastName = String(currentPeer?.lastName || '').trim(); const fullName = [firstName, lastName].filter(Boolean).join(' '); nameEl.textContent = fullName || cleanLogin; + if (muted) { + const mutedIcon = document.createElement('span'); + mutedIcon.className = 'chat-header-muted'; + mutedIcon.title = 'Без звука'; + mutedIcon.innerHTML = iconHtml('bell-off'); + nameEl.append(mutedIcon); + } const relation = chatRelationLabel(currentPeer?.relationType); // Статус аккаунта, а не «в сети»: присутствие сервер не сообщает, выдумывать его нельзя const shining = String(currentPeer?.shineStatus || '').toLowerCase() === 'shining' ? '✧ сияющий аккаунт' : ''; @@ -175,6 +196,10 @@ function createChatHeaderParts(login, navigate) { return { center: identityButton, updatePeer, + setMuted: (value) => { + muted = Boolean(value); + renderPeer(); + }, getPeer: () => ({ ...currentPeer }), cleanup: () => identityMenu.destroy(), }; @@ -198,7 +223,7 @@ function openDeleteMessageConfirmModal({ onConfirm }) { if (!root) return; root.innerHTML = `