diff --git a/packages/bridge/src/bridge-service.ts b/packages/bridge/src/bridge-service.ts index eb89136d..2f725280 100644 --- a/packages/bridge/src/bridge-service.ts +++ b/packages/bridge/src/bridge-service.ts @@ -4,6 +4,7 @@ import type { DialogRpc } from './dialogs.js' import type { IMPlatform, PlatformSession } from './platform.js' import type { StickerRpc } from './sticker-rpc.js' import type { MessageProjectionPipeline } from './message-projection.js' +import { VirtualForwardSources, type VirtualForwardSource } from './virtual-forward.js' export interface BridgeSessionState { generation: object @@ -28,6 +29,8 @@ export class MtprotoBridgeService extends Service { private readonly _resolveSession: BridgeSessionResolver, /** Data centre this bridge advertises for its own synthetic media locations. */ readonly dcId = 1, + /** Peers the relay only projects, so plugins can make their messages forwardable. */ + readonly virtualForward = new VirtualForwardSources(), ) { super(ctx, 'mtprotoBridge') } @@ -35,4 +38,9 @@ export class MtprotoBridgeService extends Service { resolveSession(rpc: ServerRpcContext): Promise { return this._resolveSession(rpc) } + + /** Register forwarded content for a peer this plugin projects instead of the platform. */ + registerForwardSource(source: VirtualForwardSource): () => void { + return this.virtualForward.register(source) + } } diff --git a/packages/bridge/src/dialogs.ts b/packages/bridge/src/dialogs.ts index 4219f50a..1d83697b 100644 --- a/packages/bridge/src/dialogs.ts +++ b/packages/bridge/src/dialogs.ts @@ -51,6 +51,7 @@ import { import type { MessageProjectionPipeline } from './message-projection.js' import type { SendEchoes } from './send-echoes.js' import type { SpeechPipeline } from './speech.js' +import type { VirtualForwardContent, VirtualForwardResolver } from './virtual-forward.js' import { convertRichMessage, markdownRichMessage, type RichMediaReference, type ResolvedRichMedia } from './rich-message.js' type GetDialogsRequest = tl.messages.RawGetDialogsRequest @@ -303,6 +304,8 @@ export interface DialogRpcOptions { conversationMembers?: ConversationMemberStore /** Builds Telegram link previews for messages whose text carries a bare URL. */ linkPreviews?: LinkPreviewService + /** Content of peers the relay projects instead of storing, e.g. merged-forward transcripts. */ + virtualForward?: VirtualForwardResolver } export class DialogRpc { @@ -378,6 +381,7 @@ export class DialogRpc { private readonly _onScheduledChange?: () => void private readonly _conversationMembers?: ConversationMemberStore private readonly _linkPreviews?: LinkPreviewService + private readonly _virtualForward?: VirtualForwardResolver constructor( private readonly _platform: IMPlatform, @@ -390,7 +394,7 @@ export class DialogRpc { onLocalEvent, authKeyId, onTrace, drafts, onDraftUpdate, notificationSettings, authenticatedSelfId, blockedPeers, dialogFolders, systemPeers, messageProjection, sendEchoes, scheduled, onScheduledChange, - conversationMembers, linkPreviews, + conversationMembers, linkPreviews, virtualForward, } = options this._uploads = uploads this._onTransferProgress = onTransferProgress @@ -414,6 +418,7 @@ export class DialogRpc { this._onScheduledChange = onScheduledChange this._conversationMembers = conversationMembers this._linkPreviews = linkPreviews + this._virtualForward = virtualForward this._actions = new PlatformMessageActions(_platform, _session) // 有 `MessageStore` 时淘汰旧条目并由数据库兜底;无存储模式不可淘汰,避免重用已分配的 ID。 const messageIndexLimit = store ? MAX_CACHED_MESSAGE_INDEX_ENTRIES : Number.POSITIVE_INFINITY @@ -3154,38 +3159,56 @@ export class DialogRpc { await this._hydratePeers() const toId = this._resolveMessageTarget(req.toPeer, req.replyTo) this._assertWritableConversation(toId) + // 合成 peer(合并转发的聊天记录就是其中一种)的消息没有落库,`_resolvePeer` + // 认不出来。先问投影它的插件要存档内容,拿到就按复制语义转发。 + const virtual = req.fromPeer._ === 'inputPeerEmpty' + ? undefined + : await this._virtualForward?.resolve(req.fromPeer, req.id) let fromId = req.fromPeer._ === 'inputPeerEmpty' ? undefined - : this._resolvePeer(req.fromPeer) + : virtual ? virtual.conversation.id : this._resolvePeer(req.fromPeer) const selected: Array<{ projected: ProjectedMessage, part: TlMessagePartRow }> = [] - for (const tlId of req.id) { - const projected = await this._store.findProjectedByTlId( - this._session.platformSessionId, - tlId, - fromId, - fromId === undefined ? 'direct' : undefined, - ) - if (!projected) throw new RpcError(400, 'MSG_ID_INVALID') - if (fromId === undefined) { - fromId = projected.source.conversationId - } else if (projected.source.conversationId !== fromId) { - throw new RpcError(400, 'MSG_ID_INVALID') + if (virtual) { + if (!virtual.messages.length) throw new RpcError(400, 'MSG_ID_INVALID') + } else { + for (const tlId of req.id) { + const projected = await this._store.findProjectedByTlId( + this._session.platformSessionId, + tlId, + fromId, + fromId === undefined ? 'direct' : undefined, + ) + if (!projected) throw new RpcError(400, 'MSG_ID_INVALID') + if (fromId === undefined) { + fromId = projected.source.conversationId + } else if (projected.source.conversationId !== fromId) { + throw new RpcError(400, 'MSG_ID_INVALID') + } + const part = projected.parts.find((candidate) => candidate.tlMessageId === tlId) + if (!part) throw new RpcError(400, 'MSG_ID_INVALID') + selected.push({ projected, part }) } - const part = projected.parts.find((candidate) => candidate.tlMessageId === tlId) - if (!part) throw new RpcError(400, 'MSG_ID_INVALID') - selected.push({ projected, part }) } if (!fromId) throw new RpcError(400, 'MSG_ID_INVALID') const systemPeer = await this._systemPeers?.resolve(this._session, toId) if (systemPeer) { return this._forwardToSystemPeer( - systemPeer, selected, req.randomId, excludeConnection, Boolean(req.dropMediaCaptions), + systemPeer, + virtual + ? this._virtualForwardInput(virtual, Boolean(req.dropMediaCaptions)) + : this._systemPeerForwardInput(selected, Boolean(req.dropMediaCaptions)), + req.randomId, excludeConnection, ) } // 一条平台多图消息会被投影成多条 Telegram 相册消息;需按物理消息去重合并,避免重复转发或错误触发合并转发。 - const { sourceIds, sourceMessages, requiresCopy } = buildForwardTargets( - selected, Boolean(req.dropMediaCaptions), - ) + // 合成 peer 没有平台消息可以原生转发,永远走复制。 + const { sourceIds, sourceMessages, requiresCopy } = virtual + ? { + sourceIds: virtual.messages.map((message) => message.sourceId), + sourceMessages: virtual.messages.map((message) => message.source), + requiresCopy: true, + } + : buildForwardTargets(selected, Boolean(req.dropMediaCaptions)) let forwarded: IMMessage[] try { forwarded = await this._actions.forward( @@ -3245,12 +3268,10 @@ export class DialogRpc { private async _forwardToSystemPeer( resolution: SystemPeerResolution, - selected: readonly { projected: ProjectedMessage, part: TlMessagePartRow }[], + input: IMMessageInput, randomIds: Long[], excludeConnection?: ServerConnection, - dropMediaCaptions = false, ): Promise { - const input = this._systemPeerForwardInput(selected, dropMediaCaptions) const sent = this._systemPeers!.makeOutgoing(this._session, resolution, input) const source: IMMessage = { ...sent, @@ -3304,6 +3325,37 @@ export class DialogRpc { return { parts } } + /** + * 合成 peer 的内容按复制语义变成一条发送内容。贴纸、卡片这类合成 peer 才有 + * 原样重发能力的部件留给适配器的复制转发去处理,这里只覆盖文本与媒体。 + */ + private _virtualForwardInput( + content: VirtualForwardContent, + dropMediaCaptions: boolean, + ): IMMessageInput { + const parts: IMMessageInput['parts'] = [] + for (const { source } of content.messages) { + const media = source.content.parts.filter((part) => part.type === 'media') + if (!(dropMediaCaptions && media.length)) { + for (const part of source.content.parts) { + // 卡片与嵌套转发只有一句可读的标题,复制成文本比丢掉更接近原意。 + if (part.type === 'card' || part.type === 'message-bundle') { + const text = messagePartText(part) + if (text) parts.push({ type: 'text', text }) + continue + } + if (part.type === 'text') parts.push({ ...part }) + } + } + for (const part of media) { + if (part.type !== 'media') continue + parts.push({ type: 'media', media: this._mediaInputFromOrigin(part.media) }) + } + } + if (!parts.length) throw new RpcError(400, 'MESSAGE_FORWARD_FORBIDDEN') + return { parts } + } + private _confirmForwardRandomIds(payload: tl.RawUpdates, randomIds: Long[]): tl.RawUpdates { const projectedCount = payload.updates.filter((update) => update._ === 'updateNewMessage' || update._ === 'updateNewChannelMessage').length diff --git a/packages/bridge/src/index.ts b/packages/bridge/src/index.ts index b05d51c8..9e340b16 100644 --- a/packages/bridge/src/index.ts +++ b/packages/bridge/src/index.ts @@ -72,6 +72,7 @@ import { ActiveSessionStore, createAuthorizationReservationQueue, registerActiveSessionRpc, } from './active-sessions.js' import { MtprotoBridgeService, type BridgeSessionState } from './bridge-service.js' +import { VirtualForwardSources } from './virtual-forward.js' import { BridgeManagementError, BridgeManagementService } from './management-service.js' import { registerGroupFilesMiniApp } from './group-files-miniapp.js' import { MessageProjectionPipeline } from './message-projection.js' @@ -90,6 +91,7 @@ export * from './postgres-search.js' export * from './detached-message-projection.js' export * from './message-store.js' export * from './message-actions.js' +export * from './virtual-forward.js' export * from './platform-manager.js' export * from './upload-manager.js' export * from './update-manager.js' @@ -242,6 +244,9 @@ export const Config = z.object({ export function apply(ctx: Context, config: BridgeConfig = {}): void { const generation = {} + // 合成 peer(例如合并转发的聊天记录)的转发内容来源;插件注册后,各会话的 + // `DialogRpc` 共用同一个注册表。 + const virtualForward = new VirtualForwardSources() const platforms = new IMPlatformService(ctx) const stickerProviders = new IMStickerService(ctx) const resources = new TelegramResourceService(ctx) @@ -623,6 +628,7 @@ export function apply(ctx: Context, config: BridgeConfig = {}): void { () => { void scheduledDispatcher?.rescan() }, conversationMembers, linkPreviews, + virtualForward, ) const requireBridgeSession: typeof resolveBridgeSession = async (rpcContext, ...rest) => { const state = await resolveBridgeSession(rpcContext, ...rest) @@ -654,7 +660,7 @@ export function apply(ctx: Context, config: BridgeConfig = {}): void { }) return () => scheduledDispatcher!.stop() }, 'mtproto-bridge.scheduled-messages') - new MtprotoBridgeService(ctx, requireBridgeSession, dcId) + new MtprotoBridgeService(ctx, requireBridgeSession, dcId, virtualForward) registerGroupFilesMiniApp(ctx, platforms, requireBridgeSession, config.groupFilesMiniApp) const reserveAuthorization = createAuthorizationReservationQueue() @@ -1795,6 +1801,7 @@ export function createSessionResolver( onScheduledChange?: () => void, conversationMembers?: ConversationMemberStore, linkPreviews?: LinkPreviewService, + virtualForward?: VirtualForwardSources, ) { const projection = messageProjection ?? new MessageProjectionPipeline(ctx) const loading = new Map>() @@ -1865,6 +1872,10 @@ export function createSessionResolver( dialogFolders, systemPeers, messageProjection: projection, + // 合成 peer 的解析绑定到本会话的状态,注册表本身保持无状态。 + virtualForward: virtualForward && { + resolve: (fromPeer, messageIds) => virtualForward.resolve(state, fromPeer, messageIds), + }, sendEchoes, scheduled, onScheduledChange, diff --git a/packages/bridge/src/virtual-forward.test.ts b/packages/bridge/src/virtual-forward.test.ts new file mode 100644 index 00000000..92aab6ef --- /dev/null +++ b/packages/bridge/src/virtual-forward.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest' +import type { BridgeSessionState } from './bridge-service.js' +import type { IMMessage } from './platform.js' +import { VirtualForwardSources, type VirtualForwardSource } from './virtual-forward.js' + +const state = {} as BridgeSessionState +const peer = { _: 'inputPeerChat', chatId: 42 } as const +const message: IMMessage = { + id: 'archived', conversationId: 'source', senderId: 'alice', timestamp: 1, + content: { parts: [{ type: 'text', text: 'hi' }] }, +} + +function source(content?: Awaited>): VirtualForwardSource { + return { resolve: vi.fn(async () => content) } +} + +describe('virtual forward sources', () => { + it('falls through to the next source until one owns the peer', async () => { + const registry = new VirtualForwardSources() + const foreign = source(undefined) + const owner = source({ + conversation: { id: 'source' }, + messages: [{ sourceId: 'archived', source: message }], + }) + registry.register(foreign) + registry.register(owner) + + await expect(registry.resolve(state, peer, [1])).resolves.toMatchObject({ + conversation: { id: 'source' }, + messages: [{ sourceId: 'archived' }], + }) + expect(foreign.resolve).toHaveBeenCalledWith(state, peer, [1]) + expect(owner.resolve).toHaveBeenCalledWith(state, peer, [1]) + }) + + it('stops asking sources once one answers', async () => { + const registry = new VirtualForwardSources() + const owner = source({ conversation: { id: 'source' }, messages: [] }) + const later = source(undefined) + registry.register(owner) + registry.register(later) + + await expect(registry.resolve(state, peer, [1])).resolves.toMatchObject({ + conversation: { id: 'source' }, + }) + expect(later.resolve).not.toHaveBeenCalled() + }) + + it('forgets a source when its disposal runs, so a disposed plugin cannot answer', async () => { + const registry = new VirtualForwardSources() + const owner = source({ conversation: { id: 'source' }, messages: [] }) + const dispose = registry.register(owner) + dispose() + + await expect(registry.resolve(state, peer, [1])).resolves.toBeUndefined() + expect(owner.resolve).not.toHaveBeenCalled() + }) +}) diff --git a/packages/bridge/src/virtual-forward.ts b/packages/bridge/src/virtual-forward.ts new file mode 100644 index 00000000..d2a6138e --- /dev/null +++ b/packages/bridge/src/virtual-forward.ts @@ -0,0 +1,65 @@ +import type { tl } from '@mtcute/core' +import type { BridgeSessionState } from './bridge-service.js' +import type { IMConversationRef, IMMessage } from './platform.js' + +/** 合成 peer(例如合并转发的聊天记录)里一条可以被复制重发的消息。 */ +export interface VirtualForwardMessage { + /** 来源平台消息 id;原生转发可能用到,复制转发时只作占位。 */ + sourceId: string + /** 存档内容自身;`copy` 语义的适配器按它重发。 */ + source: IMMessage +} + +/** 一次合成 peer 转发请求解析出的内容。 */ +export interface VirtualForwardContent { + /** 存档内容所属的平台会话;`copy` 语义的适配器只把它当来源标识。 */ + conversation: IMConversationRef + /** 按请求顺序给出的内容,同一条消息的多个相册分片已经合并。 */ + messages: readonly VirtualForwardMessage[] +} + +/** + * 扩展点:relay 会投影一些不存在于平台存储里的 peer(合并转发的聊天记录就是 + * 其中之一),这些 peer 的消息没有落库,普通转发只能报 `PEER_ID_INVALID`。 + * 拥有这类 peer 的插件注册一个来源,就能让自己的消息按复制语义转发出去。 + */ +export interface VirtualForwardSource { + /** 不是本插件的 peer 时返回 `undefined`,由 bridge 走默认实现。 */ + resolve( + state: BridgeSessionState, + fromPeer: tl.TypeInputPeer, + messageIds: readonly number[], + ): Promise +} + +/** bridge 侧的解析入口:`bridge` 已经把它绑到了当前会话上。 */ +export interface VirtualForwardResolver { + resolve( + fromPeer: tl.TypeInputPeer, + messageIds: readonly number[], + ): Promise +} + +/** 合成 peer 转发来源的注册表;bridge 与插件共用同一个实例。 */ +export class VirtualForwardSources { + private readonly _sources = new Set() + + register(source: VirtualForwardSource): () => void { + this._sources.add(source) + return () => { + this._sources.delete(source) + } + } + + async resolve( + state: BridgeSessionState, + fromPeer: tl.TypeInputPeer, + messageIds: readonly number[], + ): Promise { + for (const source of this._sources) { + const content = await source.resolve(state, fromPeer, messageIds) + if (content) return content + } + return undefined + } +} diff --git a/packages/merged-forward/src/forward-source.e2e.test.ts b/packages/merged-forward/src/forward-source.e2e.test.ts new file mode 100644 index 00000000..3dead0f5 --- /dev/null +++ b/packages/merged-forward/src/forward-source.e2e.test.ts @@ -0,0 +1,270 @@ +import { Context } from 'cordis' +import { afterEach, describe, expect, it } from 'vitest' +import Database from '@cordisjs/plugin-database' +import SQLiteDriver from '@cordisjs/plugin-database-sqlite' +import type { tl } from '@mtcute/core' +import Long from 'long' +import { + DialogRpc, + MessageProjectionPipeline, + MessageStore, + MtprotoBridgeService, + defineModels, + type BridgeSessionState, + type IMConversation, + type IMMessage, + type IMMessageBundle, + type IMMessageInput, + type IMMessageSnapshot, + type IMForwardMessagesOptions, + type IMPlatform, + type PlatformSession, +} from '@mtproto-relay/bridge' +import { Mtproto } from '@mtproto-relay/mtproto' +import * as mergedForward from './index.js' + +const session: PlatformSession = { + platformId: 'test', platformSessionId: 'merged-forward-forward-e2e', userId: 'self', + credentials: {}, metadata: { firstName: 'Self' }, +} + +const outer: IMConversation = { id: 'outer-dialog', kind: 'group', title: 'Outer dialog' } +const bundle: IMMessageBundle = { + id: 'bundle:forward-e2e', title: '群聊的聊天记录', preview: 'Alice: 有点烦', + locator: { root: 'forward-e2e', conversationId: outer.id }, +} +const archived: IMMessageSnapshot[] = [ + { + id: 'archived-1', senderId: 'alice', timestamp: 100, + sender: { id: 'alice', firstName: 'Alice' }, + content: { parts: [{ type: 'text', text: '有点烦' }] }, + }, + { + id: 'archived-2', senderId: 'alice', timestamp: 101, + sender: { id: 'alice', firstName: 'Alice' }, + content: { parts: [{ type: 'text', text: '这老师好像想要我发论文' }] }, + }, +] +const outerMessage: IMMessage = { + id: 'outer-message', conversationId: outer.id, senderId: 'alice', timestamp: 102, + sender: { id: 'alice', firstName: 'Alice' }, + content: { parts: [{ type: 'message-bundle', bundle }] }, +} + +interface ForwardCall { + from: string + messageIds: string[] + to: string + options: IMForwardMessagesOptions +} + +const forwards: ForwardCall[] = [] +const sentInputs: IMMessageInput[] = [] + +function makePlatform(): IMPlatform { + return { + capabilities: { + history: true, + readState: { markRead: false, events: false }, + send: { text: true, images: true, files: true, mixed: true, maxTextLength: 20_000, maxMedia: 9 }, + conversations: { groups: true, channels: false, subchannels: false }, + messageActions: { + delete: { own: { supported: true }, others: { supported: true } }, + edit: { mode: 'delete-and-resend' }, + forward: { mode: 'native', preservesAuthor: true }, + }, + }, + messageBundles: { + async load() { return archived }, + }, + async subscribe() { return () => {} }, + async sendMessage(_session, conversation, content) { + sentInputs.push(content) + return { + id: `sent-${sentInputs.length}`, conversationId: conversation.id, senderId: session.userId, + timestamp: 300 + sentInputs.length, outgoing: true, + content: { parts: content.parts.flatMap((part) => part.type === 'text' + ? [{ type: 'text' as const, text: part.text }] + : []) }, + } + }, + // QQNT 的复制转发语义:按适配器拿到的源内容重发,不使用来源会话。 + async forwardMessages(_session, from, messageIds, to, options: IMForwardMessagesOptions = {}) { + forwards.push({ from: from.id, messageIds: [...messageIds], to: to.id, options }) + return messageIds.map((_, index) => { + const source = options.sourceMessages?.[index] + if (!source) throw new Error('synthetic peer content was not passed to the adapter') + return { + id: `forwarded-${forwards.length}-${index}`, conversationId: to.id, senderId: session.userId, + timestamp: 200 + index, outgoing: true, + content: { + parts: source.content.parts.flatMap((part) => part.type === 'text' + ? [{ type: 'text' as const, text: part.text }] + : []), + }, + } + }) + }, + async getDialogs() { + return { dialogs: [{ conversation: outer, lastMessage: outerMessage, unreadCount: 0 }] } + }, + async getHistory(_session, conversation) { + return { messages: conversation.id === outer.id ? [outerMessage] : [] } + }, + async getUser(_session, id) { return { id, firstName: id } }, + } as unknown as IMPlatform +} + +const platform = makePlatform() +const disposals: Array<() => Promise> = [] + +afterEach(async () => { + for (const dispose of disposals.splice(0).reverse()) await dispose() + forwards.length = 0 + sentInputs.length = 0 +}) + +interface Harness { + ctx: Context + dialogs: DialogRpc + dispatch(request: tl.RpcMethod): Promise +} + +async function boot(): Promise { + const ctx = new Context() + const database = ctx.plugin(Database) + const sqlite = ctx.plugin(SQLiteDriver, { path: ':memory:' }) + await Promise.all([database, sqlite]) + await new Promise((resolve) => setTimeout(resolve, 25)) + defineModels(ctx) + await ctx.database.prepared() + const mtproto = ctx.plugin(Mtproto, { host: '127.0.0.1', port: 0 }) + await mtproto + const pipeline = new MessageProjectionPipeline(ctx) + const store = new MessageStore(ctx.database, undefined, undefined, undefined, pipeline) + // 会话状态先建好,`DialogRpc` 再通过插件注册表解析合成 peer 的内容。 + const state = { + generation: {}, platform, session, projection: pipeline, stickers: {} as never, + dialogs: undefined as never, + } as unknown as BridgeSessionState + const bridge = ctx.plugin((scope) => { + new MtprotoBridgeService(scope, async () => state, 1) + }) + await bridge + state.dialogs = new DialogRpc(platform, session, store, { + messageProjection: pipeline, + virtualForward: { + resolve: (fromPeer, messageIds) => ctx.mtprotoBridge.virtualForward.resolve(state, fromPeer, messageIds), + }, + }) + const plugin = ctx.plugin(mergedForward) + await plugin + disposals.push(async () => { + await plugin.dispose() + await bridge.dispose() + await mtproto.dispose() + await sqlite.dispose() + await database.dispose() + }) + const rpc = { connection: { remoteAddress: '127.0.0.1' } } as never + return { + ctx, + dialogs: state.dialogs, + dispatch: (request) => ctx.mtproto.dispatch(rpc, request), + } +} + +/** 让客户端看到外层消息,并从卡片链接里拿到合成 chat 与外层的输入 peer。 */ +async function openTranscript( + harness: Harness, +): Promise<{ chatId: number, firstId: number, toPeer: tl.TypeInputPeer }> { + const listed = await harness.dialogs.getDialogs({ + _: 'messages.getDialogs', offsetDate: 0, offsetId: 0, + offsetPeer: { _: 'inputPeerEmpty' }, limit: 100, hash: Long.ZERO, + }) as tl.messages.RawDialogs + const projected = listed.messages.find((item) => item._ === 'message') as tl.RawMessage + const url = projected.entities?.find( + (item): item is tl.RawMessageEntityTextUrl => item._ === 'messageEntityTextUrl', + )?.url + if (!url) throw new Error('merged-forward projection did not create a deep link') + const [, chatText, firstText] = /bridgebundle_(\d+)\/(\d+)$/.exec(url)! + const peer = listed.dialogs.find((item) => item._ === 'dialog')!.peer + if (peer._ !== 'peerChannel') throw new Error('the outer dialog was not projected as a channel') + return { + chatId: Number(chatText), firstId: Number(firstText), + toPeer: { _: 'inputPeerChannel', channelId: peer.channelId, accessHash: Long.ONE }, + } +} + +describe('merged-forward transcript forwarding', () => { + it('copies the archived messages into the target conversation', async () => { + const harness = await boot() + const { chatId, firstId, toPeer } = await openTranscript(harness) + const secondId = mergedForward.transcriptMessageId(1, 0) + + const updates = await harness.dialogs.forwardMessages({ + _: 'messages.forwardMessages', + fromPeer: { _: 'inputPeerChat', chatId }, + toPeer, + id: [firstId, secondId], + randomId: [Long.fromNumber(11), Long.fromNumber(12)], + dropAuthor: false, dropMediaCaptions: false, noforwards: false, silent: false, + }) as tl.RawUpdates + + expect(forwards).toHaveLength(1) + expect(forwards[0]).toMatchObject({ + from: outer.id, + messageIds: ['archived-1', 'archived-2'], + to: outer.id, + // 合成 peer 没有平台消息可以原生转发,只能复制。 + options: { dropAuthor: true }, + }) + expect(forwards[0]!.options.sourceMessages?.map((message) => message.content.parts)) + .toEqual([ + [{ type: 'text', text: '有点烦' }], + [{ type: 'text', text: '这老师好像想要我发论文' }], + ]) + expect(updates.updates.filter((update) => + update._ === 'updateNewMessage' || update._ === 'updateNewChannelMessage') + .map((update) => (update as { message: tl.RawMessage }).message.message)) + .toEqual(['有点烦', '这老师好像想要我发论文']) + }) + + it('forwards a single archived message and drops the transcript author', async () => { + const harness = await boot() + const { chatId, toPeer } = await openTranscript(harness) + const secondId = mergedForward.transcriptMessageId(1, 0) + + const updates = await harness.dialogs.forwardMessages({ + _: 'messages.forwardMessages', + fromPeer: { _: 'inputPeerChat', chatId }, + toPeer, + id: [secondId], + randomId: [Long.fromNumber(13)], + dropAuthor: true, dropMediaCaptions: false, noforwards: false, silent: false, + }) as tl.RawUpdates + + expect(forwards).toHaveLength(1) + expect(forwards[0]!.messageIds).toEqual(['archived-2']) + expect(updates.updates.some((update) => update._ === 'updateMessageID')).toBe(true) + expect(updates.updates + .filter((update) => update._ === 'updateNewMessage' || update._ === 'updateNewChannelMessage') + .map((update) => (update as { message: tl.RawMessage }).message.message)) + .toEqual(['这老师好像想要我发论文']) + }) + + it('rejects a message id that is not part of the transcript', async () => { + const harness = await boot() + const { chatId, toPeer } = await openTranscript(harness) + + await expect(harness.dialogs.forwardMessages({ + _: 'messages.forwardMessages', + fromPeer: { _: 'inputPeerChat', chatId }, + toPeer, + id: [mergedForward.transcriptMessageId(99, 0)], + randomId: [Long.fromNumber(14)], + dropAuthor: false, dropMediaCaptions: false, noforwards: false, silent: false, + })).rejects.toMatchObject({ code: 400, text: 'MSG_ID_INVALID' }) + expect(forwards).toHaveLength(0) + }) +}) diff --git a/packages/merged-forward/src/index.ts b/packages/merged-forward/src/index.ts index af46c070..686b3ea9 100644 --- a/packages/merged-forward/src/index.ts +++ b/packages/merged-forward/src/index.ts @@ -10,6 +10,8 @@ import { type IMMessageSnapshot, type MessageProjectionInput, type MessageProjectionResult, + type VirtualForwardContent, + type VirtualForwardMessage, } from '@mtproto-relay/bridge' import { RpcError, type ServerRpcContext } from '@mtproto-relay/mtproto' @@ -377,6 +379,46 @@ export class MergedForwardProjection { return next() } + /** + * 客户端在聊天记录里点「转发」时给出的内容。 + * + * 聊天记录是合成 peer:它的消息只按需投影出来,从未落库,所以 `forwardMessages` + * 找不到来源会直接报 `PEER_ID_INVALID`,客户端只能把本地占位画成发送失败。这里把 + * 选中的归档消息原样交给 bridge 按复制语义重发。 + */ + async forwardContent( + state: BridgeSessionState, + fromPeer: tl.TypeInputPeer, + messageIds: readonly number[], + ): Promise { + if (fromPeer._ !== 'inputPeerChat') return + const record = await this.lookup(state, fromPeer.chatId) + if (!record) return + const snapshots = await this.loadSnapshots(state, record) + const ranks = transcriptRanks(snapshots) + const byRank = new Map() + for (const snapshot of snapshots) byRank.set(ranks.get(snapshot.id) ?? 0, snapshot) + // 只有真正投影出来的消息才能转发:客户端缓存的旧 ID 不该被当成某条消息。 + const projected = await this.materialize(state, record) + const rendered = new Set(projected.messages.map((message) => message.id)) + // 适配器在 locator 里留了归档来源会话时就用它,否则退回转发自身的标识。 + const conversation = { id: archivedConversationId(record.bundle.locator) ?? record.bundle.id } + const messages: VirtualForwardMessage[] = [] + for (const tlId of messageIds) { + const rank = transcriptMessageRank(tlId) + const snapshot = rank === undefined ? undefined : byRank.get(rank) + // 不是这份聊天记录里的消息:聊天记录是只读的,不能假装转发成功。 + if (!snapshot || !rendered.has(tlId)) throw new RpcError(400, 'MSG_ID_INVALID') + // 一条归档消息会拆成多个 part,一起选中时只复制一次。 + if (messages.some((entry) => entry.sourceId === snapshot.id)) continue + messages.push({ + sourceId: snapshot.id, + source: { ...snapshot, conversationId: conversation.id }, + }) + } + return messages.length ? { conversation, messages } : undefined + } + makeLink(record: BundleRecord, messageId?: number): string { return `https://t.me/bridgebundle_${record.chatId}${messageId ? `/${messageId}` : ''}` } @@ -631,6 +673,9 @@ export function apply(ctx: Context): void { return result } as never, { prepend: true }) ctx.effect(() => () => projection.clear(), 'mergedForward.clear') + ctx.effect(() => ctx.mtprotoBridge.registerForwardSource({ + resolve: (state, fromPeer, messageIds) => projection.forwardContent(state, fromPeer, messageIds), + }), 'mergedForward.forwardSource') } async function routeMergedForwardRpc( @@ -977,6 +1022,20 @@ export function transcriptMessageId(rank: number, ordinal: number): number { return TRANSCRIPT_MESSAGE_ID_BASE + rank * TRANSCRIPT_MESSAGE_ID_STRIDE + ordinal } +/** 聊天记录消息 ID 对应的归档序号;不是聊天记录里的 ID 时返回 `undefined`。 */ +export function transcriptMessageRank(messageId: number): number | undefined { + const offset = messageId - TRANSCRIPT_MESSAGE_ID_BASE + if (!Number.isSafeInteger(offset) || offset < 0) return + return Math.floor(offset / TRANSCRIPT_MESSAGE_ID_STRIDE) +} + +/** 适配器在 bundle locator 里记下的归档来源会话。 */ +function archivedConversationId(locator: unknown): string | undefined { + if (!locator || typeof locator !== 'object') return + const value = (locator as { conversationId?: unknown }).conversationId + return typeof value === 'string' && value ? value : undefined +} + function chronologicalSnapshots(snapshots: readonly IMMessageSnapshot[]): IMMessageSnapshot[] { return snapshots .map((snapshot, index) => ({ snapshot, index }))