refactor(core): extract MediaUrlResolver + MediaIndexer from OneBotInstance
The OneBotInstance constructor still carried two non-trivial closures
inside its converterCtx object — a 26-line mediaUrlResolver that
branched bridge URL fetches by element.type + isGroup, and a 60-line
mediaSegmentSink that fanned out to mediaStore.rememberImage / Record /
Video with subtly different field maps. Both closed over `this` and
were untestable without instantiating the whole instance.
Extracted into two small, focused modules:
onebot/media-url-resolver.ts (64 lines)
class MediaUrlResolver(bridge, rkeyCache)
.resolve(element, isGroup, sessionId): Promise<string>
Picks the right Bridge.fetchXxx based on element.type + isGroup,
mutates element.url in-place (preserved behavior), then applies
the cached RKey via rkeyCache.resolveMediaUrl. Bridge-fetch
errors are swallowed so the RKey pass always runs.
onebot/media-indexer.ts (90 lines)
class MediaIndexer(mediaStore)
.remember(mediaType, element, data, isGroup, sessionId): void
One method, dispatches to mediaStore.rememberImage / Record /
Video with the right field map per mediaType. Defaults are
preserved exactly (?? 0 for missing numbers, ?? '' for strings).
OneBotInstance constructor shrinks from 134 lines to ~50 lines (-62%).
The converterCtx is now visually obvious — four callbacks each one
line, delegating to the right collaborator:
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
const mediaIndexer = new MediaIndexer(this.mediaStore);
this.converterCtx = {
selfId: parseInt(this.uin, 10) || 0,
imageUrlResolver: (el, ig) => this.rkeyCache.resolveImageUrl(this.bridge, el, ig),
mediaUrlResolver: (el, ig, sid) => mediaUrlResolver.resolve(el, ig, sid),
messageIdResolver: (ig, sid, seq, name) => hashMessageIdInt32(...),
mediaSegmentSink: (mt, el, d, ig, sid) => mediaIndexer.remember(mt, el, d, ig, sid),
};
Adds 19 happy-path tests:
media-url-resolver.test.ts (12 tests):
- file element: group / c2c-with-hash / c2c-without-hash
- record element: group / c2c
- video element: group / c2c
- record without mediaNode: no bridge call
- element.url already set: short-circuit, only rkey runs
- bridge throws: swallowed, rkey still applied
- rkey is always called at the end
media-indexer.test.ts (7 tests):
- image: full field map, file falls back to fileId
- record: full field map, file falls back to fileName
- video: full field map, data.file overrides element fields
- record: file falls back to fileId when fileName also missing
- missing numeric / string fields default to 0 / ''
- only the matching rememberX is called
Behavior preserved end-to-end: same bridge methods, same field
mappings into MediaStore, same in-place element.url mutation, same
RKey-always-runs guarantee, same best-effort error swallowing.
The existing media-store integration test (which still wires the
sink through the real converter) continues to pass unchanged.
334 tests pass (was 317); 3 stability runs, same pre-existing
macOS-arm64 websocket addon failure, unrelated.
This commit is contained in:
5 files changed
+431
-89
No files matched your search
@@ -3,8 +3,10 @@ import type { Bridge } from '../bridge/bridge';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { MessageStore } from './message-store';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { MessageStore } from './message-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
@@ -50,100 +52,21 @@ export class OneBotInstance {
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
|
||||
// Build the converter context once. The four callbacks below used
|
||||
// to live as setter-injected fields on an EventConverter class; the
|
||||
// converter is now a free function family that takes this context.
|
||||
// The converter context's four callbacks delegate to small, focused
|
||||
// modules so this constructor doesn't carry the bridge-URL fetch
|
||||
// branching or the mediaStore field-mapping fanout inline.
|
||||
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
|
||||
const mediaIndexer = new MediaIndexer(this.mediaStore);
|
||||
this.converterCtx = {
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
imageUrlResolver: (element, isGroup) =>
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: async (element, isGroup, sessionId) => {
|
||||
// Fetch URL from the bridge if not already present on the element.
|
||||
if (!element.url) {
|
||||
try {
|
||||
if (element.type === 'file' && element.fileId) {
|
||||
element.url = isGroup
|
||||
? await this.bridge.fetchGroupFileUrl(sessionId, element.fileId)
|
||||
: element.fileHash
|
||||
? await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash)
|
||||
: '';
|
||||
} else if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
|
||||
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
|
||||
} else {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
|
||||
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
|
||||
}
|
||||
}
|
||||
} catch { /* best-effort */ }
|
||||
}
|
||||
// Then apply the cached RKey if the URL needs one.
|
||||
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||
},
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) => {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
picFormat: element.picFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (mediaType === 'record') {
|
||||
this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
voiceFormat: element.voiceFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// video
|
||||
this.mediaStore.rememberVideo({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
videoFormat: element.videoFormat,
|
||||
});
|
||||
},
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
|
||||
// Shared instance context. Only carries fields that are actually read
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Side-channel observer that watches every image / record / video
|
||||
// segment emitted by the event converter and writes a row into the
|
||||
// MediaStore so later `get_image` / `get_record` OneBot actions can
|
||||
// resolve the original `data.file` back to a URL + metadata.
|
||||
//
|
||||
// Used as the `mediaSegmentSink` callback in `ConverterContext`.
|
||||
//
|
||||
// The fan-out is uniform (always one rememberX call per segment), but
|
||||
// each mediaType maps to a slightly different MediaStore record shape;
|
||||
// keeping the three field maps in one place makes the divergence
|
||||
// visible at a glance.
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonObject } from './types';
|
||||
import type { MediaStore } from './media-store';
|
||||
|
||||
export type MediaType = 'image' | 'record' | 'video';
|
||||
|
||||
export class MediaIndexer {
|
||||
constructor(private readonly mediaStore: MediaStore) {}
|
||||
|
||||
remember(
|
||||
mediaType: MediaType,
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): void {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileId ?? '',
|
||||
subType: element.subType ?? 0,
|
||||
summary: element.summary ?? '',
|
||||
imageUrl: element.imageUrl ?? '',
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
picFormat: element.picFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (mediaType === 'record') {
|
||||
this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
voiceFormat: element.voiceFormat,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// video
|
||||
this.mediaStore.rememberVideo({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
fileName: element.fileName ?? '',
|
||||
duration: element.duration ?? 0,
|
||||
fileHash: element.fileHash ?? '',
|
||||
mediaNode: element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
md5Hex: element.md5Hex,
|
||||
sha1Hex: element.sha1Hex,
|
||||
width: element.width,
|
||||
height: element.height,
|
||||
videoFormat: element.videoFormat,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Resolves the URL for an image / record / video / file element on its
|
||||
// way out of the bridge into an OneBot segment.
|
||||
//
|
||||
// Two steps:
|
||||
// 1. If the bridge event arrived without a `url` (the receive path
|
||||
// sometimes does), fetch a fresh URL from the right Bridge API
|
||||
// based on element.type + isGroup, mutating the element in-place
|
||||
// so any downstream cache sees the URL too.
|
||||
// 2. Apply the cached RKey (the per-UIN signed download key) the
|
||||
// RKeyCache knows about — both to brand-new URLs from step 1 and
|
||||
// to URLs that came in with the event already.
|
||||
//
|
||||
// Used as the `mediaUrlResolver` callback in `ConverterContext`.
|
||||
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { RKeyCache } from './instance-rkey';
|
||||
|
||||
export class MediaUrlResolver {
|
||||
constructor(
|
||||
private readonly bridge: Bridge,
|
||||
private readonly rkeyCache: RKeyCache,
|
||||
) {}
|
||||
|
||||
async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise<string> {
|
||||
if (!element.url) {
|
||||
try {
|
||||
await this.populateUrl(element, isGroup, sessionId);
|
||||
} catch {
|
||||
// Best-effort: a URL fetch hiccup should never block the
|
||||
// outgoing segment. The RKey pass below still runs.
|
||||
}
|
||||
}
|
||||
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
|
||||
}
|
||||
|
||||
/** Branches by element.type + isGroup to pick the right Bridge API.
|
||||
* Mutates `element.url` in-place so the caller sees the same URL
|
||||
* the downstream rkey/media-store path will see. */
|
||||
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
|
||||
if (element.type === 'file' && element.fileId) {
|
||||
if (isGroup) {
|
||||
element.url = await this.bridge.fetchGroupFileUrl(sessionId, element.fileId);
|
||||
} else if (element.fileHash) {
|
||||
element.url = await this.bridge.fetchPrivateFileUrl(sessionId, element.fileId, element.fileHash);
|
||||
} else {
|
||||
element.url = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchGroupPttUrlByNode(sessionId, element.mediaNode)
|
||||
: await this.bridge.fetchGroupVideoUrlByNode(sessionId, element.mediaNode);
|
||||
} else {
|
||||
element.url = element.type === 'record'
|
||||
? await this.bridge.fetchPrivatePttUrlByNode(element.mediaNode)
|
||||
: await this.bridge.fetchPrivateVideoUrlByNode(element.mediaNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { MediaIndexer } from '../src/onebot/media-indexer';
|
||||
import type { MessageElement } from '../src/bridge/events';
|
||||
|
||||
function makeMediaStore() {
|
||||
return {
|
||||
rememberImage: vi.fn(),
|
||||
rememberRecord: vi.fn(),
|
||||
rememberVideo: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('MediaIndexer', () => {
|
||||
it('image: maps element fields into rememberImage with file fallback to fileId', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'image',
|
||||
fileId: 'img-fid',
|
||||
fileSize: 1024,
|
||||
subType: 1,
|
||||
summary: '[image]',
|
||||
imageUrl: 'http://orig',
|
||||
md5Hex: 'abcd',
|
||||
sha1Hex: 'efgh',
|
||||
width: 800,
|
||||
height: 600,
|
||||
picFormat: 1000,
|
||||
};
|
||||
indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
|
||||
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
expect(arg).toMatchObject({
|
||||
file: 'img-fid', // data.file was '', fell back to element.fileId
|
||||
url: 'http://x',
|
||||
fileSize: 1024,
|
||||
subType: 1,
|
||||
summary: '[image]',
|
||||
imageUrl: 'http://orig',
|
||||
isGroup: true,
|
||||
sessionId: 99999,
|
||||
md5Hex: 'abcd',
|
||||
sha1Hex: 'efgh',
|
||||
width: 800,
|
||||
height: 600,
|
||||
picFormat: 1000,
|
||||
});
|
||||
});
|
||||
|
||||
it('record: maps element fields into rememberRecord with file fallback chain', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'record',
|
||||
fileId: 'rec-fid',
|
||||
fileName: 'voice.amr',
|
||||
fileSize: 2048,
|
||||
duration: 5,
|
||||
fileHash: 'h',
|
||||
mediaNode: { fileUuid: 'uuid' },
|
||||
md5Hex: 'm',
|
||||
sha1Hex: 's',
|
||||
voiceFormat: 1,
|
||||
};
|
||||
indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
|
||||
|
||||
const arg = store.rememberRecord.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('voice.amr'); // data.file '' → element.fileName
|
||||
expect(arg.fileId).toBe('rec-fid');
|
||||
expect(arg.duration).toBe(5);
|
||||
expect(arg.isGroup).toBe(false);
|
||||
expect(arg.sessionId).toBe(12345);
|
||||
expect(arg.voiceFormat).toBe(1);
|
||||
});
|
||||
|
||||
it('video: maps element fields into rememberVideo', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
type: 'video',
|
||||
fileId: 'vid-fid',
|
||||
fileName: 'clip.mp4',
|
||||
fileSize: 99999,
|
||||
duration: 30,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
videoFormat: 2,
|
||||
};
|
||||
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
|
||||
|
||||
const arg = store.rememberVideo.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
|
||||
expect(arg.fileId).toBe('vid-fid');
|
||||
expect(arg.duration).toBe(30);
|
||||
expect(arg.width).toBe(1920);
|
||||
expect(arg.videoFormat).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
|
||||
indexer.remember('record', element, { url: '', file: '' }, false, 1);
|
||||
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
|
||||
});
|
||||
|
||||
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
expect(arg.fileSize).toBe(0);
|
||||
expect(arg.subType).toBe(0);
|
||||
expect(arg.summary).toBe('');
|
||||
expect(arg.imageUrl).toBe('');
|
||||
});
|
||||
|
||||
it('only the matching rememberX is called', () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
expect(store.rememberRecord).not.toHaveBeenCalled();
|
||||
expect(store.rememberVideo).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MediaUrlResolver } from '../src/onebot/media-url-resolver';
|
||||
import type { MessageElement } from '../src/bridge/events';
|
||||
|
||||
// Minimal stand-ins for the two collaborators. Each test wires whatever
|
||||
// subset of Bridge methods the element type exercises.
|
||||
|
||||
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
|
||||
return {
|
||||
fetchGroupFileUrl: vi.fn(async () => 'http://group/file'),
|
||||
fetchPrivateFileUrl: vi.fn(async () => 'http://private/file'),
|
||||
fetchGroupPttUrlByNode: vi.fn(async () => 'http://group/ptt'),
|
||||
fetchPrivatePttUrlByNode: vi.fn(async () => 'http://private/ptt'),
|
||||
fetchGroupVideoUrlByNode: vi.fn(async () => 'http://group/video'),
|
||||
fetchPrivateVideoUrlByNode: vi.fn(async () => 'http://private/video'),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRkey(overrides: { resolveMediaUrl?: ReturnType<typeof vi.fn> } = {}) {
|
||||
return {
|
||||
resolveMediaUrl: overrides.resolveMediaUrl ?? vi.fn(async (_bridge, el: MessageElement) => el.url ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
const MEDIA_NODE = { fileUuid: 'uuid-1' };
|
||||
|
||||
describe('MediaUrlResolver — file element', () => {
|
||||
let bridge: ReturnType<typeof makeBridge>;
|
||||
let rkey: ReturnType<typeof makeRkey>;
|
||||
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
|
||||
|
||||
it('group + fileId: uses fetchGroupFileUrl, then applies rkey', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.fetchGroupFileUrl).toHaveBeenCalledWith(12345, 'fid-x');
|
||||
expect(element.url).toBe('http://group/file');
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
expect(out).toBe('http://group/file');
|
||||
});
|
||||
|
||||
it('c2c + fileId + fileHash: uses fetchPrivateFileUrl', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.fetchPrivateFileUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
|
||||
expect(element.url).toBe('http://private/file');
|
||||
});
|
||||
|
||||
it('c2c + fileId but no fileHash: sets url to empty string (no bridge call)', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.fetchPrivateFileUrl).not.toHaveBeenCalled();
|
||||
expect(element.url).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaUrlResolver — record / video element', () => {
|
||||
let bridge: ReturnType<typeof makeBridge>;
|
||||
let rkey: ReturnType<typeof makeRkey>;
|
||||
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
|
||||
|
||||
it('group record: uses fetchGroupPttUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.fetchGroupPttUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
|
||||
expect(element.url).toBe('http://group/ptt');
|
||||
});
|
||||
|
||||
it('c2c record: uses fetchPrivatePttUrlByNode (no sessionId argument)', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.fetchPrivatePttUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
|
||||
expect(element.url).toBe('http://private/ptt');
|
||||
});
|
||||
|
||||
it('group video: uses fetchGroupVideoUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.fetchGroupVideoUrlByNode).toHaveBeenCalledWith(12345, MEDIA_NODE);
|
||||
expect(element.url).toBe('http://group/video');
|
||||
});
|
||||
|
||||
it('c2c video: uses fetchPrivateVideoUrlByNode', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
|
||||
await resolver.resolve(element, false, 67890);
|
||||
expect(bridge.fetchPrivateVideoUrlByNode).toHaveBeenCalledWith(MEDIA_NODE);
|
||||
expect(element.url).toBe('http://private/video');
|
||||
});
|
||||
|
||||
it('record without mediaNode: no bridge call, url untouched', async () => {
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'record' };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.fetchGroupPttUrlByNode).not.toHaveBeenCalled();
|
||||
expect(element.url).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaUrlResolver — short-circuits and resilience', () => {
|
||||
it('element.url already set: no bridge call, just rkey pass', async () => {
|
||||
const bridge = makeBridge();
|
||||
const rkey = makeRkey();
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' };
|
||||
await resolver.resolve(element, true, 12345);
|
||||
expect(bridge.fetchGroupFileUrl).not.toHaveBeenCalled();
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('bridge throws: swallowed, rkey still applied', async () => {
|
||||
const bridge = makeBridge({
|
||||
fetchGroupFileUrl: vi.fn(async () => { throw new Error('network down'); }),
|
||||
});
|
||||
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(out).toBe('rkey-fallback');
|
||||
expect(element.url).toBeUndefined(); // bridge threw before assignment
|
||||
});
|
||||
|
||||
it('always calls rkey.resolveMediaUrl at the end', async () => {
|
||||
const bridge = makeBridge();
|
||||
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'http://signed') });
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'image' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
expect(out).toBe('http://signed');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user