Поддержать range-загрузку публичных файлов

This commit is contained in:
AidarKC
2026-10-10 16:48:22 +03:00
parent 5e9699613d
commit 4d10096ba2
7 changed files with 278 additions and 35 deletions
+32 -3
View File
@@ -214,6 +214,17 @@ function createFileCard({ item, url, messageTimestampMs, slide }) {
return card;
}
function formatVideoDuration(seconds) {
if (!Number.isFinite(seconds) || seconds < 0) return '';
const wholeSeconds = Math.floor(seconds);
const hours = Math.floor(wholeSeconds / 3600);
const minutes = Math.floor((wholeSeconds % 3600) / 60);
const secondsPart = String(wholeSeconds % 60).padStart(2, '0');
return hours > 0
? `${hours}:${String(minutes).padStart(2, '0')}:${secondsPart}`
: `${String(minutes).padStart(2, '0')}:${secondsPart}`;
}
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }) {
const frame = document.createElement('div');
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
@@ -261,10 +272,26 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
video.playsInline = true;
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
// Размер известен из S:att, длительность появляется после получения метаданных.
// <video> сам запрашивает небольшие диапазоны через HTTP Range, без fetch всего файла.
const info = document.createElement('span');
info.className = 'message-attachment-video-info';
const videoSize = formatBytes(item.size);
info.textContent = videoSize;
video.addEventListener('loadedmetadata', () => {
const duration = formatVideoDuration(video.duration);
info.textContent = duration ? `${videoSize} · ${duration}` : videoSize;
// Metadata сама по себе не гарантирует первого кадра. Переход к самому
// началу видео побуждает браузер запросить только нужные части файла.
if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA && Number.isFinite(video.duration) && video.duration > 0) {
try { video.currentTime = Math.min(0.05, video.duration); } catch { /* зависит от кодека */ }
}
}, { once: true });
const play = document.createElement('span');
play.className = 'message-attachment-play';
play.textContent = '▶';
frame.append(video, play);
frame.append(video, play, info);
}
return frame;
@@ -334,9 +361,11 @@ async function resolveAttachmentDisplayUrl(item, options = {}) {
fallbackServerLogin: options.fallbackServerLogin,
});
const kind = getAttachmentKind(item);
if (kind === 'file') return { url: serverUrl, objectUrl: false };
// Видео подключаем напрямую. Иначе fetch + Blob + полный SHA-256 сначала
// скачает ВСЕ байты и браузер не сможет запрашивать Range для просмотра.
if (kind === 'video' || kind === 'file') return { url: serverUrl, objectUrl: false };
// /files хранит только байты и SHA-256. Для media тип задаёт клиент по имени из S:att.
// Для изображений сохраняем прежнюю проверку SHA-256 после скачивания.
const response = await fetch(serverUrl);
if (!response.ok) throw new Error(`HTTP ${response.status} ${serverUrl}`);
const buffer = await response.arrayBuffer();