refactor: normalizeToInput* now throws an error by itself, never returning null

This commit is contained in:
teidesu 2022-08-29 16:15:37 +03:00
parent 1cc3594f09
commit e7219ed2de
28 changed files with 45 additions and 126 deletions

View file

@ -13,13 +13,8 @@ export async function getBotMenuButton(
this: TelegramClient, this: TelegramClient,
user: InputPeerLike user: InputPeerLike
): Promise<tl.TypeBotMenuButton> { ): Promise<tl.TypeBotMenuButton> {
const userId = normalizeToInputUser(await this.resolvePeer(user))
if (!userId) {
throw new MtInvalidPeerTypeError(user, 'user')
}
return await this.call({ return await this.call({
_: 'bots.getBotMenuButton', _: 'bots.getBotMenuButton',
userId, userId: normalizeToInputUser(await this.resolvePeer(user), user),
}) })
} }

View file

@ -27,10 +27,7 @@ export async function getGameHighScores(
let user: tl.TypeInputUser let user: tl.TypeInputUser
if (userId) { if (userId) {
const res = normalizeToInputUser(await this.resolvePeer(userId)) user = normalizeToInputUser(await this.resolvePeer(userId), userId)
if (!res) throw new MtInvalidPeerTypeError(userId, 'user')
user = res
} else { } else {
user = { _: 'inputUserEmpty' } user = { _: 'inputUserEmpty' }
} }
@ -63,10 +60,7 @@ export async function getInlineGameHighScores(
let user: tl.TypeInputUser let user: tl.TypeInputUser
if (userId) { if (userId) {
const res = normalizeToInputUser(await this.resolvePeer(userId)) user = normalizeToInputUser(await this.resolvePeer(userId), userId)
if (!res) throw new MtInvalidPeerTypeError(userId, 'user')
user = res
} else { } else {
user = { _: 'inputUserEmpty' } user = { _: 'inputUserEmpty' }
} }

View file

@ -26,12 +26,11 @@ export async function _normalizeCommandScope(
} }
} }
case 'member': { case 'member': {
const chat = await this.resolvePeer(scope.chat)
const user = normalizeToInputUser( const user = normalizeToInputUser(
await this.resolvePeer(scope.user) await this.resolvePeer(scope.user),
scope.user
) )
const chat = await this.resolvePeer(scope.chat)
if (!user) throw new MtInvalidPeerTypeError(scope.user, 'user')
return { return {
_: 'botCommandScopePeerUser', _: 'botCommandScopePeerUser',

View file

@ -14,14 +14,9 @@ export async function setBotMenuButton(
user: InputPeerLike, user: InputPeerLike,
button: tl.TypeBotMenuButton button: tl.TypeBotMenuButton
): Promise<void> { ): Promise<void> {
const userId = normalizeToInputUser(await this.resolvePeer(user))
if (!userId) {
throw new MtInvalidPeerTypeError(user, 'user')
}
await this.call({ await this.call({
_: 'bots.setBotMenuButton', _: 'bots.setBotMenuButton',
userId, userId: normalizeToInputUser(await this.resolvePeer(user), user),
button, button,
}) })
} }

View file

@ -37,9 +37,8 @@ export async function setGameScore(
): Promise<Message> { ): Promise<Message> {
if (!params) params = {} if (!params) params = {}
const user = normalizeToInputUser(await this.resolvePeer(userId), userId)
const chat = await this.resolvePeer(chatId) const chat = await this.resolvePeer(chatId)
const user = normalizeToInputUser(await this.resolvePeer(userId))
if (!user) throw new MtInvalidPeerTypeError(userId, 'user')
const res = await this.call({ const res = await this.call({
_: 'messages.setGameScore', _: 'messages.setGameScore',
@ -85,8 +84,7 @@ export async function setInlineGameScore(
): Promise<void> { ): Promise<void> {
if (!params) params = {} if (!params) params = {}
const user = normalizeToInputUser(await this.resolvePeer(userId)) const user = normalizeToInputUser(await this.resolvePeer(userId), userId)
if (!user) throw new MtInvalidPeerTypeError(userId, 'user')
const [id, connection] = await this._normalizeInline(messageId) const [id, connection] = await this._normalizeInline(messageId)

View file

@ -32,7 +32,6 @@ export async function addChatMembers(
if (isInputPeerChat(chat)) { if (isInputPeerChat(chat)) {
for (const user of users) { for (const user of users) {
const p = normalizeToInputUser(await this.resolvePeer(user)) const p = normalizeToInputUser(await this.resolvePeer(user))
if (!p) continue
const updates = await this.call({ const updates = await this.call({
_: 'messages.addChatUser', _: 'messages.addChatUser',

View file

@ -44,13 +44,10 @@ export async function banChatMember(
}, },
}) })
} else if (isInputPeerChat(chat)) { } else if (isInputPeerChat(chat)) {
const normUser = normalizeToInputUser(user)
if (!normUser) throw new MtInvalidPeerTypeError(userId, 'user')
res = await this.call({ res = await this.call({
_: 'messages.deleteChatUser', _: 'messages.deleteChatUser',
chatId: chat.chatId, chatId: chat.chatId,
userId: normUser, userId: normalizeToInputUser(user),
}) })
} else throw new MtInvalidPeerTypeError(chatId, 'chat or channel') } else throw new MtInvalidPeerTypeError(chatId, 'chat or channel')

View file

@ -13,12 +13,9 @@ export async function deleteChannel(
this: TelegramClient, this: TelegramClient,
chatId: InputPeerLike chatId: InputPeerLike
): Promise<void> { ): Promise<void> {
const peer = normalizeToInputChannel(await this.resolvePeer(chatId))
if (!peer) throw new MtInvalidPeerTypeError(chatId, 'channel')
const res = await this.call({ const res = await this.call({
_: 'channels.deleteChannel', _: 'channels.deleteChannel',
channel: peer, channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
}) })
this._handleUpdate(res) this._handleUpdate(res)
} }

View file

@ -2,7 +2,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client' import { TelegramClient } from '../../client'
import { InputPeerLike } from '../../types' import { InputPeerLike } from '../../types'
import { normalizeToInputChannel } from '../../utils/peer-utils' import { isInputPeerChannel, normalizeToInputChannel } from "../../utils/peer-utils";
import { createDummyUpdate } from '../../utils/updates-utils' import { createDummyUpdate } from '../../utils/updates-utils'
/** /**
@ -36,13 +36,12 @@ export async function deleteHistory(
maxId, maxId,
}) })
const channel = normalizeToInputChannel(peer) if (isInputPeerChannel(peer)) {
if (channel) {
this._handleUpdate( this._handleUpdate(
createDummyUpdate( createDummyUpdate(
res.pts, res.pts,
res.ptsCount, res.ptsCount,
(channel as tl.RawInputChannel).channelId peer.channelId
) )
) )
} else { } else {

View file

@ -2,10 +2,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client' import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types' import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import { import { normalizeToInputChannel } from '../../utils/peer-utils'
normalizeToInputChannel,
normalizeToInputPeer,
} from '../../utils/peer-utils'
import { createDummyUpdate } from '../../utils/updates-utils' import { createDummyUpdate } from '../../utils/updates-utils'
/** /**
@ -20,10 +17,9 @@ export async function deleteUserHistory(
chatId: InputPeerLike, chatId: InputPeerLike,
participantId: InputPeerLike participantId: InputPeerLike
): Promise<void> { ): Promise<void> {
const channel = normalizeToInputChannel(await this.resolvePeer(chatId)) const channel = normalizeToInputChannel(await this.resolvePeer(chatId), chatId)
if (!channel) throw new MtInvalidPeerTypeError(chatId, 'channel')
const peer = normalizeToInputPeer(await this.resolvePeer(participantId)) const peer = await this.resolvePeer(participantId)
const res = await this.call({ const res = await this.call({
_: 'channels.deleteParticipantHistory', _: 'channels.deleteParticipantHistory',

View file

@ -23,11 +23,8 @@ export async function editAdminRights(
rights: Omit<tl.RawChatAdminRights, '_'>, rights: Omit<tl.RawChatAdminRights, '_'>,
rank = '' rank = ''
): Promise<void> { ): Promise<void> {
const chat = normalizeToInputChannel(await this.resolvePeer(chatId)) const chat = normalizeToInputChannel(await this.resolvePeer(chatId), chatId)
if (!chat) throw new MtInvalidPeerTypeError(chatId, 'channel') const user = normalizeToInputUser(await this.resolvePeer(userId), userId)
const user = normalizeToInputUser(await this.resolvePeer(userId))
if (!user) throw new MtInvalidPeerTypeError(userId, 'user')
const res = await this.call({ const res = await this.call({
_: 'channels.editAdmin', _: 'channels.editAdmin',

View file

@ -86,8 +86,7 @@ export async function* getChatEventLog(
): AsyncIterableIterator<ChatEvent> { ): AsyncIterableIterator<ChatEvent> {
if (!params) params = {} if (!params) params = {}
const channel = normalizeToInputChannel(await this.resolvePeer(chatId)) const channel = normalizeToInputChannel(await this.resolvePeer(chatId), chatId)
if (!channel) throw new MtInvalidPeerTypeError(chatId, 'channel')
let current = 0 let current = 0
let maxId = params.maxId ?? Long.ZERO let maxId = params.maxId ?? Long.ZERO

View file

@ -37,12 +37,9 @@ export async function joinChat(
} }
} }
const peer = normalizeToInputChannel(await this.resolvePeer(chatId))
if (!peer) throw new MtNotFoundError()
const res = await this.call({ const res = await this.call({
_: 'channels.joinChannel', _: 'channels.joinChannel',
channel: peer, channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
}) })
assertIsUpdatesGroup('channels.joinChannel', res) assertIsUpdatesGroup('channels.joinChannel', res)

View file

@ -16,12 +16,9 @@ export async function setChatUsername(
chatId: InputPeerLike, chatId: InputPeerLike,
username: string | null username: string | null
): Promise<void> { ): Promise<void> {
const chat = normalizeToInputChannel(await this.resolvePeer(chatId))
if (!chat) throw new MtInvalidPeerTypeError(chatId, 'channel')
await this.call({ await this.call({
_: 'channels.updateUsername', _: 'channels.updateUsername',
channel: chat, channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
username: username || '', username: username || '',
}) })
} }

View file

@ -17,12 +17,9 @@ export async function setSlowMode(
chatId: InputPeerLike, chatId: InputPeerLike,
seconds = 0 seconds = 0
): Promise<void> { ): Promise<void> {
const chat = normalizeToInputChannel(await this.resolvePeer(chatId))
if (!chat) throw new MtInvalidPeerTypeError(chatId, 'channel')
const res = await this.call({ const res = await this.call({
_: 'channels.toggleSlowMode', _: 'channels.toggleSlowMode',
channel: chat, channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
seconds, seconds,
}) })
this._handleUpdate(res) this._handleUpdate(res)

View file

@ -36,8 +36,7 @@ export async function addContact(
sharePhone?: boolean sharePhone?: boolean
} }
): Promise<User> { ): Promise<User> {
const peer = normalizeToInputUser(await this.resolvePeer(userId)) const peer = normalizeToInputUser(await this.resolvePeer(userId), userId)
if (!peer) throw new MtInvalidPeerTypeError(userId, 'user')
const res = await this.call({ const res = await this.call({
_: 'contacts.addContact', _: 'contacts.addContact',

View file

@ -53,9 +53,7 @@ export async function* getInviteLinks(
const chunkSize = Math.min(params.chunkSize ?? 100, total) const chunkSize = Math.min(params.chunkSize ?? 100, total)
const peer = await this.resolvePeer(chatId) const peer = await this.resolvePeer(chatId)
const admin = normalizeToInputUser(await this.resolvePeer(adminId)) const admin = normalizeToInputUser(await this.resolvePeer(adminId), adminId)
if (!admin) throw new MtInvalidPeerTypeError(adminId, 'user')
let offsetDate: number | undefined = undefined let offsetDate: number | undefined = undefined
let offsetLink: string | undefined = undefined let offsetLink: string | undefined = undefined

View file

@ -18,10 +18,7 @@ export async function hideAllJoinRequests(
action: 'approve' | 'deny', action: 'approve' | 'deny',
link?: string link?: string
): Promise<void> { ): Promise<void> {
const userId = normalizeToInputUser(await this.resolvePeer(user)) const userId = normalizeToInputUser(await this.resolvePeer(user), user)
if (!userId) {
throw new MtInvalidPeerTypeError(user, 'user')
}
await this.call({ await this.call({
_: 'messages.hideAllChatJoinRequests', _: 'messages.hideAllChatJoinRequests',

View file

@ -16,10 +16,7 @@ export async function hideJoinRequest(
user: InputPeerLike, user: InputPeerLike,
action: 'approve' | 'deny' action: 'approve' | 'deny'
): Promise<void> { ): Promise<void> {
const userId = normalizeToInputUser(await this.resolvePeer(user)) const userId = normalizeToInputUser(await this.resolvePeer(user), user)
if (!userId) {
throw new MtInvalidPeerTypeError(user, 'user')
}
await this.call({ await this.call({
_: 'messages.hideChatJoinRequest', _: 'messages.hideChatJoinRequest',

View file

@ -74,7 +74,7 @@ export async function getMessages(
? { ? {
_: 'channels.getMessages', _: 'channels.getMessages',
id: ids, id: ids,
channel: normalizeToInputChannel(peer)!, channel: normalizeToInputChannel(peer),
} }
: { : {
_: 'messages.getMessages', _: 'messages.getMessages',

View file

@ -41,7 +41,8 @@ export async function _parseEntities(
if (ent._ === 'messageEntityMentionName') { if (ent._ === 'messageEntityMentionName') {
try { try {
const inputPeer = normalizeToInputUser( const inputPeer = normalizeToInputUser(
await this.resolvePeer(ent.userId) await this.resolvePeer(ent.userId),
ent.userId
) )
// not a user // not a user

View file

@ -106,8 +106,7 @@ export async function createStickerSet(
) )
} }
const owner = normalizeToInputUser(await this.resolvePeer(params.owner)) const owner = normalizeToInputUser(await this.resolvePeer(params.owner), params.owner)
if (!owner) throw new MtInvalidPeerTypeError(params.owner, 'user')
const inputStickers: tl.TypeInputStickerSetItem[] = [] const inputStickers: tl.TypeInputStickerSetItem[] = []

View file

@ -1800,7 +1800,7 @@ async function _fetchChannelDifference(
try { try {
channel = normalizeToInputChannel( channel = normalizeToInputChannel(
await this.resolvePeer(toggleChannelIdMark(channelId)) await this.resolvePeer(toggleChannelIdMark(channelId))
)! )
} catch (e) { } catch (e) {
this._updsLog.warn( this._updsLog.warn(
'fetchChannelDifference failed for channel %d: input peer not found', 'fetchChannelDifference failed for channel %d: input peer not found',

View file

@ -14,12 +14,9 @@ export async function getCommonChats(
this: TelegramClient, this: TelegramClient,
userId: InputPeerLike userId: InputPeerLike
): Promise<Chat[]> { ): Promise<Chat[]> {
const peer = normalizeToInputUser(await this.resolvePeer(userId))
if (!peer) throw new MtInvalidPeerTypeError(userId, 'user')
return this.call({ return this.call({
_: 'messages.getCommonChats', _: 'messages.getCommonChats',
userId: peer, userId: normalizeToInputUser(await this.resolvePeer(userId), userId),
maxId: 0, maxId: 0,
limit: 100, limit: 100,
}).then((res) => res.chats.map((it) => new Chat(this, it))) }).then((res) => res.chats.map((it) => new Chat(this, it)))

View file

@ -33,12 +33,9 @@ export async function getProfilePhotos(
): Promise<Photo[]> { ): Promise<Photo[]> {
if (!params) params = {} if (!params) params = {}
const peer = normalizeToInputUser(await this.resolvePeer(userId))
if (!peer) throw new MtInvalidPeerTypeError(userId, 'user')
const res = await this.call({ const res = await this.call({
_: 'photos.getUserPhotos', _: 'photos.getUserPhotos',
userId: peer, userId: normalizeToInputUser(await this.resolvePeer(userId), userId),
offset: params.offset ?? 0, offset: params.offset ?? 0,
limit: params.limit ?? 100, limit: params.limit ?? 100,
maxId: Long.ZERO, maxId: Long.ZERO,

View file

@ -46,8 +46,7 @@ export async function* iterProfilePhotos(
): AsyncIterableIterator<Photo> { ): AsyncIterableIterator<Photo> {
if (!params) params = {} if (!params) params = {}
const peer = normalizeToInputUser(await this.resolvePeer(userId)) const peer = normalizeToInputUser(await this.resolvePeer(userId), userId)
if (!peer) throw new MtInvalidPeerTypeError(userId, 'user')
let offset = params.offset || 0 let offset = params.offset || 0
let current = 0 let current = 0

View file

@ -362,15 +362,10 @@ export namespace BotKeyboard {
text: string, text: string,
user: tl.TypeInputPeer user: tl.TypeInputPeer
): tl.RawInputKeyboardButtonUserProfile { ): tl.RawInputKeyboardButtonUserProfile {
const userId = normalizeToInputUser(user)
if (!userId) {
throw new MtInvalidPeerTypeError(user, 'user')
}
return { return {
_: 'inputKeyboardButtonUserProfile', _: 'inputKeyboardButtonUserProfile',
text, text,
userId, userId: normalizeToInputUser(user),
} }
} }

View file

@ -1,6 +1,7 @@
import Long from 'long' import Long from 'long'
import { tl } from '@mtcute/tl' import { tl } from '@mtcute/tl'
import { assertNever } from '@mtcute/core' import { assertNever } from '@mtcute/core'
import { InputPeerLike, MtInvalidPeerTypeError } from '../types'
export const INVITE_LINK_REGEX = export const INVITE_LINK_REGEX =
/^(?:https?:\/\/)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)\/(?:joinchat\/|\+))([\w-]+)$/i /^(?:https?:\/\/)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)\/(?:joinchat\/|\+))([\w-]+)$/i
@ -50,18 +51,9 @@ export function normalizeToInputPeer(
} }
export function normalizeToInputUser( export function normalizeToInputUser(
res: res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel,
| tl.TypeInputUser input?: InputPeerLike
| tl.RawInputPeerUser ): tl.TypeInputUser {
| tl.RawInputPeerUserFromMessage
| tl.RawInputPeerSelf
): tl.TypeInputUser
export function normalizeToInputUser(
res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel
): tl.TypeInputUser | null
export function normalizeToInputUser(
res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel
): tl.TypeInputUser | null {
if (tl.isAnyInputUser(res)) return res if (tl.isAnyInputUser(res)) return res
switch (res._) { switch (res._) {
@ -82,21 +74,13 @@ export function normalizeToInputUser(
} }
} }
return null throw new MtInvalidPeerTypeError(input ?? res, 'user')
} }
export function normalizeToInputChannel( export function normalizeToInputChannel(
res: res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel,
| tl.TypeInputChannel input?: InputPeerLike
| tl.RawInputPeerChannel ): tl.TypeInputChannel {
| tl.RawInputPeerChannelFromMessage
): tl.TypeInputChannel
export function normalizeToInputChannel(
res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel
): tl.TypeInputChannel | null
export function normalizeToInputChannel(
res: tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel
): tl.TypeInputChannel | null {
if (tl.isAnyInputChannel(res)) return res if (tl.isAnyInputChannel(res)) return res
switch (res._) { switch (res._) {
@ -115,7 +99,7 @@ export function normalizeToInputChannel(
} }
} }
return null throw new MtInvalidPeerTypeError(input ?? res, 'user')
} }
export function isInputPeerUser( export function isInputPeerUser(