SHA256
Исправить отображение публичных медиа-вложений
Добавить предпросмотр изображений и видео из R2 и Arweave; неподдерживаемые форматы оставить доступными как файлы.
This commit is contained in:
@@ -125,6 +125,15 @@ export function getAttachmentExtension(name) {
|
||||
}
|
||||
|
||||
export function getAttachmentKind(attachment = {}) {
|
||||
// Для новых публичных файлов доверяем mm: имя файла может не иметь расширения
|
||||
// или не совпадать с MIME, записанным при загрузке в R2/Arweave.
|
||||
// Для старых вложений (и зашифрованных DM) остаётся проверка расширения.
|
||||
const mime = String(attachment.mm || '').trim().toLowerCase();
|
||||
if (mime && mime !== 'application/octet-stream') {
|
||||
if (mime.startsWith('image/')) return 'image';
|
||||
if (mime.startsWith('video/')) return 'video';
|
||||
return 'file';
|
||||
}
|
||||
const ext = getAttachmentExtension(attachment.name);
|
||||
if (IMAGE_EXTENSIONS.has(ext)) return 'image';
|
||||
if (VIDEO_EXTENSIONS.has(ext)) return 'video';
|
||||
@@ -231,12 +240,16 @@ function formatVideoDuration(seconds) {
|
||||
: `${String(minutes).padStart(2, '0')}:${secondsPart}`;
|
||||
}
|
||||
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }) {
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen, onError = null }) {
|
||||
const frame = document.createElement('div');
|
||||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||||
frame.role = 'button';
|
||||
frame.tabIndex = 0;
|
||||
frame.title = kind === 'video' ? t('remaining.attachments.open_video') : t('remaining.attachments.open_image');
|
||||
const handleError = () => {
|
||||
if (onError) onError();
|
||||
else replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item));
|
||||
};
|
||||
frame.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
onOpen?.();
|
||||
@@ -265,21 +278,20 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
if (kind === 'image') {
|
||||
const img = document.createElement('img');
|
||||
img.className = 'message-attachment-media';
|
||||
img.src = url;
|
||||
img.alt = item.name;
|
||||
img.loading = 'lazy';
|
||||
bindImageLayout(img);
|
||||
img.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||||
img.addEventListener('error', handleError, { once: true });
|
||||
img.src = url;
|
||||
frame.append(img);
|
||||
} else {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'message-attachment-media';
|
||||
video.src = url;
|
||||
video.preload = 'metadata';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||||
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
|
||||
video.addEventListener('error', handleError, { once: true });
|
||||
video.addEventListener('loadedmetadata', () => frame.classList.add('is-loaded'), { once: true });
|
||||
|
||||
// Размер известен из S:att, длительность появляется после получения метаданных.
|
||||
// <video> сам запрашивает небольшие диапазоны через HTTP Range, без fetch всего файла.
|
||||
@@ -297,6 +309,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
try { video.currentTime = Math.min(0.05, video.duration); } catch { /* зависит от кодека */ }
|
||||
}
|
||||
}, { once: true });
|
||||
video.src = url;
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
play.textContent = '▶';
|
||||
@@ -370,8 +383,8 @@ async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||||
solanaEndpoint: options.solanaEndpoint,
|
||||
fallbackServerLogin: options.fallbackServerLogin,
|
||||
});
|
||||
if (item.pr) return { url: serverUrl, objectUrl: false };
|
||||
// Public MVP: direct URL, no image downloads, media viewer or full SHA checks.
|
||||
// Прямая ссылка для R2 (pr) или совместимого старого SHA-256 сервера.
|
||||
// Отображение в <img>/<video> не требует полной загрузки через JS.
|
||||
return { url: serverUrl, objectUrl: false };
|
||||
}
|
||||
|
||||
@@ -401,20 +414,48 @@ 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.
|
||||
// Публичные вложения отображаются списком: медиа — непосредственно в сообщении,
|
||||
// остальные файлы — карточками. DM по-прежнему используют отдельную карусель
|
||||
// и переданный извне resolveUrl (расшифровка на устройстве).
|
||||
if (!resolveUrl) {
|
||||
wrap.className = 'message-attachments message-attachment-list';
|
||||
const options = { gateway, authorLogin, solanaEndpoint, fallbackServerLogin };
|
||||
for (const item of items) {
|
||||
const resolvedUrls = new Map();
|
||||
const openPublicViewer = (selectedIndex) => {
|
||||
const media = items.flatMap((entry, i) => {
|
||||
const kind = getAttachmentKind(entry);
|
||||
const url = resolvedUrls.get(i);
|
||||
return url && (kind === 'image' || kind === 'video')
|
||||
? [{ i, kind, url, name: entry.name }]
|
||||
: [];
|
||||
});
|
||||
const viewerIndex = media.findIndex((entry) => entry.i === selectedIndex);
|
||||
if (viewerIndex >= 0) openMediaViewer(media, viewerIndex);
|
||||
};
|
||||
items.forEach((item, index) => {
|
||||
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))));
|
||||
}
|
||||
.then(({ url }) => {
|
||||
const kind = getAttachmentKind(item);
|
||||
const content = kind === 'file'
|
||||
? createFileCard({ item, url, messageTimestampMs, slide: slot })
|
||||
: createMediaSlide({
|
||||
item, url, kind, messageTimestampMs, slide: slot,
|
||||
onOpen: () => openPublicViewer(index),
|
||||
// Если формат/кодек не поддерживается браузером, файл всё ещё
|
||||
// можно открыть или скачать через обычную карточку.
|
||||
onError: () => slot.replaceChildren(createFileCard({ item, url, messageTimestampMs, slide: slot })),
|
||||
});
|
||||
resolvedUrls.set(index, url);
|
||||
slot.replaceChildren(content);
|
||||
})
|
||||
.catch(() => {
|
||||
slot.replaceChildren(createUnavailableBlock(messageTimestampMs, attachmentStorage(item)));
|
||||
});
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user