import { createTopBar } from '../components/topbar.js'; import { authService } from '../state.js'; import { KeyRotationClient } from '../services/key-rotation-service.js'; import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js'; import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js'; import { actionErrorText } from '../services/ui-error-texts.js'; export const pageMeta = { id: 'my-blockchain-view', title: 'Мой блокчейн' }; const PROFILE_LABELS = new Map([ ['first_name', 'Имя'], ['last_name', 'Фамилия'], ['address', 'Адрес'], ['web', 'Ссылки'], ['phone', 'Телефон'], ['about', 'О себе'], ['spiritual_path', 'Духовный путь'], ['account_role', 'Тип аккаунта'], ['shine', 'Сияние'], ['gender', 'Пол'], ['ava', 'Аватар'], ]); const CONNECTION_LABELS = new Map([ [10, ['Добавлен близкий друг', 'Близкий друг']], [11, ['Удалён из близких друзей', 'Близкий друг']], [14, ['Добавлен друг', 'Друг']], [15, ['Удалён из друзей', 'Друг']], [20, ['Добавлен контакт', 'Контакт']], [21, ['Удалён из контактов', 'Контакт']], [30, ['Оформлена подписка', 'Подписка']], [31, ['Подписка отменена', 'Подписка']], [40, ['Добавлена связь «супруг/супруга»', 'Супруг/супруга']], [41, ['Удалена связь «супруг/супруга»', 'Супруг/супруга']], [50, ['Добавлена связь «родитель»', 'Родитель']], [51, ['Удалена связь «родитель»', 'Родитель']], [52, ['Добавлена связь «ребёнок»', 'Ребёнок']], [53, ['Удалена связь «ребёнок»', 'Ребёнок']], [54, ['Добавлена связь «брат/сестра»', 'Брат/сестра']], [55, ['Удалена связь «брат/сестра»', 'Брат/сестра']], [60, ['Устаревшая отметка знакомства', 'Legacy-связь']], [61, ['Устаревшая отмена отметки знакомства', 'Legacy-связь']], [70, ['Подтверждён сияющий пользователь', 'Подтверждение сияния']], [71, ['Снято подтверждение сияния', 'Подтверждение сияния']], [74, ['Отмечен как замеченный сияющим', 'Отметка сияния']], [75, ['Снята отметка «видел сияющим»', 'Отметка сияния']], [80, ['Подтверждён официальный аккаунт', 'Официальный аккаунт']], [81, ['Снято подтверждение официального аккаунта', 'Официальный аккаунт']], ]); const STATUS_LABELS = new Map([ [10, 'Упражнение выполнено один раз'], [20, 'Упражнение изучено'], [30, 'Услуга / процедура пройдена'], [100, 'Статус подтверждён'], [110, 'Отмечен интерес к курсу'], [120, 'Курс начат'], [130, 'Курс изучается'], [140, 'Курс заброшен'], [150, 'Курс завершён'], ]); const FORK_REASON_LABELS = new Map([ [1, 'Обычная смена ключей'], [2, 'Возможная компрометация'], [3, 'Откат после подтверждённой компрометации'], [4, 'Восстановление доступа'], ]); function shortHash(value) { const text = String(value || ''); return text.length > 18 ? `${text.slice(0, 9)}…${text.slice(-7)}` : text; } function formatDate(ms) { try { return new Date(Number(ms) || 0).toLocaleString('ru-RU'); } catch { return ''; } } function previewText(value) { const rows = String(value || '') .replace(/\r\n/g, '\n') .replace(/\r/g, '\n') .split('\n') .slice(0, 3) .map((row) => row.trim()) .filter(Boolean); return rows.join(' '); } function profileValueLabel(key, value) { const clean = String(value || '').trim(); if (key === 'account_role') { if (clean === 'primary') return 'Основной аккаунт'; if (clean === 'non_voting') return 'Не учитывать мой голос'; } if (key === 'shine') { if (clean === 'shining' || clean === 'yes') return 'Сияющий'; if (clean === 'not_interested') return 'Сияние неинтересно'; if (clean === 'unknown') return 'Неизвестно'; } if (key === 'gender') { if (clean === 'male') return 'Мужской'; if (clean === 'female') return 'Женский'; if (clean === 'unknown') return 'Не указан'; } if (key === 'ava') return 'Изменена аватарка'; return clean; } function targetText(target) { if (!target) return ''; const login = String(target.toLogin || '').trim(); const block = Number(target.toBlockNumber); if (login && Number.isInteger(block) && block >= 0) return `${login} · блок #${block}`; if (Number.isInteger(block) && block >= 0) return `блок #${block}`; return login || ''; } function channelNameText(lineCode, channelNames) { const code = Number(lineCode); if (!Number.isInteger(code) || code < 0) return ''; const known = channelNames.get(code); if (known) return `«${known}»`; if (code === 0) return '«stories»'; return `#${code}`; } function channelLabel(lineCode, channelNames) { const name = channelNameText(lineCode, channelNames); return name ? `канале ${name}` : 'канале'; } function lineTextKindLabel(subType) { if (subType === 100) return 'Входная страница'; if (subType === 110) return 'Упражнение'; if (subType === 120) return 'Услуга'; if (subType === 130) return 'Курс'; return 'Сообщение'; } function describeEntry(item, inspection, channelNames) { if (!inspection?.frame) { return { title: `Событие ${item.msgType}/${item.msgSubType}`, detailTitle: `Событие ${item.msgType}/${item.msgSubType}`, text: '', attachmentsCount: 0, }; } const { frame } = inspection; const body = frame.body || {}; const type = Number(frame.type); const subType = Number(frame.subType); if (type === 0 && subType === 0) { return { title: 'Начало блокчейна', detailTitle: 'Начало блокчейна', text: body.login ? `Владелец: ${body.login}` : '', attachmentsCount: 0 }; } if (type === 0 && subType === 1) { const displayName = String(body.channelMeta?.title || body.channelName || '').trim() || `#${frame.blockNumber}`; return { title: `Создан канал «${displayName}»`, detailTitle: 'Создание канала', text: String(body.channelMeta?.description || '').trim(), attachmentsCount: 0, }; } if (type === 0 && subType === 2) { const reason = FORK_REASON_LABELS.get(Number(body.reasonCode)) || `Причина ${body.reasonCode ?? '—'}`; return { title: `Создан новый fork · ${reason}`, detailTitle: 'Смена ключей / fork', text: String(body.comment || '').trim(), attachmentsCount: 0, }; } if (type === 1 && [10, 100, 110, 120, 130].includes(subType)) { const kind = lineTextKindLabel(subType); const preview = previewText(body.text) || (body.attachmentsCount ? `Вложений: ${body.attachmentsCount}` : 'Без текста'); return { title: `${kind} в ${channelLabel(body.line?.lineCode, channelNames)}: ${preview}`, detailTitle: `${kind} в ${channelLabel(body.line?.lineCode, channelNames)}`, text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 11) { const preview = previewText(body.text) || (body.attachmentsCount ? `Вложений: ${body.attachmentsCount}` : 'Сообщение удалено'); return { title: `Отредактировано сообщение: ${preview}`, detailTitle: 'Редактирование сообщения', text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 20) { const preview = previewText(body.text) || (body.attachmentsCount ? `Вложений: ${body.attachmentsCount}` : 'Без текста'); return { title: `Ответ ${targetText(body.target)}: ${preview}`, detailTitle: `Ответ на ${targetText(body.target)}`, text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 21) { const preview = previewText(body.text) || (body.attachmentsCount ? `Вложений: ${body.attachmentsCount}` : 'Ответ удалён'); return { title: `Отредактирован ответ: ${preview}`, detailTitle: 'Редактирование ответа', text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 30) { const preview = previewText(body.text) || 'Без текста'; return { title: `Добавлен отзыв ${targetText(body.target)}: ${preview}`, detailTitle: `Отзыв на ${targetText(body.target)}`, text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 50) { const preview = previewText(body.text) || 'Без комментария'; return { title: `Репост в ${channelLabel(body.line?.lineCode, channelNames)}: ${preview}`, detailTitle: `Репост ${targetText(body.target)}`, text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } if (type === 1 && subType === 90) { const channelName = channelNameText(body.line?.lineCode, channelNames); const title = String(body.channelMeta?.title || '').trim(); const description = previewText(body.channelMeta?.description || ''); const changed = [title ? `название «${title}»` : '', body.channelMeta?.avatarAr ? 'аватар' : '', description ? `описание: ${description}` : ''].filter(Boolean).join(' · '); return { title: `Изменён профиль канала${channelName ? ` ${channelName}` : ''}${changed ? ` · ${changed}` : ''}`, detailTitle: `Профиль канала${channelName ? ` ${channelName}` : ''}`, text: String(body.channelMeta?.description || ''), attachmentsCount: 0, }; } if (type === 1 && subType === 92) { return { title: `Удалён канал${channelNameText(body.line?.lineCode, channelNames) ? ` ${channelNameText(body.line?.lineCode, channelNames)}` : ''}`, detailTitle: 'Удаление канала', text: '', attachmentsCount: 0, }; } if (type === 2 && (subType === 1 || subType === 2)) { const action = subType === 1 ? 'Поставлен лайк' : 'Лайк снят'; return { title: `${action} · ${targetText(body.target)}`, detailTitle: action, text: '', attachmentsCount: 0 }; } if (type === 3) { const connection = CONNECTION_LABELS.get(subType); const action = connection?.[0] || `Изменена связь (${subType})`; const target = targetText(body.target); return { title: `${action}${target ? ` · ${target}` : ''}`, detailTitle: connection?.[1] || 'Связь', text: '', attachmentsCount: 0 }; } if (type === 4 && subType === 1) { const key = String(body.key || '').trim(); const label = PROFILE_LABELS.get(key) || key || 'Параметр'; const value = profileValueLabel(key, body.value); return { title: key === 'ava' ? 'Профиль · Изменена аватарка' : `Профиль · ${label}: ${previewText(value) || '—'}`, detailTitle: `Изменение профиля · ${label}`, text: key === 'ava' ? '' : String(value || ''), attachmentsCount: 0, }; } if (type === 5) { const action = STATUS_LABELS.get(subType) || `Статус ${subType}`; const preview = previewText(body.text); return { title: `${action} · ${targetText(body.target)}${preview ? `: ${preview}` : ''}`, detailTitle: action, text: String(body.text || ''), attachmentsCount: Number(body.attachmentsCount || 0), }; } return { title: `Событие ${type}/${subType}`, detailTitle: `Событие ${type}/${subType}`, text: '', attachmentsCount: 0, }; } function targetBlockchainName(target) { const login = String(target?.toLogin || '').trim(); const fork = Number(target?.toForkNumber); if (!login || !Number.isInteger(fork) || fork < 1 || fork > 999) return ''; return `${login}-${String(fork).padStart(3, '0')}`; } function buildInternalAction({ inspection, blockchainName, login }) { const frame = inspection?.frame; const body = frame?.body || {}; const type = Number(frame?.type); const subType = Number(frame?.subType); if (type === 0 && subType === 1 && body.channelName) { const route = makeShineChannelRoute({ ownerBlockchainName: blockchainName, channelName: body.channelName }); return route ? { label: 'Открыть канал →', route } : null; } if (type === 1 && [10, 20, 50, 100, 110, 120, 130].includes(subType)) { const route = makeShineMessageRoute({ messageBlockchainName: blockchainName, messageBlockNumber: frame.blockNumber }); return route ? { label: subType === 20 ? 'Открыть ответ →' : 'Открыть сообщение →', route } : null; } if (type === 1 && [11, 21].includes(subType) && Number.isInteger(Number(body.target?.toBlockNumber))) { const route = makeShineMessageRoute({ messageBlockchainName: blockchainName, messageBlockNumber: Number(body.target.toBlockNumber) }); return route ? { label: subType === 11 ? 'Открыть исходное сообщение →' : 'Открыть исходный ответ →', route } : null; } if ((type === 1 && subType === 30) || type === 2 || type === 5) { const targetBch = targetBlockchainName(body.target); if (!targetBch) return null; const route = makeShineMessageRoute({ messageBlockchainName: targetBch, messageBlockNumber: body.target.toBlockNumber }); return route ? { label: 'Открыть цель →', route } : null; } if (type === 4) { const route = makeProfileRoute(login); return route ? { label: 'Открыть профиль →', route } : null; } return null; } function addDetailRow(container, label, value, { code = false } = {}) { const clean = String(value ?? '').trim(); if (!clean) return; const row = document.createElement('div'); row.className = 'my-blockchain-entry__detail-row'; const name = document.createElement('span'); name.className = 'my-blockchain-entry__detail-key'; name.textContent = label; const content = document.createElement(code ? 'code' : 'span'); content.className = 'my-blockchain-entry__detail-value'; content.textContent = clean; row.append(name, content); container.append(row); } function addTargetRows(container, target, fallbackLogin = '') { if (!target) return; const login = String(target.toLogin || fallbackLogin || '').trim(); if (login) addDetailRow(container, 'Цель', login); if (Number.isInteger(Number(target.toForkNumber))) addDetailRow(container, 'Fork цели', target.toForkNumber); if (Number.isInteger(Number(target.toBlockNumber))) addDetailRow(container, 'Блок цели', `#${target.toBlockNumber}`); if (target.toBlockHash) addDetailRow(container, 'Хэш цели', target.toBlockHash, { code: true }); } function createEntryCard({ item, inspection, parseError, channelNames, blockchainName, login, navigate }) { const frame = inspection?.frame; const description = describeEntry(item, inspection, channelNames); const card = document.createElement('article'); card.className = 'card my-blockchain-entry'; const head = document.createElement('div'); head.className = 'my-blockchain-entry__head'; const copy = document.createElement('div'); copy.className = 'my-blockchain-entry__copy'; const title = document.createElement('div'); title.className = 'my-blockchain-entry__title'; title.textContent = `#${item.blockNumber} · ${description.title}`; title.title = title.textContent; const meta = document.createElement('div'); meta.className = 'my-blockchain-entry__meta meta-muted'; meta.textContent = `${formatDate(item.timestampMs)} · hash ${shortHash(item.blockHash)}`; copy.append(title, meta); const toggle = document.createElement('button'); toggle.type = 'button'; toggle.className = 'ui-button my-blockchain-entry__toggle'; toggle.setAttribute('aria-expanded', 'false'); toggle.setAttribute('aria-label', `Подробнее о блоке #${item.blockNumber}`); const triangle = document.createElement('span'); triangle.className = 'my-blockchain-entry__triangle'; triangle.setAttribute('aria-hidden', 'true'); toggle.append(triangle); head.append(copy, toggle); const details = document.createElement('div'); details.className = 'my-blockchain-entry__details'; details.hidden = true; const detailTitle = document.createElement('strong'); detailTitle.className = 'my-blockchain-entry__detail-title'; detailTitle.textContent = description.detailTitle; details.append(detailTitle); if (description.text) { const fullText = document.createElement('div'); fullText.className = 'my-blockchain-entry__full-text'; fullText.textContent = description.text; details.append(fullText); } if (description.attachmentsCount > 0) { const attachments = document.createElement('div'); attachments.className = 'my-blockchain-entry__attachments meta-muted'; attachments.textContent = description.attachmentsCount === 1 ? 'Вложение: 1' : `Вложения: ${description.attachmentsCount}`; details.append(attachments); } const action = buildInternalAction({ inspection, blockchainName, login }); const actions = document.createElement('div'); actions.className = 'my-blockchain-entry__actions'; if (action) { const open = document.createElement('button'); open.type = 'button'; open.className = 'text-btn my-blockchain-entry__action'; open.textContent = action.label; open.addEventListener('click', () => navigate(action.route)); actions.append(open); } if (inspection?.arweaveUrl) { const arweave = document.createElement('a'); arweave.className = 'my-blockchain-entry__action my-blockchain-entry__external'; arweave.href = inspection.arweaveUrl; arweave.target = '_blank'; arweave.rel = 'noopener noreferrer'; arweave.textContent = 'Открыть запись в блокчейне ↗'; actions.append(arweave); } if (actions.childElementCount) details.append(actions); const info = document.createElement('div'); info.className = 'my-blockchain-entry__detail-grid'; const effectiveType = frame ? `${frame.type}/${frame.subType} · v${frame.version}` : `${item.msgType}/${item.msgSubType} · v${item.msgVersion}`; addDetailRow(info, 'Тип', effectiveType); addDetailRow(info, 'Блок', `#${item.blockNumber}`); addDetailRow(info, 'Дата', formatDate(item.timestampMs)); addDetailRow(info, 'Хэш блока', item.blockHash, { code: true }); if (inspection?.dataItemId) addDetailRow(info, 'DataItem ID', inspection.dataItemId, { code: true }); const body = frame?.body || {}; if (body.line) { if (Number.isInteger(Number(body.line.lineCode))) addDetailRow(info, 'Линия', `#${body.line.lineCode}`); if (Number.isInteger(Number(body.line.lineSequence))) addDetailRow(info, 'Шаг линии', body.line.lineSequence); } if (body.kind === 'profile') { addDetailRow(info, 'Параметр', body.key); addDetailRow(info, 'Значение', body.value, { code: body.key === 'ava' }); } if (body.kind === 'create_channel') { addDetailRow(info, 'Техническое имя', body.channelName); addDetailRow(info, 'Тип канала', `${body.channelType} · v${body.channelTypeVersion}`); } if (body.kind === 'fork') { addDetailRow(info, 'Fork point', `#${body.forkPointBlockNumber}`); addDetailRow(info, 'Старый tip', `#${body.parentTipBlockNumber}`); addDetailRow(info, 'Отброшено блоков', body.discardedBlocksCount); } if (body.target) addTargetRows(info, body.target, (frame?.type === 1 && [11, 21].includes(Number(frame?.subType))) ? login : ''); if (!body.target && item.toLogin) { addTargetRows(info, { toLogin: item.toLogin, toForkNumber: item.toForkNumber, toBlockNumber: item.toBlockNumber, toBlockHash: item.toBlockHash, }); } if (parseError) addDetailRow(info, 'Разбор блока', parseError); details.append(info); toggle.addEventListener('click', () => { const expanded = toggle.getAttribute('aria-expanded') !== 'true'; toggle.setAttribute('aria-expanded', String(expanded)); details.hidden = !expanded; card.classList.toggle('is-expanded', expanded); }); card.append(head, details); return card; } export function render({ navigate, chrome }, { historyOnly = false } = {}) { const screen = document.createElement('section'); screen.className = 'stack my-blockchain-screen'; chrome?.setTopbar(createTopBar({ title: historyOnly ? 'История моего блокчейна' : 'Мой блокчейн', back: { label: '←', onClick: () => navigate(historyOnly ? 'my-blockchain-view' : 'settings-view') }, })); if (!historyOnly) { const intro = document.createElement('div'); intro.className = 'card stack'; const historyButton = document.createElement('button'); historyButton.type = 'button'; historyButton.className = 'nav-row'; historyButton.textContent = 'Показать историю моего блокчейна'; historyButton.addEventListener('click', () => navigate('my-blockchain-history-view')); const filesButton = document.createElement('button'); filesButton.type = 'button'; filesButton.className = 'nav-row'; filesButton.textContent = 'Файлы в блокчейне'; filesButton.addEventListener('click', () => navigate('arweave-uploads-view')); const remoteButton = document.createElement('button'); remoteButton.type = 'button'; remoteButton.className = 'nav-row'; remoteButton.textContent = 'Использовать ключ блокчейна с внешнего устройства'; remoteButton.addEventListener('click', () => navigate('remote-addblock-session-view')); intro.append(historyButton, filesButton, remoteButton); screen.append(intro); return screen; } const list = document.createElement('div'); list.className = 'stack my-blockchain-list'; list.hidden = false; screen.append(list); const more = document.createElement('button'); more.type = 'button'; more.className = 'secondary-btn'; more.textContent = 'Показать более ранние записи'; more.hidden = true; screen.append(more); const client = new KeyRotationClient(authService); const channelNames = new Map([[0, 'stories']]); let channelsLoaded = false; let before = null; let loading = false; let disposed = false; let loadSeq = 0; async function ensureChannelNames(login) { if (channelsLoaded || !login) return; channelsLoaded = true; try { const payload = await authService.listUserProfileChannels(login, 'owned', 500, 0, true); if (disposed) return; for (const row of Array.isArray(payload?.channels) ? payload.channels : []) { const root = Number(row?.rootBlockNumber); if (!Number.isInteger(root) || root < 0) continue; const name = String(row?.displayName || row?.slug || '').trim(); if (name) channelNames.set(root, name); } } catch { // Имена каналов улучшают подписи, но их отсутствие не мешает читать сам сырой блок. } } async function load(reset = false) { if (loading || disposed) return; loading = true; more.disabled = true; const seq = ++loadSeq; if (reset) { list.innerHTML = ''; before = null; } try { const data = await client.getMyBlockchain({ beforeBlock: before, limit: 50, includeBlockBytes: true }); if (disposed || seq !== loadSeq) return; await ensureChannelNames(String(data.login || '').trim()); if (disposed || seq !== loadSeq) return; if (reset) { const head = document.createElement('div'); head.className = 'card stack'; head.innerHTML = `${escapeHtml(data.blockchainName || '—')}Последний блок: #${Number(data.tipBlockNumber ?? -1)} · ${shortHash(data.tipBlockHash)}`; list.append(head); } const rows = await Promise.all((data.blocks || []).map(async (item) => { if (!item?.blockBytesB64) return { item, inspection: null, parseError: 'Сервер не вернул сырые bytes блока.' }; try { const inspection = await inspectBlockchainDataItem(item.blockBytesB64); const body = inspection?.frame?.body; if (inspection?.frame?.type === 0 && inspection?.frame?.subType === 1) { const root = Number(inspection.frame.blockNumber); const name = String(body?.channelMeta?.title || body?.channelName || '').trim(); if (Number.isInteger(root) && root >= 0 && name) channelNames.set(root, name); } return { item, inspection, parseError: '' }; } catch (error) { return { item, inspection: null, parseError: String(error?.message || error || 'Неизвестная ошибка разбора') }; } })); if (disposed || seq !== loadSeq) return; for (const row of rows) { list.append(createEntryCard({ ...row, channelNames, blockchainName: String(data.blockchainName || '').trim(), login: String(data.login || '').trim(), navigate, })); } before = data.nextBeforeBlock; more.hidden = before == null; if (!(data.blocks || []).length && reset) { const empty = document.createElement('div'); empty.className = 'card'; empty.textContent = 'Записей пока нет.'; list.append(empty); } } catch (error) { if (disposed || seq !== loadSeq) return; const err = document.createElement('div'); err.className = 'card'; err.textContent = actionErrorText('Не удалось загрузить блокчейн', error); list.append(err); } finally { if (seq === loadSeq) { loading = false; more.disabled = false; } } } more.addEventListener('click', () => void load(false)); void load(true); screen.cleanup = () => { if (disposed) return; disposed = true; loadSeq += 1; }; return screen; } function escapeHtml(value) { return String(value ?? '').replace(/[&<>"]/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[char])); }