chore: changed prettier width to 120

This commit is contained in:
alina 🌸 2023-09-24 01:32:22 +03:00
parent fbe264aab0
commit befbceaf8a
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI
312 changed files with 2429 additions and 7867 deletions

View file

@ -6,14 +6,14 @@
"insertPragma": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"printWidth": 80,
"printWidth": 120,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": false,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5",
"trailingComma": "all",
"useTabs": false,
"vueIndentScriptAndStyle": false
}

File diff suppressed because it is too large Load diff

View file

@ -3,10 +3,4 @@ export * from './client'
export * from './types'
export * from './utils/peer-utils'
export { createDummyUpdate } from './utils/updates-utils'
export {
assertNever,
JsonFileStorage,
LocalstorageStorage,
MemoryStorage,
tl,
} from '@mtcute/core'
export { assertNever, JsonFileStorage, LocalstorageStorage, MemoryStorage, tl } from '@mtcute/core'

View file

@ -5,13 +5,7 @@ import { Readable } from 'stream'
// @copy
import { MaybeArray, MaybeAsync } from '@mtcute/core'
// @copy
import {
AsyncLock,
ConditionVariable,
Deque,
Logger,
SortedLinkedList,
} from '@mtcute/core/utils'
import { AsyncLock, ConditionVariable, Deque, Logger, SortedLinkedList } from '@mtcute/core/utils'
// @copy
import { tdFileId } from '@mtcute/file-id'

View file

