Обновить обработку аватаров и вложений

This commit is contained in:
AidarKC
2026-10-07 14:05:01 +03:00
parent 7b8e178723
commit d8f42c769c
35 changed files with 628 additions and 222 deletions
@@ -1,4 +1,4 @@
import { openArweaveAttachmentManager } from './arweave-attachment-manager.js';
import { openArweaveAttachmentManager, prepareAvatarImageFile } 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';
@@ -10,8 +10,10 @@ export function openChannelAttachmentManager({
gateway = '',
selectedTxIds = [],
signal = null,
mode = 'attachment',
} = {}) {
const cleanLogin = String(login || '').trim();
const isAvatarMode = String(mode || '').trim() === 'avatar';
const root = document.createElement('div');
root.className = 'public-attachment-manager-root';
document.body.append(root);
@@ -19,10 +21,14 @@ export function openChannelAttachmentManager({
let closed = false;
let selectedFile = null;
let uploading = false;
let arweaveStarted = false;
const arweaveAbortController = new AbortController();
if (signal) signal.addEventListener('abort', () => arweaveAbortController.abort(), { once: true });
const close = (resolve, value = null) => {
if (closed) return;
closed = true;
arweaveAbortController.abort();
root.remove();
resolve(value);
};
@@ -36,39 +42,35 @@ export function openChannelAttachmentManager({
<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>
<h3 class="modal-title" id="public-attachment-title">${isAvatarMode ? 'Добавить аватар' : 'Добавить файл'}</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>
<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>
<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>
<label class="ar-attachment-file-picker public-attachment-manager__file-picker">
<input class="ar-attachment-file-input" type="file" data-role="file" ${isAvatarMode ? 'accept="image/*"' : ''} />
<span class="ar-attachment-file-btn">Выбрать файл</span>
<span class="ar-attachment-file-name" data-role="selected">Файл не выбран</span>
</label>
<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>
<button class="primary-btn" type="button" data-action="upload" disabled>${isAvatarMode ? 'Загрузить аватар на сервер' : 'Загрузить на сервер и добавить'}</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>
<p class="meta-muted">Выберите Turbo — более удобный способ загрузки в Arweave через сторонний сервис — или прямую загрузку в сеть Arweave.</p>
<div class="public-attachment-manager__arweave-loading meta-muted">Открываем настройки Arweave…</div>
</div>
</div>
</div>
@@ -80,7 +82,6 @@ export function openChannelAttachmentManager({
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) => {
@@ -91,7 +92,41 @@ export function openChannelAttachmentManager({
root.querySelector('[data-panel="arweave"]').hidden = value !== 'arweave';
};
radios.forEach((radio) => radio.addEventListener('change', () => setSource(radio.value)));
const openArweaveFlow = async () => {
if (arweaveStarted || closed) return;
arweaveStarted = true;
const hostElement = root.querySelector('[data-panel="arweave"]');
if (!(hostElement instanceof HTMLElement)) { arweaveStarted = false; return; }
try {
const item = await openArweaveAttachmentManager({
login: cleanLogin,
storagePwd,
gateway,
selectedTxIds,
signal: arweaveAbortController.signal,
mode: isAvatarMode ? 'avatar' : 'attachment',
historyPurpose: isAvatarMode ? 'avatar' : '',
autoOpenFileDialog: false,
hostElement,
embedded: true,
});
if (item && !closed) close(resolve, item);
} catch (error) {
arweaveStarted = false;
if (!closed && hostElement) {
hostElement.replaceChildren();
const message = document.createElement('p');
message.className = 'inline-error';
message.textContent = toUserMessage(error, 'Не удалось открыть Arweave.');
hostElement.append(message);
}
}
};
radios.forEach((radio) => radio.addEventListener('change', () => {
setSource(radio.value);
if (radio.value === 'arweave' && radio.checked) void openArweaveFlow();
}));
root.querySelector('[data-action="close"]')?.addEventListener('click', () => close(resolve, null));
modal?.addEventListener('click', (event) => {
if (event.target === modal && !uploading) close(resolve, null);
@@ -101,7 +136,7 @@ export function openChannelAttachmentManager({
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;
@@ -114,14 +149,15 @@ export function openChannelAttachmentManager({
fileInput.disabled = true;
if (errorEl) errorEl.textContent = '';
try {
const uploadFile = isAvatarMode ? await prepareAvatarImageFile(selectedFile) : selectedFile;
const item = await uploadPublicFile({
file: selectedFile,
file: uploadFile,
login: cleanLogin,
sessionId: state.session.sessionId,
wsUrl: state.entrySettings.shineServer,
onStatus: (message) => { if (statusEl) statusEl.textContent = message; },
});
close(resolve, item);
close(resolve, { ...item, purpose: isAvatarMode ? 'avatar' : 'attachment' });
} catch (error) {
if (errorEl) errorEl.textContent = toUserMessage(error, 'Не удалось загрузить файл.');
if (statusEl) statusEl.textContent = '';
@@ -131,28 +167,5 @@ export function openChannelAttachmentManager({
}
});
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.');
}
});
});
}