SHA256
WIP: добавить MVP загрузки вложений в Cloudflare R2
Работа ещё не готова: предпросмотр публичных R2-вложений в UI пока не завершён.
This commit is contained in:
@@ -42,27 +42,25 @@ function normalizeName(name) {
|
||||
export function normalizeAttachment(input = {}) {
|
||||
const txId = String(input.ar || input.txId || '').trim();
|
||||
const sha256Hex = String(input.sha256 || input.sha256Hex || '').trim().toLowerCase();
|
||||
const pr = String(input.pr || '').trim();
|
||||
const mm = String(input.mm || '').trim();
|
||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||||
if (!validateSha256Hex(sha256Hex)) throw new Error(t('remaining.attachment_errors.invalid_file_sha_256'));
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
||||
if (pr && !/^[A-Za-z0-9_-]{43}$/.test(pr)) throw new Error('Некорректный Pieces Root');
|
||||
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||||
const out = {
|
||||
v: 1,
|
||||
name,
|
||||
size,
|
||||
sha256: sha256Hex,
|
||||
ar: txId,
|
||||
uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now(),
|
||||
};
|
||||
return out;
|
||||
return { v: 1, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||
}
|
||||
|
||||
export function buildAttachmentBlock(attachment) {
|
||||
const item = normalizeAttachment(attachment);
|
||||
const encodedName = encodeURIComponent(item.name);
|
||||
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
||||
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
||||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size};sha256=${item.sha256}${arPart}>`;
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||
}
|
||||
|
||||
export function composeMessageWithAttachments(text, attachments = []) {
|
||||
@@ -103,6 +101,8 @@ export function parseMessageAttachments(rawText) {
|
||||
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
|
||||
sz: fields.sz || fields.size,
|
||||
sha256: fields.sha256,
|
||||
pr: fields.pr,
|
||||
mm: fields.mm,
|
||||
ar: fields.ar,
|
||||
}));
|
||||
} catch {
|
||||
@@ -365,23 +365,14 @@ async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||||
|
||||
const serverUrl = await resolvePublicFileUrl({
|
||||
sha256: item.sha256,
|
||||
pr: item.pr,
|
||||
authorLogin: options.authorLogin,
|
||||
solanaEndpoint: options.solanaEndpoint,
|
||||
fallbackServerLogin: options.fallbackServerLogin,
|
||||
});
|
||||
const kind = getAttachmentKind(item);
|
||||
// Видео подключаем напрямую. Иначе fetch + Blob + полный SHA-256 сначала
|
||||
// скачает ВСЕ байты и браузер не сможет запрашивать Range для просмотра.
|
||||
if (kind === 'video' || kind === 'file') return { url: serverUrl, objectUrl: false };
|
||||
|
||||
// Для изображений сохраняем прежнюю проверку SHA-256 после скачивания.
|
||||
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(t('remaining.attachment_error.hash_mismatch', { actual: actualSha, expected: item.sha256, url: serverUrl }));
|
||||
const blob = new Blob([buffer], { type: mimeTypeForAttachment(item, kind) });
|
||||
return { url: URL.createObjectURL(blob), sourceUrl: serverUrl, objectUrl: true };
|
||||
if (item.pr) return { url: serverUrl, objectUrl: false };
|
||||
// Public MVP: direct URL, no image downloads, media viewer or full SHA checks.
|
||||
return { url: serverUrl, objectUrl: false };
|
||||
}
|
||||
|
||||
export function createAttachmentCarouselElement(attachments = [], {
|
||||
@@ -410,6 +401,23 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
wrap.addEventListener('click', (event) => event.stopPropagation());
|
||||
if (!items.length) return wrap;
|
||||
|
||||
// Public attachments are a simple file list. The DM renderer supplies resolveUrl
|
||||
// and retains its separate encrypted-file carousel/viewer unchanged.
|
||||
if (!resolveUrl) {
|
||||
wrap.className = 'message-attachments message-attachment-list';
|
||||
const options = { gateway, authorLogin, solanaEndpoint, fallbackServerLogin };
|
||||
for (const item of items) {
|
||||
const slot = document.createElement('div');
|
||||
slot.className = 'message-attachment-item';
|
||||
slot.textContent = t('remaining.attachments.loading_file');
|
||||
wrap.append(slot);
|
||||
void resolveAttachmentDisplayUrl(item, options)
|
||||
.then(({ url }) => slot.replaceChildren(createFileCard({ item, url, messageTimestampMs, slide: slot })))
|
||||
.catch(() => slot.replaceChildren(createUnavailableBlock(messageTimestampMs, attachmentStorage(item))));
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
let index = 0;
|
||||
let pointerStartX = 0;
|
||||
let renderGeneration = 0;
|
||||
@@ -486,9 +494,10 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
void getResolved(currentIndex)
|
||||
.then(({ url }) => {
|
||||
if (generation !== renderGeneration || currentIndex !== index || !wrap.isConnected) return;
|
||||
slide.replaceChildren(kind === 'file'
|
||||
slide.replaceChildren(!resolveUrl
|
||||
? createFileCard({ item, url, messageTimestampMs, slide })
|
||||
: createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen: () => openViewer(currentIndex) }));
|
||||
: (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;
|
||||
|
||||
Reference in New Issue
Block a user