Обновить хранение вложений R2

This commit is contained in:
AidarKC
2026-11-16 10:47:43 +03:00
parent fed28527ae
commit 1b86bca19a
17 changed files with 321 additions and 276 deletions
+4 -1
View File
@@ -4429,7 +4429,10 @@
"next_attachment": "Next attachment",
"loading_file": "Loading file…",
"bytes": "{count} B",
"counter": "{current} of {total}"
"counter": "{current} of {total}",
"external_file_title": "Open external file",
"external_file_warning": "You are opening a user-uploaded file. It may contain active code or unwanted content. SHiNE is not responsible for third-party file content. Continue?",
"open_external_file": "Open file"
},
"call_ui": {
"user": "user",
+4 -1
View File
@@ -4429,7 +4429,10 @@
"next_attachment": "Следующее вложение",
"loading_file": "Загружаем файл…",
"bytes": "{count} Б",
"counter": "{current} из {total}"
"counter": "{current} из {total}",
"external_file_title": "Переход к внешнему файлу",
"external_file_warning": "Вы открываете файл, загруженный пользователем. Он может содержать активный код или нежелательное содержимое. SHiNE не отвечает за содержимое сторонних файлов. Продолжить?",
"open_external_file": "Открыть файл"
},
"call_ui": {
"user": "пользователь",
+89 -10
View File
@@ -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);
@@ -49,12 +49,15 @@ class TestElement {
function loadRenderer() {
const viewerCalls = [];
const warningCalls = [];
const navigations = [];
let approveWarning = true;
const normalized = source
.replace(/^import .*;\s*$/gm, '')
.replace(/^export /gm, '');
const factory = new Function('t', 'th', 'formatNumber', 'openMediaViewer', 'buildArweaveDataUrl',
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'validatePublicPiecesRoot', 'document', 'window', 'fetch',
`${normalized}\nreturn { getAttachmentKind, createAttachmentCarouselElement, parseMessageAttachments };`);
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'validatePublicPiecesRoot', 'confirmDialog', 'document', 'window', 'fetch',
`${normalized}\nreturn { getAttachmentKind, isPotentiallyActiveAttachment, createAttachmentCarouselElement, parseMessageAttachments };`);
const api = factory(
(key) => key,
() => '<span>FILE</span></div>',
@@ -65,11 +68,12 @@ function loadRenderer() {
(id) => /^[a-f0-9]{64}$/.test(id),
async ({ pr, sha256 }) => pr ? `https://files.shineup.me/${pr}` : `https://old.example/files/${sha256}`,
validatePublicPiecesRoot,
async (options) => { warningCalls.push(options); return approveWarning; },
{ createElement: (tag) => new TestElement(tag) },
{ location: { origin: 'https://shineup.me' }, open() {} },
{ location: { origin: 'https://shineup.me', assign: (url) => navigations.push(url) }, open() {} },
async () => ({ ok: true }),
);
return { ...api, viewerCalls };
return { ...api, viewerCalls, warningCalls, navigations, setApproveWarning: (value) => { approveWarning = value; } };
}
const settle = () => new Promise((resolve) => setImmediate(resolve));
@@ -154,3 +158,55 @@ test('просмотрщик импортирует t для aria-label диал
const viewer = await readFile(new URL('../js/components/media-viewer.js', import.meta.url), 'utf8');
assert.match(viewer, /import \{ t, th \} from '\.\.\/i18n\/index\.js';/);
});
test('публичное видео не получает src до входа в область просмотра', async () => {
const previous = globalThis.IntersectionObserver;
const observers = [];
class FakeIntersectionObserver {
constructor(callback, options) { this.callback = callback; this.options = options; this.targets = new Set(); observers.push(this); }
observe(node) { this.targets.add(node); }
unobserve(node) { this.targets.delete(node); }
disconnect() { this.targets.clear(); }
reveal(node) { this.callback([{ target: node, isIntersecting: true }]); }
}
globalThis.IntersectionObserver = FakeIntersectionObserver;
try {
const { createAttachmentCarouselElement } = loadRenderer();
const root = createAttachmentCarouselElement([{ name: 'clip.mp4', size: 1000, pr: 'A'.repeat(43), mm: 'video/mp4' }]);
await settle();
const video = root.querySelectorAll('video')[0];
assert.equal(video.preload, 'none');
assert.equal(video.src, undefined);
assert.equal(observers.length, 1);
observers[0].reveal(video);
assert.equal(video.src, `https://files.shineup.me/${'A'.repeat(43)}`);
assert.equal(video.preload, 'metadata');
assert.equal(observers[0].targets.size, 0);
} finally {
if (previous === undefined) delete globalThis.IntersectionObserver;
else globalThis.IntersectionObserver = previous;
}
});
test('HTML/SVG открываются только после подтверждения, отказ не навигирует', async () => {
const api = loadRenderer();
const root = api.createAttachmentCarouselElement([
{ name: 'vector.svg', size: 500, pr: 'A'.repeat(43), mm: 'image/svg+xml' },
{ name: 'run.html', size: 400, pr: 'A'.repeat(43), mm: 'text/html' },
]);
await settle();
assert.equal(root.querySelectorAll('img').length, 0);
assert.equal(root.querySelectorAll('video').length, 0);
assert.match(root.children[0].children[0].className, /file-card/);
api.setApproveWarning(false);
root.children[0].children[0].fire('click');
await settle();
assert.equal(api.warningCalls.length, 1);
assert.equal(api.navigations.length, 0);
api.setApproveWarning(true);
root.children[1].children[0].fire('click');
await settle();
assert.equal(api.warningCalls.length, 2);
assert.deepEqual(api.navigations, [`https://files.shineup.me/${'A'.repeat(43)}`]);
});
+1 -1
View File
@@ -8,7 +8,7 @@ const settings = (preset) => ({ preset, custom: { dark: {}, light: {} } });
test('новая палитра доступна в настройках, а стандартная сохранена', () => {
assert.equal(PALETTE_PRESETS.tg_midnight.label, 'TG · Midnight');
assert.equal(PALETTE_PRESETS.aurora.label, 'Сияние');
assert.equal(PALETTE_PRESETS.aurora.label, 'remaining.theme.shine'); // i18n ещё не инициализирован в Node
});
test('каждая роль в тёмном и светлом TG содержит корректный HEX', () => {