SHA256
Вложения файлов со своего сервера доступа пользователя
This commit is contained in:
@@ -7,7 +7,7 @@ import {
|
||||
validateArweaveTxId,
|
||||
} from '../services/arweave-file-service.js';
|
||||
import { addArweaveWalletSecret, getArweaveBalance, getArweaveWalletChoices } from '../services/arweave-wallet-service.js';
|
||||
import { escapeHtml, formatBytes, getAttachmentKind, normalizeAttachment } from '../services/attachment-format.js';
|
||||
import { escapeHtml, formatBytes, normalizeAttachment } from '../services/attachment-format.js';
|
||||
import { getStoredSolanaWalletChoices } from '../services/solana-wallet-service.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import {
|
||||
@@ -36,25 +36,6 @@ function normalizeHistoryItem(input = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function hasAttachmentPreview(item) {
|
||||
return !!String(item?.preview?.ar || '').trim();
|
||||
}
|
||||
|
||||
function isVideoAttachmentName(name) {
|
||||
return getAttachmentKind({ name }) === 'video';
|
||||
}
|
||||
|
||||
function buildHistoryPreviewMarkup(item, gateway) {
|
||||
if (!hasAttachmentPreview(item)) return '';
|
||||
const previewTxId = String(item.preview.ar || '').trim();
|
||||
const previewUrl = buildArweaveDataUrl({ gateway, txId: previewTxId });
|
||||
return `
|
||||
<div class="ar-attachment-history-preview">
|
||||
<img class="ar-attachment-history-preview-image" src="${escapeHtml(previewUrl)}" alt="Превью ${escapeHtml(item.name)}" loading="lazy" />
|
||||
<div class="ar-attachment-history-preview-badge">Есть превью</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
export function readArweaveAttachmentHistory(login) {
|
||||
try {
|
||||
@@ -217,45 +198,6 @@ async function resizeImageFileToAvatar(file) {
|
||||
return new File([blob], 'avatar.jpg', { type: 'image/jpeg', lastModified: Date.now() });
|
||||
}
|
||||
|
||||
async function createVideoPreviewFile(file) {
|
||||
const source = file instanceof File ? file : null;
|
||||
if (!source) throw new Error('Выберите видеофайл.');
|
||||
const blobUrl = URL.createObjectURL(source);
|
||||
try {
|
||||
const video = await new Promise((resolve, reject) => {
|
||||
const node = document.createElement('video');
|
||||
node.preload = 'metadata';
|
||||
node.muted = true;
|
||||
node.playsInline = true;
|
||||
node.onloadeddata = () => resolve(node);
|
||||
node.onerror = () => reject(new Error('Не удалось открыть видео для создания превью.'));
|
||||
node.src = blobUrl;
|
||||
});
|
||||
const width = Number(video.videoWidth || 0);
|
||||
const height = Number(video.videoHeight || 0);
|
||||
if (!width || !height) {
|
||||
throw new Error('Не удалось определить размер видео для превью.');
|
||||
}
|
||||
const maxSide = 640;
|
||||
const scale = Math.min(1, maxSide / Math.max(width, height));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.round(width * scale));
|
||||
canvas.height = Math.max(1, Math.round(height * scale));
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas недоступен для создания превью.');
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.86));
|
||||
if (!blob) throw new Error('Не удалось собрать preview image.');
|
||||
const baseName = String(source.name || 'video').replace(/\.[^.]+$/u, '') || 'video';
|
||||
return new File([blob], `${baseName}-preview.jpg`, {
|
||||
type: 'image/jpeg',
|
||||
lastModified: Date.now(),
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
}
|
||||
}
|
||||
|
||||
export function openArweaveAttachmentManager({
|
||||
login,
|
||||
storagePwd,
|
||||
@@ -298,10 +240,6 @@ export function openArweaveAttachmentManager({
|
||||
let selectedUploadTransport = String(uploadTransport || '').trim().toLowerCase() === 'arweave' ? 'arweave' : 'turbo';
|
||||
let selectedFile = null;
|
||||
let selectedSha256 = '';
|
||||
let selectedPreviewEnabled = false;
|
||||
let selectedPreviewFile = null;
|
||||
let selectedPreviewSha256 = '';
|
||||
let selectedPreviewPriceInfo = null;
|
||||
let priceInfo = null;
|
||||
let balanceInfo = null;
|
||||
let autoOpenedFileDialogOnce = false;
|
||||
@@ -394,14 +332,14 @@ export function openArweaveAttachmentManager({
|
||||
}
|
||||
};
|
||||
|
||||
const renderTurboMeta = (mainMetaEl, previewMetaEl) => {
|
||||
if (!mainMetaEl || !previewMetaEl) return;
|
||||
const renderTurboMeta = (mainMetaEl) => {
|
||||
if (!mainMetaEl) return;
|
||||
const turboAddress = String(balanceInfo?.address || priceInfo?.address || '').trim();
|
||||
const turboCredits = balanceInfo ? formatTurboCredits(balanceInfo.effectiveCredits, 6) : '–';
|
||||
const solBalance = balanceInfo ? `${escapeHtml(String(balanceInfo.solBalance ?? 0))} SOL` : '–';
|
||||
const uploadPrice = priceInfo ? `${formatTurboCredits(priceInfo.credits, 6)} credits` : '–';
|
||||
const fileSize = selectedFile ? formatBytes(selectedFile.size) : '–';
|
||||
const isFreeSize = selectedFile && combinedUploadSize() <= getFreeTurboUploadBytesLimit();
|
||||
const isFreeSize = selectedFile && Number(selectedFile.size || 0) <= getFreeTurboUploadBytesLimit();
|
||||
const summary = selectedFile
|
||||
? `Размер ${escapeHtml(fileSize)} · ${isFreeSize
|
||||
? '<span class="ar-attachment-ok">бесплатно через Turbo</span>'
|
||||
@@ -419,26 +357,16 @@ export function openArweaveAttachmentManager({
|
||||
<div>Бесплатно до ${escapeHtml(formatBytes(getFreeTurboUploadBytesLimit()))}</div>
|
||||
</details>
|
||||
`;
|
||||
previewMetaEl.innerHTML = '';
|
||||
if (selectedPreviewEnabled && selectedPreviewFile) {
|
||||
previewMetaEl.innerHTML = `
|
||||
<div><strong>Файл превью</strong></div>
|
||||
<div>Имя: ${escapeHtml(selectedPreviewFile.name)}</div>
|
||||
<div>Размер превью: ${escapeHtml(formatBytes(selectedPreviewFile.size))}</div>
|
||||
<div>SHA-256 превью: ${escapeHtml(selectedPreviewSha256 || '–')}</div>
|
||||
<div>Цена превью: ${escapeHtml(selectedPreviewPriceInfo ? `${formatTurboCredits(selectedPreviewPriceInfo.credits, 6)} credits` : '–')}</div>
|
||||
`;
|
||||
}
|
||||
};
|
||||
|
||||
const refreshTurboBalance = async (mainMetaEl, previewMetaEl, errorEl) => {
|
||||
const refreshTurboBalance = async (mainMetaEl, errorEl) => {
|
||||
try {
|
||||
balanceInfo = await getTurboBalanceForStoredSolanaKey({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
});
|
||||
renderTurboMeta(mainMetaEl, previewMetaEl);
|
||||
renderTurboMeta(mainMetaEl);
|
||||
if (errorEl && String(errorEl.textContent || '').includes('Turbo balance')) {
|
||||
setText(errorEl, '');
|
||||
}
|
||||
@@ -447,7 +375,7 @@ export function openArweaveAttachmentManager({
|
||||
}
|
||||
};
|
||||
|
||||
const promptTurboTopUp = async (mainMetaEl, previewMetaEl, errorEl) => {
|
||||
const promptTurboTopUp = async (mainMetaEl, errorEl) => {
|
||||
const value = window.prompt('Сколько SOL перевести в Turbo?', '0.01');
|
||||
if (value == null) return;
|
||||
setText(errorEl, 'Пополняем Turbo...');
|
||||
@@ -458,32 +386,15 @@ export function openArweaveAttachmentManager({
|
||||
keySource: selectedTurboKeySource,
|
||||
amountSol: value,
|
||||
});
|
||||
await refreshTurboBalance(mainMetaEl, previewMetaEl, errorEl);
|
||||
await refreshTurboBalance(mainMetaEl, errorEl);
|
||||
setText(errorEl, `Turbo пополнен. Tx: ${result.txId || 'отправлено'}`);
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || 'Не удалось пополнить Turbo.');
|
||||
}
|
||||
};
|
||||
|
||||
const resetPreviewState = () => {
|
||||
selectedPreviewEnabled = false;
|
||||
selectedPreviewFile = null;
|
||||
selectedPreviewSha256 = '';
|
||||
selectedPreviewPriceInfo = null;
|
||||
};
|
||||
|
||||
const isPreviewEligibleForCurrentFile = () => (
|
||||
!isAvatarMode
|
||||
&& selectedFile instanceof File
|
||||
&& isVideoAttachmentName(selectedFile.name)
|
||||
);
|
||||
|
||||
const combinedUploadSize = () => {
|
||||
return Number(selectedFile?.size || 0) + Number(selectedPreviewEnabled ? (selectedPreviewFile?.size || 0) : 0);
|
||||
};
|
||||
|
||||
const renderArweaveMeta = (mainMetaEl, previewMetaEl) => {
|
||||
if (!mainMetaEl || !previewMetaEl) return;
|
||||
const renderArweaveMeta = (mainMetaEl) => {
|
||||
if (!mainMetaEl) return;
|
||||
mainMetaEl.innerHTML = `
|
||||
${isAvatarMode ? '' : `<div>Имя: ${escapeHtml(selectedFile?.name || 'file')}</div>`}
|
||||
<div>Размер: ${escapeHtml(formatBytes(selectedFile?.size || 0))}</div>
|
||||
@@ -491,44 +402,27 @@ export function openArweaveAttachmentManager({
|
||||
<div>Цена: ${escapeHtml(Number(priceInfo?.ar || 0).toLocaleString('ru-RU', { maximumFractionDigits: 6 }))} AR</div>
|
||||
<div>Баланс кошелька: ${escapeHtml(Number(balanceInfo?.ar || 0).toLocaleString('ru-RU', { maximumFractionDigits: 6 }))} AR</div>
|
||||
`;
|
||||
previewMetaEl.innerHTML = '';
|
||||
if (selectedPreviewEnabled && selectedPreviewFile) {
|
||||
previewMetaEl.innerHTML = `
|
||||
<div><strong>Файл превью</strong></div>
|
||||
<div>Имя: ${escapeHtml(selectedPreviewFile.name)}</div>
|
||||
<div>Размер превью: ${escapeHtml(formatBytes(selectedPreviewFile.size))}</div>
|
||||
<div>SHA-256 превью: ${escapeHtml(selectedPreviewSha256 || '–')}</div>
|
||||
<div>Цена превью: ${escapeHtml(selectedPreviewPriceInfo ? `${Number(selectedPreviewPriceInfo.ar || 0).toLocaleString('ru-RU', { maximumFractionDigits: 6 })} AR` : '–')}</div>
|
||||
`;
|
||||
}
|
||||
};
|
||||
|
||||
const recalculateArweaveState = async (mainMetaEl, previewMetaEl, errorEl, uploadBtn) => {
|
||||
const recalculateArweaveState = async (mainMetaEl, errorEl, uploadBtn) => {
|
||||
uploadBtn.disabled = true;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
selectedPreviewPriceInfo = null;
|
||||
setText(errorEl, '');
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
setText(mainMetaEl, '');
|
||||
setText(previewMetaEl, '');
|
||||
return;
|
||||
}
|
||||
const wallet = selectedWallet();
|
||||
if (!wallet?.address) throw new Error('Выберите Arweave-кошелёк.');
|
||||
const mainPrice = await getArweaveUploadPrice({ gateway: cleanGateway, byteLength: selectedFile.size });
|
||||
let totalWinston = BigInt(mainPrice.winston);
|
||||
if (selectedPreviewEnabled && selectedPreviewFile) {
|
||||
const previewPrice = await getArweaveUploadPrice({ gateway: cleanGateway, byteLength: selectedPreviewFile.size });
|
||||
selectedPreviewPriceInfo = previewPrice;
|
||||
totalWinston += BigInt(previewPrice.winston);
|
||||
}
|
||||
const totalWinston = BigInt(mainPrice.winston);
|
||||
balanceInfo = await getArweaveBalance({ gateway: cleanGateway, address: wallet.address });
|
||||
priceInfo = {
|
||||
ar: Number(totalWinston) / 1e12,
|
||||
winston: totalWinston.toString(),
|
||||
};
|
||||
renderArweaveMeta(mainMetaEl, previewMetaEl);
|
||||
renderArweaveMeta(mainMetaEl);
|
||||
const hasFunds = BigInt(balanceInfo.winston) >= totalWinston;
|
||||
if (!hasFunds) {
|
||||
setText(errorEl, 'Недостаточно AR на выбранном кошельке.');
|
||||
@@ -537,14 +431,13 @@ export function openArweaveAttachmentManager({
|
||||
uploadBtn.disabled = false;
|
||||
};
|
||||
|
||||
const refreshTurboStateForCurrentFile = async (mainMetaEl, previewMetaEl, errorEl, uploadBtn) => {
|
||||
const refreshTurboStateForCurrentFile = async (mainMetaEl, errorEl, uploadBtn) => {
|
||||
uploadBtn.disabled = true;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
selectedPreviewPriceInfo = null;
|
||||
setText(errorEl, '');
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
renderTurboMeta(mainMetaEl, previewMetaEl);
|
||||
renderTurboMeta(mainMetaEl);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -554,21 +447,11 @@ export function openArweaveAttachmentManager({
|
||||
keySource: selectedTurboKeySource,
|
||||
byteLength: selectedFile.size,
|
||||
});
|
||||
let totalWinc = BigInt(mainPrice.winc);
|
||||
if (selectedPreviewEnabled && selectedPreviewFile) {
|
||||
const previewPrice = await estimateTurboUploadPrice({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
byteLength: selectedPreviewFile.size,
|
||||
});
|
||||
selectedPreviewPriceInfo = previewPrice;
|
||||
totalWinc += BigInt(previewPrice.winc);
|
||||
}
|
||||
const totalWinc = BigInt(mainPrice.winc);
|
||||
priceInfo = {
|
||||
...mainPrice,
|
||||
byteLength: combinedUploadSize(),
|
||||
isFree: combinedUploadSize() <= getFreeTurboUploadBytesLimit(),
|
||||
byteLength: Number(selectedFile.size || 0),
|
||||
isFree: Number(selectedFile.size || 0) <= getFreeTurboUploadBytesLimit(),
|
||||
winc: totalWinc.toString(),
|
||||
credits: Number(totalWinc) / 1_000_000_000_000,
|
||||
};
|
||||
@@ -577,7 +460,7 @@ export function openArweaveAttachmentManager({
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
});
|
||||
renderTurboMeta(mainMetaEl, previewMetaEl);
|
||||
renderTurboMeta(mainMetaEl);
|
||||
if (!priceInfo.isFree && BigInt(balanceInfo.effectiveWinc) < BigInt(priceInfo.winc)) {
|
||||
setText(errorEl, 'Turbo balance недостаточен. Нажмите «Пополнить Turbo».');
|
||||
return;
|
||||
@@ -632,11 +515,6 @@ export function openArweaveAttachmentManager({
|
||||
<span class="ar-attachment-file-name" data-file-name="true">Файл не выбран</span>
|
||||
</label>`}
|
||||
<div class="ar-attachment-meta" data-meta-main="true"></div>
|
||||
<label class="meta-muted" data-preview-option="true" hidden>
|
||||
<input type="checkbox" data-preview-toggle="true" />
|
||||
Добавить превью
|
||||
</label>
|
||||
<div class="ar-attachment-meta" data-meta-preview="true"></div>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
${turboMode ? '<button class="secondary-btn" type="button" data-action="topup">Пополнить Turbo</button>' : '<button class="secondary-btn" type="button" data-action="cancel">Отмена</button>'}
|
||||
@@ -649,18 +527,14 @@ export function openArweaveAttachmentManager({
|
||||
const walletEl = root.querySelector('#ar-attach-wallet');
|
||||
const fileEl = root.querySelector('#ar-attach-file');
|
||||
const mainMetaEl = root.querySelector('[data-meta-main="true"]');
|
||||
const previewMetaEl = root.querySelector('[data-meta-preview="true"]');
|
||||
const errorEl = root.querySelector('[data-error="true"]');
|
||||
const uploadBtn = root.querySelector('[data-action="upload"]');
|
||||
const previewOptionEl = root.querySelector('[data-preview-option="true"]');
|
||||
const previewToggleEl = root.querySelector('[data-preview-toggle="true"]');
|
||||
|
||||
root.querySelector('[data-action="switch-arweave"]')?.addEventListener('click', async () => {
|
||||
if (selectedUploadTransport === 'arweave') return;
|
||||
selectedUploadTransport = 'arweave';
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
resetPreviewState();
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
await showUpload();
|
||||
@@ -670,7 +544,6 @@ export function openArweaveAttachmentManager({
|
||||
selectedUploadTransport = 'turbo';
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
resetPreviewState();
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
await showUpload();
|
||||
@@ -680,7 +553,7 @@ export function openArweaveAttachmentManager({
|
||||
|
||||
if (turboMode) {
|
||||
await loadTurboKeyChoices(errorEl);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await loadWallets(errorEl);
|
||||
if (walletEl) {
|
||||
@@ -692,21 +565,19 @@ export function openArweaveAttachmentManager({
|
||||
uploadBtn.disabled = true;
|
||||
selectedFile = null;
|
||||
selectedSha256 = '';
|
||||
resetPreviewState();
|
||||
priceInfo = null;
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
if (fileEl) fileEl.value = '';
|
||||
setText(mainMetaEl, '');
|
||||
setText(previewMetaEl, '');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
root.querySelectorAll('[data-action="cancel"]').forEach((btn) => btn.addEventListener('click', () => close(resolve, null)));
|
||||
root.querySelector('[data-action="topup"]')?.addEventListener('click', async () => {
|
||||
await promptTurboTopUp(mainMetaEl, previewMetaEl, errorEl);
|
||||
await promptTurboTopUp(mainMetaEl, errorEl);
|
||||
if (turboMode && selectedFile && selectedSha256) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
});
|
||||
if (!turboMode) {
|
||||
@@ -720,15 +591,11 @@ export function openArweaveAttachmentManager({
|
||||
fileEl?.addEventListener('change', async () => {
|
||||
selectedFile = fileEl.files?.[0] || null;
|
||||
selectedSha256 = '';
|
||||
resetPreviewState();
|
||||
priceInfo = null;
|
||||
balanceInfo = null;
|
||||
uploadBtn.disabled = true;
|
||||
setText(errorEl, '');
|
||||
setText(mainMetaEl, '');
|
||||
setText(previewMetaEl, '');
|
||||
if (previewToggleEl instanceof HTMLInputElement) previewToggleEl.checked = false;
|
||||
if (previewOptionEl) previewOptionEl.hidden = true;
|
||||
if (!selectedFile) return;
|
||||
|
||||
try {
|
||||
@@ -740,46 +607,16 @@ export function openArweaveAttachmentManager({
|
||||
}
|
||||
const buffer = await selectedFile.arrayBuffer();
|
||||
selectedSha256 = await sha256HexFromArrayBuffer(buffer);
|
||||
if (previewOptionEl && isPreviewEligibleForCurrentFile()) {
|
||||
previewOptionEl.hidden = false;
|
||||
}
|
||||
if (turboMode) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await recalculateArweaveState(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await recalculateArweaveState(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
} catch (error) {
|
||||
setText(errorEl, error?.message || 'Не удалось подготовить файл.');
|
||||
}
|
||||
});
|
||||
|
||||
previewToggleEl?.addEventListener('change', async () => {
|
||||
if (!(previewToggleEl instanceof HTMLInputElement)) return;
|
||||
if (!selectedFile || !isPreviewEligibleForCurrentFile()) {
|
||||
previewToggleEl.checked = false;
|
||||
return;
|
||||
}
|
||||
uploadBtn.disabled = true;
|
||||
selectedPreviewEnabled = previewToggleEl.checked;
|
||||
selectedPreviewFile = null;
|
||||
selectedPreviewSha256 = '';
|
||||
setText(errorEl, '');
|
||||
try {
|
||||
if (selectedPreviewEnabled) {
|
||||
selectedPreviewFile = await createVideoPreviewFile(selectedFile);
|
||||
selectedPreviewSha256 = await sha256HexFromArrayBuffer(await selectedPreviewFile.arrayBuffer());
|
||||
}
|
||||
if (turboMode) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await recalculateArweaveState(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
} catch (error) {
|
||||
resetPreviewState();
|
||||
previewToggleEl.checked = false;
|
||||
setText(errorEl, error?.message || 'Не удалось подготовить превью.');
|
||||
}
|
||||
});
|
||||
|
||||
uploadBtn?.addEventListener('click', async () => {
|
||||
if (!selectedFile || !selectedSha256) {
|
||||
@@ -796,31 +633,6 @@ export function openArweaveAttachmentManager({
|
||||
uploadBtn.disabled = true;
|
||||
setText(errorEl, turboMode ? 'Загружаем файл через Turbo...' : 'Загружаем файл в Arweave...');
|
||||
try {
|
||||
let previewUpload = null;
|
||||
if (selectedPreviewEnabled && selectedPreviewFile && selectedPreviewSha256) {
|
||||
previewUpload = turboMode
|
||||
? await uploadFileWithTurbo({
|
||||
login: cleanLogin,
|
||||
storagePwd: cleanStoragePwd,
|
||||
keySource: selectedTurboKeySource,
|
||||
file: selectedPreviewFile,
|
||||
shineType: 'attachment-preview',
|
||||
tags: [
|
||||
{ name: 'SHiNE-Login', value: cleanLogin },
|
||||
{ name: 'SHiNE-Attachment-Preview-For', value: selectedFile.name || 'file' },
|
||||
],
|
||||
})
|
||||
: await uploadArweaveFile({
|
||||
gateway: cleanGateway,
|
||||
jwk: selectedWallet()?.jwk,
|
||||
file: selectedPreviewFile,
|
||||
shineType: 'attachment-preview',
|
||||
tags: [
|
||||
{ name: 'SHiNE-Login', value: cleanLogin },
|
||||
{ name: 'SHiNE-Attachment-Preview-For', value: selectedFile.name || 'file' },
|
||||
],
|
||||
});
|
||||
}
|
||||
const uploaded = turboMode
|
||||
? await uploadFileWithTurbo({
|
||||
login: cleanLogin,
|
||||
@@ -851,12 +663,6 @@ export function openArweaveAttachmentManager({
|
||||
sha256: selectedSha256,
|
||||
ar: uploaded.id,
|
||||
uploadTransport: turboMode ? 'turbo' : 'arweave',
|
||||
preview: previewUpload?.id && selectedPreviewSha256
|
||||
? {
|
||||
ar: previewUpload.id,
|
||||
sha256: selectedPreviewSha256,
|
||||
}
|
||||
: undefined,
|
||||
uploadedAtMs: Date.now(),
|
||||
purpose: isAvatarMode ? 'avatar' : 'attachment',
|
||||
}, { pendingPlacement: historyOnly && !isAvatarMode });
|
||||
@@ -867,13 +673,10 @@ export function openArweaveAttachmentManager({
|
||||
});
|
||||
|
||||
if (selectedFile && selectedSha256) {
|
||||
if (previewOptionEl && isPreviewEligibleForCurrentFile()) {
|
||||
previewOptionEl.hidden = false;
|
||||
}
|
||||
if (turboMode) {
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await refreshTurboStateForCurrentFile(mainMetaEl, errorEl, uploadBtn);
|
||||
} else {
|
||||
await recalculateArweaveState(mainMetaEl, previewMetaEl, errorEl, uploadBtn);
|
||||
await recalculateArweaveState(mainMetaEl, errorEl, uploadBtn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -894,14 +697,6 @@ export function openArweaveAttachmentManager({
|
||||
<label class="meta-muted" for="ar-existing-name">Имя файла в сообщении</label>
|
||||
<input class="input" id="ar-existing-name" type="text" maxlength="180" placeholder="например report.pdf" />
|
||||
`}
|
||||
<label class="meta-muted" data-existing-preview-wrap="true" ${isAvatarMode ? 'hidden' : 'hidden'}>
|
||||
<input type="checkbox" data-existing-preview-toggle="true" />
|
||||
Добавить превью
|
||||
</label>
|
||||
<div class="stack" data-existing-preview-fields="true" hidden>
|
||||
<label class="meta-muted" for="ar-existing-preview-txid">Transaction ID превью</label>
|
||||
<input class="input" id="ar-existing-preview-txid" type="text" maxlength="64" placeholder="43 символа txId превью" />
|
||||
</div>
|
||||
<div class="ar-attachment-meta" data-meta="true"></div>
|
||||
<p class="meta-muted inline-error" data-error="true"></p>
|
||||
<div class="form-actions-grid">
|
||||
@@ -914,67 +709,33 @@ export function openArweaveAttachmentManager({
|
||||
bindBackdrop();
|
||||
const txEl = root.querySelector('#ar-existing-txid');
|
||||
const nameEl = root.querySelector('#ar-existing-name');
|
||||
const previewWrapEl = root.querySelector('[data-existing-preview-wrap="true"]');
|
||||
const previewToggleEl = root.querySelector('[data-existing-preview-toggle="true"]');
|
||||
const previewFieldsEl = root.querySelector('[data-existing-preview-fields="true"]');
|
||||
const previewTxEl = root.querySelector('#ar-existing-preview-txid');
|
||||
const metaEl = root.querySelector('[data-meta="true"]');
|
||||
const errorEl = root.querySelector('[data-error="true"]');
|
||||
const checkBtn = root.querySelector('[data-action="check"]');
|
||||
root.querySelector('[data-action="back"]')?.addEventListener('click', showUpload);
|
||||
nameEl?.addEventListener('input', () => {
|
||||
const isVideo = isVideoAttachmentName(String(nameEl.value || '').trim());
|
||||
if (previewWrapEl) previewWrapEl.hidden = !isVideo;
|
||||
if (!isVideo) {
|
||||
if (previewToggleEl instanceof HTMLInputElement) previewToggleEl.checked = false;
|
||||
if (previewFieldsEl) previewFieldsEl.hidden = true;
|
||||
if (previewTxEl) previewTxEl.value = '';
|
||||
}
|
||||
});
|
||||
previewToggleEl?.addEventListener('change', () => {
|
||||
if (previewFieldsEl && previewToggleEl instanceof HTMLInputElement) {
|
||||
previewFieldsEl.hidden = !previewToggleEl.checked;
|
||||
}
|
||||
});
|
||||
checkBtn?.addEventListener('click', async () => {
|
||||
const txId = String(txEl?.value || '').trim();
|
||||
const name = isAvatarMode ? 'Аватар' : (String(nameEl?.value || '').trim() || 'arweave-file');
|
||||
const wantsPreview = !isAvatarMode && previewToggleEl instanceof HTMLInputElement && previewToggleEl.checked;
|
||||
const previewTxId = String(previewTxEl?.value || '').trim();
|
||||
if (!validateArweaveTxId(txId)) {
|
||||
setText(errorEl, 'Некорректный Transaction ID Arweave.');
|
||||
return;
|
||||
}
|
||||
if (wantsPreview && !validateArweaveTxId(previewTxId)) {
|
||||
setText(errorEl, 'Некорректный Transaction ID превью.');
|
||||
return;
|
||||
}
|
||||
checkBtn.disabled = true;
|
||||
setText(errorEl, 'Скачиваем файл и считаем SHA-256...');
|
||||
setText(metaEl, '');
|
||||
try {
|
||||
const meta = await loadArweaveFileMetadata({ gateway: cleanGateway, txId });
|
||||
let preview = null;
|
||||
if (wantsPreview) {
|
||||
const previewMeta = await loadArweaveFileMetadata({ gateway: cleanGateway, txId: previewTxId });
|
||||
preview = {
|
||||
ar: previewTxId,
|
||||
sha256: previewMeta.sha256Hex,
|
||||
};
|
||||
}
|
||||
const item = normalizeAttachment({
|
||||
name,
|
||||
size: meta.sizeBytes,
|
||||
sha256: meta.sha256Hex,
|
||||
ar: txId,
|
||||
preview,
|
||||
uploadedAtMs: Date.now(),
|
||||
purpose: isAvatarMode ? 'avatar' : 'attachment',
|
||||
});
|
||||
metaEl.innerHTML = `
|
||||
<div>Размер: ${escapeHtml(formatBytes(item.size))}</div>
|
||||
<div>SHA-256: ${escapeHtml(item.sha256)}</div>
|
||||
${item.preview ? '<div>Превью будет добавлено вместе с файлом.</div>' : ''}
|
||||
`;
|
||||
setText(errorEl, '');
|
||||
const addBtn = document.createElement('button');
|
||||
@@ -1005,13 +766,11 @@ export function openArweaveAttachmentManager({
|
||||
${rows.length ? rows.map((item, index) => {
|
||||
const isSelected = selectedTxIdSet.has(item.ar);
|
||||
return `
|
||||
<article class="ar-attachment-history-tile${hasAttachmentPreview(item) ? ' ar-attachment-history-tile--with-preview' : ''}${isSelected ? ' is-selected' : ''}" data-history-tile="${index}">
|
||||
${buildHistoryPreviewMarkup(item, cleanGateway)}
|
||||
<article class="ar-attachment-history-tile${isSelected ? ' is-selected' : ''}" data-history-tile="${index}">
|
||||
<strong class="ar-attachment-history-name">${escapeHtml(item.name)}${item.purpose === 'avatar' ? ' · аватар' : ''}</strong>
|
||||
<div class="ar-attachment-history-meta-row">
|
||||
<span>${escapeHtml(formatBytes(item.size))}</span>
|
||||
<span>${escapeHtml(formatArweaveHistoryTime(item.uploadedAtMs))}</span>
|
||||
${hasAttachmentPreview(item) ? '<span class="ar-attachment-placement-flag">С превью</span>' : ''}
|
||||
<span class="ar-attachment-status ar-attachment-status--pending" data-status="${index}">Проверяем...</span>
|
||||
${item.pendingPlacement ? '<span class="ar-attachment-placement-flag">Ещё не прикреплён</span>' : ''}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { openArweaveAttachmentManager } from './arweave-attachment-manager.js';
|
||||
import { formatBytes } from '../services/attachment-format.js';
|
||||
import { uploadPublicFile } from '../services/public-file-service.js';
|
||||
import { state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export function openChannelAttachmentManager({
|
||||
login,
|
||||
storagePwd = '',
|
||||
gateway = '',
|
||||
selectedTxIds = [],
|
||||
signal = null,
|
||||
} = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const root = document.createElement('div');
|
||||
root.className = 'public-attachment-manager-root';
|
||||
document.body.append(root);
|
||||
|
||||
let closed = false;
|
||||
let selectedFile = null;
|
||||
let uploading = false;
|
||||
|
||||
const close = (resolve, value = null) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
root.remove();
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const onAbort = () => close(resolve, null);
|
||||
if (signal?.aborted) { onAbort(); return; }
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal public-attachment-manager" data-public-attachment-modal="true">
|
||||
<div class="modal-card stack public-attachment-manager__card" role="dialog" aria-modal="true" aria-labelledby="public-attachment-title">
|
||||
<div class="public-attachment-manager__header">
|
||||
<h3 class="modal-title" id="public-attachment-title">Добавить файл</h3>
|
||||
<button class="icon-btn" type="button" data-action="close" aria-label="Закрыть">×</button>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__sources" role="radiogroup" aria-label="Место хранения файла">
|
||||
<label class="public-attachment-manager__source is-selected">
|
||||
<input type="radio" name="attachment-storage" value="server" checked />
|
||||
<span><strong>Сервер доступа</strong><small>Бесплатно · пока доступно</small></span>
|
||||
</label>
|
||||
<label class="public-attachment-manager__source">
|
||||
<input type="radio" name="attachment-storage" value="arweave" />
|
||||
<span><strong>Arweave</strong><small>Постоянное децентрализованное хранение</small></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__server" data-panel="server">
|
||||
<div class="public-attachment-manager__notice">
|
||||
<strong>САМ ФАЙЛ БУДЕТ ХРАНИТЬСЯ ТОЛЬКО НА ВАШЕМ СЕРВЕРЕ ДОСТУПА.</strong>
|
||||
<p>В блокчейн SHiNE записываются имя, размер и SHA-256-хеш файла, но не сам файл. Хранение на сервере доступа бесплатно.</p>
|
||||
<p>Если сервер доступа перестанет работать, файл станет недоступен. При обычном переходе на другой сервер доступа в дальнейшем файлы смогут переноситься автоматически.</p>
|
||||
<p>Храните собственные копии важных вложений. Если сервер внезапно исчезнет, тот же исходный файл можно будет загрузить на другой сервер доступа: совпадающий SHA-256 позволит старым сообщениям снова найти правильные байты.</p>
|
||||
<p>Сейчас у пользователя может быть только один сервер доступа. В расширенной версии SHiNE планируется поддержка нескольких серверов доступа, в том числе дополнительных оплачиваемых серверов.</p>
|
||||
</div>
|
||||
<input class="input" type="file" data-role="file" />
|
||||
<div class="public-attachment-manager__selected meta-muted" data-role="selected">Файл не выбран.</div>
|
||||
<div class="public-attachment-manager__status meta-muted" data-role="status"></div>
|
||||
<div class="public-attachment-manager__error inline-error" data-role="error"></div>
|
||||
<button class="primary-btn" type="button" data-action="upload" disabled>Загрузить и добавить</button>
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__arweave" data-panel="arweave" hidden>
|
||||
<p class="meta-muted">Файл будет загружен через существующий механизм Arweave/Turbo.</p>
|
||||
<button class="primary-btn" type="button" data-action="arweave">Продолжить в Arweave</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const modal = root.querySelector('[data-public-attachment-modal="true"]');
|
||||
const fileInput = root.querySelector('[data-role="file"]');
|
||||
const selectedEl = root.querySelector('[data-role="selected"]');
|
||||
const statusEl = root.querySelector('[data-role="status"]');
|
||||
const errorEl = root.querySelector('[data-role="error"]');
|
||||
const uploadButton = root.querySelector('[data-action="upload"]');
|
||||
const arweaveButton = root.querySelector('[data-action="arweave"]');
|
||||
const radios = [...root.querySelectorAll('input[name="attachment-storage"]')];
|
||||
|
||||
const setSource = (value) => {
|
||||
root.querySelectorAll('.public-attachment-manager__source').forEach((label) => {
|
||||
label.classList.toggle('is-selected', label.querySelector('input')?.value === value);
|
||||
});
|
||||
root.querySelector('[data-panel="server"]').hidden = value !== 'server';
|
||||
root.querySelector('[data-panel="arweave"]').hidden = value !== 'arweave';
|
||||
};
|
||||
|
||||
radios.forEach((radio) => radio.addEventListener('change', () => setSource(radio.value)));
|
||||
root.querySelector('[data-action="close"]')?.addEventListener('click', () => close(resolve, null));
|
||||
modal?.addEventListener('click', (event) => {
|
||||
if (event.target === modal && !uploading) close(resolve, null);
|
||||
});
|
||||
|
||||
fileInput?.addEventListener('change', () => {
|
||||
selectedFile = fileInput.files?.[0] || null;
|
||||
if (selectedEl) selectedEl.textContent = selectedFile
|
||||
? `${selectedFile.name} · ${formatBytes(selectedFile.size)}`
|
||||
: 'Файл не выбран.';
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
if (statusEl) statusEl.textContent = '';
|
||||
if (uploadButton) uploadButton.disabled = !selectedFile;
|
||||
});
|
||||
|
||||
uploadButton?.addEventListener('click', async () => {
|
||||
if (!selectedFile || uploading) return;
|
||||
uploading = true;
|
||||
uploadButton.disabled = true;
|
||||
fileInput.disabled = true;
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
try {
|
||||
const item = await uploadPublicFile({
|
||||
file: selectedFile,
|
||||
login: cleanLogin,
|
||||
sessionId: state.session.sessionId,
|
||||
wsUrl: state.entrySettings.shineServer,
|
||||
onStatus: (message) => { if (statusEl) statusEl.textContent = message; },
|
||||
});
|
||||
close(resolve, item);
|
||||
} catch (error) {
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, 'Не удалось загрузить файл.');
|
||||
if (statusEl) statusEl.textContent = '';
|
||||
uploading = false;
|
||||
fileInput.disabled = false;
|
||||
uploadButton.disabled = !selectedFile;
|
||||
}
|
||||
});
|
||||
|
||||
arweaveButton?.addEventListener('click', async () => {
|
||||
if (uploading) return;
|
||||
uploading = true;
|
||||
root.hidden = true;
|
||||
try {
|
||||
const item = await openArweaveAttachmentManager({
|
||||
login: cleanLogin,
|
||||
storagePwd,
|
||||
gateway,
|
||||
selectedTxIds,
|
||||
signal,
|
||||
});
|
||||
if (item) close(resolve, item);
|
||||
else {
|
||||
uploading = false;
|
||||
root.hidden = false;
|
||||
}
|
||||
} catch (error) {
|
||||
uploading = false;
|
||||
root.hidden = false;
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, 'Не удалось открыть Arweave.');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from './arweave-attachment-manager.js';
|
||||
import { markArweaveAttachmentPlaced } from './arweave-attachment-manager.js';
|
||||
import { openChannelAttachmentManager } from './channel-attachment-manager.js';
|
||||
import { composeMessageWithAttachments, MAX_MESSAGE_ATTACHMENTS } from '../services/attachment-format.js';
|
||||
import { state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
@@ -266,7 +267,7 @@ export function openChannelEditor({
|
||||
attachments: [...attachments],
|
||||
});
|
||||
completed = true;
|
||||
attachments.forEach((item) => markArweaveAttachmentPlaced(login, item));
|
||||
attachments.filter((item) => item?.ar).forEach((item) => markArweaveAttachmentPlaced(login, item));
|
||||
// Не удаляем новый черновик, открытый после закрытия отправляющего редактора.
|
||||
if (!closed || drafts.get(storageKey)?.text === textarea.value) drafts.delete(storageKey);
|
||||
if (!isActive() || closed) return;
|
||||
@@ -286,7 +287,7 @@ export function openChannelEditor({
|
||||
};
|
||||
|
||||
const onDocumentKeydown = (event) => {
|
||||
if (!overlay.isConnected || document.querySelector('.ar-attachment-manager-root')) return;
|
||||
if (!overlay.isConnected || document.querySelector('.ar-attachment-manager-root, .public-attachment-manager-root')) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
close();
|
||||
@@ -338,7 +339,7 @@ export function openChannelEditor({
|
||||
picking = true;
|
||||
dialog.inert = true;
|
||||
sync();
|
||||
const item = await openArweaveAttachmentManager({
|
||||
const item = await openChannelAttachmentManager({
|
||||
login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
|
||||
@@ -2,6 +2,7 @@ const paths = {
|
||||
heart: '<path d="M12 21S2.3 15.5 2.3 8.7C2.3 3.6 8.1 1.9 12 6.5c3.9-4.6 9.7-2.9 9.7 2.2C21.7 15.5 12 21 12 21Z"/>',
|
||||
message: '<path d="M5.2 2.35h13.6a2.7 2.7 0 0 1 2.7 2.7v9.7a2.7 2.7 0 0 1-2.7 2.7h-7.1L7.2 21v-3.55h-2a2.7 2.7 0 0 1-2.7-2.7v-9.7a2.7 2.7 0 0 1 2.7-2.7Z"/>',
|
||||
more: '<circle cx="4" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="20" cy="12" r="1.6" fill="currentColor" stroke="none"/>',
|
||||
moreVertical: '<circle cx="12" cy="4" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="20" r="1.6" fill="currentColor" stroke="none"/>',
|
||||
forward: '<path d="m14.4 3.1 7.2 7.1-7.2 6.6v-4.4C8.5 12.4 5 15.1 2.4 20c.4-7.6 4.4-11.7 12-12.4Z"/>',
|
||||
download: '<path d="M12 4v11M7 10.5l5 5 5-5M5 20h14"/>',
|
||||
reply: '<path d="M9 7 4 12l5 5"/><path d="M4 12h9a7 7 0 0 1 7 7"/>',
|
||||
|
||||
@@ -21,7 +21,7 @@ function setStatusBadge(node, status, label) {
|
||||
|
||||
function renderTile(item, index) {
|
||||
const tile = document.createElement('article');
|
||||
tile.className = `ar-attachment-history-tile ar-attachment-history-tile--page${item?.preview?.ar ? ' ar-attachment-history-tile--with-preview' : ''}`;
|
||||
tile.className = 'ar-attachment-history-tile ar-attachment-history-tile--page';
|
||||
|
||||
const name = document.createElement('strong');
|
||||
name.className = 'ar-attachment-history-name';
|
||||
@@ -39,12 +39,6 @@ function renderTile(item, index) {
|
||||
const time = document.createElement('span');
|
||||
time.textContent = formatArweaveHistoryTime(item.uploadedAtMs);
|
||||
meta.append(status, size, time);
|
||||
if (item?.preview?.ar) {
|
||||
const previewFlag = document.createElement('span');
|
||||
previewFlag.className = 'ar-attachment-placement-flag';
|
||||
previewFlag.textContent = 'С превью';
|
||||
meta.append(previewFlag);
|
||||
}
|
||||
if (item.pendingPlacement) {
|
||||
const flag = document.createElement('span');
|
||||
flag.className = 'ar-attachment-placement-flag';
|
||||
|
||||
@@ -2,6 +2,7 @@ import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { markArweaveAttachmentPlaced, openArweaveAttachmentManager } from '../components/arweave-attachment-manager.js';
|
||||
import { authService, setChannelsFeed, state } from '../state.js';
|
||||
import { navigateBack, getPreviousTrackedPath } from '../router.js';
|
||||
import {
|
||||
@@ -70,6 +71,112 @@ function ownerDisplayName(snapshot, ownerLogin) {
|
||||
return [firstName, lastName].filter(Boolean).join(' ').trim() || String(ownerLogin || '').trim() || 'Владелец канала';
|
||||
}
|
||||
|
||||
function formatChannelCreatedAt(value) {
|
||||
const time = Number(value || 0);
|
||||
if (!Number.isFinite(time) || time <= 0) return 'Неизвестно';
|
||||
try {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: 'long', year: 'numeric' }).format(new Date(time));
|
||||
} catch {
|
||||
return new Date(time).toLocaleDateString('ru-RU');
|
||||
}
|
||||
}
|
||||
|
||||
function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return;
|
||||
let selectedAvatar = String(channel?.avaAr || '').trim() ? {
|
||||
name: 'Аватар',
|
||||
ar: String(channel.avaAr || '').trim(),
|
||||
sha256: String(channel?.avaSha256 || '').trim(),
|
||||
size: Number(channel?.avaSize || 0),
|
||||
purpose: 'avatar',
|
||||
} : null;
|
||||
|
||||
const cleanTitle = String(channel?.displayName || channel?.displayTitle || channel?.channelName || '').trim();
|
||||
const cleanDescription = String(channel?.channelDescription || channel?.description || '').trim();
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="channel-profile-edit-modal">
|
||||
<div class="modal-card stack channel-profile-card">
|
||||
<h3 class="modal-title">Изменить профиль канала</h3>
|
||||
<div id="channel-profile-edit-avatar-preview"></div>
|
||||
<button class="secondary-btn" id="channel-profile-edit-avatar" type="button">Изменить аватар</button>
|
||||
<label class="meta-muted" for="channel-profile-edit-title">Публичное название</label>
|
||||
<input class="input" id="channel-profile-edit-title" type="text" maxlength="50" value="${escapeHtml(cleanTitle)}" />
|
||||
<label class="meta-muted" for="channel-profile-edit-description">Описание канала</label>
|
||||
<textarea class="input" id="channel-profile-edit-description" rows="4" maxlength="250">${escapeHtml(cleanDescription)}</textarea>
|
||||
<p class="meta-muted inline-error" id="channel-profile-edit-error"></p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="channel-profile-edit-cancel" type="button">Отмена</button>
|
||||
<button class="primary-btn" id="channel-profile-edit-save" type="button">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const renderPreview = () => {
|
||||
const slot = root.querySelector('#channel-profile-edit-avatar-preview');
|
||||
if (!slot) return;
|
||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || cleanTitle).trim();
|
||||
slot.innerHTML = '';
|
||||
slot.append(renderAvatar({
|
||||
initials: (title || 'К').slice(0, 1).toUpperCase(),
|
||||
avatar: selectedAvatar?.ar ? { ar: selectedAvatar.ar } : null,
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
title: title || 'Канал',
|
||||
alt: 'Аватар канала',
|
||||
}));
|
||||
};
|
||||
renderPreview();
|
||||
|
||||
root.querySelector('#channel-profile-edit-cancel')?.addEventListener('click', () => { root.innerHTML = ''; });
|
||||
root.querySelector('#channel-profile-edit-title')?.addEventListener('input', renderPreview);
|
||||
root.querySelector('#channel-profile-edit-avatar')?.addEventListener('click', async () => {
|
||||
const errorEl = root.querySelector('#channel-profile-edit-error');
|
||||
try {
|
||||
const item = await openArweaveAttachmentManager({
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
mode: 'avatar',
|
||||
historyPurpose: 'avatar',
|
||||
});
|
||||
if (!item) return;
|
||||
selectedAvatar = item;
|
||||
renderPreview();
|
||||
} catch (error) {
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, 'Не удалось выбрать аватар.');
|
||||
}
|
||||
});
|
||||
|
||||
root.querySelector('#channel-profile-edit-save')?.addEventListener('click', async () => {
|
||||
const save = root.querySelector('#channel-profile-edit-save');
|
||||
const errorEl = root.querySelector('#channel-profile-edit-error');
|
||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || '').trim();
|
||||
const description = String(root.querySelector('#channel-profile-edit-description')?.value || '').trim();
|
||||
if (Array.from(title).length > 50 || Array.from(description).length > 250) {
|
||||
if (errorEl) errorEl.textContent = 'Название — до 50 символов, описание — до 250.';
|
||||
return;
|
||||
}
|
||||
save.disabled = true;
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
try {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
if (!login || !storagePwd) throw new Error('Для изменения профиля нужно войти заново.');
|
||||
await authService.addBlockChannelMeta({ login, storagePwd, channel: selector, title, description, avatar: selectedAvatar });
|
||||
if (selectedAvatar?.ar) markArweaveAttachmentPlaced(login, selectedAvatar);
|
||||
root.innerHTML = '';
|
||||
showToast('Профиль канала обновлён');
|
||||
onSaved?.();
|
||||
} catch (error) {
|
||||
save.disabled = false;
|
||||
if (errorEl) errorEl.textContent = toUserMessage(error, 'Не удалось изменить профиль канала.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isSelectorMatch(row, selector) {
|
||||
return Boolean(
|
||||
row?.channel
|
||||
@@ -109,13 +216,26 @@ async function resolveChannelSelector(route) {
|
||||
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName.toLowerCase()
|
||||
&& String(item?.channel?.ownerLogin || '').trim().toLowerCase() === ownerLoginNormalized
|
||||
));
|
||||
if (!row?.channel?.channelRoot) throw new Error('Канал не найден.');
|
||||
if (row?.channel?.channelRoot) {
|
||||
const rootBlockchainName = String(row.channel.ownerBlockchainName || ownerRef).trim();
|
||||
return {
|
||||
ownerBlockchainName: rootBlockchainName,
|
||||
channelRootBlockNumber: Number(row.channel.channelRoot.blockNumber),
|
||||
channelRootBlockHash: normalizeHash(row.channel.channelRoot.blockHash),
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
|
||||
const rootBlockchainName = String(row.channel.ownerBlockchainName || ownerRef).trim();
|
||||
const profileChannels = await authService.listUserProfileChannels(ownerLogin, 'owned', 500, 0, true);
|
||||
const deletedRow = (Array.isArray(profileChannels?.channels) ? profileChannels.channels : []).find((item) => (
|
||||
String(item?.slug || '').trim().toLowerCase() === channelName.toLowerCase()
|
||||
&& String(item?.ownerLogin || '').trim().toLowerCase() === ownerLoginNormalized
|
||||
));
|
||||
if (!deletedRow) throw new Error('Канал не найден.');
|
||||
return {
|
||||
ownerBlockchainName: rootBlockchainName,
|
||||
channelRootBlockNumber: Number(row.channel.channelRoot.blockNumber),
|
||||
channelRootBlockHash: normalizeHash(row.channel.channelRoot.blockHash),
|
||||
ownerBlockchainName: String(deletedRow.ownerBlockchainName || ownerRef).trim(),
|
||||
channelRootBlockNumber: Number(deletedRow.rootBlockNumber),
|
||||
channelRootBlockHash: normalizeHash(deletedRow.rootBlockHashHex),
|
||||
channelName,
|
||||
};
|
||||
}
|
||||
@@ -479,6 +599,7 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
<div class="channel-about-tiles">
|
||||
${cameFromChannel ? '' : `<button class="channel-about-tile" id="channel-about-open" type="button">${iconHtml('open')}<span>Открыть</span></button>`}
|
||||
${isOwnChannel ? `<button class="channel-about-tile" id="channel-about-edit" type="button">${iconHtml('edit')}<span>Изменить профиль</span></button>` : ''}
|
||||
${subscriptionTile}
|
||||
${isOwnChannel ? '' : `<button class="channel-about-tile" id="channel-about-support" type="button">${iconHtml('gift')}<span>Поддержать автора</span></button>`}
|
||||
</div>
|
||||
@@ -488,6 +609,9 @@ export function render({ navigate, route, chrome }) {
|
||||
<span class="channel-about-row-label">Описание</span>
|
||||
<p class="channel-about-description">${escapeHtml(description || 'Описание не задано.')}</p>
|
||||
</div>
|
||||
<div class="channel-about-row channel-about-row--static">
|
||||
<span class="channel-about-row-main"><span class="channel-about-row-label">Создан</span><strong>${escapeHtml(formatChannelCreatedAt(channel?.createdAtMs))}</strong></span>
|
||||
</div>
|
||||
<button class="channel-about-row" id="channel-about-owner" type="button">
|
||||
<span class="channel-about-owner-avatar" id="channel-about-owner-avatar"></span>
|
||||
<span class="channel-about-row-main">
|
||||
@@ -497,7 +621,7 @@ export function render({ navigate, route, chrome }) {
|
||||
<span class="channel-about-row-chevron">${iconHtml('chevron')}</span>
|
||||
</button>
|
||||
${isOwnChannel && !isDeleted ? `<button class="channel-about-row" id="channel-about-delete" type="button">
|
||||
<span class="channel-about-row-main"><span class="channel-about-row-label">Удалить канал</span><span class="meta-muted">Канал можно будет восстановить новой публикацией</span></span>
|
||||
<span class="channel-about-row-main"><span class="channel-about-row-label">Удалить канал</span><span class="meta-muted">Канал останется в блокчейне, но будет помечен как удалённый. Новая публикация восстановит его.</span></span>
|
||||
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('trash')}</span>
|
||||
</button>` : ''}
|
||||
<button class="channel-about-row" id="channel-about-copy-row" type="button">
|
||||
@@ -526,6 +650,10 @@ export function render({ navigate, route, chrome }) {
|
||||
alt: '',
|
||||
}));
|
||||
|
||||
content.querySelector('#channel-about-edit')?.addEventListener('click', () => {
|
||||
requireSigningSession();
|
||||
openChannelProfileEditor({ channel, selector, onSaved: () => void refresh() });
|
||||
});
|
||||
content.querySelector('#channel-about-owner')?.addEventListener('click', () => {
|
||||
const profileRoute = makeProfileRoute(ownerLogin);
|
||||
if (profileRoute) navigate(profileRoute);
|
||||
|
||||
@@ -767,6 +767,9 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
card.append(createAttachmentCarouselElement(parsedText.attachments, {
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
messageTimestampMs: node?.createdAtMs,
|
||||
authorLogin: author,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
fallbackServerLogin: state.entrySettings.shineServerLogin,
|
||||
}));
|
||||
}
|
||||
if (isRating) {
|
||||
@@ -1009,6 +1012,15 @@ function renderThreadContext(node, { onOpenPost }) {
|
||||
toPost.addEventListener('click', onOpenPost);
|
||||
meta.append(time, expand, toPost);
|
||||
box.append(text, meta);
|
||||
if (parsed.attachments.length) {
|
||||
box.append(createAttachmentCarouselElement(parsed.attachments, {
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
messageTimestampMs: node?.createdAtMs,
|
||||
authorLogin: node?.authorLogin,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
fallbackServerLogin: state.entrySettings.shineServerLogin,
|
||||
}));
|
||||
}
|
||||
// обрезан ли текст — видно только после вставки в документ
|
||||
requestAnimationFrame(() => { expand.hidden = text.scrollHeight <= text.clientHeight + 1; });
|
||||
return box;
|
||||
@@ -1066,7 +1078,13 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
|
||||
}
|
||||
|
||||
if (parsed.attachments.length) {
|
||||
item.append(createAttachmentCarouselElement(parsed.attachments, { gateway: state.entrySettings.arweaveServer, messageTimestampMs: node?.createdAtMs }));
|
||||
item.append(createAttachmentCarouselElement(parsed.attachments, {
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
messageTimestampMs: node?.createdAtMs,
|
||||
authorLogin: node?.authorLogin,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
fallbackServerLogin: state.entrySettings.shineServerLogin,
|
||||
}));
|
||||
}
|
||||
const text = document.createElement('p');
|
||||
text.className = 'thread-comment__text';
|
||||
|
||||
@@ -1417,6 +1417,38 @@ async function loadFromApi(route, channelId) {
|
||||
} catch {
|
||||
// ignore owner feed lookup failures
|
||||
}
|
||||
if (!channel) {
|
||||
try {
|
||||
const profileChannels = await authService.listUserProfileChannels(ownerLoginForLookup, 'owned', 500, 0, true);
|
||||
const deletedRow = (Array.isArray(profileChannels?.channels) ? profileChannels.channels : []).find((item) => (
|
||||
String(item?.slug || '').trim().toLowerCase() === selector.channelName.toLowerCase()
|
||||
&& String(item?.ownerLogin || '').trim().toLowerCase() === ownerLoginForLookup.toLowerCase()
|
||||
));
|
||||
if (deletedRow) {
|
||||
channel = {
|
||||
channel: {
|
||||
ownerLogin: deletedRow.ownerLogin,
|
||||
ownerBlockchainName: deletedRow.ownerBlockchainName,
|
||||
channelName: deletedRow.slug,
|
||||
displayName: deletedRow.displayName,
|
||||
avaAr: deletedRow.avatarAr,
|
||||
deleted: !!deletedRow.deleted,
|
||||
deletedAtMs: Number(deletedRow.deletedAtMs || 0),
|
||||
channelRoot: {
|
||||
blockNumber: Number(deletedRow.rootBlockNumber),
|
||||
blockHash: normalizeRouteHash(deletedRow.rootBlockHashHex),
|
||||
},
|
||||
},
|
||||
unreadCount: 0,
|
||||
messagesCount: 0,
|
||||
readCount: 0,
|
||||
readStateInitialized: true,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore deleted-channel lookup failures
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!channel?.channel?.ownerBlockchainName || channel?.channel?.channelRoot?.blockNumber == null) {
|
||||
@@ -1956,6 +1988,9 @@ function renderPostCard(post, {
|
||||
card.append(createAttachmentCarouselElement(parsedBody.attachments, {
|
||||
gateway: state.entrySettings.arweaveServer,
|
||||
messageTimestampMs: post.timestampMs,
|
||||
authorLogin: post.authorLogin,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
fallbackServerLogin: state.entrySettings.shineServerLogin,
|
||||
}));
|
||||
}
|
||||
if (post.isRating) {
|
||||
@@ -2451,7 +2486,7 @@ export function render({ navigate, route, chrome }) {
|
||||
className: 'channel-view-topbar topbar--identity',
|
||||
actions: [
|
||||
{
|
||||
label: '⋮',
|
||||
icon: 'moreVertical',
|
||||
title: 'Действия канала',
|
||||
ariaLabel: 'Открыть меню канала',
|
||||
className: 'channel-header-more-btn',
|
||||
@@ -2468,7 +2503,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const aboutRoute = makeShineChannelAboutRoute(routeArgs);
|
||||
const donateRoute = makeShineChannelDonateRoute(routeArgs);
|
||||
const items = [];
|
||||
items.push({ label: 'О канале', iconHtml: iconHtml('info'), action: () => { if (aboutRoute) navigate(aboutRoute); } });
|
||||
items.push({ label: apiData?.isOwnChannel ? 'Редактировать' : 'О канале', iconHtml: iconHtml(apiData?.isOwnChannel ? 'edit' : 'info'), action: () => { if (aboutRoute) navigate(aboutRoute); } });
|
||||
if (apiData?.isOwnChannel && !apiData?.isDiary) {
|
||||
items.push({ label: 'Новая запись', iconHtml: iconHtml('compose'), action: () => activeAddMessage?.() });
|
||||
}
|
||||
@@ -2497,7 +2532,7 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
}
|
||||
}
|
||||
const aboutIndex = items.findIndex((item) => item.label === 'О канале');
|
||||
const aboutIndex = items.findIndex((item) => item.label === 'О канале' || item.label === 'Редактировать');
|
||||
if (aboutIndex > 0) items.unshift(...items.splice(aboutIndex, 2));
|
||||
return items;
|
||||
},
|
||||
@@ -2946,7 +2981,15 @@ export function render({ navigate, route, chrome }) {
|
||||
restorePosition,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = () => {
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
|
||||
@@ -32,6 +32,7 @@ const DIARY_DISPLAY_NAME = 'Дневник';
|
||||
const CHANNELS_VIEW_ALL = 'all';
|
||||
const CHANNELS_VIEW_OWNED = 'owned';
|
||||
const CHANNELS_VIEW_FOLLOWING = 'following';
|
||||
const CHANNELS_VIEW_DELETED = 'deleted';
|
||||
const listQueries = new Map();
|
||||
|
||||
function channelMenuIcon(name) {
|
||||
@@ -278,18 +279,21 @@ function normalizeChannelsViewMode(route = null) {
|
||||
const scope = String(route?.params?.scope || '').trim().toLowerCase();
|
||||
if (mode === 'my' || scope === 'owned') return CHANNELS_VIEW_OWNED;
|
||||
if (mode === 'following' || scope === 'following') return CHANNELS_VIEW_FOLLOWING;
|
||||
if (mode === 'deleted' || scope === 'deleted') return CHANNELS_VIEW_DELETED;
|
||||
return CHANNELS_VIEW_ALL;
|
||||
}
|
||||
|
||||
function buildChannelsViewRoute(mode) {
|
||||
if (mode === CHANNELS_VIEW_OWNED) return 'channels/my';
|
||||
if (mode === CHANNELS_VIEW_FOLLOWING) return 'channels/following';
|
||||
if (mode === CHANNELS_VIEW_DELETED) return 'channels/deleted';
|
||||
return 'channels';
|
||||
}
|
||||
|
||||
function channelsViewTitle(mode) {
|
||||
if (mode === CHANNELS_VIEW_OWNED) return 'Мои каналы';
|
||||
if (mode === CHANNELS_VIEW_FOLLOWING) return 'Подписки';
|
||||
if (mode === CHANNELS_VIEW_DELETED) return 'Удалённые каналы';
|
||||
return 'Каналы';
|
||||
}
|
||||
|
||||
@@ -765,6 +769,46 @@ function mapApiChannelRow(summary, bucketKey, idx, index, notificationsState) {
|
||||
};
|
||||
}
|
||||
|
||||
function mapDeletedOwnedChannels(payload, notificationsState = {}) {
|
||||
const rows = Array.isArray(payload?.channels) ? payload.channels : [];
|
||||
return rows.filter((item) => item?.deleted === true).map((item, idx) => {
|
||||
const rowId = `own-deleted-${idx}`;
|
||||
const ownerLogin = String(item?.ownerLogin || state.session.login || '').trim();
|
||||
const channelName = String(item?.slug || '').trim();
|
||||
const displayTitle = String(item?.displayName || channelName || 'Канал').trim();
|
||||
return {
|
||||
id: rowId,
|
||||
sourceBucket: 'ownDeleted',
|
||||
route: makeShineChannelShortRoute({
|
||||
ownerBlockchainName: String(item?.ownerBlockchainName || '').trim(),
|
||||
channelName,
|
||||
}),
|
||||
ownerName: ownerLogin,
|
||||
ownerBlockchainName: String(item?.ownerBlockchainName || '').trim(),
|
||||
channelRootBlockNumber: Number(item?.rootBlockNumber),
|
||||
channelRootBlockHash: normalizeHash(item?.rootBlockHashHex),
|
||||
avatar: avatarLetterFromName(displayTitle),
|
||||
avaAr: String(item?.avatarAr || '').trim(),
|
||||
title: displayTitle,
|
||||
technicalLabel: `@${ownerLogin}/${channelName}`,
|
||||
channelName,
|
||||
displayTitle,
|
||||
channelDescription: '',
|
||||
channelTypeCode: 1,
|
||||
channelTypeVersion: 1,
|
||||
messagePreview: 'Канал помечен как удалённый',
|
||||
messagesCount: 0,
|
||||
unreadCount: 0,
|
||||
lastMessageAt: Number(item?.deletedAtMs || 0),
|
||||
isOwnChannel: true,
|
||||
isDeleted: true,
|
||||
isSubscribed: false,
|
||||
notificationsEnabled: notificationsState[rowId] === true,
|
||||
pending: false,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function pullCreateSuccessFlash() {
|
||||
try {
|
||||
const value = String(sessionStorage.getItem(CREATE_CHANNEL_FLASH_KEY) || '').trim();
|
||||
@@ -856,10 +900,10 @@ function renderEmptyState(listState, navigate) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'channels-empty-state channels-empty-state--compact channels-empty-state--silent';
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = listState.query ? 'Ничего не найдено' : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? 'Пока нет подписок' : listState.viewMode === CHANNELS_VIEW_OWNED ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
||||
heading.textContent = listState.query ? 'Ничего не найдено' : listState.viewMode === CHANNELS_VIEW_DELETED ? 'Удалённых каналов нет' : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? 'Пока нет подписок' : listState.viewMode === CHANNELS_VIEW_OWNED ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = state.session.isAuthorized ? 'Найдите канал по имени автора или создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? 'Здесь появятся только ваши каналы, помеченные как удалённые.' : state.session.isAuthorized ? 'Найдите канал по имени автора или создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = 'primary-btn';
|
||||
@@ -1005,9 +1049,10 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
|
||||
const allChannels = listState.channels || [];
|
||||
const filtered = allChannels.filter((channel) => {
|
||||
if (listState.viewMode === CHANNELS_VIEW_OWNED) return channel.isOwnChannel === true;
|
||||
if (listState.viewMode === CHANNELS_VIEW_OWNED) return channel.isOwnChannel === true && channel.isDeleted !== true;
|
||||
if (listState.viewMode === CHANNELS_VIEW_FOLLOWING) return channel.sourceBucket === 'followedChannels';
|
||||
return true;
|
||||
if (listState.viewMode === CHANNELS_VIEW_DELETED) return channel.isDeleted === true;
|
||||
return channel.isDeleted !== true;
|
||||
}).filter((channel) => {
|
||||
const query = String(listState.query || '').trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
@@ -1091,6 +1136,20 @@ async function loadFeedAndRender({ screen, listState, contentEl, navigate, silen
|
||||
}
|
||||
|
||||
try {
|
||||
if (listState.viewMode === CHANNELS_VIEW_DELETED) {
|
||||
const payload = await authService.listUserProfileChannels(state.session.login, 'owned', 500, 0, true);
|
||||
if (listState.disposed || seq !== listState.loadSeq) return;
|
||||
listState.channels = mapDeletedOwnedChannels(payload, listState.notificationsState);
|
||||
renderListContent({
|
||||
screen,
|
||||
container: contentEl,
|
||||
listState,
|
||||
navigate,
|
||||
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const feed = await authService.listSubscriptionsFeed(state.session.login, 200);
|
||||
if (listState.disposed || seq !== listState.loadSeq) return;
|
||||
|
||||
@@ -1160,15 +1219,25 @@ export function render({ navigate, route, chrome }) {
|
||||
contentEl.className = 'channels-list-content';
|
||||
|
||||
const topBarEl = createTopBar({
|
||||
title: 'Каналы',
|
||||
title: channelsViewTitle(listState.viewMode),
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'plus',
|
||||
title: 'Создать канал',
|
||||
ariaLabel: 'Создать канал',
|
||||
className: 'channels-create-btn',
|
||||
onClick: () => navigate('add-channel-view'),
|
||||
icon: 'moreVertical',
|
||||
title: 'Меню каналов',
|
||||
ariaLabel: 'Открыть меню каналов',
|
||||
className: 'channels-menu-btn',
|
||||
menu: {
|
||||
minWidth: 240,
|
||||
items: () => [
|
||||
{ label: 'Создать канал', iconHtml: channelMenuIcon('add'), action: () => navigate('add-channel-view') },
|
||||
{ divider: true },
|
||||
{ label: 'Показать все каналы', iconHtml: channelMenuIcon('all'), selected: listState.viewMode === CHANNELS_VIEW_ALL, action: () => navigate(buildChannelsViewRoute(CHANNELS_VIEW_ALL)) },
|
||||
{ label: 'Показать подписки', iconHtml: channelMenuIcon('following'), selected: listState.viewMode === CHANNELS_VIEW_FOLLOWING, action: () => navigate(buildChannelsViewRoute(CHANNELS_VIEW_FOLLOWING)) },
|
||||
{ label: 'Показать мои', iconHtml: channelMenuIcon('mine'), selected: listState.viewMode === CHANNELS_VIEW_OWNED, action: () => navigate(buildChannelsViewRoute(CHANNELS_VIEW_OWNED)) },
|
||||
{ label: 'Показать мои удалённые каналы', iconHtml: iconHtml('trash'), selected: listState.viewMode === CHANNELS_VIEW_DELETED, action: () => navigate(buildChannelsViewRoute(CHANNELS_VIEW_DELETED)) },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { openMediaViewer } from '../components/media-viewer.js';
|
||||
import { buildArweaveDataUrl, validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer, validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { resolvePublicFileUrl } from './public-file-service.js';
|
||||
|
||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>]*)>\n?/u;
|
||||
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
||||
@@ -32,30 +33,12 @@ function normalizeName(name) {
|
||||
return clean || 'file';
|
||||
}
|
||||
|
||||
function normalizePreview(input = {}) {
|
||||
const previewTxId = String(input.preAr || input.previewAr || input.ar || input.txId || '').trim();
|
||||
const previewSha256Hex = String(input.preSha256 || input.previewSha256 || input.sha256 || input.sha256Hex || '').trim().toLowerCase();
|
||||
if (!previewTxId || !previewSha256Hex) return null;
|
||||
if (!validateArweaveTxId(previewTxId)) return null;
|
||||
if (!validateSha256Hex(previewSha256Hex)) return null;
|
||||
return {
|
||||
ar: previewTxId,
|
||||
sha256: previewSha256Hex,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeAttachment(input = {}) {
|
||||
const txId = String(input.ar || input.txId || '').trim();
|
||||
const sha256Hex = String(input.sha256 || input.sha256Hex || '').trim().toLowerCase();
|
||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||
const preview = normalizePreview(input.preview || {
|
||||
preAr: input.preAr,
|
||||
preSha256: input.preSha256,
|
||||
previewAr: input.previewAr,
|
||||
previewSha256: input.previewSha256,
|
||||
});
|
||||
if (!validateArweaveTxId(txId)) throw new Error('Некорректный Transaction ID Arweave.');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error('Некорректный Transaction ID Arweave.');
|
||||
if (!validateSha256Hex(sha256Hex)) throw new Error('Некорректный SHA-256 файла.');
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error('Некорректный размер файла.');
|
||||
const out = {
|
||||
@@ -66,20 +49,14 @@ export function normalizeAttachment(input = {}) {
|
||||
ar: txId,
|
||||
uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now(),
|
||||
};
|
||||
if (preview) {
|
||||
out.v = 2;
|
||||
out.preview = preview;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function buildAttachmentBlock(attachment) {
|
||||
const item = normalizeAttachment(attachment);
|
||||
const encodedName = encodeURIComponent(item.name);
|
||||
const previewFields = item.preview
|
||||
? `;preAr=${item.preview.ar};preSha256=${item.preview.sha256}`
|
||||
: '';
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size};sha256=${item.sha256};ar=${item.ar}${previewFields}>`;
|
||||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size};sha256=${item.sha256}${arPart}>`;
|
||||
}
|
||||
|
||||
export function composeMessageWithAttachments(text, attachments = []) {
|
||||
@@ -121,10 +98,6 @@ export function parseMessageAttachments(rawText) {
|
||||
sz: fields.sz || fields.size,
|
||||
sha256: fields.sha256,
|
||||
ar: fields.ar,
|
||||
preAr: fields.preAr,
|
||||
preSha256: fields.preSha256,
|
||||
previewAr: fields.previewAr,
|
||||
previewSha256: fields.previewSha256,
|
||||
}));
|
||||
} catch {
|
||||
// Битый attach-блок скрываем из UI, но не ломаем отображение текста.
|
||||
@@ -158,12 +131,38 @@ function isRecentMessage(messageTimestampMs) {
|
||||
return Date.now() - ts < RECENT_UNAVAILABLE_MS;
|
||||
}
|
||||
|
||||
function createUnavailableBlock(messageTimestampMs) {
|
||||
function attachmentStorage(item) {
|
||||
return item?.ar ? 'arweave' : 'server';
|
||||
}
|
||||
|
||||
function buildCurrentServerDebugUrl(item) {
|
||||
const sha = String(item?.sha256 || '').trim().toLowerCase();
|
||||
if (!validateSha256Hex(sha)) return '';
|
||||
return `${window.location.origin.replace(/\/$/, '')}/files/${sha}`;
|
||||
}
|
||||
|
||||
function createUnavailableBlock(messageTimestampMs, storage = 'arweave', detail = null) {
|
||||
const block = document.createElement('div');
|
||||
block.className = 'message-attachment-unavailable';
|
||||
block.textContent = isRecentMessage(messageTimestampMs)
|
||||
? 'Скорее всего файл недоступен, потому что сообщение было создано недавно и файл ещё не распространился в Arweave. Попробуйте повторить через несколько минут.'
|
||||
: 'Файл недоступен.';
|
||||
if (storage === 'server') {
|
||||
block.textContent = 'Файл недоступен на сервере доступа автора.';
|
||||
} else {
|
||||
block.textContent = isRecentMessage(messageTimestampMs)
|
||||
? 'Скорее всего файл недоступен, потому что сообщение было создано недавно и файл ещё не распространился в Arweave. Попробуйте повторить через несколько минут.'
|
||||
: 'Файл недоступен.';
|
||||
}
|
||||
if (detail) {
|
||||
const debug = document.createElement('pre');
|
||||
debug.className = 'message-attachment-debug';
|
||||
debug.textContent = [
|
||||
'DEBUG server attachment',
|
||||
detail.name ? `name: ${detail.name}` : '',
|
||||
detail.sha256 ? `sha256: ${detail.sha256}` : '',
|
||||
detail.url ? `url: ${detail.url}` : '',
|
||||
detail.error ? `error: ${detail.error}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
block.append(debug);
|
||||
}
|
||||
return block;
|
||||
}
|
||||
|
||||
@@ -178,10 +177,10 @@ function stopVideos(root) {
|
||||
});
|
||||
}
|
||||
|
||||
function replaceWithUnavailable(slide, messageTimestampMs) {
|
||||
function replaceWithUnavailable(slide, messageTimestampMs, storage = 'arweave', detail = null) {
|
||||
if (!slide || slide.dataset.unavailable === '1') return;
|
||||
slide.dataset.unavailable = '1';
|
||||
slide.replaceChildren(createUnavailableBlock(messageTimestampMs));
|
||||
slide.replaceChildren(createUnavailableBlock(messageTimestampMs, storage, detail));
|
||||
}
|
||||
|
||||
function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
@@ -209,13 +208,13 @@ function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
});
|
||||
void fetch(url, { method: 'HEAD', cache: 'no-store' })
|
||||
.then((response) => {
|
||||
if (!response.ok) replaceWithUnavailable(slide, messageTimestampMs);
|
||||
if (!response.ok) replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item));
|
||||
})
|
||||
.catch(() => replaceWithUnavailable(slide, messageTimestampMs));
|
||||
.catch(() => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)));
|
||||
return card;
|
||||
}
|
||||
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewUrl = '', onOpen }) {
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }) {
|
||||
const frame = document.createElement('div');
|
||||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||||
frame.role = 'button';
|
||||
@@ -251,20 +250,8 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewU
|
||||
img.alt = item.name;
|
||||
img.loading = 'lazy';
|
||||
bindImageLayout(img);
|
||||
img.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs), { once: true });
|
||||
img.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||||
frame.append(img);
|
||||
} else if (previewUrl) {
|
||||
const img = document.createElement('img');
|
||||
img.className = 'message-attachment-media';
|
||||
img.src = previewUrl;
|
||||
img.alt = `${item.name} preview`;
|
||||
img.loading = 'lazy';
|
||||
bindImageLayout(img);
|
||||
img.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs), { once: true });
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
play.textContent = '▶';
|
||||
frame.append(img, play);
|
||||
} else {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'message-attachment-media';
|
||||
@@ -272,7 +259,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewU
|
||||
video.preload = 'metadata';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs), { once: true });
|
||||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||||
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
@@ -283,7 +270,89 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewU
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function createAttachmentCarouselElement(attachments = [], { gateway = '', messageTimestampMs = 0 } = {}) {
|
||||
function mimeTypeForAttachment(item, kind) {
|
||||
const ext = getAttachmentExtension(item?.name);
|
||||
if (kind === 'image') {
|
||||
if (ext === 'svg') return 'image/svg+xml';
|
||||
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg';
|
||||
if (ext === 'png') return 'image/png';
|
||||
if (ext === 'gif') return 'image/gif';
|
||||
if (ext === 'webp') return 'image/webp';
|
||||
if (ext === 'avif') return 'image/avif';
|
||||
if (ext === 'bmp') return 'image/bmp';
|
||||
if (ext === 'apng') return 'image/apng';
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
if (kind === 'video') {
|
||||
if (ext === 'mp4' || ext === 'm4v') return 'video/mp4';
|
||||
if (ext === 'webm') return 'video/webm';
|
||||
if (ext === 'ogg' || ext === 'ogv') return 'video/ogg';
|
||||
if (ext === 'mov') return 'video/quicktime';
|
||||
if (ext === 'mpeg' || ext === 'mpg') return 'video/mpeg';
|
||||
if (ext === 'avi') return 'video/x-msvideo';
|
||||
if (ext === 'mkv') return 'video/x-matroska';
|
||||
}
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
|
||||
const attachmentObjectUrls = new Map();
|
||||
let attachmentObjectUrlObserver = null;
|
||||
|
||||
function registerAttachmentObjectUrl(owner, url) {
|
||||
if (!owner || !url) return;
|
||||
if (!owner.isConnected) {
|
||||
URL.revokeObjectURL(url);
|
||||
return;
|
||||
}
|
||||
const urls = attachmentObjectUrls.get(owner) || new Set();
|
||||
urls.add(url);
|
||||
attachmentObjectUrls.set(owner, urls);
|
||||
if (attachmentObjectUrlObserver) return;
|
||||
attachmentObjectUrlObserver = new MutationObserver(() => {
|
||||
attachmentObjectUrls.forEach((ownedUrls, element) => {
|
||||
if (element.isConnected) return;
|
||||
ownedUrls.forEach((ownedUrl) => URL.revokeObjectURL(ownedUrl));
|
||||
attachmentObjectUrls.delete(element);
|
||||
});
|
||||
if (!attachmentObjectUrls.size) {
|
||||
attachmentObjectUrlObserver.disconnect();
|
||||
attachmentObjectUrlObserver = null;
|
||||
}
|
||||
});
|
||||
attachmentObjectUrlObserver.observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||||
if (item.ar) {
|
||||
return { url: buildArweaveDataUrl({ gateway: options.gateway, txId: item.ar }), objectUrl: false };
|
||||
}
|
||||
|
||||
const serverUrl = await resolvePublicFileUrl({
|
||||
sha256: item.sha256,
|
||||
authorLogin: options.authorLogin,
|
||||
solanaEndpoint: options.solanaEndpoint,
|
||||
fallbackServerLogin: options.fallbackServerLogin,
|
||||
});
|
||||
const kind = getAttachmentKind(item);
|
||||
if (kind === 'file') return { url: serverUrl, objectUrl: false };
|
||||
|
||||
// /files хранит только байты и SHA-256. Для media тип задаёт клиент по имени из S:att.
|
||||
const response = await fetch(serverUrl);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} ${serverUrl}`);
|
||||
const buffer = await response.arrayBuffer();
|
||||
const actualSha = await sha256HexFromArrayBuffer(buffer);
|
||||
if (actualSha !== item.sha256) throw new Error(`SHA-256 скачанного файла не совпал с блокчейном: ${actualSha} != ${item.sha256} (${serverUrl})`);
|
||||
const blob = new Blob([buffer], { type: mimeTypeForAttachment(item, kind) });
|
||||
return { url: URL.createObjectURL(blob), sourceUrl: serverUrl, objectUrl: true };
|
||||
}
|
||||
|
||||
export function createAttachmentCarouselElement(attachments = [], {
|
||||
gateway = '',
|
||||
messageTimestampMs = 0,
|
||||
authorLogin = '',
|
||||
solanaEndpoint = '',
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
const items = (Array.isArray(attachments) ? attachments : [])
|
||||
.slice(0, MAX_MESSAGE_ATTACHMENTS)
|
||||
.map((raw) => {
|
||||
@@ -296,13 +365,16 @@ export function createAttachmentCarouselElement(attachments = [], { gateway = ''
|
||||
.filter(Boolean);
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'message-attachments message-attachment-carousel';
|
||||
wrap.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
wrap.addEventListener('click', (event) => event.stopPropagation());
|
||||
if (!items.length) return wrap;
|
||||
|
||||
let index = 0;
|
||||
let pointerStartX = 0;
|
||||
let renderGeneration = 0;
|
||||
const resolved = new Map();
|
||||
const pending = new Map();
|
||||
const options = { gateway, authorLogin, solanaEndpoint, fallbackServerLogin };
|
||||
|
||||
const viewport = document.createElement('div');
|
||||
viewport.className = 'message-attachment-carousel-viewport';
|
||||
const slide = document.createElement('div');
|
||||
@@ -321,27 +393,71 @@ export function createAttachmentCarouselElement(attachments = [], { gateway = ''
|
||||
counter.className = 'message-attachment-counter';
|
||||
wrap.classList.toggle('has-single-attachment', items.length <= 1);
|
||||
|
||||
// Просмотр на весь экран листает все фото и видео записи, файлы пропускает.
|
||||
const mediaItems = items
|
||||
.map((item, i) => ({ i, kind: getAttachmentKind(item), url: buildArweaveDataUrl({ gateway, txId: item.ar }), name: item.name }))
|
||||
.filter((entry) => entry.kind === 'image' || entry.kind === 'video');
|
||||
const getResolved = (itemIndex) => {
|
||||
if (resolved.has(itemIndex)) return Promise.resolve(resolved.get(itemIndex));
|
||||
if (pending.has(itemIndex)) return pending.get(itemIndex);
|
||||
const promise = resolveAttachmentDisplayUrl(items[itemIndex], options)
|
||||
.then((value) => {
|
||||
resolved.set(itemIndex, value);
|
||||
pending.delete(itemIndex);
|
||||
if (value.objectUrl) registerAttachmentObjectUrl(wrap, value.url);
|
||||
return value;
|
||||
})
|
||||
.catch((error) => {
|
||||
pending.delete(itemIndex);
|
||||
throw error;
|
||||
});
|
||||
pending.set(itemIndex, promise);
|
||||
return promise;
|
||||
};
|
||||
|
||||
const openViewer = (itemIndex) => {
|
||||
openMediaViewer(mediaItems, Math.max(0, mediaItems.findIndex((entry) => entry.i === itemIndex)));
|
||||
const entries = items
|
||||
.map((item, i) => {
|
||||
const kind = getAttachmentKind(item);
|
||||
if (kind !== 'image' && kind !== 'video') return null;
|
||||
if (item.ar) return { i, kind, url: buildArweaveDataUrl({ gateway, txId: item.ar }), name: item.name };
|
||||
const cached = resolved.get(i);
|
||||
return cached ? { i, kind, url: cached.url, name: item.name } : null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
const viewerIndex = Math.max(0, entries.findIndex((entry) => entry.i === itemIndex));
|
||||
if (entries.length) openMediaViewer(entries, viewerIndex);
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
const generation = ++renderGeneration;
|
||||
stopVideos(wrap);
|
||||
const item = items[index];
|
||||
const currentIndex = index;
|
||||
const kind = getAttachmentKind(item);
|
||||
const url = buildArweaveDataUrl({ gateway, txId: item.ar });
|
||||
const previewUrl = item.preview?.ar ? buildArweaveDataUrl({ gateway, txId: item.preview.ar }) : '';
|
||||
viewport.classList.remove('has-landscape-media');
|
||||
slide.className = 'message-attachment-slide';
|
||||
slide.dataset.unavailable = '0';
|
||||
slide.replaceChildren();
|
||||
slide.append(kind === 'file'
|
||||
? createFileCard({ item, url, messageTimestampMs, slide })
|
||||
: createMediaSlide({ item, url, kind, messageTimestampMs, slide, previewUrl, onOpen: () => openViewer(index) }));
|
||||
|
||||
const loading = document.createElement('div');
|
||||
loading.className = 'message-attachment-unavailable';
|
||||
loading.textContent = 'Загружаем файл…';
|
||||
slide.append(loading);
|
||||
|
||||
void getResolved(currentIndex)
|
||||
.then(({ url }) => {
|
||||
if (generation !== renderGeneration || currentIndex !== index || !wrap.isConnected) return;
|
||||
slide.replaceChildren(kind === 'file'
|
||||
? createFileCard({ item, url, messageTimestampMs, slide })
|
||||
: createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen: () => openViewer(currentIndex) }));
|
||||
})
|
||||
.catch((error) => {
|
||||
if (generation !== renderGeneration || currentIndex !== index || !wrap.isConnected) return;
|
||||
replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item), {
|
||||
name: item?.name || '',
|
||||
sha256: item?.sha256 || '',
|
||||
url: buildCurrentServerDebugUrl(item) || error?.message?.match(/https?:\/\/\S+/)?.[0] || '',
|
||||
error: error?.message || String(error || ''),
|
||||
});
|
||||
});
|
||||
|
||||
prev.hidden = items.length <= 1 || index <= 0;
|
||||
next.hidden = items.length <= 1 || index >= items.length - 1;
|
||||
counter.hidden = items.length <= 1;
|
||||
@@ -355,21 +471,12 @@ export function createAttachmentCarouselElement(attachments = [], { gateway = ''
|
||||
render();
|
||||
};
|
||||
|
||||
prev.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
move(-1);
|
||||
});
|
||||
next.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
move(1);
|
||||
});
|
||||
viewport.addEventListener('pointerdown', (event) => {
|
||||
pointerStartX = event.clientX;
|
||||
});
|
||||
prev.addEventListener('click', (event) => { event.stopPropagation(); move(-1); });
|
||||
next.addEventListener('click', (event) => { event.stopPropagation(); move(1); });
|
||||
viewport.addEventListener('pointerdown', (event) => { pointerStartX = event.clientX; });
|
||||
viewport.addEventListener('pointerup', (event) => {
|
||||
const dx = event.clientX - pointerStartX;
|
||||
if (Math.abs(dx) < 40) return;
|
||||
move(dx < 0 ? 1 : -1);
|
||||
if (Math.abs(dx) >= 40) move(dx < 0 ? 1 : -1);
|
||||
});
|
||||
|
||||
viewport.append(slide, prev, next);
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
|
||||
import { sha256HexFromArrayBuffer, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { loadSessionMaterial } from './key-vault.js';
|
||||
import {
|
||||
DEFAULT_SHINE_SERVER_HTTP,
|
||||
resolveShineServerForUserLogin,
|
||||
} from './shine-server-resolver.js';
|
||||
|
||||
const ACCESS_SERVER_CACHE_TTL_MS = 60_000;
|
||||
const accessServerCache = new Map();
|
||||
|
||||
async function publicFileExists(url) {
|
||||
try {
|
||||
const response = await fetch(url, { method: 'HEAD', cache: 'no-store' });
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function wsUrlToHttpBase(wsUrl = '') {
|
||||
const parsed = new URL(String(wsUrl || ''), window.location.href);
|
||||
if (parsed.protocol === 'wss:') parsed.protocol = 'https:';
|
||||
else if (parsed.protocol === 'ws:') parsed.protocol = 'http:';
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('Не удалось определить HTTP-адрес сервера доступа.');
|
||||
}
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
function publicFileUrl(serverBase, sha256) {
|
||||
const cleanSha = String(sha256 || '').trim().toLowerCase();
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error('Некорректный SHA-256 файла.');
|
||||
return `${String(serverBase || '').replace(/\/$/, '')}/files/${cleanSha}`;
|
||||
}
|
||||
|
||||
function uploadPreimage({ sessionId, sha256, size, timeMs }) {
|
||||
return `PUBLIC_FILE_UPLOAD_V1:${sessionId}:${sha256}:${Number(size)}:${Number(timeMs)}`;
|
||||
}
|
||||
|
||||
async function readErrorMessage(response) {
|
||||
try {
|
||||
const raw = String(await response.text()).trim();
|
||||
if (!raw) return '';
|
||||
try {
|
||||
const payload = JSON.parse(raw);
|
||||
return String(payload?.message || payload?.error || raw).trim();
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error('Нет активной пользовательской сессии.');
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет session key для загрузки файла.');
|
||||
}
|
||||
if (sessionMaterial.sessionId && String(sessionMaterial.sessionId) !== cleanSessionId) {
|
||||
throw new Error('Сохранённый session key относится к другой сессии.');
|
||||
}
|
||||
return {
|
||||
sessionId: cleanSessionId,
|
||||
serverBase: wsUrlToHttpBase(wsUrl),
|
||||
privateKey: await importPkcs8Ed25519(sessionMaterial.sessionPrivPkcs8),
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null } = {}) {
|
||||
if (!(file instanceof File)) throw new Error('Файл не выбран.');
|
||||
if (Number(file.size || 0) <= 0) throw new Error('Нельзя загрузить пустой файл.');
|
||||
|
||||
onStatus?.('Считаем SHA-256…');
|
||||
const bytes = await file.arrayBuffer();
|
||||
const sha256 = await sha256HexFromArrayBuffer(bytes);
|
||||
const context = await createUploadContext({ login, sessionId, wsUrl });
|
||||
const url = publicFileUrl(context.serverBase, sha256);
|
||||
|
||||
onStatus?.('Проверяем, есть ли файл на сервере…');
|
||||
try {
|
||||
const existing = await fetch(url, { method: 'HEAD', cache: 'no-store' });
|
||||
if (existing.ok) {
|
||||
const storedSize = Number(existing.headers.get('Content-Length') || -1);
|
||||
if (storedSize < 0 || storedSize === file.size) {
|
||||
return {
|
||||
v: 1,
|
||||
name: String(file.name || 'file'),
|
||||
size: Number(file.size),
|
||||
sha256,
|
||||
ar: '',
|
||||
uploadedAtMs: Date.now(),
|
||||
alreadyExists: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// HEAD — только оптимизация. PUT сам проверит hash и дедупликацию.
|
||||
}
|
||||
|
||||
const timeMs = Date.now();
|
||||
const signature = await signBase64(context.privateKey, uploadPreimage({
|
||||
sessionId: context.sessionId,
|
||||
sha256,
|
||||
size: file.size,
|
||||
timeMs,
|
||||
}));
|
||||
|
||||
onStatus?.('Загружаем на сервер доступа…');
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'X-Shine-Session-Id': context.sessionId,
|
||||
'X-Shine-Time-Ms': String(timeMs),
|
||||
'X-Shine-Content-Length': String(file.size),
|
||||
'X-Shine-Signature': signature,
|
||||
},
|
||||
body: bytes,
|
||||
cache: 'no-store',
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Не удалось загрузить файл на сервер доступа: ${error?.message || 'network error'}`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const detail = await readErrorMessage(response);
|
||||
throw new Error(detail || `Сервер отклонил файл (HTTP ${response.status}).`);
|
||||
}
|
||||
|
||||
let alreadyExists = false;
|
||||
try {
|
||||
const payload = await response.clone().json();
|
||||
alreadyExists = Boolean(payload?.alreadyExists);
|
||||
} catch {
|
||||
// Успешного HTTP достаточно.
|
||||
}
|
||||
|
||||
return {
|
||||
v: 1,
|
||||
name: String(file.name || 'file'),
|
||||
size: Number(file.size),
|
||||
sha256,
|
||||
ar: '',
|
||||
uploadedAtMs: Date.now(),
|
||||
alreadyExists,
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolvePublicFileUrl({
|
||||
sha256,
|
||||
authorLogin,
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
const currentServerUrl = publicFileUrl(DEFAULT_SHINE_SERVER_HTTP, sha256);
|
||||
if (await publicFileExists(currentServerUrl)) {
|
||||
return currentServerUrl;
|
||||
}
|
||||
|
||||
const cleanLogin = String(authorLogin || '').trim().toLowerCase();
|
||||
if (!cleanLogin) throw new Error('Не указан автор server-вложения.');
|
||||
const cacheKey = `${cleanLogin}|${String(solanaEndpoint || '').trim()}|${String(fallbackServerLogin || '').trim().toLowerCase()}`;
|
||||
const cached = accessServerCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.atMs < ACCESS_SERVER_CACHE_TTL_MS) {
|
||||
return publicFileUrl(cached.httpBase, sha256);
|
||||
}
|
||||
const resolved = await resolveShineServerForUserLogin({
|
||||
login: cleanLogin,
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin,
|
||||
});
|
||||
accessServerCache.set(cacheKey, { atMs: Date.now(), httpBase: resolved.httpBase });
|
||||
return publicFileUrl(resolved.httpBase, sha256);
|
||||
}
|
||||
@@ -190,6 +190,7 @@
|
||||
background: var(--surface);
|
||||
color: var(--danger);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-weight: 700;
|
||||
justify-content: center;
|
||||
min-height: 12rem;
|
||||
@@ -197,6 +198,22 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.message-attachment-debug {
|
||||
width: 100%;
|
||||
margin: 10px 0 0;
|
||||
padding: 8px;
|
||||
overflow-x: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 8px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
line-height: 1.35;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
|
||||
.message-attachment-card {
|
||||
align-items: center;
|
||||
@@ -430,45 +447,6 @@
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-history-tile--with-preview {
|
||||
gap: 0.32rem;
|
||||
padding: 0.42rem;
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-history-preview {
|
||||
align-items: flex-end;
|
||||
background: var(--border-subtle);
|
||||
border-radius: 0.42rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
min-height: 7rem;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-history-preview-image {
|
||||
display: block;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-history-preview-badge {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 999px;
|
||||
bottom: 0.42rem;
|
||||
color: var(--text-primary);
|
||||
font-size: 0.6875rem;
|
||||
left: 0.42rem;
|
||||
padding: 0.2rem 0.46rem;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
|
||||
.ar-attachment-history-tile-head {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
@@ -561,3 +539,87 @@
|
||||
line-height: 1;
|
||||
padding: 0.2rem 0.32rem;
|
||||
}
|
||||
|
||||
/* ===== Public / Arweave attachment source picker ===== */
|
||||
.public-attachment-manager-root {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1200;
|
||||
}
|
||||
|
||||
.public-attachment-manager {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
background: var(--scrim);
|
||||
}
|
||||
|
||||
.public-attachment-manager__card {
|
||||
width: min(620px, 100%);
|
||||
max-height: min(820px, calc(100dvh - 40px));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.public-attachment-manager__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.public-attachment-manager__sources {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.public-attachment-manager__source {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border-control);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.public-attachment-manager__source.is-selected {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.public-attachment-manager__source input { margin-top: 3px; }
|
||||
.public-attachment-manager__source span { display: grid; gap: 3px; }
|
||||
.public-attachment-manager__source small { color: var(--text-secondary); line-height: 1.35; }
|
||||
|
||||
.public-attachment-manager__server,
|
||||
.public-attachment-manager__arweave {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.public-attachment-manager__notice {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--quote-bg);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-sm);
|
||||
line-height: var(--leading-sm);
|
||||
}
|
||||
|
||||
.public-attachment-manager__notice strong { color: var(--text-primary); }
|
||||
.public-attachment-manager__notice p { margin: 0; }
|
||||
.public-attachment-manager__status { min-height: 1.25rem; }
|
||||
.public-attachment-manager__error { min-height: 1.25rem; }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.public-attachment-manager { padding: 10px; place-items: end center; }
|
||||
.public-attachment-manager__card { width: 100%; max-height: calc(100dvh - 20px); }
|
||||
.public-attachment-manager__sources { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user