SHA256
Вложения файлов со своего сервера доступа пользователя
This commit is contained in:
@@ -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.');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user