SHA256
Обновить хранение вложений R2
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { openMediaViewer } from '../components/media-viewer.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer, validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { resolvePublicFileUrl } from './public-file-service.js';
|
||||
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
||||
@@ -141,6 +142,69 @@ export function getAttachmentKind(attachment = {}) {
|
||||
return 'file';
|
||||
}
|
||||
|
||||
// HTML/SVG и похожие активные файлы не показываем встроенным медиаплеером.
|
||||
// Проверяем как MIME, так и расширение: оба значения сообщает сам отправитель.
|
||||
const ACTIVE_FILE_EXTENSIONS = new Set(['html', 'htm', 'xhtml', 'svg', 'js', 'mjs', 'xml']);
|
||||
const ACTIVE_FILE_MIMES = new Set([
|
||||
'text/html', 'application/xhtml+xml', 'image/svg+xml', 'text/javascript',
|
||||
'application/javascript', 'application/xml', 'text/xml',
|
||||
]);
|
||||
export function isPotentiallyActiveAttachment(item = {}) {
|
||||
const mime = String(item.mm || '').trim().toLowerCase().split(';')[0];
|
||||
return ACTIVE_FILE_MIMES.has(mime) || ACTIVE_FILE_EXTENSIONS.has(getAttachmentExtension(item.name));
|
||||
}
|
||||
|
||||
// Один наблюдатель на все видео, чтобы лента с сотней сообщений не создавалa
|
||||
// сотню сетевых запросов и отдельных IntersectionObserver.
|
||||
const pendingPublicVideoLoads = new Map();
|
||||
let publicVideoObserver = null;
|
||||
let publicVideoRemovalObserver = null;
|
||||
function stopUnusedVideoObservers() {
|
||||
if (pendingPublicVideoLoads.size) return;
|
||||
publicVideoObserver?.disconnect();
|
||||
publicVideoRemovalObserver?.disconnect();
|
||||
publicVideoObserver = null;
|
||||
publicVideoRemovalObserver = null;
|
||||
}
|
||||
function preparePublicVideoLazyLoad(video, url) {
|
||||
if (typeof IntersectionObserver !== 'function') {
|
||||
// Старые браузеры сохраняют обычное поведение.
|
||||
video.preload = 'metadata';
|
||||
video.src = url;
|
||||
return;
|
||||
}
|
||||
if (!publicVideoObserver) {
|
||||
publicVideoObserver = new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isIntersecting) continue;
|
||||
const source = pendingPublicVideoLoads.get(entry.target);
|
||||
if (!source) continue;
|
||||
pendingPublicVideoLoads.delete(entry.target);
|
||||
publicVideoObserver?.unobserve(entry.target);
|
||||
if (entry.target.isConnected) {
|
||||
entry.target.preload = 'metadata';
|
||||
entry.target.src = source;
|
||||
}
|
||||
}
|
||||
stopUnusedVideoObservers();
|
||||
}, { rootMargin: '240px 0px' });
|
||||
}
|
||||
pendingPublicVideoLoads.set(video, url);
|
||||
publicVideoObserver.observe(video);
|
||||
// Отписка для удалённых из DOM видео: observer иначе держит ссылки на них.
|
||||
if (!publicVideoRemovalObserver && typeof MutationObserver === 'function' && document.documentElement) {
|
||||
publicVideoRemovalObserver = new MutationObserver(() => {
|
||||
for (const pending of pendingPublicVideoLoads.keys()) {
|
||||
if (pending.isConnected) continue;
|
||||
publicVideoObserver?.unobserve(pending);
|
||||
pendingPublicVideoLoads.delete(pending);
|
||||
}
|
||||
stopUnusedVideoObservers();
|
||||
});
|
||||
publicVideoRemovalObserver.observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
}
|
||||
|
||||
function isRecentMessage(messageTimestampMs) {
|
||||
const ts = Number(messageTimestampMs || 0);
|
||||
if (!Number.isFinite(ts) || ts <= 0) return false;
|
||||
@@ -199,7 +263,7 @@ function replaceWithUnavailable(slide, messageTimestampMs, storage = 'arweave',
|
||||
slide.replaceChildren(createUnavailableBlock(messageTimestampMs, storage, detail));
|
||||
}
|
||||
|
||||
function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
function createFileCard({ item, url, messageTimestampMs, slide, warnOnOpen = false }) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'message-attachment-file-card';
|
||||
card.role = 'button';
|
||||
@@ -212,7 +276,21 @@ function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
<div class="message-attachment-meta">${escapeHtml(formatBytes(item.size))}</div>
|
||||
</div>
|
||||
`;
|
||||
const openFile = () => window.open(url, '_blank', 'noopener');
|
||||
const openFile = async () => {
|
||||
if (warnOnOpen && isPotentiallyActiveAttachment(item)) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t('remaining.attachments.external_file_title'),
|
||||
text: t('remaining.attachments.external_file_warning'),
|
||||
confirmLabel: t('remaining.attachments.open_external_file'),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
// Навигация в этой вкладке работает и после асинхронного подтверждения:
|
||||
// window.open() после Promise браузер может заблокировать как popup.
|
||||
window.location.assign(url);
|
||||
return;
|
||||
}
|
||||
window.open(url, '_blank', 'noopener');
|
||||
};
|
||||
card.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
openFile();
|
||||
@@ -241,7 +319,7 @@ function formatVideoDuration(seconds) {
|
||||
: `${String(minutes).padStart(2, '0')}:${secondsPart}`;
|
||||
}
|
||||
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen, onError = null }) {
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen, onError = null, lazyVideo = false }) {
|
||||
const frame = document.createElement('div');
|
||||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||||
frame.role = 'button';
|
||||
@@ -288,7 +366,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen,
|
||||
} else {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'message-attachment-media';
|
||||
video.preload = 'metadata';
|
||||
video.preload = 'none';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.addEventListener('error', handleError, { once: true });
|
||||
@@ -310,7 +388,8 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen,
|
||||
try { video.currentTime = Math.min(0.05, video.duration); } catch { /* зависит от кодека */ }
|
||||
}
|
||||
}, { once: true });
|
||||
video.src = url;
|
||||
if (lazyVideo) preparePublicVideoLazyLoad(video, url);
|
||||
else { video.preload = 'metadata'; video.src = url; }
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
play.textContent = '▶';
|
||||
@@ -424,7 +503,7 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
const resolvedUrls = new Map();
|
||||
const openPublicViewer = (selectedIndex) => {
|
||||
const media = items.flatMap((entry, i) => {
|
||||
const kind = getAttachmentKind(entry);
|
||||
const kind = isPotentiallyActiveAttachment(entry) ? 'file' : getAttachmentKind(entry);
|
||||
const url = resolvedUrls.get(i);
|
||||
return url && (kind === 'image' || kind === 'video')
|
||||
? [{ i, kind, url, name: entry.name }]
|
||||
@@ -440,15 +519,15 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
wrap.append(slot);
|
||||
void resolveAttachmentDisplayUrl(item, options)
|
||||
.then(({ url }) => {
|
||||
const kind = getAttachmentKind(item);
|
||||
const kind = isPotentiallyActiveAttachment(item) ? 'file' : getAttachmentKind(item);
|
||||
const content = kind === 'file'
|
||||
? createFileCard({ item, url, messageTimestampMs, slide: slot })
|
||||
? createFileCard({ item, url, messageTimestampMs, slide: slot, warnOnOpen: true })
|
||||
: createMediaSlide({
|
||||
item, url, kind, messageTimestampMs, slide: slot,
|
||||
item, url, kind, messageTimestampMs, slide: slot, lazyVideo: true,
|
||||
onOpen: () => openPublicViewer(index),
|
||||
// Если формат/кодек не поддерживается браузером, файл всё ещё
|
||||
// можно открыть или скачать через обычную карточку.
|
||||
onError: () => slot.replaceChildren(createFileCard({ item, url, messageTimestampMs, slide: slot })),
|
||||
onError: () => slot.replaceChildren(createFileCard({ item, url, messageTimestampMs, slide: slot, warnOnOpen: true })),
|
||||
});
|
||||
resolvedUrls.set(index, url);
|
||||
slot.replaceChildren(content);
|
||||
|
||||
Reference in New Issue
Block a user