SHA256
Исправить отображение публичных медиа-вложений
Добавить предпросмотр изображений и видео из R2 и Arweave; неподдерживаемые форматы оставить доступными как файлы.
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const source = await readFile(new URL('../js/services/attachment-format.js', import.meta.url), 'utf8');
|
||||
|
||||
class TestElement {
|
||||
constructor(tagName) {
|
||||
this.tagName = tagName.toUpperCase();
|
||||
this.className = '';
|
||||
this.children = [];
|
||||
this.dataset = {};
|
||||
this.listeners = {};
|
||||
this.isConnected = true;
|
||||
this.classList = {
|
||||
add: (...values) => { this.className = [...new Set([...this.className.split(' '), ...values])].filter(Boolean).join(' '); },
|
||||
remove: (...values) => { this.className = this.className.split(' ').filter((x) => !values.includes(x)).join(' '); },
|
||||
toggle: (value, force) => {
|
||||
const has = this.className.split(' ').includes(value);
|
||||
const enabled = force ?? !has;
|
||||
if (enabled) this.classList.add(value);
|
||||
else this.classList.remove(value);
|
||||
return enabled;
|
||||
},
|
||||
};
|
||||
}
|
||||
append(...nodes) {
|
||||
for (const node of nodes) {
|
||||
this.children.push(node);
|
||||
if (node && typeof node === 'object') node.parentElement = this;
|
||||
}
|
||||
}
|
||||
replaceChildren(...nodes) { this.children = []; this.append(...nodes); }
|
||||
addEventListener(name, callback) { (this.listeners[name] ||= []).push(callback); }
|
||||
setAttribute(name, value) { (this.attributes ||= {})[name] = String(value); }
|
||||
fire(name, event = {}) {
|
||||
for (const listener of this.listeners[name] || []) listener({ stopPropagation() {}, preventDefault() {}, ...event });
|
||||
}
|
||||
querySelectorAll(tag) {
|
||||
const result = [];
|
||||
for (const child of this.children) {
|
||||
if (child.tagName?.toLowerCase() === tag) result.push(child);
|
||||
result.push(...(child.querySelectorAll?.(tag) || []));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function loadRenderer() {
|
||||
const viewerCalls = [];
|
||||
const normalized = source
|
||||
.replace(/^import .*;\s*$/gm, '')
|
||||
.replace(/^export /gm, '');
|
||||
const factory = new Function('t', 'th', 'formatNumber', 'openMediaViewer', 'buildArweaveDataUrl',
|
||||
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'document', 'window', 'fetch',
|
||||
`${normalized}\nreturn { getAttachmentKind, createAttachmentCarouselElement, parseMessageAttachments };`);
|
||||
const api = factory(
|
||||
(key) => key,
|
||||
() => '<span>FILE</span></div>',
|
||||
(number) => String(number),
|
||||
(...args) => viewerCalls.push(args),
|
||||
({ txId }) => `https://arweave.net/${txId}`,
|
||||
(id) => /^[A-Za-z0-9_-]{43}$/.test(id),
|
||||
(id) => /^[a-f0-9]{64}$/.test(id),
|
||||
async ({ pr, sha256 }) => pr ? `https://files.shineup.me/${pr}` : `https://old.example/files/${sha256}`,
|
||||
{ createElement: (tag) => new TestElement(tag) },
|
||||
{ location: { origin: 'https://shineup.me' }, open() {} },
|
||||
async () => ({ ok: true }),
|
||||
);
|
||||
return { ...api, viewerCalls };
|
||||
}
|
||||
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
test('MIME имеет приоритет над расширением, старые файлы определяются по расширению', () => {
|
||||
const { getAttachmentKind } = loadRenderer();
|
||||
assert.equal(getAttachmentKind({ name: 'без расширения', mm: 'image/jpeg' }), 'image');
|
||||
assert.equal(getAttachmentKind({ name: 'clip.bin', mm: 'video/mp4' }), 'video');
|
||||
assert.equal(getAttachmentKind({ name: 'photo.jpg', mm: 'application/pdf' }), 'file');
|
||||
assert.equal(getAttachmentKind({ name: 'legacy.webp' }), 'image');
|
||||
assert.equal(getAttachmentKind({ name: 'legacy.mp4', mm: 'application/octet-stream' }), 'video');
|
||||
assert.equal(getAttachmentKind({ name: 'archive.zip' }), 'file');
|
||||
});
|
||||
|
||||
test('публичный R2: img/video отображаются в сообщении, PDF остаётся карточкой; просмотрщик открывается', async () => {
|
||||
const { createAttachmentCarouselElement, viewerCalls } = loadRenderer();
|
||||
const pr = 'A'.repeat(43);
|
||||
const wrap = createAttachmentCarouselElement([
|
||||
{ name: 'photo.jpg', size: 234, pr, mm: 'image/jpeg' },
|
||||
{ name: 'clip.bin', size: 456, pr, mm: 'video/mp4' },
|
||||
{ name: 'manual.pdf', size: 567, pr, mm: 'application/pdf' },
|
||||
]);
|
||||
assert.match(wrap.className, /message-attachment-list/);
|
||||
await settle();
|
||||
const [imageSlot, videoSlot, fileSlot] = wrap.children;
|
||||
assert.equal(imageSlot.children[0].querySelectorAll('img').length, 1);
|
||||
assert.equal(imageSlot.children[0].children[0].src, `https://files.shineup.me/${pr}`);
|
||||
assert.equal(videoSlot.children[0].querySelectorAll('video').length, 1);
|
||||
assert.equal(videoSlot.children[0].children[0].preload, 'metadata');
|
||||
assert.match(fileSlot.children[0].className, /message-attachment-file-card/);
|
||||
imageSlot.children[0].fire('click');
|
||||
assert.equal(viewerCalls.length, 1);
|
||||
assert.equal(viewerCalls[0][0].length, 2);
|
||||
assert.equal(viewerCalls[0][1], 0);
|
||||
videoSlot.children[0].fire('click');
|
||||
assert.equal(viewerCalls[1][1], 1);
|
||||
});
|
||||
|
||||
test('публичный Arweave и старые sha256-вложения тоже показывают изображения', async () => {
|
||||
const { createAttachmentCarouselElement } = loadRenderer();
|
||||
const wrap = createAttachmentCarouselElement([
|
||||
{ name: 'arweave.png', size: 90, pr: 'A'.repeat(43), ar: 'B'.repeat(43), mm: 'image/png' },
|
||||
{ name: 'old.jpeg', size: 91, sha256: 'a'.repeat(64) },
|
||||
]);
|
||||
await settle();
|
||||
assert.equal(wrap.children[0].children[0].children[0].src, `https://arweave.net/${'B'.repeat(43)}`);
|
||||
assert.equal(wrap.children[1].children[0].children[0].src, `https://old.example/files/${'a'.repeat(64)}`);
|
||||
});
|
||||
|
||||
test('DM сохраняют отдельную карусель с переданным resolveUrl', async () => {
|
||||
const { createAttachmentCarouselElement } = loadRenderer();
|
||||
const wrap = createAttachmentCarouselElement([
|
||||
{ name: 'secret.jpg', size: 123 },
|
||||
], { resolveUrl: async () => ({ url: 'blob:test-secret', objectUrl: false }) });
|
||||
assert.match(wrap.className, /message-attachment-carousel/);
|
||||
await settle();
|
||||
assert.equal(wrap.querySelectorAll('img').length, 1);
|
||||
assert.equal(wrap.querySelectorAll('img')[0].src, 'blob:test-secret');
|
||||
});
|
||||
|
||||
|
||||
test('S:att pr/mm разбирается без изменения формата сообщения', () => {
|
||||
const { parseMessageAttachments, getAttachmentKind } = loadRenderer();
|
||||
const pr = 'A'.repeat(43);
|
||||
const parsed = parseMessageAttachments(`<S:att;v=1;nm=photo.jpg;sz=123456;pr=${pr};mm=image/jpeg>\nКомментарий`);
|
||||
assert.equal(parsed.attachments.length, 1);
|
||||
assert.equal(parsed.attachments[0].pr, pr);
|
||||
assert.equal(parsed.attachments[0].mm, 'image/jpeg');
|
||||
assert.equal(getAttachmentKind(parsed.attachments[0]), 'image');
|
||||
assert.equal(parsed.text, 'Комментарий');
|
||||
});
|
||||
|
||||
test('если браузер не может декодировать медиа, остаётся карточка для скачивания', async () => {
|
||||
const { createAttachmentCarouselElement } = loadRenderer();
|
||||
const wrap = createAttachmentCarouselElement([{ name: 'bad.png', size: 100, pr: 'A'.repeat(43), mm: 'image/png' }]);
|
||||
await settle();
|
||||
wrap.querySelectorAll('img')[0].fire('error');
|
||||
assert.match(wrap.children[0].children[0].className, /message-attachment-file-card/);
|
||||
});
|
||||
|
||||
test('просмотрщик импортирует t для aria-label диалога', async () => {
|
||||
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';/);
|
||||
});
|
||||
Reference in New Issue
Block a user