Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/bridge/src/bridge-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -28,11 +29,18 @@ 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')
}

resolveSession(rpc: ServerRpcContext): Promise<BridgeSessionState> {
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)
}
}
100 changes: 76 additions & 24 deletions packages/bridge/src/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<any>,
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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<any>[]
try {
forwarded = await this._actions.forward(
Expand Down Expand Up @@ -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<tl.TypeUpdates> {
const input = this._systemPeerForwardInput(selected, dropMediaCaptions)
const sent = this._systemPeers!.makeOutgoing(this._session, resolution, input)
const source: IMMessage = {
...sent,
Expand Down Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion packages/bridge/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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<string, Promise<BridgeSessionState>>()
Expand Down Expand Up @@ -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,
Expand Down
58 changes: 58 additions & 0 deletions packages/bridge/src/virtual-forward.test.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<VirtualForwardSource['resolve']>>): 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()
})
})
65 changes: 65 additions & 0 deletions packages/bridge/src/virtual-forward.ts
Original file line number Diff line number Diff line change
@@ -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<any>
}

/** 一次合成 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<VirtualForwardContent | undefined>
}

/** bridge 侧的解析入口:`bridge` 已经把它绑到了当前会话上。 */
export interface VirtualForwardResolver {
resolve(
fromPeer: tl.TypeInputPeer,
messageIds: readonly number[],
): Promise<VirtualForwardContent | undefined>
}

/** 合成 peer 转发来源的注册表;bridge 与插件共用同一个实例。 */
export class VirtualForwardSources {
private readonly _sources = new Set<VirtualForwardSource>()

register(source: VirtualForwardSource): () => void {
this._sources.add(source)
return () => {
this._sources.delete(source)
}
}

async resolve(
state: BridgeSessionState,
fromPeer: tl.TypeInputPeer,
messageIds: readonly number[],
): Promise<VirtualForwardContent | undefined> {
for (const source of this._sources) {
const content = await source.resolve(state, fromPeer, messageIds)
if (content) return content
}
return undefined
}
}
Loading
Loading