@ -8,10 +8,7 @@ import { TelegramClient } from '../../client'
* @param tosId TOS id
* @internal
*/
export async function acceptTos(
this: TelegramClient,
tosId: string,
): Promise<boolean> {
export async function acceptTos(this: TelegramClient, tosId: string): Promise<boolean> {
const res = await this.call({
_: 'help.acceptTermsOfService',
id: {
@ -21,11 +18,7 @@ export async function acceptTos(
})
if (!res) {
throw new MtTypeAssertionError(
'help.acceptTermsOfService',
'true',
'false',
)
throw new MtTypeAssertionError('help.acceptTermsOfService', 'true', 'false')
}
return true

View file

@ -11,10 +11,7 @@ import { User } from '../../types'
* @throws BadRequestError In case the password is invalid
* @internal
*/
export async function checkPassword(
this: TelegramClient,
password: string,
): Promise<User> {
export async function checkPassword(this: TelegramClient, password: string): Promise<User> {
const res = await this.call({
_: 'auth.checkPassword',
password: await computeSrpParams(
@ -26,16 +23,8 @@ export async function checkPassword(
),
})
assertTypeIs(
'checkPassword (@ auth.checkPassword)',
res,
'auth.authorization',
)
assertTypeIs(
'checkPassword (@ auth.checkPassword -> user)',
res.user,
'user',
)
assertTypeIs('checkPassword (@ auth.checkPassword)', res, 'auth.authorization')
assertTypeIs('checkPassword (@ auth.checkPassword -> user)', res.user, 'user')
this._userId = res.user.id
this.log.prefix = `[USER ${this._userId}] `

View file

@ -11,25 +11,14 @@ import { User } from '../../types'
* @throws BadRequestError In case the code is invalid
* @internal
*/
export async function recoverPassword(
this: TelegramClient,
recoveryCode: string,
): Promise<User> {
export async function recoverPassword(this: TelegramClient, recoveryCode: string): Promise<User> {
const res = await this.call({
_: 'auth.recoverPassword',
code: recoveryCode,
})
assertTypeIs(
'recoverPassword (@ auth.recoverPassword)',
res,
'auth.authorization',
)
assertTypeIs(
'recoverPassword (@ auth.recoverPassword -> user)',
res.user,
'user',
)
assertTypeIs('recoverPassword (@ auth.recoverPassword)', res, 'auth.authorization')
assertTypeIs('recoverPassword (@ auth.recoverPassword -> user)', res.user, 'user')
this._userId = res.user.id
this._isBot = false

View file

@ -14,11 +14,7 @@ import { normalizePhoneNumber } from '../../utils/misc-utils'
* @param phoneCodeHash Confirmation code identifier from {@link SentCode}
* @internal
*/
export async function resendCode(
this: TelegramClient,
phone: string,
phoneCodeHash: string,
): Promise<SentCode> {
export async function resendCode(this: TelegramClient, phone: string, phoneCodeHash: string): Promise<SentCode> {
phone = normalizePhoneNumber(phone)
const res = await this.call({

View file

@ -11,10 +11,7 @@ import { normalizePhoneNumber } from '../../utils/misc-utils'
* @returns An object containing information about the sent confirmation code
* @internal
*/
export async function sendCode(
this: TelegramClient,
phone: string,
): Promise<SentCode> {
export async function sendCode(this: TelegramClient, phone: string): Promise<SentCode> {
phone = normalizePhoneNumber(phone)
const res = await this.call({

View file

@ -11,10 +11,7 @@ import { User } from '../../types'
* @throws BadRequestError In case the bot token is invalid
* @internal
*/
export async function signInBot(
this: TelegramClient,
token: string,
): Promise<User> {
export async function signInBot(this: TelegramClient, token: string): Promise<User> {
const res = await this.call({
_: 'auth.importBotAuthorization',
flags: 0,
@ -23,16 +20,8 @@ export async function signInBot(
botAuthToken: token,
})
assertTypeIs(
'signInBot (@ auth.importBotAuthorization)',
res,
'auth.authorization',
)
assertTypeIs(
'signInBot (@ auth.importBotAuthorization -> user)',
res.user,
'user',
)
assertTypeIs('signInBot (@ auth.importBotAuthorization)', res, 'auth.authorization')
assertTypeIs('signInBot (@ auth.importBotAuthorization -> user)', res.user, 'user')
this._userId = res.user.id
this.log.prefix = `[USER ${this._userId}] `

View file

@ -72,9 +72,7 @@ export async function startTest(
if (phone) {
if (!phone.match(/^99966\d{5}/)) {
throw new MtArgumentError(
`${phone} is an invalid test phone number`,
)
throw new MtArgumentError(`${phone} is an invalid test phone number`)
}
const id = parseInt(phone[5])

View file

@ -3,17 +3,8 @@ import { MtArgumentError } from '@mtcute/core'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
MaybeAsync,
MaybeDynamic,
SentCode,
TermsOfService,
User,
} from '../../types'
import {
normalizePhoneNumber,
resolveMaybeDynamic,
} from '../../utils/misc-utils'
import { MaybeAsync, MaybeDynamic, SentCode, TermsOfService, User } from '../../types'
import { normalizePhoneNumber, resolveMaybeDynamic } from '../../utils/misc-utils'
/**
* Start the client in an interactive and declarative manner,
@ -148,13 +139,7 @@ export async function start(
// user is already authorized
this.log.prefix = `[USER ${me.id}] `
this.log.info(
'Logged in as %s (ID: %s, username: %s, bot: %s)',
me.displayName,
me.id,
me.username,
me.isBot,
)
this.log.info('Logged in as %s (ID: %s, username: %s, bot: %s)', me.displayName, me.id, me.username, me.isBot)
this.network.setIsPremium(me.isPremium)
@ -191,14 +176,10 @@ export async function start(
throw new MtArgumentError('You must pass `code` to use `phone`')
}
} else {
const botToken = params.botToken ?
await resolveMaybeDynamic(params.botToken) :
null
const botToken = params.botToken ? await resolveMaybeDynamic(params.botToken) : null
if (!botToken) {
throw new MtArgumentError(
'Either bot token or phone number must be provided',
)
throw new MtArgumentError('Either bot token or phone number must be provided')
}
return await this.signInBot(botToken)
@ -258,9 +239,7 @@ export async function start(
if (has2fa) {
if (!params.password) {
throw new MtArgumentError(
'2FA is enabled, but `password` was not provided.',
)
throw new MtArgumentError('2FA is enabled, but `password` was not provided.')
}
for (;;) {

View file

@ -97,11 +97,7 @@ export async function answerInlineQuery(
): Promise<void> {
if (!params) params = {}
const [gallery, tlResults] = await BotInline._convertToTl(
this,
results,
params.parseMode,
)
const [gallery, tlResults] = await BotInline._convertToTl(this, results, params.parseMode)
await this.call({
_: 'messages.setInlineBotResults',

View file

@ -9,11 +9,7 @@ import { TelegramClient } from '../../client'
* @param error If pre-checkout is rejected, error message to show to the user
* @internal
*/
export async function answerPreCheckoutQuery(
this: TelegramClient,
queryId: tl.Long,
error?: string,
): Promise<void> {
export async function answerPreCheckoutQuery(this: TelegramClient, queryId: tl.Long, error?: string): Promise<void> {
await this.call({
_: 'messages.setBotPrecheckoutResults',
queryId,

View file

@ -9,10 +9,7 @@ import { normalizeToInputUser } from '../../utils/peer-utils'
*
* @internal
*/
export async function getBotMenuButton(
this: TelegramClient,
user: InputPeerLike,
): Promise<tl.TypeBotMenuButton> {
export async function getBotMenuButton(this: TelegramClient, user: InputPeerLike): Promise<tl.TypeBotMenuButton> {
return await this.call({
_: 'bots.getBotMenuButton',
userId: normalizeToInputUser(await this.resolvePeer(user), user),

View file

@ -18,18 +18,12 @@ export async function _normalizeCommandScope(
const peer = await this.resolvePeer(scope.peer)
return {
_:
scope.type === 'peer' ?
'botCommandScopePeer' :
'botCommandScopePeerAdmins',
_: scope.type === 'peer' ? 'botCommandScopePeer' : 'botCommandScopePeerAdmins',
peer,
}
}
case 'member': {
const user = normalizeToInputUser(
await this.resolvePeer(scope.user),
scope.user,
)
const user = normalizeToInputUser(await this.resolvePeer(scope.user), scope.user)
const chat = await this.resolvePeer(scope.chat)
return {

View file

@ -15,10 +15,7 @@ export async function setMyDefaultRights(
rights: Omit<tl.RawChatAdminRights, '_'>,
): Promise<void> {
await this.call({
_:
target === 'group' ?
'bots.setBotGroupDefaultAdminRights' :
'bots.setBotBroadcastDefaultAdminRights',
_: target === 'group' ? 'bots.setBotGroupDefaultAdminRights' : 'bots.setBotBroadcastDefaultAdminRights',
adminRights: {
_: 'chatAdminRights',
...rights,

View file

@ -10,10 +10,7 @@ import { InputPeerLike } from '../../types'
* @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"`
* @internal
*/
export async function archiveChats(
this: TelegramClient,
chats: MaybeArray<InputPeerLike>,
): Promise<void> {
export async function archiveChats(this: TelegramClient, chats: MaybeArray<InputPeerLike>): Promise<void> {
if (!Array.isArray(chats)) chats = [chats]
const folderPeers: tl.TypeInputFolderPeer[] = []

View file

@ -51,10 +51,7 @@ export async function banChatMember(
try {
return this._findMessageInUpdate(res)
} catch (e) {
if (
e instanceof MtTypeAssertionError &&
e.context === '_findInUpdate (@ .updates[*])'
) {
if (e instanceof MtTypeAssertionError && e.context === '_findInUpdate (@ .updates[*])') {
// no service message
return null
}

View file

@ -10,11 +10,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @returns Newly created channel
* @internal
*/
export async function createChannel(
this: TelegramClient,
title: string,
description = '',
): Promise<Chat> {
export async function createChannel(this: TelegramClient, title: string, description = ''): Promise<Chat> {
const res = await this.call({
_: 'channels.createChannel',
title,

View file

@ -9,11 +9,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @param description Description of the supergroup
* @internal
*/
export async function createSupergroup(
this: TelegramClient,
title: string,
description = '',
): Promise<Chat> {
export async function createSupergroup(this: TelegramClient, title: string, description = ''): Promise<Chat> {
const res = await this.call({
_: 'channels.createChannel',
title,

View file

@ -9,16 +9,10 @@ import { normalizeToInputChannel } from '../../utils/peer-utils'
* @param chatId Chat ID or username
* @internal
*/
export async function deleteChannel(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function deleteChannel(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
const res = await this.call({
_: 'channels.deleteChannel',
channel: normalizeToInputChannel(
await this.resolvePeer(chatId),
chatId,
),
channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
})
this._handleUpdate(res)
}

View file

@ -1,10 +1,6 @@
import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Delete a chat photo
@ -14,10 +10,7 @@ import {
* @param chatId Chat ID or username
* @internal
*/
export async function deleteChatPhoto(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function deleteChatPhoto(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
const chat = await this.resolvePeer(chatId)
let res

View file

@ -8,10 +8,7 @@ import { isInputPeerChat } from '../../utils/peer-utils'
* @param chatId Chat ID
* @internal
*/
export async function deleteGroup(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function deleteGroup(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
const chat = await this.resolvePeer(chatId)
if (!isInputPeerChat(chat)) throw new MtInvalidPeerTypeError(chatId, 'chat')

View file

@ -35,9 +35,7 @@ export async function deleteHistory(
})
if (isInputPeerChannel(peer)) {
this._handleUpdate(
createDummyUpdate(res.pts, res.ptsCount, peer.channelId),
)
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, peer.channelId))
} else {
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount))
}

View file

@ -17,10 +17,7 @@ export async function deleteUserHistory(
chatId: InputPeerLike,
participantId: InputPeerLike,
): Promise<void> {
const channel = normalizeToInputChannel(
await this.resolvePeer(chatId),
chatId,
)
const channel = normalizeToInputChannel(await this.resolvePeer(chatId), chatId)
const peer = await this.resolvePeer(participantId)
@ -30,11 +27,5 @@ export async function deleteUserHistory(
participant: peer,
})
this._handleUpdate(
createDummyUpdate(
res.pts,
res.ptsCount,
(channel as tl.RawInputChannel).channelId,
),
)
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, (channel as tl.RawInputChannel).channelId))
}

View file

@ -2,10 +2,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import { InputPeerLike } from '../../types'
import {
normalizeToInputChannel,
normalizeToInputUser,
} from '../../utils/peer-utils'
import { normalizeToInputChannel, normalizeToInputUser } from '../../utils/peer-utils'
/**
* Edit supergroup/channel admin rights of a user.

View file

@ -4,16 +4,8 @@ import { assertNever, MaybeArray } from '@mtcute/core'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
ChatAction,
ChatEvent,
InputPeerLike,
PeersIndex,
} from '../../types'
import {
normalizeToInputChannel,
normalizeToInputUser,
} from '../../utils/peer-utils'
import { ChatAction, ChatEvent, InputPeerLike, PeersIndex } from '../../types'
import { normalizeToInputChannel, normalizeToInputUser } from '../../utils/peer-utils'
/**
* Get chat event log ("Recent actions" in official
@ -66,9 +58,7 @@ export async function* getChatEventLog(
* and when passing one or more action types,
* they will be filtered locally.
*/
filters?:
| tl.TypeChannelAdminLogEventsFilter
| MaybeArray<Exclude<ChatAction, null>['type']>
filters?: tl.TypeChannelAdminLogEventsFilter | MaybeArray<Exclude<ChatAction, null>['type']>
/**
* Limit the number of events returned.
@ -101,16 +91,11 @@ export async function* getChatEventLog(
await this.resolvePeerMany(params.users, normalizeToInputUser) :
undefined
let serverFilter:
| tl.Mutable<tl.TypeChannelAdminLogEventsFilter>
| undefined = undefined
let serverFilter: tl.Mutable<tl.TypeChannelAdminLogEventsFilter> | undefined = undefined
let localFilter: Record<string, true> | undefined = undefined
if (params.filters) {
if (
typeof params.filters === 'string' ||
Array.isArray(params.filters)
) {
if (typeof params.filters === 'string' || Array.isArray(params.filters)) {
let input = params.filters
if (!Array.isArray(input)) input = [input]
@ -224,10 +209,9 @@ export async function* getChatEventLog(
for (const evt of res.events) {
const parsed = new ChatEvent(this, evt, peers)
if (
localFilter &&
(!parsed.action || !localFilter[parsed.action.type])
) { continue }
if (localFilter && (!parsed.action || !localFilter[parsed.action.type])) {
continue
}
current += 1
yield parsed

View file

@ -2,18 +2,8 @@ import { assertTypeIs } from '@mtcute/core/utils'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
ChatMember,
InputPeerLike,
MtInvalidPeerTypeError,
PeersIndex,
} from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
isInputPeerUser,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { ChatMember, InputPeerLike, MtInvalidPeerTypeError, PeersIndex } from '../../types'
import { isInputPeerChannel, isInputPeerChat, isInputPeerUser, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Get information about a single chat member
@ -41,23 +31,16 @@ export async function getChatMember(
chatId: chat.chatId,
})
assertTypeIs(
'getChatMember (@ messages.getFullChat)',
res.fullChat,
'chatFull',
)
assertTypeIs('getChatMember (@ messages.getFullChat)', res.fullChat, 'chatFull')
const members =
res.fullChat.participants._ === 'chatParticipantsForbidden' ?
[] :
res.fullChat.participants.participants
res.fullChat.participants._ === 'chatParticipantsForbidden' ? [] : res.fullChat.participants.participants
const peers = PeersIndex.from(res)
for (const m of members) {
if (
(user._ === 'inputPeerSelf' &&
(peers.user(m.userId) as tl.RawUser).self) ||
(user._ === 'inputPeerSelf' && (peers.user(m.userId) as tl.RawUser).self) ||
(user._ === 'inputPeerUser' && m.userId === user.userId)
) {
return new ChatMember(this, m, peers)

View file

@ -5,18 +5,8 @@ import { assertTypeIs } from '@mtcute/core/utils'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
ArrayWithTotal,
ChatMember,
InputPeerLike,
MtInvalidPeerTypeError,
PeersIndex,
} from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { ArrayWithTotal, ChatMember, InputPeerLike, MtInvalidPeerTypeError, PeersIndex } from '../../types'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Get a chunk of members of some chat.
@ -63,15 +53,7 @@ export async function getChatMembers(
*
* Only used for channels and supergroups. Defaults to `recent`
*/
type?:
| 'all'
| 'banned'
| 'restricted'
| 'bots'
| 'recent'
| 'admins'
| 'contacts'
| 'mention'
type?: 'all' | 'banned' | 'restricted' | 'bots' | 'recent' | 'admins' | 'contacts' | 'mention'
},
): Promise<ArrayWithTotal<ChatMember>> {
if (!params) params = {}
@ -84,25 +66,17 @@ export async function getChatMembers(
chatId: chat.chatId,
})
assertTypeIs(
'getChatMember (@ messages.getFullChat)',
res.fullChat,
'chatFull',
)
assertTypeIs('getChatMember (@ messages.getFullChat)', res.fullChat, 'chatFull')
let members =
res.fullChat.participants._ === 'chatParticipantsForbidden' ?
[] :
res.fullChat.participants.participants
res.fullChat.participants._ === 'chatParticipantsForbidden' ? [] : res.fullChat.participants.participants
if (params.offset) members = members.slice(params.offset)
if (params.limit) members = members.slice(0, params.limit)
const peers = PeersIndex.from(res)
const ret = members.map(
(m) => new ChatMember(this, m, peers),
) as ArrayWithTotal<ChatMember>
const ret = members.map((m) => new ChatMember(this, m, peers)) as ArrayWithTotal<ChatMember>
ret.total = ret.length
@ -153,17 +127,11 @@ export async function getChatMembers(
hash: Long.ZERO,
})
assertTypeIs(
'getChatMembers (@ channels.getParticipants)',
res,
'channels.channelParticipants',
)
assertTypeIs('getChatMembers (@ channels.getParticipants)', res, 'channels.channelParticipants')
const peers = PeersIndex.from(res)
const ret = res.participants.map(
(i) => new ChatMember(this, i, peers),
) as ArrayWithTotal<ChatMember>
const ret = res.participants.map((i) => new ChatMember(this, i, peers)) as ArrayWithTotal<ChatMember>
ret.total = res.count
return ret

View file

@ -14,10 +14,7 @@ import { INVITE_LINK_REGEX } from '../../utils/peer-utils'
* Use {@link getChat} or {@link getFullChat} instead.
* @internal
*/
export async function getChatPreview(
this: TelegramClient,
inviteLink: string,
): Promise<ChatPreview> {
export async function getChatPreview(this: TelegramClient, inviteLink: string): Promise<ChatPreview> {
const m = inviteLink.match(INVITE_LINK_REGEX)
if (!m) throw new MtArgumentError('Invalid invite link')

View file

@ -21,10 +21,7 @@ import {
* Use {@link getChatPreview} instead.
* @internal
*/
export async function getChat(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<Chat> {
export async function getChat(this: TelegramClient, chatId: InputPeerLike): Promise<Chat> {
if (typeof chatId === 'string') {
const m = chatId.match(INVITE_LINK_REGEX)
@ -35,9 +32,7 @@ export async function getChat(
})
if (res._ === 'chatInvite') {
throw new MtArgumentError(
`You haven't joined ${JSON.stringify(res.title)}`,
)
throw new MtArgumentError(`You haven't joined ${JSON.stringify(res.title)}`)
}
return new Chat(this, res.chat)

View file

@ -21,10 +21,7 @@ import {
* Use {@link getChatPreview} instead.
* @internal
*/
export async function getFullChat(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<Chat> {
export async function getFullChat(this: TelegramClient, chatId: InputPeerLike): Promise<Chat> {
if (typeof chatId === 'string') {
const m = chatId.match(INVITE_LINK_REGEX)
@ -35,9 +32,7 @@ export async function getFullChat(
})
if (res._ === 'chatInvite') {
throw new MtArgumentError(
`You haven't joined ${JSON.stringify(res.title)}`,
)
throw new MtArgumentError(`You haven't joined ${JSON.stringify(res.title)}`)
}
// we still need to fetch full chat info

View file

@ -13,11 +13,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @param longitude Longitude of the location
* @internal
*/
export async function getNearbyChats(
this: TelegramClient,
latitude: number,
longitude: number,
): Promise<Chat[]> {
export async function getNearbyChats(this: TelegramClient, latitude: number, longitude: number): Promise<Chat[]> {
const res = await this.call({
_: 'contacts.getLocated',
geoPoint: {
@ -32,11 +28,7 @@ export async function getNearbyChats(
if (!res.updates.length) return []
assertTypeIs(
'contacts.getLocated (@ .updates[0])',
res.updates[0],
'updatePeerLocated',
)
assertTypeIs('contacts.getLocated (@ .updates[0])', res.updates[0], 'updatePeerLocated')
const chats = res.chats.map((it) => new Chat(this, it))

View file

@ -1,9 +1,6 @@
import { TelegramClient } from '../../client'
import { Chat, InputPeerLike } from '../../types'
import {
INVITE_LINK_REGEX,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { INVITE_LINK_REGEX, normalizeToInputChannel } from '../../utils/peer-utils'
import { assertIsUpdatesGroup } from '../../utils/updates-utils'
/**
@ -18,10 +15,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* or ID of the linked supergroup or channel.
* @internal
*/
export async function joinChat(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<Chat> {
export async function joinChat(this: TelegramClient, chatId: InputPeerLike): Promise<Chat> {
if (typeof chatId === 'string') {
const m = chatId.match(INVITE_LINK_REGEX)
@ -40,10 +34,7 @@ export async function joinChat(
const res = await this.call({
_: 'channels.joinChannel',
channel: normalizeToInputChannel(
await this.resolvePeer(chatId),
chatId,
),
channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
})
assertIsUpdatesGroup('channels.joinChannel', res)

View file

@ -1,10 +1,6 @@
import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Leave a group chat, supergroup or channel
@ -13,11 +9,7 @@ import {
* @param clear Whether to clear history after leaving (only for legacy group chats)
* @internal
*/
export async function leaveChat(
this: TelegramClient,
chatId: InputPeerLike,
clear = false,
): Promise<void> {
export async function leaveChat(this: TelegramClient, chatId: InputPeerLike, clear = false): Promise<void> {
const chat = await this.resolvePeer(chatId)
if (isInputPeerChannel(chat)) {

View file

@ -7,10 +7,7 @@ import { InputPeerLike } from '../../types'
* @param chatId Chat ID
* @internal
*/
export async function markChatUnread(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function markChatUnread(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
await this.call({
_: 'messages.markDialogUnread',
peer: {

View file

@ -3,10 +3,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import { normalizeDate } from '../../utils/misc-utils'
import {
isInputPeerChannel,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Restrict a user in a supergroup.
@ -34,7 +31,9 @@ export async function restrictChatMember(
): Promise<void> {
const chat = await this.resolvePeer(chatId)
if (!isInputPeerChannel(chat)) { throw new MtInvalidPeerTypeError(chatId, 'channel') }
if (!isInputPeerChannel(chat)) {
throw new MtInvalidPeerTypeError(chatId, 'channel')
}
const user = await this.resolvePeer(userId)

View file

@ -3,17 +3,8 @@ import { fileIdToInputPhoto, tdFileId } from '@mtcute/file-id'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
InputFileLike,
InputPeerLike,
isUploadedFile,
MtInvalidPeerTypeError,
} from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { InputFileLike, InputPeerLike, isUploadedFile, MtInvalidPeerTypeError } from '../../types'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Set a new chat photo or video.

View file

@ -1,10 +1,6 @@
import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Change chat title
@ -15,11 +11,7 @@ import {
* @param title New chat title, 1-255 characters
* @internal
*/
export async function setChatTitle(
this: TelegramClient,
chatId: InputPeerLike,
title: string,
): Promise<void> {
export async function setChatTitle(this: TelegramClient, chatId: InputPeerLike, title: string): Promise<void> {
const chat = await this.resolvePeer(chatId)
let res

View file

@ -18,10 +18,7 @@ export async function setChatUsername(
): Promise<void> {
await this.call({
_: 'channels.updateUsername',
channel: normalizeToInputChannel(
await this.resolvePeer(chatId),
chatId,
),
channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
username: username || '',
})
}

View file

@ -12,17 +12,10 @@ import { normalizeToInputChannel } from '../../utils/peer-utils'
* Valid values are: `0 (off), 10, 30, 60 (1m), 300 (5m), 900 (15m) or 3600 (1h)`
* @internal
*/
export async function setSlowMode(
this: TelegramClient,
chatId: InputPeerLike,
seconds = 0,
): Promise<void> {
export async function setSlowMode(this: TelegramClient, chatId: InputPeerLike, seconds = 0): Promise<void> {
const res = await this.call({
_: 'channels.toggleSlowMode',
channel: normalizeToInputChannel(
await this.resolvePeer(chatId),
chatId,
),
channel: normalizeToInputChannel(await this.resolvePeer(chatId), chatId),
seconds,
})
this._handleUpdate(res)

View file

@ -10,10 +10,7 @@ import { InputPeerLike } from '../../types'
* @param chats Chat ID(s), username(s), phone number(s), `"me"` or `"self"`
* @internal
*/
export async function unarchiveChats(
this: TelegramClient,
chats: MaybeArray<InputPeerLike>,
): Promise<void> {
export async function unarchiveChats(this: TelegramClient, chats: MaybeArray<InputPeerLike>): Promise<void> {
if (!Array.isArray(chats)) chats = [chats]
const folderPeers: tl.TypeInputFolderPeer[] = []

View file

@ -1,10 +1,6 @@
import { TelegramClient } from '../../client'
import { InputPeerLike, MtInvalidPeerTypeError } from '../../types'
import {
isInputPeerChannel,
isInputPeerChat,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, isInputPeerChat, normalizeToInputChannel } from '../../utils/peer-utils'
// @alias=unrestrictChatMember
/**

View file

@ -14,10 +14,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @param userId User ID, username or phone number
* @internal
*/
export async function deleteContacts(
this: TelegramClient,
userId: InputPeerLike
): Promise<User | null>
export async function deleteContacts(this: TelegramClient, userId: InputPeerLike): Promise<User | null>
/**
* Delete one or more contacts from your Telegram contacts list
@ -28,10 +25,7 @@ export async function deleteContacts(
* @param userIds User IDs, usernames or phone numbers
* @internal
*/
export async function deleteContacts(
this: TelegramClient,
userIds: InputPeerLike[]
): Promise<User[]>
export async function deleteContacts(this: TelegramClient, userIds: InputPeerLike[]): Promise<User[]>
/** @internal */
export async function deleteContacts(
@ -41,16 +35,10 @@ export async function deleteContacts(
const single = !Array.isArray(userIds)
if (single) userIds = [userIds as InputPeerLike]
const inputPeers = await this.resolvePeerMany(
userIds as InputPeerLike[],
normalizeToInputUser,
)
const inputPeers = await this.resolvePeerMany(userIds as InputPeerLike[], normalizeToInputUser)
if (single && !inputPeers.length) {
throw new MtInvalidPeerTypeError(
(userIds as InputPeerLike[])[0],
'user',
)
throw new MtInvalidPeerTypeError((userIds as InputPeerLike[])[0], 'user')
}
const res = await this.call({

View file

@ -17,11 +17,7 @@ function _initializeConversation(this: TelegramClient) {
}
/** @internal */
export function _pushConversationMessage(
this: TelegramClient,
msg: Message,
incoming = false,
): void {
export function _pushConversationMessage(this: TelegramClient, msg: Message, incoming = false): void {
// shortcut
if (!this._hasConversations) return

View file

@ -8,10 +8,7 @@ import { TelegramClient } from '../../client'
* @param id Folder ID or folder itself
* @internal
*/
export async function deleteFolder(
this: TelegramClient,
id: number | tl.RawDialogFilter,
): Promise<void> {
export async function deleteFolder(this: TelegramClient, id: number | tl.RawDialogFilter): Promise<void> {
await this.call({
_: 'messages.updateDialogFilter',
id: typeof id === 'number' ? id : id.id,

View file

@ -25,11 +25,7 @@ export async function editFolder(
}
if (typeof folder === 'number' || typeof folder === 'string') {
const old = await this.getFolders()
const found = old.find(
(it) =>
it._ === 'dialogFilter' &&
(it.id === folder || it.title === folder),
)
const found = old.find((it) => it._ === 'dialogFilter' && (it.id === folder || it.title === folder))
if (!found) {
throw new MtArgumentError(`Could not find a folder ${folder}`)

View file

@ -122,10 +122,7 @@ export async function* getDialogs(
// fetch folder if needed
let filters: tl.TypeDialogFilter | undefined
if (
typeof params.folder === 'string' ||
typeof params.folder === 'number'
) {
if (typeof params.folder === 'string' || typeof params.folder === 'number') {
const folders = await this.getFolders()
const found = folders.find((it) => {
if (it._ === 'dialogFilterDefault') {
@ -157,38 +154,28 @@ export async function* getDialogs(
}
}
const fetchPinnedDialogsFromFolder =
async (): Promise<tl.messages.RawPeerDialogs | null> => {
if (
!filters ||
filters._ === 'dialogFilterDefault' ||
!filters.pinnedPeers.length
) {
return null
}
const res = await this.call({
_: 'messages.getPeerDialogs',
peers: filters.pinnedPeers.map((peer) => ({
_: 'inputDialogPeer',
peer,
})),
})
res.dialogs.forEach(
(dialog: tl.Mutable<tl.TypeDialog>) => (dialog.pinned = true),
)
return res
const fetchPinnedDialogsFromFolder = async (): Promise<tl.messages.RawPeerDialogs | null> => {
if (!filters || filters._ === 'dialogFilterDefault' || !filters.pinnedPeers.length) {
return null
}
const res = await this.call({
_: 'messages.getPeerDialogs',
peers: filters.pinnedPeers.map((peer) => ({
_: 'inputDialogPeer',
peer,
})),
})
res.dialogs.forEach((dialog: tl.Mutable<tl.TypeDialog>) => (dialog.pinned = true))
return res
}
const pinned = params.pinned ?? 'include'
let archived = params.archived ?? 'exclude'
if (filters) {
archived =
filters._ !== 'dialogFilterDefault' && filters.excludeArchived ?
'exclude' :
'keep'
archived = filters._ !== 'dialogFilterDefault' && filters.excludeArchived ? 'exclude' : 'keep'
}
if (pinned === 'only') {
@ -215,12 +202,7 @@ export async function* getDialogs(
let offsetDate = normalizeDate(params.offsetDate) ?? 0
let offsetPeer = params.offsetPeer ?? { _: 'inputPeerEmpty' }
if (
filters &&
filters._ !== 'dialogFilterDefault' &&
filters.pinnedPeers.length &&
pinned === 'include'
) {
if (filters && filters._ !== 'dialogFilterDefault' && filters.pinnedPeers.length && pinned === 'include') {
const res = await fetchPinnedDialogsFromFolder()
if (res) {
@ -238,9 +220,7 @@ export async function* getDialogs(
// if pinned is `exclude`, we want to exclude them
// if pinned is `include`, we already yielded them, so we also want to exclude them
// if pinned is `keep`, we want to keep them
const filterFolder = filters ?
Dialog.filterFolder(filters, pinned !== 'keep') :
undefined
const filterFolder = filters ? Dialog.filterFolder(filters, pinned !== 'keep') : undefined
let folderId

View file

@ -6,9 +6,7 @@ import { TelegramClient } from '../../client'
* Get list of folders.
* @internal
*/
export async function getFolders(
this: TelegramClient,
): Promise<tl.TypeDialogFilter[]> {
export async function getFolders(this: TelegramClient): Promise<tl.TypeDialogFilter[]> {
return this.call({
_: 'messages.getDialogFilters',
})

View file

@ -9,20 +9,14 @@ import { Dialog, InputPeerLike } from '../../types'
* @param peers Peers for which to fetch dialogs.
* @internal
*/
export async function getPeerDialogs(
this: TelegramClient,
peers: InputPeerLike
): Promise<Dialog>
export async function getPeerDialogs(this: TelegramClient, peers: InputPeerLike): Promise<Dialog>
/**
* Get dialogs with certain peers.
*
* @param peers Peers for which to fetch dialogs.
* @internal
*/
export async function getPeerDialogs(
this: TelegramClient,
peers: InputPeerLike[]
): Promise<Dialog[]>
export async function getPeerDialogs(this: TelegramClient, peers: InputPeerLike[]): Promise<Dialog[]>
/**
* @internal
@ -36,12 +30,11 @@ export async function getPeerDialogs(
const res = await this.call({
_: 'messages.getPeerDialogs',
peers: await this.resolvePeerMany(peers as InputPeerLike[]).then(
(peers) =>
peers.map((it) => ({
_: 'inputDialogPeer',
peer: it,
})),
peers: await this.resolvePeerMany(peers as InputPeerLike[]).then((peers) =>
peers.map((it) => ({
_: 'inputDialogPeer',
peer: it,
})),
),
})

View file

@ -7,10 +7,7 @@ import { TelegramClient } from '../../client'
*
* @internal
*/
export async function setFoldersOrder(
this: TelegramClient,
order: number[],
): Promise<void> {
export async function setFoldersOrder(this: TelegramClient, order: number[]): Promise<void> {
await this.call({
_: 'messages.updateDialogFiltersOrder',
order,

View file

@ -10,14 +10,8 @@ import { FileDownloadParameters, FileLocation } from '../../types'
* @param params File download parameters
* @internal
*/
export async function downloadAsBuffer(
this: TelegramClient,
params: FileDownloadParameters,
): Promise<Buffer> {
if (
params.location instanceof FileLocation &&
Buffer.isBuffer(params.location.location)
) {
export async function downloadAsBuffer(this: TelegramClient, params: FileDownloadParameters): Promise<Buffer> {
if (params.location instanceof FileLocation && Buffer.isBuffer(params.location.location)) {
return params.location.location
}

View file

@ -16,21 +16,12 @@ try {
* @param params File download parameters
* @internal
*/
export function downloadToFile(
this: TelegramClient,
filename: string,
params: FileDownloadParameters,
): Promise<void> {
export function downloadToFile(this: TelegramClient, filename: string, params: FileDownloadParameters): Promise<void> {
if (!fs) {
throw new MtUnsupportedError(
'Downloading to file is only supported in NodeJS',
)
throw new MtUnsupportedError('Downloading to file is only supported in NodeJS')
}
if (
params.location instanceof FileLocation &&
Buffer.isBuffer(params.location.location)
) {
if (params.location instanceof FileLocation && Buffer.isBuffer(params.location.location)) {
// early return for inline files
const buf = params.location.location
@ -46,10 +37,6 @@ export function downloadToFile(
const stream = this.downloadAsStream(params)
return new Promise((resolve, reject) => {
stream
.on('error', reject)
.pipe(output)
.on('finish', resolve)
.on('error', reject)
stream.on('error', reject).pipe(output).on('finish', resolve).on('error', reject)
})
}

View file

@ -1,14 +1,6 @@
import {
ConnectionKind,
MtArgumentError,
MtUnsupportedError,
} from '@mtcute/core'
import { ConnectionKind, MtArgumentError, MtUnsupportedError } from '@mtcute/core'
import { ConditionVariable } from '@mtcute/core/utils'
import {
fileIdToInputFileLocation,
fileIdToInputWebFileLocation,
parseFileId,
} from '@mtcute/file-id'
import { fileIdToInputFileLocation, fileIdToInputWebFileLocation, parseFileId } from '@mtcute/file-id'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
@ -36,9 +28,7 @@ export async function* downloadAsIterable(
const offset = params.offset ?? 0
if (offset % 4096 !== 0) {
throw new MtArgumentError(
`Invalid offset: ${offset}. Must be divisible by 4096`,
)
throw new MtArgumentError(`Invalid offset: ${offset}. Must be divisible by 4096`)
}
let dcId = params.dcId
@ -76,13 +66,10 @@ export async function* downloadAsIterable(
// we will receive a FileMigrateError in case this is invalid
if (!dcId) dcId = this._defaultDcs.main.id
const partSizeKb =
params.partSize ?? (fileSize ? determinePartSize(fileSize) : 64)
const partSizeKb = params.partSize ?? (fileSize ? determinePartSize(fileSize) : 64)
if (partSizeKb % 4 !== 0) {
throw new MtArgumentError(
`Invalid part size: ${partSizeKb}. Must be divisible by 4.`,
)
throw new MtArgumentError(`Invalid part size: ${partSizeKb}. Must be divisible by 4.`)
}
const chunkSize = partSizeKb * 1024
@ -90,10 +77,7 @@ export async function* downloadAsIterable(
let limitBytes = params.limit ?? fileSize ?? Infinity
if (limitBytes === 0) return
let numChunks =
limitBytes === Infinity ?
Infinity :
~~((limitBytes + chunkSize - offset - 1) / chunkSize)
let numChunks = limitBytes === Infinity ? Infinity : ~~((limitBytes + chunkSize - offset - 1) / chunkSize)
let nextChunkIdx = 0
let nextWorkerChunkIdx = 0
@ -104,8 +88,7 @@ export async function* downloadAsIterable(
let connectionKind: ConnectionKind
if (isSmall) {
connectionKind =
dcId === this.network.getPrimaryDcId() ? 'main' : 'downloadSmall'
connectionKind = dcId === this.network.getPrimaryDcId() ? 'main' : 'downloadSmall'
} else {
connectionKind = 'download'
}
@ -119,12 +102,8 @@ export async function* downloadAsIterable(
poolSize,
)
const downloadChunk = async (
chunk = nextWorkerChunkIdx++,
): Promise<void> => {
let result:
| tl.RpcCallReturn['upload.getFile']
| tl.RpcCallReturn['upload.getWebFile']
const downloadChunk = async (chunk = nextWorkerChunkIdx++): Promise<void> => {
let result: tl.RpcCallReturn['upload.getFile'] | tl.RpcCallReturn['upload.getWebFile']
try {
result = await this.call(
@ -155,16 +134,10 @@ export async function* downloadAsIterable(
// we shouldnt receive them since cdnSupported is not set in the getFile request.
// also, i couldnt find any media that would be downloaded from cdn, so even if
// i implemented that, i wouldnt be able to test that, so :shrug:
throw new MtUnsupportedError(
'Received CDN redirect, which is not supported (yet)',
)
throw new MtUnsupportedError('Received CDN redirect, which is not supported (yet)')
}
if (
result._ === 'upload.webFile' &&
result.size &&
limitBytes === Infinity
) {
if (result._ === 'upload.webFile' && result.size && limitBytes === Infinity) {
limitBytes = result.size
numChunks = ~~((limitBytes + chunkSize - offset - 1) / chunkSize)
}
@ -175,21 +148,13 @@ export async function* downloadAsIterable(
nextChunkCv.notify()
}
if (
nextWorkerChunkIdx < numChunks &&
result.bytes.length === chunkSize
) {
if (nextWorkerChunkIdx < numChunks && result.bytes.length === chunkSize) {
return downloadChunk()
}
}
let error: unknown = undefined
void Promise.all(
Array.from(
{ length: Math.min(poolSize * REQUESTS_PER_CONNECTION, numChunks) },
downloadChunk,
),
)
void Promise.all(Array.from({ length: Math.min(poolSize * REQUESTS_PER_CONNECTION, numChunks) }, downloadChunk))
.catch((e) => {
this.log.debug('download workers errored: %s', e.message)
error = e

View file

@ -11,14 +11,8 @@ import { bufferToStream } from '../../utils/stream-utils'
* @param params File download parameters
* @internal
*/
export function downloadAsStream(
this: TelegramClient,
params: FileDownloadParameters,
): Readable {
if (
params.location instanceof FileLocation &&
Buffer.isBuffer(params.location.location)
) {
export function downloadAsStream(this: TelegramClient, params: FileDownloadParameters): Readable {
if (params.location instanceof FileLocation && Buffer.isBuffer(params.location.location)) {
return bufferToStream(params.location.location)
}

View file

@ -22,9 +22,7 @@ export async function _normalizeInputFile(
},
): Promise<tl.TypeInputFile> {
if (typeof input === 'object' && tl.isAnyInputMedia(input)) {
throw new MtArgumentError(
"InputFile can't be created from an InputMedia",
)
throw new MtArgumentError("InputFile can't be created from an InputMedia")
} else if (tdFileId.isFileIdLike(input)) {
if (typeof input === 'string' && input.match(/^file:/)) {
const uploaded = await this.uploadFile({
@ -34,9 +32,7 @@ export async function _normalizeInputFile(
return uploaded.inputFile
}
throw new MtArgumentError(
"InputFile can't be created from an URL or a File ID",
)
throw new MtArgumentError("InputFile can't be created from an URL or a File ID")
} else if (isUploadedFile(input)) {
return input.inputFile
} else if (typeof input === 'object' && tl.isAnyInputFile(input)) {

View file

@ -1,12 +1,7 @@
import Long from 'long'
import { assertTypeIs } from '@mtcute/core/utils'
import {
fileIdToInputDocument,
fileIdToInputPhoto,
parseFileId,
tdFileId,
} from '@mtcute/file-id'
import { fileIdToInputDocument, fileIdToInputPhoto, parseFileId, tdFileId } from '@mtcute/file-id'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
@ -205,9 +200,7 @@ export async function _normalizeInputMedia(
let sendMime
if (media.type === 'sticker') {
sendMime = media.isAnimated ?
'application/x-tgsticker' :
'image/webp'
sendMime = media.isAnimated ? 'application/x-tgsticker' : 'image/webp'
} else {
sendMime = media.fileMime
}
@ -225,10 +218,7 @@ export async function _normalizeInputMedia(
const uploadPeer = params.uploadPeer ?? { _: 'inputPeerSelf' }
const uploadMediaIfNeeded = async (
inputMedia: tl.TypeInputMedia,
photo: boolean,
): Promise<tl.TypeInputMedia> => {
const uploadMediaIfNeeded = async (inputMedia: tl.TypeInputMedia, photo: boolean): Promise<tl.TypeInputMedia> => {
if (!uploadMedia) return inputMedia
const res = await this.call({
@ -238,16 +228,8 @@ export async function _normalizeInputMedia(
})
if (photo) {
assertTypeIs(
'normalizeInputMedia (@ messages.uploadMedia)',
res,
'messageMediaPhoto',
)
assertTypeIs(
'normalizeInputMedia (@ messages.uploadMedia)',
res.photo!,
'photo',
)
assertTypeIs('normalizeInputMedia (@ messages.uploadMedia)', res, 'messageMediaPhoto')
assertTypeIs('normalizeInputMedia (@ messages.uploadMedia)', res.photo!, 'photo')
return {
_: 'inputMediaPhoto',
@ -260,16 +242,8 @@ export async function _normalizeInputMedia(
ttlSeconds: media.ttlSeconds,
}
}
assertTypeIs(
'normalizeInputMedia (@ messages.uploadMedia)',
res,
'messageMediaDocument',
)
assertTypeIs(
'normalizeInputMedia (@ messages.uploadMedia)',
res.document!,
'document',
)
assertTypeIs('normalizeInputMedia (@ messages.uploadMedia)', res, 'messageMediaDocument')
assertTypeIs('normalizeInputMedia (@ messages.uploadMedia)', res.document!, 'document')
return {
_: 'inputMediaDocument',
@ -289,10 +263,7 @@ export async function _normalizeInputMedia(
if (typeof input === 'string' && input.match(/^https?:\/\//)) {
return uploadMediaIfNeeded(
{
_:
media.type === 'photo' ?
'inputMediaPhotoExternal' :
'inputMediaDocumentExternal',
_: media.type === 'photo' ? 'inputMediaPhotoExternal' : 'inputMediaDocumentExternal',
url: input,
},
media.type === 'photo',
@ -300,8 +271,7 @@ export async function _normalizeInputMedia(
} else if (typeof input === 'string' && input.match(/^file:/)) {
await upload(input.substring(5))
} else {
const parsed =
typeof input === 'string' ? parseFileId(input) : input
const parsed = typeof input === 'string' ? parseFileId(input) : input
if (parsed.location._ === 'photo') {
return {
@ -359,11 +329,7 @@ export async function _normalizeInputMedia(
if (media.type !== 'voice') {
attributes.push({
_: 'documentAttributeFilename',
fileName:
media.fileName ||
(typeof media.file === 'string' ?
extractFileName(media.file) :
'unnamed'),
fileName: media.fileName || (typeof media.file === 'string' ? extractFileName(media.file) : 'unnamed'),
})
}
@ -389,10 +355,7 @@ export async function _normalizeInputMedia(
duration: media.duration || 0,
title: media.type === 'audio' ? media.title : undefined,
performer: media.type === 'audio' ? media.performer : undefined,
waveform:
media.type === 'voice' && media.waveform ?
encodeWaveform(media.waveform) :
undefined,
waveform: media.type === 'voice' && media.waveform ? encodeWaveform(media.waveform) : undefined,
})
}

View file

@ -9,11 +9,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import { UploadedFile, UploadFileLike } from '../../types'
import { determinePartSize, isProbablyPlainText } from '../../utils/file-utils'
import {
bufferToStream,
convertWebStreamToNodeReadable,
readBytesFromStream,
} from '../../utils/stream-utils'
import { bufferToStream, convertWebStreamToNodeReadable, readBytesFromStream } from '../../utils/stream-utils'
let fs: typeof import('fs') | null = null
let path: typeof import('path') | null = null
@ -124,9 +120,7 @@ export async function uploadFile(
if (typeof file === 'string') {
if (!fs) {
throw new MtArgumentError(
'Local paths are only supported for NodeJS!',
)
throw new MtArgumentError('Local paths are only supported for NodeJS!')
}
file = fs.createReadStream(file)
}
@ -142,19 +136,11 @@ export async function uploadFile(
// fs.ReadStream is a subclass of Readable, no conversion needed
}
if (
typeof ReadableStream !== 'undefined' &&
file instanceof ReadableStream
) {
if (typeof ReadableStream !== 'undefined' && file instanceof ReadableStream) {
file = convertWebStreamToNodeReadable(file)
}
if (
typeof file === 'object' &&
'headers' in file &&
'body' in file &&
'url' in file
) {
if (typeof file === 'object' && 'headers' in file && 'body' in file && 'url' in file) {
// fetch() response
const length = parseInt(file.headers.get('content-length') || '0')
if (!isNaN(length) && length) fileSize = length
@ -186,10 +172,7 @@ export async function uploadFile(
throw new MtArgumentError('Fetch response contains `null` body')
}
if (
typeof ReadableStream !== 'undefined' &&
file.body instanceof ReadableStream
) {
if (typeof ReadableStream !== 'undefined' && file.body instanceof ReadableStream) {
file = convertWebStreamToNodeReadable(file.body)
} else {
file = file.body
@ -206,9 +189,7 @@ export async function uploadFile(
if (!partSizeKb) {
if (fileSize === -1) {
partSizeKb = params.estimatedSize ?
determinePartSize(params.estimatedSize) :
64
partSizeKb = params.estimatedSize ? determinePartSize(params.estimatedSize) : 64
} else {
partSizeKb = determinePartSize(fileSize)
}
@ -223,27 +204,18 @@ export async function uploadFile(
}
const partSize = partSizeKb * 1024
let partCount =
fileSize === -1 ? -1 : ~~((fileSize + partSize - 1) / partSize)
const maxPartCount = this.network.params.isPremium ?
MAX_PART_COUNT_PREMIUM :
MAX_PART_COUNT
let partCount = fileSize === -1 ? -1 : ~~((fileSize + partSize - 1) / partSize)
const maxPartCount = this.network.params.isPremium ? MAX_PART_COUNT_PREMIUM : MAX_PART_COUNT
if (partCount > maxPartCount) {
throw new MtArgumentError(
`File is too large (max ${maxPartCount} parts, got ${partCount})`,
)
throw new MtArgumentError(`File is too large (max ${maxPartCount} parts, got ${partCount})`)
}
const isBig = fileSize === -1 || fileSize > BIG_FILE_MIN_SIZE
const isSmall = fileSize !== -1 && fileSize < SMALL_FILE_MAX_SIZE
const connectionKind = isSmall ? 'main' : 'upload'
const connectionPoolSize = Math.min(
this.network.getPoolSize(connectionKind),
partCount,
)
const requestsPerConnection =
params.requestsPerConnection ?? REQUESTS_PER_CONNECTION
const connectionPoolSize = Math.min(this.network.getPoolSize(connectionKind), partCount)
const requestsPerConnection = params.requestsPerConnection ?? REQUESTS_PER_CONNECTION
this.log.debug(
'uploading %d bytes file in %d chunks, each %d bytes in %s connection pool of size %d',
@ -278,26 +250,18 @@ export async function uploadFile(
if (fileSize === -1 && stream.readableEnded) {
fileSize = pos + (part?.length ?? 0)
partCount = ~~((fileSize + partSize - 1) / partSize)
this.log.debug(
'readable ended, file size = %d, part count = %d',
fileSize,
partCount,
)
this.log.debug('readable ended, file size = %d, part count = %d', fileSize, partCount)
}
if (!part) {
throw new MtArgumentError(
`Unexpected EOS (there were only ${idx} parts, but expected ${partCount})`,
)
throw new MtArgumentError(`Unexpected EOS (there were only ${idx} parts, but expected ${partCount})`)
}
if (!Buffer.isBuffer(part)) {
throw new MtArgumentError(`Part ${thisIdx} was not a Buffer!`)
}
if (part.length > partSize) {
throw new MtArgumentError(
`Part ${thisIdx} had invalid size (expected ${partSize}, got ${part.length})`,
)
throw new MtArgumentError(`Part ${thisIdx} had invalid size (expected ${partSize}, got ${part.length})`)
}
if (thisIdx === 0 && fileMime === undefined) {
@ -310,9 +274,7 @@ export async function uploadFile(
// if all 8 bytes are printable ASCII characters,
// the entire file is probably plain text
const isPlainText = isProbablyPlainText(part.slice(0, 8))
fileMime = isPlainText ?
'text/plain' :
'application/octet-stream'
fileMime = isPlainText ? 'text/plain' : 'application/octet-stream'
}
}

View file

@ -1,18 +1,8 @@
import {
assertNever,
MtArgumentError,
MtTypeAssertionError,
} from '@mtcute/core'
import { assertNever, MtArgumentError, MtTypeAssertionError } from '@mtcute/core'
import { assertTypeIs } from '@mtcute/core/utils'
import { TelegramClient } from '../../client'
import {
InputMediaLike,
InputPeerLike,
MessageMedia,
Photo,
RawDocument,
} from '../../types'
import { InputMediaLike, InputPeerLike, MessageMedia, Photo, RawDocument } from '../../types'
import { parseDocument } from '../../types/media/document-utils'
/**
@ -72,11 +62,7 @@ export async function uploadMedia(
})
if (res._ === 'messageMediaEmpty') {
throw new MtTypeAssertionError(
'uploadMedia',
'not messageMediaEmpty',
'messageMediaEmpty',
)
throw new MtTypeAssertionError('uploadMedia', 'not messageMediaEmpty', 'messageMediaEmpty')
}
switch (normMedia._) {

View file

@ -11,10 +11,7 @@ import { ChatInviteLink, InputPeerLike } from '../../types'
* @param chatId Chat IDs
* @internal
*/
export async function exportInviteLink(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<ChatInviteLink> {
export async function exportInviteLink(this: TelegramClient, chatId: InputPeerLike): Promise<ChatInviteLink> {
const res = await this.call({
_: 'messages.exportChatInvite',
peer: await this.resolvePeer(chatId),

View file

@ -50,17 +50,16 @@ export async function* getInviteLinkMembers(
for (;;) {
// for some reason ts needs annotation, idk
const res: tl.RpcCallReturn['messages.getChatInviteImporters'] =
await this.call({
_: 'messages.getChatInviteImporters',
limit: Math.min(100, limit - current),
peer,
link: params.link,
requested: params.requested,
q: params.requestedSearch,
offsetDate,
offsetUser,
})
const res: tl.RpcCallReturn['messages.getChatInviteImporters'] = await this.call({
_: 'messages.getChatInviteImporters',
limit: Math.min(100, limit - current),
peer,
link: params.link,
requested: params.requested,
q: params.requestedSearch,
offsetDate,
offsetUser,
})
if (!res.importers.length) break

View file

@ -54,15 +54,14 @@ export async function* getInviteLinks(
let offsetLink: string | undefined = undefined
for (;;) {
const res: tl.RpcCallReturn['messages.getExportedChatInvites'] =
await this.call({
_: 'messages.getExportedChatInvites',
peer,
adminId: admin,
limit: Math.min(chunkSize, total - current),
offsetDate,
offsetLink,
})
const res: tl.RpcCallReturn['messages.getExportedChatInvites'] = await this.call({
_: 'messages.getExportedChatInvites',
peer,
adminId: admin,
limit: Math.min(chunkSize, total - current),
offsetDate,
offsetLink,
})
if (!res.invites.length) break
@ -71,11 +70,7 @@ export async function* getInviteLinks(
const last = res.invites[res.invites.length - 1]
if (last._ === 'chatInvitePublicJoinRequests') {
throw new MtTypeAssertionError(
'getInviteLinks',
'chatInviteExported',
last._,
)
throw new MtTypeAssertionError('getInviteLinks', 'chatInviteExported', last._)
}
offsetDate = last.date
offsetLink = last.link

View file

@ -9,10 +9,7 @@ import { ChatInviteLink, InputPeerLike, PeersIndex } from '../../types'
* @param chatId Chat ID
* @internal
*/
export async function getPrimaryInviteLink(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<ChatInviteLink> {
export async function getPrimaryInviteLink(this: TelegramClient, chatId: InputPeerLike): Promise<ChatInviteLink> {
const res = await this.call({
_: 'messages.getExportedChatInvites',
peer: await this.resolvePeer(chatId),
@ -30,11 +27,7 @@ export async function getPrimaryInviteLink(
}
if (!res.invites[0].permanent) {
throw new MtTypeAssertionError(
'messages.getExportedChatInvites (@ .invites[0].permanent)',
'true',
'false',
)
throw new MtTypeAssertionError('messages.getExportedChatInvites (@ .invites[0].permanent)', 'true', 'false')
}
const peers = PeersIndex.from(res)

View file

@ -26,10 +26,7 @@ export async function revokeInviteLink(
const peers = PeersIndex.from(res)
const invite =
res._ === 'messages.exportedChatInviteReplaced' ?
res.newInvite :
res.invite
const invite = res._ === 'messages.exportedChatInviteReplaced' ? res.newInvite : res.invite
return new ChatInviteLink(this, invite, peers)
}

View file

@ -17,11 +17,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @param message Message ID where this poll was found
* @internal
*/
export async function closePoll(
this: TelegramClient,
chatId: InputPeerLike,
message: number,
): Promise<Poll> {
export async function closePoll(this: TelegramClient, chatId: InputPeerLike, message: number): Promise<Poll> {
const res = await this.call({
_: 'messages.editMessage',
peer: await this.resolvePeer(chatId),
@ -43,18 +39,10 @@ export async function closePoll(
this._handleUpdate(res, true)
const upd = res.updates[0]
assertTypeIs(
'messages.editMessage (@ .updates[0])',
upd,
'updateMessagePoll',
)
assertTypeIs('messages.editMessage (@ .updates[0])', upd, 'updateMessagePoll')
if (!upd.poll) {
throw new MtTypeAssertionError(
'messages.editMessage (@ .updates[0].poll)',
'poll',
'undefined',
)
throw new MtTypeAssertionError('messages.editMessage (@ .updates[0].poll)', 'poll', 'undefined')
}
const peers = PeersIndex.from(res)

View file

@ -2,10 +2,7 @@ import { MaybeArray } from '@mtcute/core'
import { TelegramClient } from '../../client'
import { InputPeerLike } from '../../types'
import {
isInputPeerChannel,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, normalizeToInputChannel } from '../../utils/peer-utils'
import { createDummyUpdate } from '../../utils/updates-utils'
/**

View file

@ -1,12 +1,7 @@
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
BotKeyboard,
FormattedString,
InputMediaLike,
ReplyMarkup,
} from '../../types'
import { BotKeyboard, FormattedString, InputMediaLike, ReplyMarkup } from '../../types'
import { normalizeInlineId } from '../../utils/inline-utils'
/**
@ -91,11 +86,7 @@ export async function editInlineMessage(
)
}
} else if (params.text) {
[content, entities] = await this._parseEntities(
params.text,
params.parseMode,
params.entities,
)
[content, entities] = await this._parseEntities(params.text, params.parseMode, params.entities)
}
let retries = 3

View file

@ -1,14 +1,7 @@
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
BotKeyboard,
FormattedString,
InputMediaLike,
InputPeerLike,
Message,
ReplyMarkup,
} from '../../types'
import { BotKeyboard, FormattedString, InputMediaLike, InputPeerLike, Message, ReplyMarkup } from '../../types'
/**
* Edit message text, media, reply markup and schedule date.
@ -96,11 +89,7 @@ export async function editMessage(
)
}
} else if (params.text) {
[content, entities] = await this._parseEntities(
params.text,
params.parseMode,
params.entities,
)
[content, entities] = await this._parseEntities(params.text, params.parseMode, params.entities)
}
const res = await this.call({

View file

@ -6,20 +6,14 @@ import { Message, PeersIndex } from '../../types'
import { assertIsUpdatesGroup } from '../../utils/updates-utils'
/** @internal */
export function _findMessageInUpdate(
this: TelegramClient,
res: tl.TypeUpdates,
isEdit = false,
): Message {
export function _findMessageInUpdate(this: TelegramClient, res: tl.TypeUpdates, isEdit = false): Message {
assertIsUpdatesGroup('_findMessageInUpdate', res)
this._handleUpdate(res, true)
for (const u of res.updates) {
if (
(isEdit &&
(u._ === 'updateEditMessage' ||
u._ === 'updateEditChannelMessage')) ||
(isEdit && (u._ === 'updateEditMessage' || u._ === 'updateEditChannelMessage')) ||
(!isEdit &&
(u._ === 'updateNewMessage' ||
u._ === 'updateNewChannelMessage' ||
@ -27,12 +21,7 @@ export function _findMessageInUpdate(
) {
const peers = PeersIndex.from(res)
return new Message(
this,
u.message,
peers,
u._ === 'updateNewScheduledMessage',
)
return new Message(this, u.message, peers, u._ === 'updateNewScheduledMessage')
}
}

View file

@ -3,13 +3,7 @@ import { randomLong } from '@mtcute/core/utils'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
FormattedString,
InputMediaLike,
InputPeerLike,
Message,
PeersIndex,
} from '../../types'
import { FormattedString, InputMediaLike, InputPeerLike, Message, PeersIndex } from '../../types'
import { normalizeDate } from '../../utils/misc-utils'
import { assertIsUpdatesGroup } from '../../utils/updates-utils'
@ -104,7 +98,7 @@ export async function forwardMessages(
* have content protection.
*/
forbidForwards?: boolean
}
},
): Promise<Message>
/**
@ -201,7 +195,7 @@ export async function forwardMessages(
* have content protection.
*/
forbidForwards?: boolean
}
},
): Promise<MaybeArray<Message>>
/** @internal */
@ -303,9 +297,7 @@ export async function forwardMessages(
// error, instead only first 100 IDs will be forwarded,
// which is definitely not the best outcome.
if (messages.length > 100) {
throw new MtArgumentError(
'You can forward no more than 100 messages at once',
)
throw new MtArgumentError('You can forward no more than 100 messages at once')
}
const toPeer = await this.resolvePeer(toChatId)
@ -314,9 +306,7 @@ export async function forwardMessages(
if (params.caption) {
if (params.captionMedia) {
throw new MtArgumentError(
'You can either pass `caption` or `captionMedia`',
)
throw new MtArgumentError('You can either pass `caption` or `captionMedia`')
}
captionMessage = await this.sendText(toPeer, params.caption, {
@ -350,9 +340,7 @@ export async function forwardMessages(
dropAuthor: params.noAuthor,
dropMediaCaptions: params.noCaption,
noforwards: params.forbidForwards,
sendAs: params.sendAs ?
await this.resolvePeer(params.sendAs) :
undefined,
sendAs: params.sendAs ? await this.resolvePeer(params.sendAs) : undefined,
})
assertIsUpdatesGroup('messages.forwardMessages', res)
@ -367,14 +355,7 @@ export async function forwardMessages(
case 'updateNewMessage':
case 'updateNewChannelMessage':
case 'updateNewScheduledMessage':
forwarded.push(
new Message(
this,
upd.message,
peers,
upd._ === 'updateNewScheduledMessage',
),
)
forwarded.push(new Message(this, upd.message, peers, upd._ === 'updateNewScheduledMessage'))
break
}
})

View file

@ -23,9 +23,7 @@ export async function _getDiscussionMessage(
}
const msg = res.messages[0]
const chat = res.chats.find(
(it) => it.id === (msg.peerId as tl.RawPeerChannel).channelId,
)! as tl.RawChannel
const chat = res.chats.find((it) => it.id === (msg.peerId as tl.RawPeerChannel).channelId)! as tl.RawChannel
return [
{

View file

@ -84,13 +84,10 @@ export async function* getHistory(
const minId = params.minId || 0
const maxId = params.maxId || 0
let offsetId =
params.offsetId ?? (params.reverse && !params.offsetDate ? 1 : 0)
let offsetId = params.offsetId ?? (params.reverse && !params.offsetDate ? 1 : 0)
const offsetDate = normalizeDate(params.offsetDate) || 0
const baseOffset = -(params.reverse ? limit : 0)
let addOffset =
(params.offset ? params.offset * (params.reverse ? -1 : 1) : 0) +
baseOffset
let addOffset = (params.offset ? params.offset * (params.reverse ? -1 : 1) : 0) + baseOffset
// resolve peer once and pass an InputPeer afterwards
const peer = await this.resolvePeer(chatId)
@ -109,18 +106,12 @@ export async function* getHistory(
})
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'messages.getHistory',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('messages.getHistory', '!messages.messagesNotModified', res._)
}
const peers = PeersIndex.from(res)
const msgs = res.messages
.filter((msg) => msg._ !== 'messageEmpty')
.map((msg) => new Message(this, msg, peers))
const msgs = res.messages.filter((msg) => msg._ !== 'messageEmpty').map((msg) => new Message(this, msg, peers))
if (!msgs.length) break

View file

@ -37,7 +37,5 @@ export async function getMessageGroup(
if (!groupedId) throw new MtArgumentError('This message is not grouped')
return messages.filter(
(it) => it && it.groupedId?.eq(groupedId),
) as Message[]
return messages.filter((it) => it && it.groupedId?.eq(groupedId)) as Message[]
}

View file

@ -20,7 +20,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
export async function getMessageReactions(
this: TelegramClient,
chatId: InputPeerLike,
messages: number
messages: number,
): Promise<MessageReactions | null>
/**
@ -38,7 +38,7 @@ export async function getMessageReactions(
export async function getMessageReactions(
this: TelegramClient,
chatId: InputPeerLike,
messages: number[]
messages: number[],
): Promise<(MessageReactions | null)[]>
/**
@ -74,11 +74,7 @@ export async function getMessageReactions(
const peers = PeersIndex.from(res)
for (const update of res.updates) {
assertTypeIs(
'messages.getMessagesReactions',
update,
'updateMessageReactions',
)
assertTypeIs('messages.getMessagesReactions', update, 'updateMessageReactions')
index[update.msgId] = new MessageReactions(
this,

View file

@ -20,7 +20,7 @@ import { Message, PeersIndex } from '../../types'
export async function getMessagesUnsafe(
this: TelegramClient,
messageId: number,
fromReply?: boolean
fromReply?: boolean,
): Promise<Message | null>
/**
* Get messages from PM or legacy group by their IDs.
@ -41,7 +41,7 @@ export async function getMessagesUnsafe(
export async function getMessagesUnsafe(
this: TelegramClient,
messageIds: number[],
fromReply?: boolean
fromReply?: boolean,
): Promise<(Message | null)[]>
/** @internal */
@ -65,11 +65,7 @@ export async function getMessagesUnsafe(
})
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'getMessages',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('getMessages', '!messages.messagesNotModified', res._)
}
const peers = PeersIndex.from(res)

View file

@ -3,10 +3,7 @@ import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import { InputPeerLike, Message, PeersIndex } from '../../types'
import {
isInputPeerChannel,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, normalizeToInputChannel } from '../../utils/peer-utils'
/**
* Get a single message in chat by its ID
@ -22,7 +19,7 @@ export async function getMessages(
this: TelegramClient,
chatId: InputPeerLike,
messageId: number,
fromReply?: boolean
fromReply?: boolean,
): Promise<Message | null>
/**
* Get messages in chat by their IDs
@ -41,7 +38,7 @@ export async function getMessages(
this: TelegramClient,
chatId: InputPeerLike,
messageIds: number[],
fromReply?: boolean
fromReply?: boolean,
): Promise<(Message | null)[]>
/** @internal */
@ -78,11 +75,7 @@ export async function getMessages(
)
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'getMessages',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('getMessages', '!messages.messagesNotModified', res._)
}
const peers = PeersIndex.from(res)
@ -95,33 +88,18 @@ export async function getMessages(
// (channels have their own message numbering)
switch (peer._) {
case 'inputPeerSelf':
if (
!(
msg.peerId._ === 'peerUser' &&
msg.peerId.userId === this._userId
)
) {
if (!(msg.peerId._ === 'peerUser' && msg.peerId.userId === this._userId)) {
return null
}
break
case 'inputPeerUser':
case 'inputPeerUserFromMessage':
if (
!(
msg.peerId._ === 'peerUser' &&
msg.peerId.userId === peer.userId
)
) {
if (!(msg.peerId._ === 'peerUser' && msg.peerId.userId === peer.userId)) {
return null
}
break
case 'inputPeerChat':
if (
!(
msg.peerId._ === 'peerChat' &&
msg.peerId.chatId === peer.chatId
)
) {
if (!(msg.peerId._ === 'peerChat' && msg.peerId.chatId === peer.chatId)) {
return null
}
break

View file

@ -69,15 +69,14 @@ export async function* getReactionUsers(
}
for (;;) {
const res: tl.RpcCallReturn['messages.getMessageReactionsList'] =
await this.call({
_: 'messages.getMessageReactionsList',
peer,
id: messageId,
reaction,
limit: Math.min(chunkSize, total - current),
offset,
})
const res: tl.RpcCallReturn['messages.getMessageReactionsList'] = await this.call({
_: 'messages.getMessageReactionsList',
peer,
id: messageId,
reaction,
limit: Math.min(chunkSize, total - current),
offset,
})
if (!res.reactions.length) break

View file

@ -13,7 +13,7 @@ import { InputPeerLike, Message, PeersIndex } from '../../types'
export async function getScheduledMessages(
this: TelegramClient,
chatId: InputPeerLike,
messageId: number
messageId: number,
): Promise<Message | null>
/**
* Get scheduled messages in chat by their IDs
@ -28,7 +28,7 @@ export async function getScheduledMessages(
export async function getScheduledMessages(
this: TelegramClient,
chatId: InputPeerLike,
messageIds: number[]
messageIds: number[],
): Promise<(Message | null)[]>
/** @internal */
@ -49,11 +49,7 @@ export async function getScheduledMessages(
})
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'getMessages',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('getMessages', '!messages.messagesNotModified', res._)
}
const peers = PeersIndex.from(res)

View file

@ -44,14 +44,10 @@ export async function _parseEntities(
for (const ent of entities) {
if (ent._ === 'messageEntityMentionName') {
try {
const inputPeer = normalizeToInputUser(
await this.resolvePeer(ent.userId),
ent.userId,
)
const inputPeer = normalizeToInputUser(await this.resolvePeer(ent.userId), ent.userId)
// not a user
if (!inputPeer) continue
(ent as any)._ = 'inputMessageEntityMentionName'
;(ent as any).userId = inputPeer
} catch (e) {}

View file

@ -1,9 +1,6 @@
import { TelegramClient } from '../../client'
import { InputPeerLike } from '../../types'
import {
isInputPeerChannel,
normalizeToInputChannel,
} from '../../utils/peer-utils'
import { isInputPeerChannel, normalizeToInputChannel } from '../../utils/peer-utils'
import { createDummyUpdate } from '../../utils/updates-utils'
/**
@ -29,9 +26,7 @@ export async function readHistory(
})
if (isInputPeerChannel(peer)) {
this._handleUpdate(
createDummyUpdate(res.pts, res.ptsCount, peer.channelId),
)
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, peer.channelId))
} else {
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount))
}

View file

@ -8,10 +8,7 @@ import { createDummyUpdate } from '../../utils/updates-utils'
* @param chatId Chat ID
* @internal
*/
export async function readReactions(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function readReactions(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
const res = await this.call({
_: 'messages.readReactions',
peer: await this.resolvePeer(chatId),

View file

@ -71,24 +71,17 @@ export async function* searchGlobal(
})
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'messages.searchGlobal',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('messages.searchGlobal', '!messages.messagesNotModified', res._)
}
const peers = PeersIndex.from(res)
const msgs = res.messages
.filter((msg) => msg._ !== 'messageEmpty')
.map((msg) => new Message(this, msg, peers))
const msgs = res.messages.filter((msg) => msg._ !== 'messageEmpty').map((msg) => new Message(this, msg, peers))
if (!msgs.length) break
const last = msgs[msgs.length - 1]
offsetRate =
(res as tl.messages.RawMessagesSlice).nextRate ?? last.raw.date
offsetRate = (res as tl.messages.RawMessagesSlice).nextRate ?? last.raw.date
offsetPeer = last.chat.inputPeer
offsetId = last.id

View file

@ -123,9 +123,7 @@ export async function* searchMessages(
const limit = Math.min(params.chunkSize || 100, total)
const peer = await this.resolvePeer(chatId)
const fromUser =
(params.fromUser ? await this.resolvePeer(params.fromUser) : null) ||
undefined
const fromUser = (params.fromUser ? await this.resolvePeer(params.fromUser) : null) || undefined
for (;;) {
const res = await this.call({
@ -145,11 +143,7 @@ export async function* searchMessages(
})
if (res._ === 'messages.messagesNotModified') {
throw new MtTypeAssertionError(
'messages.search',
'!messages.messagesNotModified',
res._,
)
throw new MtTypeAssertionError('messages.search', '!messages.messagesNotModified', res._)
}
// for successive chunks, we need to reset the offset
@ -157,9 +151,7 @@ export async function* searchMessages(
const peers = PeersIndex.from(res)
const msgs = res.messages
.filter((msg) => msg._ !== 'messageEmpty')
.map((msg) => new Message(this, msg, peers))
const msgs = res.messages.filter((msg) => msg._ !== 'messageEmpty').map((msg) => new Message(this, msg, peers))
if (!msgs.length) break

View file

@ -2,13 +2,7 @@ import { getMarkedPeerId } from '@mtcute/core'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
FormattedString,
InputPeerLike,
Message,
MtMessageNotFoundError,
ReplyMarkup,
} from '../../types'
import { FormattedString, InputPeerLike, Message, MtMessageNotFoundError, ReplyMarkup } from '../../types'
/**
* Copy a message (i.e. send the same message,
@ -107,11 +101,7 @@ export async function sendCopy(
const msg = await this.getMessages(fromPeer, message)
if (!msg) {
throw new MtMessageNotFoundError(
getMarkedPeerId(fromPeer),
message,
'to copy',
)
throw new MtMessageNotFoundError(getMarkedPeerId(fromPeer), message, 'to copy')
}
return msg.sendCopy(toChatId, params)

View file

@ -3,13 +3,7 @@ import { randomLong } from '@mtcute/core/utils'
import { tl } from '@mtcute/tl'
import { TelegramClient } from '../../client'
import {
InputMediaLike,
InputPeerLike,
Message,
MtMessageNotFoundError,
PeersIndex,
} from '../../types'
import { InputMediaLike, InputPeerLike, Message, MtMessageNotFoundError, PeersIndex } from '../../types'
import { normalizeDate, normalizeMessageId } from '../../utils/misc-utils'
import { assertIsUpdatesGroup } from '../../utils/updates-utils'
@ -86,11 +80,7 @@ export async function sendMediaGroup(
* @param uploaded Number of bytes already uploaded
* @param total Total file size
*/
progressCallback?: (
index: number,
uploaded: number,
total: number
) => void
progressCallback?: (index: number, uploaded: number, total: number) => void
/**
* Whether to clear draft after sending this message.
@ -120,27 +110,18 @@ export async function sendMediaGroup(
let replyTo = normalizeMessageId(params.replyTo)
if (params.commentTo) {
[peer, replyTo] = await this._getDiscussionMessage(
peer,
normalizeMessageId(params.commentTo)!,
)
[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!)
}
if (params.mustReply) {
if (!replyTo) {
throw new MtArgumentError(
'mustReply used, but replyTo was not passed',
)
throw new MtArgumentError('mustReply used, but replyTo was not passed')
}
const msg = await this.getMessages(peer, replyTo)
if (!msg) {
throw new MtMessageNotFoundError(
getMarkedPeerId(peer),
replyTo,
'to reply to',
)
throw new MtMessageNotFoundError(getMarkedPeerId(peer), replyTo, 'to reply to')
}
}
@ -200,9 +181,7 @@ export async function sendMediaGroup(
scheduleDate: normalizeDate(params.schedule),
clearDraft: params.clearDraft,
noforwards: params.forbidForwards,
sendAs: params.sendAs ?
await this.resolvePeer(params.sendAs) :
undefined,
sendAs: params.sendAs ? await this.resolvePeer(params.sendAs) : undefined,
})
assertIsUpdatesGroup('_findMessageInUpdate', res)
@ -212,25 +191,10 @@ export async function sendMediaGroup(
const msgs = res.updates
.filter(
(
u,
): u is
| tl.RawUpdateNewMessage
| tl.RawUpdateNewChannelMessage
| tl.RawUpdateNewScheduledMessage =>
u._ === 'updateNewMessage' ||
u._ === 'updateNewChannelMessage' ||
u._ === 'updateNewScheduledMessage',
)
.map(
(u) =>
new Message(
this,
u.message,
peers,
u._ === 'updateNewScheduledMessage',
),
(u): u is tl.RawUpdateNewMessage | tl.RawUpdateNewChannelMessage | tl.RawUpdateNewScheduledMessage =>
u._ === 'updateNewMessage' || u._ === 'updateNewChannelMessage' || u._ === 'updateNewScheduledMessage',
)
.map((u) => new Message(this, u.message, peers, u._ === 'updateNewScheduledMessage'))
this._pushConversationMessage(msgs[msgs.length - 1])

View file

@ -146,11 +146,9 @@ export async function sendMedia(
// some types dont have `caption` field, and ts warns us,
// but since it's JS, they'll just be `undefined` and properly
// handled by _parseEntities method
params.caption ||
(media as Extract<typeof media, { caption?: unknown }>).caption,
params.caption || (media as Extract<typeof media, { caption?: unknown }>).caption,
params.parseMode,
params.entities ||
(media as Extract<typeof media, { entities?: unknown }>).entities,
params.entities || (media as Extract<typeof media, { entities?: unknown }>).entities,
)
let peer = await this.resolvePeer(chatId)
@ -159,27 +157,18 @@ export async function sendMedia(
let replyTo = normalizeMessageId(params.replyTo)
if (params.commentTo) {
[peer, replyTo] = await this._getDiscussionMessage(
peer,
normalizeMessageId(params.commentTo)!,
)
[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!)
}
if (params.mustReply) {
if (!replyTo) {
throw new MtArgumentError(
'mustReply used, but replyTo was not passed',
)
throw new MtArgumentError('mustReply used, but replyTo was not passed')
}
const msg = await this.getMessages(peer, replyTo)
if (!msg) {
throw new MtMessageNotFoundError(
getMarkedPeerId(peer),
replyTo,
'to reply to',
)
throw new MtMessageNotFoundError(getMarkedPeerId(peer), replyTo, 'to reply to')
}
}
@ -201,9 +190,7 @@ export async function sendMedia(
entities,
clearDraft: params.clearDraft,
noforwards: params.forbidForwards,
sendAs: params.sendAs ?
await this.resolvePeer(params.sendAs) :
undefined,
sendAs: params.sendAs ? await this.resolvePeer(params.sendAs) : undefined,
})
const msg = this._findMessageInUpdate(res)

View file

@ -60,16 +60,12 @@ export async function sendReaction(
this._handleUpdate(res, true)
const upd = res.updates.find(
(it) => it._ === 'updateEditChannelMessage',
) as tl.RawUpdateEditChannelMessage | undefined
const upd = res.updates.find((it) => it._ === 'updateEditChannelMessage') as
| tl.RawUpdateEditChannelMessage
| undefined
if (!upd) {
throw new MtTypeAssertionError(
'messages.sendReaction (@ .updates[*])',
'updateEditChannelMessage',
'undefined',
)
throw new MtTypeAssertionError('messages.sendReaction (@ .updates[*])', 'updateEditChannelMessage', 'undefined')
}
const peers = PeersIndex.from(res)

View file

@ -15,11 +15,7 @@ import { assertIsUpdatesGroup } from '../../utils/updates-utils'
* @param id ID of the message
* @internal
*/
export async function sendScheduled(
this: TelegramClient,
peer: InputPeerLike,
id: number
): Promise<Message>
export async function sendScheduled(this: TelegramClient, peer: InputPeerLike, id: number): Promise<Message>
/**
* Send previously scheduled message(s)
@ -32,11 +28,7 @@ export async function sendScheduled(
* @param ids ID(s) of the messages
* @internal
*/
export async function sendScheduled(
this: TelegramClient,
peer: InputPeerLike,
ids: number[]
): Promise<Message[]>
export async function sendScheduled(this: TelegramClient, peer: InputPeerLike, ids: number[]): Promise<Message[]>
/** @internal */
export async function sendScheduled(

View file

@ -1,8 +1,4 @@
import {
getMarkedPeerId,
MtArgumentError,
MtTypeAssertionError,
} from '@mtcute/core'
import { getMarkedPeerId, MtArgumentError, MtTypeAssertionError } from '@mtcute/core'
import { randomLong } from '@mtcute/core/utils'
import { tl } from '@mtcute/tl'
@ -122,11 +118,7 @@ export async function sendText(
): Promise<Message> {
if (!params) params = {}
const [message, entities] = await this._parseEntities(
text,
params.parseMode,
params.entities,
)
const [message, entities] = await this._parseEntities(text, params.parseMode, params.entities)
let peer = await this.resolvePeer(chatId)
const replyMarkup = BotKeyboard._convertToTl(params.replyMarkup)
@ -134,27 +126,18 @@ export async function sendText(
let replyTo = normalizeMessageId(params.replyTo)
if (params.commentTo) {
[peer, replyTo] = await this._getDiscussionMessage(
peer,
normalizeMessageId(params.commentTo)!,
)
[peer, replyTo] = await this._getDiscussionMessage(peer, normalizeMessageId(params.commentTo)!)
}
if (params.mustReply) {
if (!replyTo) {
throw new MtArgumentError(
'mustReply used, but replyTo was not passed',
)
throw new MtArgumentError('mustReply used, but replyTo was not passed')
}
const msg = await this.getMessages(peer, replyTo)
if (!msg) {
throw new MtMessageNotFoundError(
getMarkedPeerId(peer),
replyTo,
'to reply to',
)
throw new MtMessageNotFoundError(getMarkedPeerId(peer), replyTo, 'to reply to')
}
}
@ -176,9 +159,7 @@ export async function sendText(
entities,
clearDraft: params.clearDraft,
noforwards: params.forbidForwards,
sendAs: params.sendAs ?
await this.resolvePeer(params.sendAs) :
undefined,
sendAs: params.sendAs ? await this.resolvePeer(params.sendAs) : undefined,
})
if (res._ === 'updateShortSentMessage') {
@ -199,9 +180,7 @@ export async function sendText(
const peers = new PeersIndex()
const fetchPeer = async (
peer: tl.TypePeer | tl.TypeInputPeer,
): Promise<void> => {
const fetchPeer = async (peer: tl.TypePeer | tl.TypeInputPeer): Promise<void> => {
const id = getMarkedPeerId(peer)
let cached = await this.storage.getFullPeerById(id)
@ -224,11 +203,7 @@ export async function sendText(
}
if (!cached) {
throw new MtTypeAssertionError(
'sendText (@ getFullPeerById)',
'user | chat',
'null',
)
throw new MtTypeAssertionError('sendText (@ getFullPeerById)', 'user | chat', 'null')
}
switch (cached._) {

View file

@ -1,18 +1,8 @@
import {
getMarkedPeerId,
MaybeArray,
MtArgumentError,
MtTypeAssertionError,
} from '@mtcute/core'
import { getMarkedPeerId, MaybeArray, MtArgumentError, MtTypeAssertionError } from '@mtcute/core'
import { assertTypeIs } from '@mtcute/core/utils'
import { TelegramClient } from '../../client'
import {
InputPeerLike,
MtMessageNotFoundError,
PeersIndex,
Poll,
} from '../../types'
import { InputPeerLike, MtMessageNotFoundError, PeersIndex, Poll } from '../../types'
import { assertIsUpdatesGroup } from '../../utils/updates-utils'
/**
@ -44,11 +34,7 @@ export async function sendVote(
const msg = await this.getMessages(peer, message)
if (!msg) {
throw new MtMessageNotFoundError(
getMarkedPeerId(peer),
message,
'to vote in',
)
throw new MtMessageNotFoundError(getMarkedPeerId(peer), message, 'to vote in')
}
if (!(msg.media instanceof Poll)) {
@ -80,11 +66,7 @@ export async function sendVote(
assertTypeIs('messages.sendVote (@ .updates[0])', upd, 'updateMessagePoll')
if (!upd.poll) {
throw new MtTypeAssertionError(
'messages.sendVote (@ .updates[0].poll)',
'poll',
'undefined',
)
throw new MtTypeAssertionError('messages.sendVote (@ .updates[0].poll)', 'poll', 'undefined')
}
const peers = PeersIndex.from(res)

View file

@ -28,10 +28,5 @@ export async function translateMessage(
toLang: toLanguage,
})
return [
res.result[0].text,
res.result[0].entities
.map((it) => MessageEntity._parse(it))
.filter(isPresent),
]
return [res.result[0].text, res.result[0].entities.map((it) => MessageEntity._parse(it)).filter(isPresent)]
}

View file

@ -11,11 +11,7 @@ import { TelegramClient } from '../../client'
* @param toLanguage Target language (two-letter ISO 639-1 language code)
* @internal
*/
export async function translateText(
this: TelegramClient,
text: string,
toLanguage: string,
): Promise<string | null> {
export async function translateText(this: TelegramClient, text: string, toLanguage: string): Promise<string | null> {
const res = await this.call({
_: 'messages.translateText',
text: [

View file

@ -9,10 +9,7 @@ import { createDummyUpdate } from '../../utils/updates-utils'
* @param chatId Chat or user ID
* @internal
*/
export async function unpinAllMessages(
this: TelegramClient,
chatId: InputPeerLike,
): Promise<void> {
export async function unpinAllMessages(this: TelegramClient, chatId: InputPeerLike): Promise<void> {
const peer = await this.resolvePeer(chatId)
const res = await this.call({
@ -21,9 +18,7 @@ export async function unpinAllMessages(
})
if (isInputPeerChannel(peer)) {
this._handleUpdate(
createDummyUpdate(res.pts, res.ptsCount, peer.channelId),
)
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount, peer.channelId))
} else {
this._handleUpdate(createDummyUpdate(res.pts, res.ptsCount))
}

View file

@ -11,11 +11,7 @@ import { InputPeerLike } from '../../types'
* @param messageId Message ID
* @internal
*/
export async function unpinMessage(
this: TelegramClient,
chatId: InputPeerLike,
messageId: number,
): Promise<void> {
export async function unpinMessage(this: TelegramClient, chatId: InputPeerLike, messageId: number): Promise<void> {
const res = await this.call({
_: 'messages.updatePinnedMessage',
peer: await this.resolvePeer(chatId),

View file

@ -12,16 +12,11 @@ import { IMessageEntityParser } from '../../types'
* @throws MtClientError When the parse mode with a given name is already registered.
* @internal
*/
export function registerParseMode(
this: TelegramClient,
parseMode: IMessageEntityParser,
): void {
export function registerParseMode(this: TelegramClient, parseMode: IMessageEntityParser): void {
const name = parseMode.name
if (this._parseModes.has(name)) {
throw new MtArgumentError(
`Parse mode ${name} is already registered. Unregister it first!`,
)
throw new MtArgumentError(`Parse mode ${name} is already registered. Unregister it first!`)
}
this._parseModes.set(name, parseMode)
@ -56,10 +51,7 @@ export function unregisterParseMode(this: TelegramClient, name: string): void {
* @throws MtClientError When `name` is omitted and there is no default parse mode
* @internal
*/
export function getParseMode(
this: TelegramClient,
name?: string | null,
): IMessageEntityParser {
export function getParseMode(this: TelegramClient, name?: string | null): IMessageEntityParser {
if (!name) {
if (!this._defaultParseMode) {
throw new MtArgumentError('There is no default parse mode')

View file

@ -1,9 +1,5 @@
import { MtArgumentError } from '@mtcute/core'
import {
assertTypeIs,
computeNewPasswordHash,
computeSrpParams,
} from '@mtcute/core/utils'
import { assertTypeIs, computeNewPasswordHash, computeSrpParams } from '@mtcute/core/utils'
import { TelegramClient } from '../../client'
@ -28,18 +24,10 @@ export async function changeCloudPassword(
}
const algo = pwd.newAlgo
assertTypeIs(
'account.getPassword',
algo,
'passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow',
)
assertTypeIs('account.getPassword', algo, 'passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow')
const oldSrp = await computeSrpParams(this._crypto, pwd, currentPassword)
const newHash = await computeNewPasswordHash(
this._crypto,
algo,
newPassword,
)
const newHash = await computeNewPasswordHash(this._crypto, algo, newPassword)
await this.call({
_: 'account.updatePasswordSettings',

View file

@ -29,11 +29,7 @@ export async function enableCloudPassword(
}
const algo = pwd.newAlgo
assertTypeIs(
'account.getPassword',
algo,
'passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow',
)
assertTypeIs('account.getPassword', algo, 'passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow')
const newHash = await computeNewPasswordHash(this._crypto, algo, password)

View file

@ -6,10 +6,7 @@ import { TelegramClient } from '../../client'
* @param code Code which was sent via email
* @internal
*/
export async function verifyPasswordEmail(
this: TelegramClient,
code: string,
): Promise<void> {
export async function verifyPasswordEmail(this: TelegramClient, code: string): Promise<void> {
await this.call({
_: 'account.confirmPasswordEmail',
code,

View file

@ -9,10 +9,7 @@ import { TelegramClient } from '../../client'
* @param password 2FA password as plaintext
* @internal
*/
export async function removeCloudPassword(
this: TelegramClient,
password: string,
): Promise<void> {
export async function removeCloudPassword(this: TelegramClient, password: string): Promise<void> {
const pwd = await this.call({ _: 'account.getPassword' })
if (!pwd.hasPassword) {

Some files were not shown because too many files have changed in this diff Show more