2024-08-13 04:53:07 +03:00
|
|
|
import EventEmitter from 'node:events'
|
2023-11-08 17:28:45 +03:00
|
|
|
|
2024-08-13 04:53:07 +03:00
|
|
|
import type { ITelegramTransport } from '@mtcute/core'
|
|
|
|
import { TransportState } from '@mtcute/core'
|
|
|
|
import type { ICryptoProvider, Logger } from '@mtcute/core/utils.js'
|
|
|
|
import type { tl } from '@mtcute/tl'
|
2023-11-08 17:28:45 +03:00
|
|
|
|
|
|
|
export class StubTelegramTransport extends EventEmitter implements ITelegramTransport {
|
|
|
|
constructor(
|
|
|
|
readonly params: {
|
|
|
|
getMtproxyInfo?: () => tl.RawInputClientProxy
|
|
|
|
onConnect?: (dc: tl.RawDcOption, testMode: boolean) => void
|
|
|
|
onClose?: () => void
|
|
|
|
onMessage?: (msg: Uint8Array) => void
|
|
|
|
},
|
|
|
|
) {
|
|
|
|
super()
|
|
|
|
|
|
|
|
if (params.getMtproxyInfo) {
|
2024-08-13 04:53:07 +03:00
|
|
|
(this as unknown as ITelegramTransport).getMtproxyInfo = params.getMtproxyInfo
|
2023-11-08 17:28:45 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-18 09:31:23 +03:00
|
|
|
_state: TransportState = TransportState.Idle
|
2023-11-08 17:28:45 +03:00
|
|
|
_currentDc: tl.RawDcOption | null = null
|
|
|
|
_crypto!: ICryptoProvider
|
|
|
|
_log!: Logger
|
|
|
|
|
|
|
|
write(data: Uint8Array): void {
|
|
|
|
this.emit('message', data)
|
|
|
|
}
|
|
|
|
|
|
|
|
setup(crypto: ICryptoProvider, log: Logger): void {
|
|
|
|
this._crypto = crypto
|
|
|
|
this._log = log
|
|
|
|
}
|
|
|
|
|
|
|
|
state(): TransportState {
|
|
|
|
return this._state
|
|
|
|
}
|
|
|
|
|
|
|
|
currentDc(): tl.RawDcOption | null {
|
|
|
|
return this._currentDc
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(dc: tl.RawDcOption, testMode: boolean): void {
|
|
|
|
this._currentDc = dc
|
|
|
|
this._state = TransportState.Ready
|
|
|
|
this.emit('ready')
|
|
|
|
this._log.debug('stubbing connection to %s:%d', dc.ipAddress, dc.port)
|
|
|
|
|
|
|
|
this.params.onConnect?.(dc, testMode)
|
|
|
|
}
|
|
|
|
|
|
|
|
close(): void {
|
|
|
|
this._currentDc = null
|
|
|
|
this._state = TransportState.Idle
|
|
|
|
this.emit('close')
|
|
|
|
this._log.debug('stub connection closed')
|
|
|
|
|
|
|
|
this.params.onClose?.()
|
|
|
|
}
|
|
|
|
|
|
|
|
async send(data: Uint8Array): Promise<void> {
|
|
|
|
this.params.onMessage?.(data)
|
|
|
|
}
|
|
|
|
}
|