@mtcute/core 0.15.2 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/highlevel/base.d.ts +3 -3
- package/cjs/highlevel/base.js.map +1 -1
- package/cjs/highlevel/methods/files/download-iterable.js +1 -1
- package/cjs/highlevel/methods/files/download-iterable.js.map +1 -1
- package/cjs/highlevel/methods/users/resolve-peer-many.js +1 -1
- package/cjs/highlevel/methods/users/resolve-peer-many.js.map +1 -1
- package/cjs/highlevel/types/messages/dialog.d.ts +4 -2
- package/cjs/highlevel/types/messages/dialog.js +4 -2
- package/cjs/highlevel/types/messages/dialog.js.map +1 -1
- package/cjs/highlevel/types/messages/message-action.d.ts +15 -1
- package/cjs/highlevel/types/messages/message-action.js +10 -0
- package/cjs/highlevel/types/messages/message-action.js.map +1 -1
- package/cjs/highlevel/types/peers/full-chat.d.ts +2 -0
- package/cjs/highlevel/types/peers/full-chat.js +4 -0
- package/cjs/highlevel/types/peers/full-chat.js.map +1 -1
- package/cjs/highlevel/updates/manager.js +3 -3
- package/cjs/highlevel/updates/manager.js.map +1 -1
- package/cjs/highlevel/worker/invoker.js +2 -1
- package/cjs/highlevel/worker/invoker.js.map +1 -1
- package/cjs/highlevel/worker/port.js +4 -3
- package/cjs/highlevel/worker/port.js.map +1 -1
- package/cjs/highlevel/worker/protocol.d.ts +10 -5
- package/cjs/highlevel/worker/protocol.js +66 -0
- package/cjs/highlevel/worker/protocol.js.map +1 -1
- package/cjs/highlevel/worker/worker.js +6 -5
- package/cjs/highlevel/worker/worker.js.map +1 -1
- package/cjs/network/client.d.ts +0 -16
- package/cjs/network/client.js +0 -2
- package/cjs/network/client.js.map +1 -1
- package/cjs/network/index.d.ts +2 -1
- package/cjs/network/index.js +1 -0
- package/cjs/network/index.js.map +1 -1
- package/cjs/network/middlewares/bundle.d.ts +3 -0
- package/cjs/network/middlewares/bundle.js +20 -0
- package/cjs/network/middlewares/bundle.js.map +1 -0
- package/cjs/network/middlewares/default.d.ts +8 -0
- package/cjs/network/middlewares/default.js +10 -0
- package/cjs/network/middlewares/default.js.map +1 -0
- package/cjs/network/middlewares/flood-waiter.d.ts +37 -0
- package/cjs/network/middlewares/flood-waiter.js +70 -0
- package/cjs/network/middlewares/flood-waiter.js.map +1 -0
- package/cjs/network/middlewares/index.d.ts +2 -0
- package/cjs/network/middlewares/index.js +29 -0
- package/cjs/network/middlewares/index.js.map +1 -0
- package/cjs/network/middlewares/internal-errors.d.ts +17 -0
- package/cjs/network/middlewares/internal-errors.js +41 -0
- package/cjs/network/middlewares/internal-errors.js.map +1 -0
- package/cjs/network/middlewares/on-error.d.ts +30 -0
- package/cjs/network/middlewares/on-error.js +44 -0
- package/cjs/network/middlewares/on-error.js.map +1 -0
- package/cjs/network/middlewares/on-method.d.ts +39 -0
- package/cjs/network/middlewares/on-method.js +45 -0
- package/cjs/network/middlewares/on-method.js.map +1 -0
- package/cjs/network/mtproto-session.js +1 -1
- package/cjs/network/mtproto-session.js.map +1 -1
- package/cjs/network/multi-session-connection.js +1 -1
- package/cjs/network/multi-session-connection.js.map +1 -1
- package/cjs/network/network-manager.d.ts +23 -6
- package/cjs/network/network-manager.js +55 -102
- package/cjs/network/network-manager.js.map +1 -1
- package/cjs/network/persistent-connection.js +5 -5
- package/cjs/network/persistent-connection.js.map +1 -1
- package/cjs/network/session-connection.js +6 -6
- package/cjs/network/session-connection.js.map +1 -1
- package/cjs/storage/driver.js +1 -1
- package/cjs/storage/driver.js.map +1 -1
- package/cjs/storage/storage.js +1 -1
- package/cjs/storage/storage.js.map +1 -1
- package/cjs/utils/abort-signal.d.ts +1 -0
- package/cjs/utils/abort-signal.js +13 -0
- package/cjs/utils/abort-signal.js.map +1 -0
- package/cjs/utils/composer.d.ts +3 -0
- package/cjs/utils/composer.js +22 -0
- package/cjs/utils/composer.js.map +1 -0
- package/cjs/utils/error-reporting.js +1 -1
- package/cjs/utils/error-reporting.js.map +1 -1
- package/cjs/utils/index.d.ts +1 -0
- package/cjs/utils/index.js +1 -0
- package/cjs/utils/index.js.map +1 -1
- package/cjs/utils/logger.js +15 -3
- package/cjs/utils/logger.js.map +1 -1
- package/esm/highlevel/base.d.ts +3 -3
- package/esm/highlevel/base.js.map +1 -1
- package/esm/highlevel/methods/files/download-iterable.js +1 -1
- package/esm/highlevel/methods/files/download-iterable.js.map +1 -1
- package/esm/highlevel/methods/users/resolve-peer-many.js +1 -1
- package/esm/highlevel/methods/users/resolve-peer-many.js.map +1 -1
- package/esm/highlevel/types/messages/dialog.d.ts +4 -2
- package/esm/highlevel/types/messages/dialog.js +4 -2
- package/esm/highlevel/types/messages/dialog.js.map +1 -1
- package/esm/highlevel/types/messages/message-action.d.ts +15 -1
- package/esm/highlevel/types/messages/message-action.js +10 -0
- package/esm/highlevel/types/messages/message-action.js.map +1 -1
- package/esm/highlevel/types/peers/full-chat.d.ts +2 -0
- package/esm/highlevel/types/peers/full-chat.js +4 -0
- package/esm/highlevel/types/peers/full-chat.js.map +1 -1
- package/esm/highlevel/updates/manager.js +3 -3
- package/esm/highlevel/updates/manager.js.map +1 -1
- package/esm/highlevel/worker/invoker.js +2 -1
- package/esm/highlevel/worker/invoker.js.map +1 -1
- package/esm/highlevel/worker/port.js +4 -3
- package/esm/highlevel/worker/port.js.map +1 -1
- package/esm/highlevel/worker/protocol.d.ts +10 -5
- package/esm/highlevel/worker/protocol.js +60 -1
- package/esm/highlevel/worker/protocol.js.map +1 -1
- package/esm/highlevel/worker/worker.js +6 -5
- package/esm/highlevel/worker/worker.js.map +1 -1
- package/esm/network/client.d.ts +0 -16
- package/esm/network/client.js +0 -2
- package/esm/network/client.js.map +1 -1
- package/esm/network/index.d.ts +2 -1
- package/esm/network/index.js +1 -0
- package/esm/network/index.js.map +1 -1
- package/esm/network/middlewares/bundle.d.ts +3 -0
- package/esm/network/middlewares/bundle.js +4 -0
- package/esm/network/middlewares/bundle.js.map +1 -0
- package/esm/network/middlewares/default.d.ts +8 -0
- package/esm/network/middlewares/default.js +6 -0
- package/esm/network/middlewares/default.js.map +1 -0
- package/esm/network/middlewares/flood-waiter.d.ts +37 -0
- package/esm/network/middlewares/flood-waiter.js +66 -0
- package/esm/network/middlewares/flood-waiter.js.map +1 -0
- package/esm/network/middlewares/index.d.ts +2 -0
- package/esm/network/middlewares/index.js +3 -0
- package/esm/network/middlewares/index.js.map +1 -0
- package/esm/network/middlewares/internal-errors.d.ts +17 -0
- package/esm/network/middlewares/internal-errors.js +37 -0
- package/esm/network/middlewares/internal-errors.js.map +1 -0
- package/esm/network/middlewares/on-error.d.ts +30 -0
- package/esm/network/middlewares/on-error.js +40 -0
- package/esm/network/middlewares/on-error.js.map +1 -0
- package/esm/network/middlewares/on-method.d.ts +39 -0
- package/esm/network/middlewares/on-method.js +41 -0
- package/esm/network/middlewares/on-method.js.map +1 -0
- package/esm/network/mtproto-session.js +1 -1
- package/esm/network/mtproto-session.js.map +1 -1
- package/esm/network/multi-session-connection.js +1 -1
- package/esm/network/multi-session-connection.js.map +1 -1
- package/esm/network/network-manager.d.ts +23 -6
- package/esm/network/network-manager.js +57 -104
- package/esm/network/network-manager.js.map +1 -1
- package/esm/network/persistent-connection.js +5 -5
- package/esm/network/persistent-connection.js.map +1 -1
- package/esm/network/session-connection.js +6 -6
- package/esm/network/session-connection.js.map +1 -1
- package/esm/storage/driver.js +1 -1
- package/esm/storage/driver.js.map +1 -1
- package/esm/storage/storage.js +1 -1
- package/esm/storage/storage.js.map +1 -1
- package/esm/utils/abort-signal.d.ts +1 -0
- package/esm/utils/abort-signal.js +9 -0
- package/esm/utils/abort-signal.js.map +1 -0
- package/esm/utils/composer.d.ts +3 -0
- package/esm/utils/composer.js +18 -0
- package/esm/utils/composer.js.map +1 -0
- package/esm/utils/error-reporting.js +1 -1
- package/esm/utils/error-reporting.js.map +1 -1
- package/esm/utils/index.d.ts +1 -0
- package/esm/utils/index.js +1 -0
- package/esm/utils/index.js.map +1 -1
- package/esm/utils/logger.js +15 -3
- package/esm/utils/logger.js.map +1 -1
- package/package.json +4 -4
package/cjs/highlevel/base.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { MtClient, MtClientOptions } from '../network/client.js';
|
|
|
3
3
|
import { ConnectionKind, RpcCallOptions } from '../network/network-manager.js';
|
|
4
4
|
import { StorageManagerExtraOptions } from '../storage/storage.js';
|
|
5
5
|
import { MustEqual } from '../types/utils.js';
|
|
6
|
-
import { StringSessionData } from '../utils/index.js';
|
|
6
|
+
import { ICryptoProvider, Logger, StringSessionData } from '../utils/index.js';
|
|
7
7
|
import { ConnectionState, ITelegramClient, ServerUpdateHandler } from './client.types.js';
|
|
8
8
|
import { AppConfigManager } from './managers/app-config-manager.js';
|
|
9
9
|
import { ITelegramStorageProvider } from './storage/provider.js';
|
|
@@ -20,9 +20,9 @@ export declare class BaseTelegramClient implements ITelegramClient {
|
|
|
20
20
|
readonly updates?: UpdatesManager;
|
|
21
21
|
private _serverUpdatesHandler;
|
|
22
22
|
private _connectionStateHandler;
|
|
23
|
-
readonly log:
|
|
23
|
+
readonly log: Logger;
|
|
24
24
|
readonly mt: MtClient;
|
|
25
|
-
readonly crypto:
|
|
25
|
+
readonly crypto: ICryptoProvider;
|
|
26
26
|
readonly storage: TelegramStorageManager;
|
|
27
27
|
constructor(params: BaseTelegramClientOptions);
|
|
28
28
|
readonly appConfig: AppConfigManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/highlevel/base.ts"],"names":[],"mappings":";;;AAAA,qDAAqD;AACrD,mCAAoC;AAEpC,oDAAgE;AAGhE,kDAAoD;AAEpD,oEAAgE;AAChE,gDAQ0B;AAC1B,kDAA+C;AAE/C,4EAAmE;AAEnE,qDAAiG;AACjG,qDAAqD;AASrD,SAAS,YAAY,CAAC,GAAwB,EAAE,KAAa,EAAE,MAAe;IAC1E,MAAM,KAAK,GAAG,OAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAA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AG,EAAE,CAAA;QAC7B,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IAClD,CAAC;IAED,KAAK,CAAC,cAAc;QAChB,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACnB,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAA;QAC7B,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,CAAA;IAC3C,CAAC;IAED,gBAAgB,CAAC,OAA+B,EAAE,QAAgB;QAC9D,OAAO,IAAA,2BAAgB,EAAC,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAA;IAC3D,CAAC;IACD,sBAAsB,CAAC,IAA4B,EAAE,QAAgB;QACjE,OAAO,IAAA,iCAAsB,EAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAA;IAC9D,CAAC;IAED,IAAI,UAAU;QACV,OAAO,IAAI,CAAC,EAAE,CAAC,UAAU,CAAA;IAC7B,CAAC;IAED,eAAe,CAAC,IAAY;QACxB,OAAO,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,CAAA;IAChD,CAAC;CACJ;AA3TD,gDA2TC","sourcesContent":["/* eslint-disable @typescript-eslint/require-await */\nimport { mtp, tl } from '@mtcute/tl'\n\nimport { MtClient, MtClientOptions } from '../network/client.js'\nimport { ConnectionKind, RpcCallOptions } from '../network/network-manager.js'\nimport { StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MtArgumentError } from '../types/errors.js'\nimport { MustEqual } from '../types/utils.js'\nimport { reportUnknownError } from '../utils/error-reporting.js'\nimport {\n asyncResettable,\n computeNewPasswordHash,\n computeSrpParams,\n isTlRpcError,\n readStringSession,\n StringSessionData,\n writeStringSession,\n} from '../utils/index.js'\nimport { LogManager } from '../utils/logger.js'\nimport { ConnectionState, ITelegramClient, ServerUpdateHandler } from './client.types.js'\nimport { AppConfigManager } from './managers/app-config-manager.js'\nimport { ITelegramStorageProvider } from './storage/provider.js'\nimport { TelegramStorageManager, TelegramStorageManagerExtraOptions } from './storage/storage.js'\nimport { UpdatesManager } from './updates/manager.js'\nimport { RawUpdateHandler, UpdatesManagerParams } from './updates/types.js'\n\nexport interface BaseTelegramClientOptions extends MtClientOptions {\n storage: ITelegramStorageProvider\n storageOptions?: StorageManagerExtraOptions & TelegramStorageManagerExtraOptions\n updates?: UpdatesManagerParams | false\n}\n\nfunction makeRpcError(raw: mtp.RawMt_rpc_error, stack: string, method?: string) {\n const error = tl.RpcError.fromTl(raw)\n error.stack = `RpcError (${error.code} ${error.text}): ${error.message}\\n at ${method}\\n${stack\n .split('\\n')\n .slice(2)\n .join('\\n')}`\n\n return error\n}\n\nexport class BaseTelegramClient implements ITelegramClient {\n readonly updates?: UpdatesManager\n private _serverUpdatesHandler: ServerUpdateHandler = () => {}\n private _connectionStateHandler: (state: ConnectionState) => void = () => {}\n\n readonly log\n readonly mt\n readonly crypto\n readonly storage\n\n constructor(readonly params: BaseTelegramClientOptions) {\n this.log = this.params.logger ?? new LogManager('client')\n this.mt = new MtClient({\n ...this.params,\n logger: this.log.create('mtproto'),\n })\n\n if (!params.disableUpdates && params.updates !== false) {\n this.updates = new UpdatesManager(this, params.updates)\n this._serverUpdatesHandler = this.updates.handleUpdate.bind(this.updates)\n this.updates.onCatchingUp((catchingUp) => {\n this._connectionStateHandler(catchingUp ? 'updating' : 'connected')\n })\n }\n\n this.mt.on('update', (update: tl.TypeUpdates) => {\n this._serverUpdatesHandler(update)\n })\n this.mt.on('usable', () => {\n this._connectionStateHandler('connected')\n })\n this.mt.on('wait', () => {\n this._connectionStateHandler('connecting')\n })\n this.mt.on('networkChanged', (connected: boolean) => {\n if (!connected) {\n this._connectionStateHandler('offline')\n }\n })\n\n this.crypto = this.mt.crypto\n this.storage = new TelegramStorageManager(this.mt.storage, {\n provider: this.params.storage,\n ...this.params.storageOptions,\n })\n }\n readonly appConfig = new AppConfigManager(this)\n\n private _prepare = asyncResettable(async () => {\n await this.mt.prepare()\n\n const self = await this.storage.self.fetch()\n this.log.prefix = `[USER ${self?.userId ?? 'n/a'}] `\n this.mt.network.setIsPremium(self?.isPremium ?? false)\n\n await this.updates?.prepare()\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n // used in a hot path, avoid extra function calls\n private _connected = false\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.mt.connect()\n this._connected = true\n })\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n return this._connect.run()\n }\n\n get isConnected(): boolean {\n return this._connected\n }\n\n async close(): Promise<void> {\n this._connected = false\n await this.mt.close()\n this.updates?.stopLoop()\n this._prepare.reset()\n this._connect.reset()\n }\n\n async notifyLoggedIn(auth: tl.auth.TypeAuthorization | tl.RawUser): Promise<tl.RawUser> {\n const user = this.mt.network.notifyLoggedIn(auth)\n\n this.log.prefix = `[USER ${user.id}] `\n const self = await this.storage.self.storeFrom(user)\n\n this.updates?.notifyLoggedIn(self)\n\n return user\n }\n\n async notifyLoggedOut(): Promise<void> {\n this.mt.network.notifyLoggedOut()\n\n this.log.prefix = '[USER n/a] '\n await this.storage.self.store(null)\n }\n\n async notifyChannelOpened(channelId: number, pts?: number): Promise<boolean> {\n return this.updates?.notifyChannelOpened(channelId, pts) ?? false\n }\n\n async notifyChannelClosed(channelId: number): Promise<boolean> {\n return this.updates?.notifyChannelClosed(channelId) ?? false\n }\n\n async startUpdatesLoop(): Promise<void> {\n await this.updates?.startLoop()\n }\n\n async stopUpdatesLoop(): Promise<void> {\n this.updates?.stopLoop()\n }\n\n /**\n * Make an RPC call\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n const res = await this.mt.call(message, params)\n\n if (isTlRpcError(res)) {\n const error = makeRpcError(res, new Error().stack ?? '', message._)\n\n if (error.unknown && this.params.enableErrorReporting) {\n reportUnknownError(this.log, error, message._)\n }\n\n throw error\n }\n\n await this.storage.peers.updatePeersFrom(res)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Import the session from the given session string.\n *\n * Note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force`).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n async importSession(session: string | StringSessionData, force = false): Promise<void> {\n await this.prepare()\n\n const defaultDcAuthKey = await this.mt.storage.provider.authKeys.get(this.mt._defaultDcs.main.id)\n\n if (defaultDcAuthKey && !force) return\n\n const data = typeof session === 'string' ? readStringSession(session) : session\n\n if (data.testMode && !this.params.testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, ` +\n `but the client is ${this.params.testMode ? 'test' : 'prod'}`,\n )\n }\n\n this.mt._defaultDcs = data.primaryDcs\n await this.mt.storage.dcs.store(data.primaryDcs)\n\n if (data.self) {\n await this.storage.self.store(data.self)\n }\n\n await this.mt.storage.provider.authKeys.set(data.primaryDcs.main.id, data.authKey)\n\n await this.mt.storage.save()\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n await this._prepare.run()\n\n const primaryDcs = (await this.mt.storage.dcs.fetch()) ?? this.mt._defaultDcs\n\n const authKey = await this.mt.storage.provider.authKeys.get(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession({\n version: 3,\n self: await this.storage.self.fetch(),\n testMode: Boolean(this.params.testMode),\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this.mt.onError(handler)\n }\n\n emitError(err: unknown): void {\n this.mt.emitError(err)\n }\n\n handleClientUpdate(updates: tl.TypeUpdates, noDispatch?: boolean): void {\n this.updates?.handleClientUpdate(updates, noDispatch)\n }\n\n onServerUpdate(handler: ServerUpdateHandler): void {\n this._serverUpdatesHandler = handler\n }\n\n getServerUpdateHandler(): ServerUpdateHandler {\n return this._serverUpdatesHandler\n }\n\n onUpdate(handler: RawUpdateHandler): void {\n if (!this.updates) {\n throw new MtArgumentError('Updates manager is disabled')\n }\n\n this.updates.setHandler(handler)\n }\n\n onConnectionState(handler: (state: ConnectionState) => void): void {\n this._connectionStateHandler = handler\n }\n\n async getApiCrenetials() {\n return {\n id: this.params.apiId,\n hash: this.params.apiHash,\n }\n }\n\n async getPoolSize(kind: ConnectionKind, dcId?: number): Promise<number> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n return this.mt.network.getPoolSize(kind, dcId)\n }\n\n async getPrimaryDcId(): Promise<number> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n return this.mt.network.getPrimaryDcId()\n }\n\n computeSrpParams(request: tl.account.RawPassword, password: string): Promise<tl.RawInputCheckPasswordSRP> {\n return computeSrpParams(this.crypto, request, password)\n }\n computeNewPasswordHash(algo: tl.TypePasswordKdfAlgo, password: string): Promise<Uint8Array> {\n return computeNewPasswordHash(this.crypto, algo, password)\n }\n\n get stopSignal(): AbortSignal {\n return this.mt.stopSignal\n }\n\n changePrimaryDc(dcId: number): Promise<void> {\n return this.mt.network.changePrimaryDc(dcId)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/highlevel/base.ts"],"names":[],"mappings":";;;AAAA,qDAAqD;AACrD,mCAAoC;AAEpC,oDAAgE;AAGhE,kDAAoD;AAEpD,oEAAgE;AAChE,gDAU0B;AAC1B,kDAA+C;AAE/C,4EAAmE;AAEnE,qDAAiG;AACjG,qDAAqD;AASrD,SAAS,YAAY,CAAC,GAAwB,EAAE,KAAa,EAAE,MAAe;IAC1E,MAAM,KAAK,GAAG,OAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACrC,KAAK,CAAC,KAAK,GAAG,aAAa,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,MAAM,KAAK,CAAC,OAAO,YAAY,MAAM,KAAK,KAAK;SAC7F,KAAK,CAAC,IAAI,CAAC;SACX,KAAK,CAAC,CAAC,CAAC;SACR,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;IAEjB,OAAO,KAAK,CAAA;AAChB,CAAC;AAED,MAAa,kBAAkB;IAUN;IATZ,OAAO,CAAiB;IACzB,qBAAqB,GAAwB,GAAG,EAAE,GAAE,CAAC,CAAA;IACrD,uBAAuB,GAAqC,GAAG,EAAE,GAAE,CAAC,CAAA;IAEnE,GAAG,CAAQ;IACX,EAAE,CAAU;IACZ,MAAM,CAAiB;IACvB,OAAO,CAAwB;IAExC,YAAqB,MAAiC;QAAjC,WAAM,GAAN,MAAM,CAA2B;QAClD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,sBAAU,CAAC,QAAQ,CAAC,CAAA;QACzD,IAAI,CAAC,EAAE,GAAG,IAAI,oBAAQ,CAAC;YACnB,G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CAAC;IAED,eAAe,CAAC,IAAY;QACxB,OAAO,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,CAAA;IAChD,CAAC;CACJ;AA3TD,gDA2TC","sourcesContent":["/* eslint-disable @typescript-eslint/require-await */\nimport { mtp, tl } from '@mtcute/tl'\n\nimport { MtClient, MtClientOptions } from '../network/client.js'\nimport { ConnectionKind, RpcCallOptions } from '../network/network-manager.js'\nimport { StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MtArgumentError } from '../types/errors.js'\nimport { MustEqual } from '../types/utils.js'\nimport { reportUnknownError } from '../utils/error-reporting.js'\nimport {\n asyncResettable,\n computeNewPasswordHash,\n computeSrpParams,\n ICryptoProvider,\n isTlRpcError,\n Logger,\n readStringSession,\n StringSessionData,\n writeStringSession,\n} from '../utils/index.js'\nimport { LogManager } from '../utils/logger.js'\nimport { ConnectionState, ITelegramClient, ServerUpdateHandler } from './client.types.js'\nimport { AppConfigManager } from './managers/app-config-manager.js'\nimport { ITelegramStorageProvider } from './storage/provider.js'\nimport { TelegramStorageManager, TelegramStorageManagerExtraOptions } from './storage/storage.js'\nimport { UpdatesManager } from './updates/manager.js'\nimport { RawUpdateHandler, UpdatesManagerParams } from './updates/types.js'\n\nexport interface BaseTelegramClientOptions extends MtClientOptions {\n storage: ITelegramStorageProvider\n storageOptions?: StorageManagerExtraOptions & TelegramStorageManagerExtraOptions\n updates?: UpdatesManagerParams | false\n}\n\nfunction makeRpcError(raw: mtp.RawMt_rpc_error, stack: string, method?: string) {\n const error = tl.RpcError.fromTl(raw)\n error.stack = `RpcError (${error.code} ${error.text}): ${error.message}\\n at ${method}\\n${stack\n .split('\\n')\n .slice(2)\n .join('\\n')}`\n\n return error\n}\n\nexport class BaseTelegramClient implements ITelegramClient {\n readonly updates?: UpdatesManager\n private _serverUpdatesHandler: ServerUpdateHandler = () => {}\n private _connectionStateHandler: (state: ConnectionState) => void = () => {}\n\n readonly log: Logger\n readonly mt: MtClient\n readonly crypto: ICryptoProvider\n readonly storage: TelegramStorageManager\n\n constructor(readonly params: BaseTelegramClientOptions) {\n this.log = this.params.logger ?? new LogManager('client')\n this.mt = new MtClient({\n ...this.params,\n logger: this.log.create('mtproto'),\n })\n\n if (!params.disableUpdates && params.updates !== false) {\n this.updates = new UpdatesManager(this, params.updates)\n this._serverUpdatesHandler = this.updates.handleUpdate.bind(this.updates)\n this.updates.onCatchingUp((catchingUp) => {\n this._connectionStateHandler(catchingUp ? 'updating' : 'connected')\n })\n }\n\n this.mt.on('update', (update: tl.TypeUpdates) => {\n this._serverUpdatesHandler(update)\n })\n this.mt.on('usable', () => {\n this._connectionStateHandler('connected')\n })\n this.mt.on('wait', () => {\n this._connectionStateHandler('connecting')\n })\n this.mt.on('networkChanged', (connected: boolean) => {\n if (!connected) {\n this._connectionStateHandler('offline')\n }\n })\n\n this.crypto = this.mt.crypto\n this.storage = new TelegramStorageManager(this.mt.storage, {\n provider: this.params.storage,\n ...this.params.storageOptions,\n })\n }\n readonly appConfig = new AppConfigManager(this)\n\n private _prepare = asyncResettable(async () => {\n await this.mt.prepare()\n\n const self = await this.storage.self.fetch()\n this.log.prefix = `[USER ${self?.userId ?? 'n/a'}] `\n this.mt.network.setIsPremium(self?.isPremium ?? false)\n\n await this.updates?.prepare()\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n // used in a hot path, avoid extra function calls\n private _connected = false\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.mt.connect()\n this._connected = true\n })\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n return this._connect.run()\n }\n\n get isConnected(): boolean {\n return this._connected\n }\n\n async close(): Promise<void> {\n this._connected = false\n await this.mt.close()\n this.updates?.stopLoop()\n this._prepare.reset()\n this._connect.reset()\n }\n\n async notifyLoggedIn(auth: tl.auth.TypeAuthorization | tl.RawUser): Promise<tl.RawUser> {\n const user = this.mt.network.notifyLoggedIn(auth)\n\n this.log.prefix = `[USER ${user.id}] `\n const self = await this.storage.self.storeFrom(user)\n\n this.updates?.notifyLoggedIn(self)\n\n return user\n }\n\n async notifyLoggedOut(): Promise<void> {\n this.mt.network.notifyLoggedOut()\n\n this.log.prefix = '[USER n/a] '\n await this.storage.self.store(null)\n }\n\n async notifyChannelOpened(channelId: number, pts?: number): Promise<boolean> {\n return this.updates?.notifyChannelOpened(channelId, pts) ?? false\n }\n\n async notifyChannelClosed(channelId: number): Promise<boolean> {\n return this.updates?.notifyChannelClosed(channelId) ?? false\n }\n\n async startUpdatesLoop(): Promise<void> {\n await this.updates?.startLoop()\n }\n\n async stopUpdatesLoop(): Promise<void> {\n this.updates?.stopLoop()\n }\n\n /**\n * Make an RPC call\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n const res = await this.mt.call(message, params)\n\n if (isTlRpcError(res)) {\n const error = makeRpcError(res, new Error().stack ?? '', message._)\n\n if (error.unknown && this.params.enableErrorReporting) {\n reportUnknownError(this.log, error, message._)\n }\n\n throw error\n }\n\n await this.storage.peers.updatePeersFrom(res)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Import the session from the given session string.\n *\n * Note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force`).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n async importSession(session: string | StringSessionData, force = false): Promise<void> {\n await this.prepare()\n\n const defaultDcAuthKey = await this.mt.storage.provider.authKeys.get(this.mt._defaultDcs.main.id)\n\n if (defaultDcAuthKey && !force) return\n\n const data = typeof session === 'string' ? readStringSession(session) : session\n\n if (data.testMode && !this.params.testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, ` +\n `but the client is ${this.params.testMode ? 'test' : 'prod'}`,\n )\n }\n\n this.mt._defaultDcs = data.primaryDcs\n await this.mt.storage.dcs.store(data.primaryDcs)\n\n if (data.self) {\n await this.storage.self.store(data.self)\n }\n\n await this.mt.storage.provider.authKeys.set(data.primaryDcs.main.id, data.authKey)\n\n await this.mt.storage.save()\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n await this._prepare.run()\n\n const primaryDcs = (await this.mt.storage.dcs.fetch()) ?? this.mt._defaultDcs\n\n const authKey = await this.mt.storage.provider.authKeys.get(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession({\n version: 3,\n self: await this.storage.self.fetch(),\n testMode: Boolean(this.params.testMode),\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this.mt.onError(handler)\n }\n\n emitError(err: unknown): void {\n this.mt.emitError(err)\n }\n\n handleClientUpdate(updates: tl.TypeUpdates, noDispatch?: boolean): void {\n this.updates?.handleClientUpdate(updates, noDispatch)\n }\n\n onServerUpdate(handler: ServerUpdateHandler): void {\n this._serverUpdatesHandler = handler\n }\n\n getServerUpdateHandler(): ServerUpdateHandler {\n return this._serverUpdatesHandler\n }\n\n onUpdate(handler: RawUpdateHandler): void {\n if (!this.updates) {\n throw new MtArgumentError('Updates manager is disabled')\n }\n\n this.updates.setHandler(handler)\n }\n\n onConnectionState(handler: (state: ConnectionState) => void): void {\n this._connectionStateHandler = handler\n }\n\n async getApiCrenetials() {\n return {\n id: this.params.apiId,\n hash: this.params.apiHash,\n }\n }\n\n async getPoolSize(kind: ConnectionKind, dcId?: number): Promise<number> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n return this.mt.network.getPoolSize(kind, dcId)\n }\n\n async getPrimaryDcId(): Promise<number> {\n if (!this._connected) {\n await this._connect.run()\n }\n\n return this.mt.network.getPrimaryDcId()\n }\n\n computeSrpParams(request: tl.account.RawPassword, password: string): Promise<tl.RawInputCheckPasswordSRP> {\n return computeSrpParams(this.crypto, request, password)\n }\n computeNewPasswordHash(algo: tl.TypePasswordKdfAlgo, password: string): Promise<Uint8Array> {\n return computeNewPasswordHash(this.crypto, algo, password)\n }\n\n get stopSignal(): AbortSignal {\n return this.mt.stopSignal\n }\n\n changePrimaryDc(dcId: number): Promise<void> {\n return this.mt.network.changePrimaryDc(dcId)\n }\n}\n"]}
|
|
@@ -145,7 +145,7 @@ async function* downloadAsIterable(client, input, params) {
|
|
|
145
145
|
let error = undefined;
|
|
146
146
|
void Promise.all(Array.from({ length: Math.min(poolSize * REQUESTS_PER_CONNECTION, numChunks) }, downloadChunk))
|
|
147
147
|
.catch((e) => {
|
|
148
|
-
client.log.debug('download workers errored: %
|
|
148
|
+
client.log.debug('download workers errored: %e', e);
|
|
149
149
|
error = e;
|
|
150
150
|
aborted = true; // not really aborted, but we dont want to download more chunks
|
|
151
151
|
nextChunkCv.notify();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"download-iterable.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/files/download-iterable.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,mCAA+B;AAG/B,sD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,IAAI,GAAG,CAAC,MAAM,CAAA;YAEtB,MAAM,EAAE,gBAAgB,EAAE,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;YAEhD,MAAM,GAAG,CAAA;YAET,YAAY,EAAE,CAAA;YAEd,IAAI,GAAG,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;gBACzB,6BAA6B;gBAC7B,OAAM;YACV,CAAC;QACL,CAAC;IACL,CAAC;AACL,CAAC;AArMD,gDAqMC","sourcesContent":["import { parseFileId } from '@mtcute/file-id'\nimport { tl } from '@mtcute/tl'\n\nimport { ConnectionKind } from '../../../network/network-manager.js'\nimport { getPlatform } from '../../../platform.js'\nimport { MtArgumentError, MtUnsupportedError } from '../../../types/errors.js'\nimport { ConditionVariable } from '../../../utils/condition-variable.js'\nimport { ITelegramClient } from '../../client.types.js'\nimport { FileDownloadLocation, FileDownloadParameters, FileLocation } from '../../types/index.js'\nimport { fileIdToInputFileLocation, fileIdToInputWebFileLocation } from '../../utils/convert-file-id.js'\nimport { determinePartSize } from '../../utils/file-utils.js'\n\n// small files (less than 128 kb) are downloaded using the \"downloadSmall\" pool\n// furthermore, if the file is small and is located on our main DC, it will be downloaded\n// using the current main connection\nconst SMALL_FILE_MAX_SIZE = 131072\nconst REQUESTS_PER_CONNECTION = 3 // some arbitrary magic value that seems to work best\n\n/**\n * Download a file and return it as an iterable, which yields file contents\n * in chunks of a given size. Order of the chunks is guaranteed to be\n * consecutive.\n *\n * @param params Download parameters\n */\nexport async function* downloadAsIterable(\n client: ITelegramClient,\n input: FileDownloadLocation,\n params?: FileDownloadParameters,\n): AsyncIterableIterator<Uint8Array> {\n const offset = params?.offset ?? 0\n\n if (offset % 4096 !== 0) {\n throw new MtArgumentError(`Invalid offset: ${offset}. Must be divisible by 4096`)\n }\n\n let dcId = params?.dcId\n let fileSize = params?.fileSize\n\n const abortSignal = params?.abortSignal\n let aborted = false\n\n let location: tl.TypeInputFileLocation | tl.TypeInputWebFileLocation\n if (input instanceof FileLocation) {\n let locationInner = input.location\n\n if (typeof locationInner === 'function') {\n locationInner = locationInner()\n }\n\n if (ArrayBuffer.isView(locationInner)) {\n yield locationInner\n\n return\n }\n if (!dcId) dcId = input.dcId\n if (!fileSize) fileSize = input.fileSize\n location = locationInner\n } else if (typeof input === 'string') {\n const parsed = parseFileId(getPlatform(), input)\n\n if (parsed.location._ === 'web') {\n location = fileIdToInputWebFileLocation(parsed)\n } else {\n location = fileIdToInputFileLocation(parsed)\n }\n } else location = input\n\n const isWeb = tl.isAnyInputWebFileLocation(location)\n\n // we will receive a FileMigrateError in case this is invalid\n const primaryDcId = await client.getPrimaryDcId()\n if (!dcId) dcId = primaryDcId\n\n const partSizeKb = params?.partSize ?? (fileSize ? determinePartSize(fileSize) : 64)\n\n if (partSizeKb % 4 !== 0) {\n throw new MtArgumentError(`Invalid part size: ${partSizeKb}. Must be divisible by 4.`)\n }\n\n const chunkSize = partSizeKb * 1024\n\n let limitBytes = params?.limit ?? fileSize ?? Infinity\n if (limitBytes === 0) return\n\n let numChunks = limitBytes === Infinity ? Infinity : ~~((limitBytes + chunkSize - offset - 1) / chunkSize)\n\n let nextChunkIdx = 0\n let nextWorkerChunkIdx = 0\n const nextChunkCv = new ConditionVariable()\n const buffer: Record<number, Uint8Array> = {}\n\n const isSmall = fileSize && fileSize <= SMALL_FILE_MAX_SIZE\n let connectionKind: ConnectionKind\n\n if (isSmall) {\n connectionKind = dcId === primaryDcId ? 'main' : 'downloadSmall'\n } else {\n connectionKind = 'download'\n }\n const poolSize = await client.getPoolSize(connectionKind, dcId)\n\n client.log.debug(\n 'Downloading file of size %d from dc %d using %s connection pool (pool size: %d)',\n limitBytes,\n dcId,\n connectionKind,\n poolSize,\n )\n\n const downloadChunk = async (chunk = nextWorkerChunkIdx++): Promise<void> => {\n let result: tl.RpcCallReturn['upload.getFile'] | tl.RpcCallReturn['upload.getWebFile']\n\n if (aborted) {\n return\n }\n\n try {\n result = await client.call(\n {\n _: isWeb ? 'upload.getWebFile' : 'upload.getFile',\n // eslint-disable-next-line\n location: location as any,\n offset: chunkSize * chunk,\n limit: chunkSize,\n },\n {\n dcId,\n kind: connectionKind,\n maxRetryCount: Infinity, // retry until explicitly aborted (or finished)\n abortSignal,\n },\n )\n } catch (e: unknown) {\n if (e instanceof DOMException && e.name === 'AbortError') return\n if (!tl.RpcError.is(e)) throw e\n\n if (e.is('FILE_MIGRATE_%d')) {\n dcId = e.newDc\n\n return downloadChunk(chunk)\n } else if (e.is('FILEREF_UPGRADE_NEEDED')) {\n // todo: implement someday\n // see: https://github.com/LonamiWebs/Telethon/blob/0e8bd8248cc649637b7c392616887c50986427a0/telethon/client/downloads.py#L99\n throw new MtUnsupportedError('File ref expired!')\n } else throw e\n }\n\n if (result._ === 'upload.fileCdnRedirect') {\n // we shouldnt receive them since cdnSupported is not set in the getFile request.\n // also, i couldnt find any media that would be downloaded from cdn, so even if\n // i implemented that, i wouldnt be able to test that, so :shrug:\n throw new MtUnsupportedError('Received CDN redirect, which is not supported (yet)')\n }\n\n if (aborted) {\n return\n }\n\n if (result._ === 'upload.webFile' && result.size && limitBytes === Infinity) {\n limitBytes = result.size\n numChunks = ~~((limitBytes + chunkSize - offset - 1) / chunkSize)\n }\n\n buffer[chunk] = result.bytes\n\n if (chunk === nextChunkIdx) {\n nextChunkCv.notify()\n }\n\n if (nextWorkerChunkIdx < numChunks && result.bytes.length === chunkSize) {\n return downloadChunk()\n }\n }\n\n let error: unknown = undefined\n void Promise.all(Array.from({ length: Math.min(poolSize * REQUESTS_PER_CONNECTION, numChunks) }, downloadChunk))\n .catch((e) => {\n client.log.debug('download workers errored: %s', e.message)\n error = e\n aborted = true // not really aborted, but we dont want to download more chunks\n nextChunkCv.notify()\n })\n .then(() => {\n client.log.debug('download workers finished')\n })\n\n // to avoid MaxListenersExceededWarning we do this instead\n // already sent requests can go to hell (they will get ignored)\n abortSignal?.addEventListener('abort', () => {\n client.log.debug('download aborted')\n error = abortSignal.reason\n aborted = true\n nextChunkCv.notify()\n })\n\n let position = offset\n\n while (position < limitBytes) {\n await nextChunkCv.wait()\n\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n if (error) throw error\n\n while (nextChunkIdx in buffer) {\n const buf = buffer[nextChunkIdx]\n delete buffer[nextChunkIdx]\n\n position += buf.length\n\n params?.progressCallback?.(position, limitBytes)\n\n yield buf\n\n nextChunkIdx++\n\n if (buf.length < chunkSize) {\n // we received the last chunk\n return\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"download-iterable.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/files/download-iterable.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,mCAA+B;AAG/B,sDAAkD;AAClD,wDAA8E;AAC9E,gFAAwE;AAExE,mDAAiG;AACjG,uEAAwG;AACxG,6DAA6D;AAE7D,+EAA+E;AAC/E,yFAAyF;AACzF,oCAAoC;AACpC,MAAM,mBAAmB,GAAG,MAAM,CAAA;AAClC,MAAM,uBAAuB,GAAG,CAAC,CAAA,CAAC,qDAAqD;AAEvF;;;;;;GAMG;AACI,KAAK,SAAS,CAAC,CAAC,kBAAkB,CACrC,MAAuB,EACvB,KAA2B,EAC3B,MAA+B;IAE/B,MAAM,MAAM,GAAG,MAAM,EAAE,MAAM,IAAI,CAAC,CAAA;IAElC,IAAI,MAAM,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC;QACtB,MAAM,IAAI,2BAAe,CAAC,mBAAmB,MAAM,6BAA6B,CAAC,CAAA;IACrF,CAAC;IAED,IAAI,IAAI,GAAG,MAAM,EAAE,IAAI,CAAA;IACvB,IAAI,QAAQ,GAAG,MAAM,EAAE,QAAQ,CAAA;IAE/B,MAAM,WAAW,GAAG,MAAM,EAAE,WAAW,CAAA;IACvC,IAAI,OAAO,GAAG,KAAK,CAAA;IAEnB,IAAI,QAAgE,CAAA;IACpE,IAAI,KAAK,YAAY,uBAAY,EAAE,CAAC;QAChC,IAAI,aAAa,GAAG,KAAK,CAAC,QAAQ,CA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GAAG,IAAI,CAAA;QACd,WAAW,CAAC,MAAM,EAAE,CAAA;IACxB,CAAC,CAAC,CAAA;IAEF,IAAI,QAAQ,GAAG,MAAM,CAAA;IAErB,OAAO,QAAQ,GAAG,UAAU,EAAE,CAAC;QAC3B,MAAM,WAAW,CAAC,IAAI,EAAE,CAAA;QAExB,+DAA+D;QAC/D,IAAI,KAAK;YAAE,MAAM,KAAK,CAAA;QAEtB,OAAO,YAAY,IAAI,MAAM,EAAE,CAAC;YAC5B,MAAM,GAAG,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;YAChC,OAAO,MAAM,CAAC,YAAY,CAAC,CAAA;YAE3B,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAA;YAEtB,MAAM,EAAE,gBAAgB,EAAE,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;YAEhD,MAAM,GAAG,CAAA;YAET,YAAY,EAAE,CAAA;YAEd,IAAI,GAAG,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;gBACzB,6BAA6B;gBAC7B,OAAM;YACV,CAAC;QACL,CAAC;IACL,CAAC;AACL,CAAC;AArMD,gDAqMC","sourcesContent":["import { parseFileId } from '@mtcute/file-id'\nimport { tl } from '@mtcute/tl'\n\nimport { ConnectionKind } from '../../../network/network-manager.js'\nimport { getPlatform } from '../../../platform.js'\nimport { MtArgumentError, MtUnsupportedError } from '../../../types/errors.js'\nimport { ConditionVariable } from '../../../utils/condition-variable.js'\nimport { ITelegramClient } from '../../client.types.js'\nimport { FileDownloadLocation, FileDownloadParameters, FileLocation } from '../../types/index.js'\nimport { fileIdToInputFileLocation, fileIdToInputWebFileLocation } from '../../utils/convert-file-id.js'\nimport { determinePartSize } from '../../utils/file-utils.js'\n\n// small files (less than 128 kb) are downloaded using the \"downloadSmall\" pool\n// furthermore, if the file is small and is located on our main DC, it will be downloaded\n// using the current main connection\nconst SMALL_FILE_MAX_SIZE = 131072\nconst REQUESTS_PER_CONNECTION = 3 // some arbitrary magic value that seems to work best\n\n/**\n * Download a file and return it as an iterable, which yields file contents\n * in chunks of a given size. Order of the chunks is guaranteed to be\n * consecutive.\n *\n * @param params Download parameters\n */\nexport async function* downloadAsIterable(\n client: ITelegramClient,\n input: FileDownloadLocation,\n params?: FileDownloadParameters,\n): AsyncIterableIterator<Uint8Array> {\n const offset = params?.offset ?? 0\n\n if (offset % 4096 !== 0) {\n throw new MtArgumentError(`Invalid offset: ${offset}. Must be divisible by 4096`)\n }\n\n let dcId = params?.dcId\n let fileSize = params?.fileSize\n\n const abortSignal = params?.abortSignal\n let aborted = false\n\n let location: tl.TypeInputFileLocation | tl.TypeInputWebFileLocation\n if (input instanceof FileLocation) {\n let locationInner = input.location\n\n if (typeof locationInner === 'function') {\n locationInner = locationInner()\n }\n\n if (ArrayBuffer.isView(locationInner)) {\n yield locationInner\n\n return\n }\n if (!dcId) dcId = input.dcId\n if (!fileSize) fileSize = input.fileSize\n location = locationInner\n } else if (typeof input === 'string') {\n const parsed = parseFileId(getPlatform(), input)\n\n if (parsed.location._ === 'web') {\n location = fileIdToInputWebFileLocation(parsed)\n } else {\n location = fileIdToInputFileLocation(parsed)\n }\n } else location = input\n\n const isWeb = tl.isAnyInputWebFileLocation(location)\n\n // we will receive a FileMigrateError in case this is invalid\n const primaryDcId = await client.getPrimaryDcId()\n if (!dcId) dcId = primaryDcId\n\n const partSizeKb = params?.partSize ?? (fileSize ? determinePartSize(fileSize) : 64)\n\n if (partSizeKb % 4 !== 0) {\n throw new MtArgumentError(`Invalid part size: ${partSizeKb}. Must be divisible by 4.`)\n }\n\n const chunkSize = partSizeKb * 1024\n\n let limitBytes = params?.limit ?? fileSize ?? Infinity\n if (limitBytes === 0) return\n\n let numChunks = limitBytes === Infinity ? Infinity : ~~((limitBytes + chunkSize - offset - 1) / chunkSize)\n\n let nextChunkIdx = 0\n let nextWorkerChunkIdx = 0\n const nextChunkCv = new ConditionVariable()\n const buffer: Record<number, Uint8Array> = {}\n\n const isSmall = fileSize && fileSize <= SMALL_FILE_MAX_SIZE\n let connectionKind: ConnectionKind\n\n if (isSmall) {\n connectionKind = dcId === primaryDcId ? 'main' : 'downloadSmall'\n } else {\n connectionKind = 'download'\n }\n const poolSize = await client.getPoolSize(connectionKind, dcId)\n\n client.log.debug(\n 'Downloading file of size %d from dc %d using %s connection pool (pool size: %d)',\n limitBytes,\n dcId,\n connectionKind,\n poolSize,\n )\n\n const downloadChunk = async (chunk = nextWorkerChunkIdx++): Promise<void> => {\n let result: tl.RpcCallReturn['upload.getFile'] | tl.RpcCallReturn['upload.getWebFile']\n\n if (aborted) {\n return\n }\n\n try {\n result = await client.call(\n {\n _: isWeb ? 'upload.getWebFile' : 'upload.getFile',\n // eslint-disable-next-line\n location: location as any,\n offset: chunkSize * chunk,\n limit: chunkSize,\n },\n {\n dcId,\n kind: connectionKind,\n maxRetryCount: Infinity, // retry until explicitly aborted (or finished)\n abortSignal,\n },\n )\n } catch (e: unknown) {\n if (e instanceof DOMException && e.name === 'AbortError') return\n if (!tl.RpcError.is(e)) throw e\n\n if (e.is('FILE_MIGRATE_%d')) {\n dcId = e.newDc\n\n return downloadChunk(chunk)\n } else if (e.is('FILEREF_UPGRADE_NEEDED')) {\n // todo: implement someday\n // see: https://github.com/LonamiWebs/Telethon/blob/0e8bd8248cc649637b7c392616887c50986427a0/telethon/client/downloads.py#L99\n throw new MtUnsupportedError('File ref expired!')\n } else throw e\n }\n\n if (result._ === 'upload.fileCdnRedirect') {\n // we shouldnt receive them since cdnSupported is not set in the getFile request.\n // also, i couldnt find any media that would be downloaded from cdn, so even if\n // i implemented that, i wouldnt be able to test that, so :shrug:\n throw new MtUnsupportedError('Received CDN redirect, which is not supported (yet)')\n }\n\n if (aborted) {\n return\n }\n\n if (result._ === 'upload.webFile' && result.size && limitBytes === Infinity) {\n limitBytes = result.size\n numChunks = ~~((limitBytes + chunkSize - offset - 1) / chunkSize)\n }\n\n buffer[chunk] = result.bytes\n\n if (chunk === nextChunkIdx) {\n nextChunkCv.notify()\n }\n\n if (nextWorkerChunkIdx < numChunks && result.bytes.length === chunkSize) {\n return downloadChunk()\n }\n }\n\n let error: unknown = undefined\n void Promise.all(Array.from({ length: Math.min(poolSize * REQUESTS_PER_CONNECTION, numChunks) }, downloadChunk))\n .catch((e) => {\n client.log.debug('download workers errored: %e', e)\n error = e\n aborted = true // not really aborted, but we dont want to download more chunks\n nextChunkCv.notify()\n })\n .then(() => {\n client.log.debug('download workers finished')\n })\n\n // to avoid MaxListenersExceededWarning we do this instead\n // already sent requests can go to hell (they will get ignored)\n abortSignal?.addEventListener('abort', () => {\n client.log.debug('download aborted')\n error = abortSignal.reason\n aborted = true\n nextChunkCv.notify()\n })\n\n let position = offset\n\n while (position < limitBytes) {\n await nextChunkCv.wait()\n\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n if (error) throw error\n\n while (nextChunkIdx in buffer) {\n const buf = buffer[nextChunkIdx]\n delete buffer[nextChunkIdx]\n\n position += buf.length\n\n params?.progressCallback?.(position, limitBytes)\n\n yield buf\n\n nextChunkIdx++\n\n if (buf.length < chunkSize) {\n // we received the last chunk\n return\n }\n }\n }\n}\n"]}
|
|
@@ -55,7 +55,7 @@ async function resolvePeerMany(client, peerIds, normalizer) {
|
|
|
55
55
|
};
|
|
56
56
|
let error = undefined;
|
|
57
57
|
void Promise.all(Array.from({ length: limit }, (_, i) => fetchNext(i))).catch((e) => {
|
|
58
|
-
client.log.debug('resolvePeerMany errored: %
|
|
58
|
+
client.log.debug('resolvePeerMany errored: %e', e);
|
|
59
59
|
error = e;
|
|
60
60
|
cv.notify();
|
|
61
61
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-peer-many.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/users/resolve-peer-many.ts"],"names":[],"mappings":";;;AAEA,gFAAwE;AAExE,qDAA2D;AAE3D,uDAA+C;AAkC/C;;GAEG;AACI,KAAK,UAAU,eAAe,CACjC,MAAuB,EACvB,OAAwB,EACxB,UAAwG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AAC;YACT,IAAI,CAAC,YAAY,+BAAmB,EAAE,CAAC;gBACnC,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;YACtB,CAAC;;gBAAM,MAAM,CAAC,CAAA;QAClB,CAAC;QAED,IAAI,OAAO,KAAK,GAAG,EAAE,CAAC;YAClB,EAAE,CAAC,MAAM,EAAE,CAAA;QACf,CAAC;QAED,IAAI,aAAa,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;YACjC,MAAM,SAAS,CAAC,aAAa,EAAE,CAAC,CAAA;QACpC,CAAC;IACL,CAAC,CAAA;IAED,IAAI,KAAK,GAAY,SAAS,CAAA;IAC9B,KAAK,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;QAChF,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,6BAA6B,EAAE,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"resolve-peer-many.js","sourceRoot":"","sources":["../../../../../src/highlevel/methods/users/resolve-peer-many.ts"],"names":[],"mappings":";;;AAEA,gFAAwE;AAExE,qDAA2D;AAE3D,uDAA+C;AAkC/C;;GAEG;AACI,KAAK,UAAU,eAAe,CACjC,MAAuB,EACvB,OAAwB,EACxB,UAAwG;IAExG,MAAM,GAAG,GAAyE,EAAE,CAAA;IAEpF,MAAM,KAAK,GAAG,CAAC,CAAA;IAEf,IAAI,OAAO,CAAC,MAAM,GAAG,KAAK,EAAE,CAAC;QACzB,gDAAgD;QAChD,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,GAAG,CACzB,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACf,IAAA,6BAAW,EAAC,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC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import { ITelegramClient } from '../../client.types.js'\nimport { MtPeerNotFoundError } from '../../types/errors.js'\nimport { InputPeerLike } from '../../types/peers/index.js'\nimport { resolvePeer } from './resolve-peer.js'\n\n/**\n * Get multiple `InputPeer`s at once,\n * while also normalizing and removing\n * peers that can't be normalized to that type.\n *\n * If a peer was not found, it will be skipped.\n *\n * Uses async pool internally, with a concurrent limit of 8\n *\n * @param peerIds Peer Ids\n * @param normalizer Normalization function\n */\nexport async function resolvePeerMany<T extends tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel>(\n client: ITelegramClient,\n peerIds: InputPeerLike[],\n normalizer: (obj: tl.TypeInputPeer) => T | null,\n): Promise<T[]>\n\n/**\n * Get multiple `InputPeer`s at once.\n *\n * If a peer was not found, `null` will be returned instead\n *\n * Uses async pool internally, with a concurrent limit of 8\n *\n * @param peerIds Peer Ids\n */\nexport async function resolvePeerMany(\n client: ITelegramClient,\n peerIds: InputPeerLike[],\n): Promise<(tl.TypeInputPeer | null)[]>\n\n/**\n * @internal\n */\nexport async function resolvePeerMany(\n client: ITelegramClient,\n peerIds: InputPeerLike[],\n normalizer?: (obj: tl.TypeInputPeer) => tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel | null,\n): Promise<(tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel | null)[]> {\n const ret: (tl.TypeInputPeer | tl.TypeInputUser | tl.TypeInputChannel | null)[] = []\n\n const limit = 8\n\n if (peerIds.length < limit) {\n // no point in using async pool for <limit peers\n const res = await Promise.all(\n peerIds.map((it) =>\n resolvePeer(client, it).catch((e) => {\n if (e instanceof MtPeerNotFoundError) {\n return null\n }\n throw e\n }),\n ),\n )\n\n if (!normalizer) return res\n\n for (const value of res) {\n if (!value) continue\n const norm = normalizer(value)\n\n if (norm) {\n ret.push(norm)\n }\n }\n\n return ret\n }\n\n const cv = new ConditionVariable()\n const buffer: Record<number, tl.TypeInputPeer | null> = {}\n\n let nextIdx = 0\n let nextWorkerIdx = 0\n\n const fetchNext = async (idx = nextWorkerIdx++): Promise<void> => {\n try {\n const result = await resolvePeer(client, peerIds[idx])\n buffer[idx] = result\n } catch (e) {\n if (e instanceof MtPeerNotFoundError) {\n buffer[idx] = null\n } else throw e\n }\n\n if (nextIdx === idx) {\n cv.notify()\n }\n\n if (nextWorkerIdx < peerIds.length) {\n await fetchNext(nextWorkerIdx++)\n }\n }\n\n let error: unknown = undefined\n void Promise.all(Array.from({ length: limit }, (_, i) => fetchNext(i))).catch((e) => {\n client.log.debug('resolvePeerMany errored: %e', e)\n error = e\n cv.notify()\n })\n\n while (nextIdx < peerIds.length) {\n await cv.wait()\n\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n if (error) throw error\n\n while (nextIdx in buffer) {\n const buf = buffer[nextIdx]\n delete buffer[nextIdx]\n\n nextIdx++\n\n if (!normalizer) {\n ret.push(buf)\n continue\n }\n\n if (buf !== null) {\n const norm = normalizer(buf)\n\n if (norm) {\n ret.push(norm)\n }\n }\n }\n }\n\n return ret\n}\n"]}
|
|
@@ -58,9 +58,11 @@ export declare class Dialog {
|
|
|
58
58
|
*/
|
|
59
59
|
get isUnread(): boolean;
|
|
60
60
|
/**
|
|
61
|
-
* Whether this dialog is muted
|
|
61
|
+
* Whether this dialog is muted.
|
|
62
|
+
*
|
|
63
|
+
* If `null`, the default account-level setting should be used.
|
|
62
64
|
*/
|
|
63
|
-
get isMuted(): boolean;
|
|
65
|
+
get isMuted(): boolean | null;
|
|
64
66
|
/**
|
|
65
67
|
* Whether this dialog is archived
|
|
66
68
|
*/
|
|
@@ -153,10 +153,12 @@ class Dialog {
|
|
|
153
153
|
return this.raw.unreadMark || this.raw.unreadCount > 1;
|
|
154
154
|
}
|
|
155
155
|
/**
|
|
156
|
-
* Whether this dialog is muted
|
|
156
|
+
* Whether this dialog is muted.
|
|
157
|
+
*
|
|
158
|
+
* If `null`, the default account-level setting should be used.
|
|
157
159
|
*/
|
|
158
160
|
get isMuted() {
|
|
159
|
-
return this.raw.notifySettings.silent;
|
|
161
|
+
return this.raw.notifySettings.silent ?? null;
|
|
160
162
|
}
|
|
161
163
|
/**
|
|
162
164
|
* Whether this dialog is archived
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dialog.js","sourceRoot":"","sources":["../../../../../src/highlevel/types/messages/dialog.ts"],"names":[],"mappings":";;;AAEA,gEAA8D;AAC9D,0EAAkF;AAClF,mDAAsD;AACtD,uDAAuD;AACvD,8CAAuC;AACvC,4DAAoD;AACpD,yDAAiD;AACjD,6CAAsC;AAStC;;;;;GAKG;AACH,MAAa,MAAM;IAEF;IACA;IACA;IAHb,YACa,GAAiB,EACjB,MAAkB,EAClB,SAAsC;QAFtC,QAAG,GAAH,GAAG,CAAc;QACjB,WAAM,GAAN,MAAM,CAAY;QAClB,cAAS,GAAT,SAAS,CAA6B;IAChD,CAAC;IAEJ;;;;;;OAMG;IACH,MAAM,CAAC,cAAc,CAAC,OAA8D,EAAE,KAAc;QAChG,IAAA,oCAAe,EAAC,cAAc,EAAE,OAAO,EAAE,6BAA6B,CAAC,CAAA;QAEvE,MAAM,KAAK,GAAG,2BAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAEtC,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAA;QAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YAC7B,IAAI,CAAC,GAAG,CAAC,MAAM;gBAAE,OAAM;YAEvB,QAAQ,CAAC,GAAG,CAAC,IAAA,+BAAe,EAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,CAAA;QAClD,CAAC,CAAC,CAAA;QAEF,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,IAAA,kCAAa,EAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,EAAE,EAAE,KAAK,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C,KAAK,cAAc,EAAE,CAAC;YACvC,OAAO,IAAI,+BAAY,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC3C,CAAC;QAED,OAAO,IAAI,CAAA;IACf,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,IAAI,IAAI,CAAA;IACrC,CAAC;CACJ;AAtPD,wBAsPC;AAED,IAAA,2BAAc,EAAC,MAAM,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC,CAAA;AAC/D,IAAA,0BAAe,EAAC,MAAM,CAAC,CAAA","sourcesContent":["import { tl } from '@mtcute/tl'\n\nimport { getMarkedPeerId } from '../../../utils/peer-utils.js'\nimport { assertTypeIsNot, hasValueAtKey } from '../../../utils/type-assertions.js'\nimport { makeInspectable } from '../../utils/index.js'\nimport { memoizeGetters } from '../../utils/memoize.js'\nimport { Chat } from '../peers/chat.js'\nimport { PeersIndex } from '../peers/peers-index.js'\nimport { DraftMessage } from './draft-message.js'\nimport { Message } from './message.js'\n\n/**\n * Type used as an input for a folder in client methods\n *\n * You can pass folder object, id or title\n */\nexport type InputDialogFolder = string | number | tl.RawDialogFilter\n\n/**\n * A dialog.\n *\n * Think of it as something that is listed\n * in Telegram's main window.\n */\nexport class Dialog {\n constructor(\n readonly raw: tl.RawDialog,\n readonly _peers: PeersIndex,\n readonly _messages: Map<number, tl.TypeMessage>,\n ) {}\n\n /**\n * Parse a list of dialogs from a TL object\n *\n * @param client Client instance\n * @param dialogs TL object\n * @param limit Maximum number of dialogs to parse\n */\n static parseTlDialogs(dialogs: tl.messages.TypeDialogs | tl.messages.TypePeerDialogs, limit?: number): Dialog[] {\n assertTypeIsNot('parseDialogs', dialogs, 'messages.dialogsNotModified')\n\n const peers = PeersIndex.from(dialogs)\n\n const messages = new Map<number, tl.TypeMessage>()\n dialogs.messages.forEach((msg) => {\n if (!msg.peerId) return\n\n messages.set(getMarkedPeerId(msg.peerId), msg)\n })\n\n const arr = dialogs.dialogs.filter(hasValueAtKey('_', 'dialog')).map((it) => new Dialog(it, peers, messages))\n\n if (limit) {\n return arr.slice(0, limit)\n }\n\n return arr\n }\n\n /**\n * Find pinned dialogs from a list of dialogs\n *\n * @param dialogs Dialogs list\n * @param folder If passed, status of pin will be checked against this folder, and not globally\n */\n static findPinned(dialogs: Dialog[], folder?: tl.RawDialogFilter): Dialog[] {\n if (folder) {\n const index: Record<number, true> = {}\n folder.pinnedPeers.forEach((peer) => {\n index[getMarkedPeerId(peer)] = true\n })\n\n return dialogs.filter((i) => index[i.chat.id])\n }\n\n return dialogs.filter((i) => i.isPinned)\n }\n\n /**\n * Create a filter predicate for the given Folder.\n * Returned predicate can be used in `Array.filter()`\n *\n * @param folder Folder to filter for\n * @param excludePinned Whether to exclude pinned folders\n */\n static filterFolder(folder: tl.TypeDialogFilter, excludePinned = true): (val: Dialog) => boolean {\n if (folder._ === 'dialogFilterDefault') {\n return () => true\n }\n\n const pinned: Record<number, true> = {}\n const include: Record<number, true> = {}\n const exclude: Record<number, true> = {}\n\n // populate indices\n if (excludePinned) {\n folder.pinnedPeers.forEach((peer) => {\n pinned[getMarkedPeerId(peer)] = true\n })\n }\n folder.includePeers.forEach((peer) => {\n include[getMarkedPeerId(peer)] = true\n })\n\n if (folder._ === 'dialogFilterChatlist') {\n return (dialog) => {\n const chatId = dialog.chat.id\n\n if (excludePinned && pinned[chatId]) return false\n\n return include[chatId] || pinned[chatId]\n }\n }\n\n folder.excludePeers.forEach((peer) => {\n exclude[getMarkedPeerId(peer)] = true\n })\n\n return (dialog) => {\n const chat = dialog.chat\n const chatId = dialog.chat.id\n const chatType = dialog.chat.chatType\n\n // manual exclusion/inclusion and pins\n if (include[chatId]) return true\n\n if (exclude[chatId] || (excludePinned && pinned[chatId])) {\n return false\n }\n\n // exclusions based on status\n if (folder.excludeRead && !dialog.isUnread) return false\n if (folder.excludeMuted && dialog.isMuted) return false\n // even though this was handled in getDialogs, this method\n // could be used outside of it, so check again\n if (folder.excludeArchived && dialog.isArchived) return false\n\n // inclusions based on chat type\n if (folder.contacts && chatType === 'private' && chat.isContact) {\n return true\n }\n if (folder.nonContacts && chatType === 'private' && !chat.isContact) {\n return true\n }\n if (folder.groups && (chatType === 'group' || chatType === 'supergroup')) {\n return true\n }\n if (folder.broadcasts && chatType === 'channel') return true\n if (folder.bots && chatType === 'bot') return true\n\n return false\n }\n }\n\n /**\n * Whether this dialog is pinned\n */\n get isPinned(): boolean {\n return this.raw.pinned!\n }\n\n /**\n * Whether this chat was manually marked as unread\n */\n get isManuallyUnread(): boolean {\n return this.raw.unreadMark!\n }\n\n /**\n * Whether this chat should be considered unread\n * (i.e. has more than 1 unread message, or has\n * a \"manually unread\" mark)\n */\n get isUnread(): boolean {\n return this.raw.unreadMark || this.raw.unreadCount > 1\n }\n\n /**\n * Whether this dialog is muted\n */\n get isMuted(): boolean {\n return this.raw.notifySettings.silent!\n }\n\n /**\n * Whether this dialog is archived\n */\n get isArchived(): boolean {\n return this.raw.folderId === 1\n }\n\n /**\n * Chat that this dialog represents\n */\n get chat(): Chat {\n return Chat._parseFromPeer(this.raw.peer, this._peers)\n }\n\n /**\n * The latest message sent in this chat (if any)\n */\n get lastMessage(): Message | null {\n const cid = this.chat.id\n\n if (this._messages.has(cid)) {\n return new Message(this._messages.get(cid)!, this._peers)\n }\n\n return null\n }\n\n /**\n * ID of the last read outgoing message in this dialog\n */\n get lastReadOutgoing(): number {\n return this.raw.readOutboxMaxId\n }\n\n /**\n * ID of the last read ingoing message in this dialog\n */\n get lastReadIngoing(): number {\n return this.raw.readInboxMaxId\n }\n\n /**\n * ID of the last read message in this dialog\n */\n get lastRead(): number {\n return Math.max(this.raw.readOutboxMaxId, this.raw.readInboxMaxId)\n }\n\n /**\n * Number of unread messages\n */\n get unreadCount(): number {\n return this.raw.unreadCount\n }\n\n /**\n * Number of unread mentions\n */\n get unreadMentionsCount(): number {\n return this.raw.unreadMentionsCount\n }\n\n /**\n * Number of unread reactions\n */\n get unreadReactionsCount(): number {\n return this.raw.unreadReactionsCount\n }\n\n /**\n * Draft message in this dialog\n */\n get draftMessage(): DraftMessage | null {\n if (this.raw.draft?._ === 'draftMessage') {\n return new DraftMessage(this.raw.draft)\n }\n\n return null\n }\n\n /**\n * TTL period of all messages in this dialog\n */\n get ttlPeriod(): number | null {\n return this.raw.ttlPeriod ?? null\n }\n}\n\nmemoizeGetters(Dialog, ['chat', 'lastMessage', 'draftMessage'])\nmakeInspectable(Dialog)\n"]}
|
|
1
|
+
{"version":3,"file":"dialog.js","sourceRoot":"","sources":["../../../../../src/highlevel/types/messages/dialog.ts"],"names":[],"mappings":";;;AAEA,gEAA8D;AAC9D,0EAAkF;AAClF,mDAAsD;AACtD,uDAAuD;AACvD,8CAAuC;AACvC,4DAAoD;AACpD,yDAAiD;AACjD,6CAAsC;AAStC;;;;;GAKG;AACH,MAAa,MAAM;IAEF;IACA;IACA;IAHb,YACa,GAAiB,EACjB,MAAkB,EAClB,SAAsC;QAFtC,QAAG,GAAH,GAAG,CAAc;QACjB,WAAM,GAAN,MAAM,CAAY;QAClB,cAAS,GAAT,SAAS,CAA6B;IAChD,CAAC;IAEJ;;;;;;OAMG;IACH,MAAM,CAAC,cAAc,CAAC,OAA8D,EAAE,KAAc;QAChG,IAAA,oCAAe,EAAC,cAAc,EAAE,OAAO,EAAE,6BAA6B,CAAC,CAAA;QAEvE,MAAM,KAAK,GAAG,2BAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAEtC,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAA;QAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YAC7B,IAAI,CAAC,GAAG,CAAC,MAAM;gBAAE,OAAM;YAEvB,QAAQ,CAAC,GAAG,CAAC,IAAA,+BAAe,EAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,CAAA;QAClD,CAAC,CAA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AC,GAAG,CAAC,mBAAmB,CAAA;IACvC,CAAC;IAED;;OAEG;IACH,IAAI,oBAAoB;QACpB,OAAO,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAA;IACxC,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACZ,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,KAAK,cAAc,EAAE,CAAC;YACvC,OAAO,IAAI,+BAAY,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC3C,CAAC;QAED,OAAO,IAAI,CAAA;IACf,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,IAAI,IAAI,CAAA;IACrC,CAAC;CACJ;AAxPD,wBAwPC;AAED,IAAA,2BAAc,EAAC,MAAM,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC,CAAA;AAC/D,IAAA,0BAAe,EAAC,MAAM,CAAC,CAAA","sourcesContent":["import { tl } from '@mtcute/tl'\n\nimport { getMarkedPeerId } from '../../../utils/peer-utils.js'\nimport { assertTypeIsNot, hasValueAtKey } from '../../../utils/type-assertions.js'\nimport { makeInspectable } from '../../utils/index.js'\nimport { memoizeGetters } from '../../utils/memoize.js'\nimport { Chat } from '../peers/chat.js'\nimport { PeersIndex } from '../peers/peers-index.js'\nimport { DraftMessage } from './draft-message.js'\nimport { Message } from './message.js'\n\n/**\n * Type used as an input for a folder in client methods\n *\n * You can pass folder object, id or title\n */\nexport type InputDialogFolder = string | number | tl.RawDialogFilter\n\n/**\n * A dialog.\n *\n * Think of it as something that is listed\n * in Telegram's main window.\n */\nexport class Dialog {\n constructor(\n readonly raw: tl.RawDialog,\n readonly _peers: PeersIndex,\n readonly _messages: Map<number, tl.TypeMessage>,\n ) {}\n\n /**\n * Parse a list of dialogs from a TL object\n *\n * @param client Client instance\n * @param dialogs TL object\n * @param limit Maximum number of dialogs to parse\n */\n static parseTlDialogs(dialogs: tl.messages.TypeDialogs | tl.messages.TypePeerDialogs, limit?: number): Dialog[] {\n assertTypeIsNot('parseDialogs', dialogs, 'messages.dialogsNotModified')\n\n const peers = PeersIndex.from(dialogs)\n\n const messages = new Map<number, tl.TypeMessage>()\n dialogs.messages.forEach((msg) => {\n if (!msg.peerId) return\n\n messages.set(getMarkedPeerId(msg.peerId), msg)\n })\n\n const arr = dialogs.dialogs.filter(hasValueAtKey('_', 'dialog')).map((it) => new Dialog(it, peers, messages))\n\n if (limit) {\n return arr.slice(0, limit)\n }\n\n return arr\n }\n\n /**\n * Find pinned dialogs from a list of dialogs\n *\n * @param dialogs Dialogs list\n * @param folder If passed, status of pin will be checked against this folder, and not globally\n */\n static findPinned(dialogs: Dialog[], folder?: tl.RawDialogFilter): Dialog[] {\n if (folder) {\n const index: Record<number, true> = {}\n folder.pinnedPeers.forEach((peer) => {\n index[getMarkedPeerId(peer)] = true\n })\n\n return dialogs.filter((i) => index[i.chat.id])\n }\n\n return dialogs.filter((i) => i.isPinned)\n }\n\n /**\n * Create a filter predicate for the given Folder.\n * Returned predicate can be used in `Array.filter()`\n *\n * @param folder Folder to filter for\n * @param excludePinned Whether to exclude pinned folders\n */\n static filterFolder(folder: tl.TypeDialogFilter, excludePinned = true): (val: Dialog) => boolean {\n if (folder._ === 'dialogFilterDefault') {\n return () => true\n }\n\n const pinned: Record<number, true> = {}\n const include: Record<number, true> = {}\n const exclude: Record<number, true> = {}\n\n // populate indices\n if (excludePinned) {\n folder.pinnedPeers.forEach((peer) => {\n pinned[getMarkedPeerId(peer)] = true\n })\n }\n folder.includePeers.forEach((peer) => {\n include[getMarkedPeerId(peer)] = true\n })\n\n if (folder._ === 'dialogFilterChatlist') {\n return (dialog) => {\n const chatId = dialog.chat.id\n\n if (excludePinned && pinned[chatId]) return false\n\n return include[chatId] || pinned[chatId]\n }\n }\n\n folder.excludePeers.forEach((peer) => {\n exclude[getMarkedPeerId(peer)] = true\n })\n\n return (dialog) => {\n const chat = dialog.chat\n const chatId = dialog.chat.id\n const chatType = dialog.chat.chatType\n\n // manual exclusion/inclusion and pins\n if (include[chatId]) return true\n\n if (exclude[chatId] || (excludePinned && pinned[chatId])) {\n return false\n }\n\n // exclusions based on status\n if (folder.excludeRead && !dialog.isUnread) return false\n if (folder.excludeMuted && dialog.isMuted) return false\n // even though this was handled in getDialogs, this method\n // could be used outside of it, so check again\n if (folder.excludeArchived && dialog.isArchived) return false\n\n // inclusions based on chat type\n if (folder.contacts && chatType === 'private' && chat.isContact) {\n return true\n }\n if (folder.nonContacts && chatType === 'private' && !chat.isContact) {\n return true\n }\n if (folder.groups && (chatType === 'group' || chatType === 'supergroup')) {\n return true\n }\n if (folder.broadcasts && chatType === 'channel') return true\n if (folder.bots && chatType === 'bot') return true\n\n return false\n }\n }\n\n /**\n * Whether this dialog is pinned\n */\n get isPinned(): boolean {\n return this.raw.pinned!\n }\n\n /**\n * Whether this chat was manually marked as unread\n */\n get isManuallyUnread(): boolean {\n return this.raw.unreadMark!\n }\n\n /**\n * Whether this chat should be considered unread\n * (i.e. has more than 1 unread message, or has\n * a \"manually unread\" mark)\n */\n get isUnread(): boolean {\n return this.raw.unreadMark || this.raw.unreadCount > 1\n }\n\n /**\n * Whether this dialog is muted.\n *\n * If `null`, the default account-level setting should be used.\n */\n get isMuted(): boolean | null {\n return this.raw.notifySettings.silent ?? null\n }\n\n /**\n * Whether this dialog is archived\n */\n get isArchived(): boolean {\n return this.raw.folderId === 1\n }\n\n /**\n * Chat that this dialog represents\n */\n get chat(): Chat {\n return Chat._parseFromPeer(this.raw.peer, this._peers)\n }\n\n /**\n * The latest message sent in this chat (if any)\n */\n get lastMessage(): Message | null {\n const cid = this.chat.id\n\n if (this._messages.has(cid)) {\n return new Message(this._messages.get(cid)!, this._peers)\n }\n\n return null\n }\n\n /**\n * ID of the last read outgoing message in this dialog\n */\n get lastReadOutgoing(): number {\n return this.raw.readOutboxMaxId\n }\n\n /**\n * ID of the last read ingoing message in this dialog\n */\n get lastReadIngoing(): number {\n return this.raw.readInboxMaxId\n }\n\n /**\n * ID of the last read message in this dialog\n */\n get lastRead(): number {\n return Math.max(this.raw.readOutboxMaxId, this.raw.readInboxMaxId)\n }\n\n /**\n * Number of unread messages\n */\n get unreadCount(): number {\n return this.raw.unreadCount\n }\n\n /**\n * Number of unread mentions\n */\n get unreadMentionsCount(): number {\n return this.raw.unreadMentionsCount\n }\n\n /**\n * Number of unread reactions\n */\n get unreadReactionsCount(): number {\n return this.raw.unreadReactionsCount\n }\n\n /**\n * Draft message in this dialog\n */\n get draftMessage(): DraftMessage | null {\n if (this.raw.draft?._ === 'draftMessage') {\n return new DraftMessage(this.raw.draft)\n }\n\n return null\n }\n\n /**\n * TTL period of all messages in this dialog\n */\n get ttlPeriod(): number | null {\n return this.raw.ttlPeriod ?? null\n }\n}\n\nmemoizeGetters(Dialog, ['chat', 'lastMessage', 'draftMessage'])\nmakeInspectable(Dialog)\n"]}
|
|
@@ -344,6 +344,20 @@ export interface ActionBoostApply {
|
|
|
344
344
|
/** Number of boosts applied */
|
|
345
345
|
count: number;
|
|
346
346
|
}
|
|
347
|
-
|
|
347
|
+
/** A payment was refunded */
|
|
348
|
+
export interface ActionPaymentRefunded {
|
|
349
|
+
readonly type: 'payment_refunded';
|
|
350
|
+
/** Three-letter ISO 4217 currency code */
|
|
351
|
+
currency: string;
|
|
352
|
+
/** Marked ID of the peer where the stars were refunded (?) */
|
|
353
|
+
peerId: number;
|
|
354
|
+
/** Number of `currency` refunded, in the smallest unit */
|
|
355
|
+
amount: tl.Long;
|
|
356
|
+
/** Payload defined by the bot */
|
|
357
|
+
payload?: Uint8Array;
|
|
358
|
+
/** Information about the charge */
|
|
359
|
+
charge: tl.TypePaymentCharge;
|
|
360
|
+
}
|
|
361
|
+
export type MessageAction = ActionChatCreated | ActionChannelCreated | ActionChatMigrateTo | ActionChannelMigrateFrom | ActionMessagePinned | ActionHistoryCleared | ActionGameScore | ActionContactJoined | ActionTitleChanged | ActionPhotoChanged | ActionPhotoDeleted | ActionUsersAdded | ActionUserLeft | ActionUserRemoved | ActionUserJoinedLink | ActionPaymentReceived | ActionPaymentSent | ActionCall | ActionScreenshotTaken | ActionBotAllowed | ActionGeoProximity | ActionGroupCallStarted | ActionGroupCallEnded | ActionGroupCallScheduled | ActionGroupInvite | ActionTtlChanged | ActionTopicCreated | ActionTopicEdited | ActionCustom | ActionThemeChanged | ActionUserJoinedApproved | ActionWebviewDataSent | ActionWebviewDataReceived | ActionPremiumGifted | ActionPhotoSuggested | ActionPeerSent | ActionPeerChosen | ActionWallpaperChanged | ActionGiftCode | ActionGiveawayStarted | ActionGiveawayEnded | ActionBoostApply | ActionPaymentRefunded | null;
|
|
348
362
|
/** @internal */
|
|
349
363
|
export declare function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): MessageAction;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports._messageActionFromTl = void 0;
|
|
4
|
+
const peer_utils_js_1 = require("../../../utils/peer-utils.js");
|
|
4
5
|
const index_js_1 = require("../calls/index.js");
|
|
5
6
|
const photo_js_1 = require("../media/photo.js");
|
|
6
7
|
const peer_js_1 = require("../peers/peer.js");
|
|
@@ -253,6 +254,15 @@ function _messageActionFromTl(act) {
|
|
|
253
254
|
type: 'boost_apply',
|
|
254
255
|
count: act.boosts,
|
|
255
256
|
};
|
|
257
|
+
case 'messageActionPaymentRefunded':
|
|
258
|
+
return {
|
|
259
|
+
type: 'payment_refunded',
|
|
260
|
+
currency: act.currency,
|
|
261
|
+
peerId: (0, peer_utils_js_1.getMarkedPeerId)(act.peer),
|
|
262
|
+
amount: act.totalAmount,
|
|
263
|
+
payload: act.payload,
|
|
264
|
+
charge: act.charge,
|
|
265
|
+
};
|
|
256
266
|
default:
|
|
257
267
|
return null;
|
|
258
268
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-action.js","sourceRoot":"","sources":["../../../../../src/highlevel/types/messages/message-action.ts"],"names":[],"mappings":";;;AAEA,gDAA+E;AAC/E,gDAAyC;AACzC,8CAAkD;AAgflD,gBAAgB;AAChB,SAAgB,oBAAoB,CAAgB,GAAyB;IACzE,kBAAkB;IAClB,6GAA6G;IAC7G,uEAAuE;IAEvE,QAAQ,GAAG,CAAC,CAAC,EAAE,CAAC;QACZ,KAAK,yBAAyB;YAC1B,OAAO;gBACH,IAAI,EAAE,cAAc;gBACpB,KAAK,EAAE,GAAG,CAAC,KAAK;gBAChB,KAAK,EAAE,GAAG,CAAC,KAAK;aACnB,CAAA;QACL,KAAK,4BAA4B;YAC7B,OAAO;gBACH,IAAI,EAAE,iBAAiB;gBACvB,KAAK,EAAE,GAAG,CAAC,KAAK;aACnB,CAAA;QACL,KAAK,4BAA4B;YAC7B,OAAO;gBACH,IAAI,EAAE,iBAAiB;gBACvB,EAAE,EAAE,GAAG,CAAC,SAAS;aACpB,CAAA;QACL,KAAK,iCAAiC;YAClC,OAAO;gBACH,IAAI,EAAE,sBAAsB;gBAC5B,EAAE,EAAE,GAAG,CAAC,MAAM;gBACd,KAAK,EAAE,GAAG,CAAC,KAAK;aACnB,CAAA;QACL,KAAK,yBAAyB;YAC1B,OAAO;gBACH,IAAI,EAAE,gBAAgB;aACzB,CAAA;QACL,KAAK,2BAA2B;YAC5B,OAAO;gBACH,IAAI,EAAE,iBAAiB;aAC1B,CAAA;QACL,KAAK,wBAAwB;YACzB,OAAO;gBACH,IAAI,EAAE,YAAY;gBAClB,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,KAAK,EAAE,GAAG,CAAC,KAAK;aACnB,CAAA;QACL,KAAK,4BAA4B;YAC7B,OAAO;gBACH,IAAI,EAAE,gBAAgB;aACzB,CAAA;QACL,KAAK,4BAA4B;YAC7B,OAAO;gBACH,IAAI,EAAE,eAAe;gBACrB,KAAK,EAAE,GAAG,CAAC,KAAK;aACnB,CAAA;QACL,KAAK,4BAA4B;YAC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E,kBAAkB;aAC3B,CAAA;QACL,KAAK,8BAA8B;YAC/B,OAAO;gBACH,IAAI,EAAE,gBAAgB;gBACtB,OAAO,EAAE,GAAG,CAAC,YAAY;gBACzB,aAAa,EAAE,GAAG,CAAC,cAAc;aACpC,CAAA;QACL,KAAK,yBAAyB;YAC1B,OAAO;gBACH,IAAI,EAAE,aAAa;gBACnB,KAAK,EAAE,GAAG,CAAC,MAAM;aACpB,CAAA;QACL;YACI,OAAO,IAAI,CAAA;IACnB,CAAC;AACL,CAAC;AAjQD,oDAiQC","sourcesContent":["import { tl } from '@mtcute/tl'\n\nimport { _callDiscardReasonFromTl, CallDiscardReason } from '../calls/index.js'\nimport { Photo } from '../media/photo.js'\nimport { parsePeer, Peer } from '../peers/peer.js'\nimport type { Message } from './message.js'\n\n/** Group was created */\nexport interface ActionChatCreated {\n readonly type: 'chat_created'\n\n /** Group name */\n readonly title: string\n\n /** IDs of the users in the group */\n readonly users: number[]\n}\n\n/** Channel/supergroup was created */\nexport interface ActionChannelCreated {\n readonly type: 'channel_created'\n\n /** Original channel/supergroup title */\n readonly title: string\n}\n\n/** Chat was migrated to a supergroup with a given ID */\nexport interface ActionChatMigrateTo {\n readonly type: 'chat_migrate_to'\n\n /** Marked ID of the supergroup chat was migrated to */\n readonly id: number\n}\n\n/** Supergroup was migrated from a chat with a given ID */\nexport interface ActionChannelMigrateFrom {\n readonly type: 'channel_migrate_from'\n\n /** Marked ID of the chat this channel was migrated from */\n readonly id: number\n\n /** Old chat's title */\n readonly title: string\n}\n\n/**\n * A message has been pinned.\n *\n * To get the message itself, use {@link Message.getReplyTo}\n */\nexport interface ActionMessagePinned {\n readonly type: 'message_pinned'\n}\n\n/** History was cleared in a private chat. */\nexport interface ActionHistoryCleared {\n readonly type: 'history_cleared'\n}\n\n/** Someone scored in a game (usually only used for newly set high scores) */\nexport interface ActionGameScore {\n readonly type: 'game_score'\n\n /** Game ID */\n readonly gameId: tl.Long\n\n /** Score */\n readonly score: number\n}\n\n/** Contact has joined Telegram */\nexport interface ActionContactJoined {\n readonly type: 'contact_joined'\n}\n\n/** Group title was changed */\nexport interface ActionTitleChanged {\n readonly type: 'title_changed'\n\n /** New group name */\n readonly title: string\n}\n\n/** Group photo was changed */\nexport interface ActionPhotoChanged {\n readonly type: 'photo_changed'\n\n /** New group photo */\n readonly photo: Photo\n}\n\n/** Group photo was deleted */\nexport interface ActionPhotoDeleted {\n readonly type: 'photo_deleted'\n}\n\n/** Users were added to the chat */\nexport interface ActionUsersAdded {\n readonly type: 'users_added'\n\n /** IDs of the users that were added */\n readonly users: number[]\n}\n\n/** User has left the group */\nexport interface ActionUserLeft {\n readonly type: 'user_left'\n}\n\n/** User was removed from the group */\nexport interface ActionUserRemoved {\n readonly type: 'user_removed'\n\n /** ID of the user that was removed from the group */\n readonly user: number\n}\n\n/** User has joined the group via an invite link */\nexport interface ActionUserJoinedLink {\n readonly type: 'user_joined_link'\n\n /** ID of the user who created the link */\n readonly inviter: number\n}\n\n/**\n * User has joined the group via an invite link\n * and was approved by an administrator\n */\nexport interface ActionUserJoinedApproved {\n readonly type: 'user_joined_approved'\n}\n\n/** A payment was received from a user (bot) */\nexport interface ActionPaymentReceived {\n readonly type: 'payment_received'\n\n /** Three-letter ISO 4217 currency code */\n readonly currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n readonly amount: tl.Long\n\n /** Bot specified invoice payload */\n readonly payload: Uint8Array\n\n /** Order information provided by the user */\n readonly info?: tl.TypePaymentRequestedInfo\n\n /** ID of the shipping option chosen by the user */\n readonly shippingOptionId?: string\n\n /** Payment provider ID */\n readonly charge?: tl.TypePaymentCharge\n}\n\n/** A payment was sent to a user */\nexport interface ActionPaymentSent {\n readonly type: 'payment_sent'\n\n /** Three-letter ISO 4217 currency code */\n readonly currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n readonly amount: tl.Long\n}\n\n/** A phone call */\nexport interface ActionCall {\n readonly type: 'call'\n\n /** Call ID */\n readonly id: tl.Long\n\n /** Whether this is a video call */\n readonly isVideo: boolean\n\n /** Duration if the call in seconds (0 if not available) */\n readonly duration: number\n\n /** Call discard reason, if available */\n readonly reason?: CallDiscardReason\n}\n\n/** A screenshot was taken */\nexport interface ActionScreenshotTaken {\n readonly type: 'screenshot_taken'\n}\n\n/** User has authorized via the bot */\nexport interface ActionBotAllowed {\n readonly type: 'bot_allowed'\n\n /** Domain where the user has logged in */\n readonly domain?: string\n}\n\n/**\n * A user is in proximity of another user\n * (see [Proximity alerts](https://core.telegram.org/api/live-location#proximity-alert))\n */\nexport interface ActionGeoProximity {\n readonly type: 'geo_proximity'\n\n /** ID of the user who sent the geolocation with proximity alerts */\n readonly targetId: number\n\n /** ID of the user who has approached `targetId` */\n readonly userId: number\n\n /** Distance between them in meters */\n readonly distance: number\n}\n\n/** Group call has started */\nexport interface ActionGroupCallStarted {\n readonly type: 'group_call_started'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n}\n\n/** Group call has ended */\nexport interface ActionGroupCallEnded {\n readonly type: 'group_call_ended'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** Duration of the call */\n readonly duration: number\n}\n\n/** Group call has been scheduled */\nexport interface ActionGroupCallScheduled {\n readonly type: 'group_call_scheduled'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** Date when the call will start */\n readonly date: Date\n}\n\n/** Group call has ended */\nexport interface ActionGroupInvite {\n readonly type: 'group_call_invite'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** IDs of the users invited to the call */\n readonly userIds: number[]\n}\n\n/** Messages TTL changed */\nexport interface ActionTtlChanged {\n readonly type: 'ttl_changed'\n\n /** New TTL period */\n readonly period: number\n}\n\n/** Forum topic was created */\nexport interface ActionTopicCreated {\n readonly type: 'topic_created'\n\n /** Title of the topic */\n title: string\n\n /** Icon color of the topic */\n iconColor: number\n\n /** Icon emoji of the topic */\n iconCustomEmoji?: tl.Long\n}\n\n/** Forum topic was modified */\nexport interface ActionTopicEdited {\n readonly type: 'topic_edited'\n\n /** New title of the topic */\n title?: string\n\n /** New icon emoji of the topic (may be empty) */\n iconCustomEmoji?: tl.Long\n\n /** Whether the topic was opened/closed */\n closed?: boolean\n\n /** Whether the topic was (un-)hidden - only for \"General\" topic (`id=1`) */\n hidden?: boolean\n}\n\n/** A non-standard action has happened in the chat */\nexport interface ActionCustom {\n readonly type: 'custom'\n\n /** Text to be shown in the interface */\n action: string\n}\n\n/** Chat theme was changed */\nexport interface ActionThemeChanged {\n readonly type: 'theme_changed'\n\n /** Emoji representing the new theme */\n emoji: string\n}\n\n/** Data was sent from a WebView (user-side action) */\nexport interface ActionWebviewDataSent {\n readonly type: 'webview_sent'\n\n /** Text of the button that was pressed to open the WebView */\n text: string\n}\n\n/** Data was received from a WebView (bot-side action) */\nexport interface ActionWebviewDataReceived {\n readonly type: 'webview_received'\n\n /** Text of the button that was pressed to open the WebView */\n text: string\n\n /** Data received from the WebView */\n data: string\n}\n\n/** Premium subscription was gifted */\nexport interface ActionPremiumGifted {\n readonly type: 'premium_gifted'\n\n /**\n * Currency in which it was paid for.\n * Three-letter ISO 4217 currency code)\n */\n currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n amount: number\n\n /** Duration of the gifted subscription in months */\n months: number\n\n /** If the subscription was bought with crypto, information about it */\n crypto?: {\n /** Crypto currency name */\n currency: string\n /** Price in the smallest units */\n amount: number\n }\n}\n\n/** A photo has been suggested as a profile photo */\nexport interface ActionPhotoSuggested {\n readonly type: 'photo_suggested'\n\n /** Photo that was suggested */\n photo: Photo\n}\n\n/**\n * A peer was chosen by the user after clicking on a RequestPeer button.\n * The user-side version of {@link ActionPeerChosen}\n */\nexport interface ActionPeerSent {\n readonly type: 'peer_sent'\n\n /** ID of the button passed earlier by the bot */\n buttonId: number\n\n /** Brief information about the chosen peers */\n peers: tl.TypeRequestedPeer[]\n}\n\n/**\n * A peer was chosen by the user after clicking on a RequestPeer button\n * The bot-side version of {@link ActionPeerSent}\n */\nexport interface ActionPeerChosen {\n readonly type: 'peer_chosen'\n\n /** ID of the button passed earlier by the bot */\n buttonId: number\n\n /** Chosen peers */\n peers: Peer[]\n}\n\n/** A wallpaper of the chathas been changed */\nexport interface ActionWallpaperChanged {\n readonly type: 'wallpaper_changed'\n\n /**\n * Whether the user has applied the same wallpaper\n * as the other party previously set in the chat\n */\n same: boolean\n\n /**\n * Whether the wallpaper was forcefully applied for\n * both sides, without explicit confirmation from the other\n * side.\n */\n forBoth: boolean\n\n /** TL object representing the new wallpaper */\n wallpaper: tl.TypeWallPaper\n}\n\n/** A Telergam Premium gift code was received */\nexport interface ActionGiftCode {\n readonly type: 'gift_code'\n\n /** Information about the gift code */\n raw: tl.RawMessageActionGiftCode\n}\n\n/** A Telergam Premium giveaway was started */\nexport interface ActionGiveawayStarted {\n readonly type: 'giveaway_started'\n}\n\n/** A Telergam Premium giveaway was ended and results are available */\nexport interface ActionGiveawayEnded {\n readonly type: 'giveaway_ended'\n\n /** Number of winners in the giveaway */\n winners: number\n\n /** Number of undistributed prizes */\n undistributed: number\n}\n\n/** Boosts were applied to the group */\nexport interface ActionBoostApply {\n readonly type: 'boost_apply'\n\n /** Number of boosts applied */\n count: number\n}\n\nexport type MessageAction =\n | ActionChatCreated\n | ActionChannelCreated\n | ActionChatMigrateTo\n | ActionChannelMigrateFrom\n | ActionMessagePinned\n | ActionHistoryCleared\n | ActionGameScore\n | ActionContactJoined\n | ActionTitleChanged\n | ActionPhotoChanged\n | ActionPhotoDeleted\n | ActionUsersAdded\n | ActionUserLeft\n | ActionUserRemoved\n | ActionUserJoinedLink\n | ActionPaymentReceived\n | ActionPaymentSent\n | ActionCall\n | ActionScreenshotTaken\n | ActionBotAllowed\n | ActionGeoProximity\n | ActionGroupCallStarted\n | ActionGroupCallEnded\n | ActionGroupCallScheduled\n | ActionGroupInvite\n | ActionTtlChanged\n | ActionTopicCreated\n | ActionTopicEdited\n | ActionCustom\n | ActionThemeChanged\n | ActionUserJoinedApproved\n | ActionWebviewDataSent\n | ActionWebviewDataReceived\n | ActionPremiumGifted\n | ActionPhotoSuggested\n | ActionPeerSent\n | ActionPeerChosen\n | ActionWallpaperChanged\n | ActionGiftCode\n | ActionGiveawayStarted\n | ActionGiveawayEnded\n | ActionBoostApply\n | null\n\n/** @internal */\nexport function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): MessageAction {\n // todo - passport\n // messageActionSecureValuesSentMe#1b287353 values:Vector<SecureValue> credentials:SecureCredentialsEncrypted\n // messageActionSecureValuesSent#d95c6154 types:Vector<SecureValueType>\n\n switch (act._) {\n case 'messageActionChatCreate':\n return {\n type: 'chat_created',\n title: act.title,\n users: act.users,\n }\n case 'messageActionChannelCreate':\n return {\n type: 'channel_created',\n title: act.title,\n }\n case 'messageActionChatMigrateTo':\n return {\n type: 'chat_migrate_to',\n id: act.channelId,\n }\n case 'messageActionChannelMigrateFrom':\n return {\n type: 'channel_migrate_from',\n id: act.chatId,\n title: act.title,\n }\n case 'messageActionPinMessage':\n return {\n type: 'message_pinned',\n }\n case 'messageActionHistoryClear':\n return {\n type: 'history_cleared',\n }\n case 'messageActionGameScore':\n return {\n type: 'game_score',\n gameId: act.gameId,\n score: act.score,\n }\n case 'messageActionContactSignUp':\n return {\n type: 'contact_joined',\n }\n case 'messageActionChatEditTitle':\n return {\n type: 'title_changed',\n title: act.title,\n }\n case 'messageActionChatEditPhoto':\n return {\n type: 'photo_changed',\n photo: new Photo(act.photo as tl.RawPhoto),\n }\n case 'messageActionChatDeletePhoto':\n return {\n type: 'photo_deleted',\n }\n case 'messageActionChatAddUser':\n return {\n type: 'users_added',\n users: act.users,\n }\n case 'messageActionChatDeleteUser':\n if (this.raw.fromId?._ === 'peerUser' && act.userId === this.raw.fromId.userId) {\n return {\n type: 'user_left',\n }\n }\n\n return {\n type: 'user_removed',\n user: act.userId,\n }\n\n case 'messageActionChatJoinedByLink':\n return {\n type: 'user_joined_link',\n inviter: act.inviterId,\n }\n case 'messageActionPaymentSentMe':\n return {\n type: 'payment_received',\n currency: act.currency,\n amount: act.totalAmount,\n payload: act.payload,\n info: act.info,\n shippingOptionId: act.shippingOptionId,\n charge: act.charge,\n }\n case 'messageActionPaymentSent':\n return {\n type: 'payment_sent',\n currency: act.currency,\n amount: act.totalAmount,\n }\n case 'messageActionPhoneCall':\n return {\n type: 'call',\n id: act.callId,\n isVideo: Boolean(act.video),\n reason: act.reason ? _callDiscardReasonFromTl(act.reason) : undefined,\n duration: act.duration ?? 0,\n }\n case 'messageActionScreenshotTaken':\n return {\n type: 'screenshot_taken',\n }\n case 'messageActionBotAllowed':\n return {\n type: 'bot_allowed',\n domain: act.domain,\n }\n case 'messageActionGeoProximityReached':\n if (act.fromId._ !== 'peerUser' || act.toId._ !== 'peerUser') {\n return null\n }\n\n return {\n type: 'geo_proximity',\n targetId: act.toId.userId,\n userId: act.fromId.userId,\n distance: act.distance,\n }\n\n case 'messageActionGroupCall':\n if (act.duration) {\n return {\n type: 'group_call_ended',\n call: act.call,\n duration: act.duration,\n }\n }\n\n return {\n type: 'group_call_started',\n call: act.call,\n }\n case 'messageActionGroupCallScheduled':\n return {\n type: 'group_call_scheduled',\n call: act.call,\n date: new Date(act.scheduleDate * 1000),\n }\n case 'messageActionInviteToGroupCall':\n return {\n type: 'group_call_invite',\n call: act.call,\n userIds: act.users,\n }\n case 'messageActionSetMessagesTTL':\n return {\n type: 'ttl_changed',\n period: act.period,\n }\n case 'messageActionTopicCreate':\n return {\n type: 'topic_created',\n title: act.title,\n iconColor: act.iconColor,\n iconCustomEmoji: act.iconEmojiId,\n }\n case 'messageActionTopicEdit':\n return {\n type: 'topic_edited',\n title: act.title,\n iconCustomEmoji: act.iconEmojiId,\n closed: act.closed,\n hidden: act.hidden,\n }\n case 'messageActionCustomAction':\n return {\n type: 'custom',\n action: act.message,\n }\n case 'messageActionSetChatTheme':\n return {\n type: 'theme_changed',\n emoji: act.emoticon,\n }\n case 'messageActionChatJoinedByRequest':\n return {\n type: 'user_joined_approved',\n }\n case 'messageActionWebViewDataSent':\n return {\n type: 'webview_sent',\n text: act.text,\n }\n case 'messageActionWebViewDataSentMe':\n return {\n type: 'webview_received',\n text: act.text,\n data: act.data,\n }\n case 'messageActionGiftPremium':\n return {\n type: 'premium_gifted',\n currency: act.currency,\n amount: act.amount.toNumber(),\n months: act.months,\n crypto: act.cryptoAmount ?\n {\n currency: act.cryptoCurrency!,\n amount: act.cryptoAmount.toNumber(),\n } :\n undefined,\n }\n case 'messageActionSuggestProfilePhoto':\n return {\n type: 'photo_suggested',\n photo: new Photo(act.photo as tl.RawPhoto),\n }\n case 'messageActionRequestedPeerSentMe':\n return {\n type: 'peer_sent',\n buttonId: act.buttonId,\n peers: act.peers,\n }\n case 'messageActionRequestedPeer':\n return {\n type: 'peer_chosen',\n buttonId: act.buttonId,\n peers: act.peers.map((it) => parsePeer(it, this._peers)),\n }\n case 'messageActionSetChatWallPaper':\n return {\n type: 'wallpaper_changed',\n same: act.same!,\n forBoth: act.forBoth!,\n wallpaper: act.wallpaper,\n }\n case 'messageActionGiftCode':\n return {\n type: 'gift_code',\n raw: act,\n }\n case 'messageActionGiveawayLaunch':\n return {\n type: 'giveaway_started',\n }\n case 'messageActionGiveawayResults':\n return {\n type: 'giveaway_ended',\n winners: act.winnersCount,\n undistributed: act.unclaimedCount,\n }\n case 'messageActionBoostApply':\n return {\n type: 'boost_apply',\n count: act.boosts,\n }\n default:\n return null\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"message-action.js","sourceRoot":"","sources":["../../../../../src/highlevel/types/messages/message-action.ts"],"names":[],"mappings":";;;AAEA,gEAA8D;AAC9D,gDAA+E;AAC/E,gDAAyC;AACzC,8CAAkD;AAqgBlD,gBAAgB;AAChB,SAAgB,o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a,EAAE,GAAG,CAAC,cAAc;aACpC,CAAA;QACL,KAAK,yBAAyB;YAC1B,OAAO;gBACH,IAAI,EAAE,aAAa;gBACnB,KAAK,EAAE,GAAG,CAAC,MAAM;aACpB,CAAA;QACL,KAAK,8BAA8B;YAC/B,OAAO;gBACH,IAAI,EAAE,kBAAkB;gBACxB,QAAQ,EAAE,GAAG,CAAC,QAAQ;gBACtB,MAAM,EAAE,IAAA,+BAAe,EAAC,GAAG,CAAC,IAAI,CAAC;gBACjC,MAAM,EAAE,GAAG,CAAC,WAAW;gBACvB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,MAAM,EAAE,GAAG,CAAC,MAAM;aACrB,CAAA;QACL;YACI,OAAO,IAAI,CAAA;IACnB,CAAC;AACL,CAAC;AA1QD,oDA0QC","sourcesContent":["import { tl } from '@mtcute/tl'\n\nimport { getMarkedPeerId } from '../../../utils/peer-utils.js'\nimport { _callDiscardReasonFromTl, CallDiscardReason } from '../calls/index.js'\nimport { Photo } from '../media/photo.js'\nimport { parsePeer, Peer } from '../peers/peer.js'\nimport type { Message } from './message.js'\n\n/** Group was created */\nexport interface ActionChatCreated {\n readonly type: 'chat_created'\n\n /** Group name */\n readonly title: string\n\n /** IDs of the users in the group */\n readonly users: number[]\n}\n\n/** Channel/supergroup was created */\nexport interface ActionChannelCreated {\n readonly type: 'channel_created'\n\n /** Original channel/supergroup title */\n readonly title: string\n}\n\n/** Chat was migrated to a supergroup with a given ID */\nexport interface ActionChatMigrateTo {\n readonly type: 'chat_migrate_to'\n\n /** Marked ID of the supergroup chat was migrated to */\n readonly id: number\n}\n\n/** Supergroup was migrated from a chat with a given ID */\nexport interface ActionChannelMigrateFrom {\n readonly type: 'channel_migrate_from'\n\n /** Marked ID of the chat this channel was migrated from */\n readonly id: number\n\n /** Old chat's title */\n readonly title: string\n}\n\n/**\n * A message has been pinned.\n *\n * To get the message itself, use {@link Message.getReplyTo}\n */\nexport interface ActionMessagePinned {\n readonly type: 'message_pinned'\n}\n\n/** History was cleared in a private chat. */\nexport interface ActionHistoryCleared {\n readonly type: 'history_cleared'\n}\n\n/** Someone scored in a game (usually only used for newly set high scores) */\nexport interface ActionGameScore {\n readonly type: 'game_score'\n\n /** Game ID */\n readonly gameId: tl.Long\n\n /** Score */\n readonly score: number\n}\n\n/** Contact has joined Telegram */\nexport interface ActionContactJoined {\n readonly type: 'contact_joined'\n}\n\n/** Group title was changed */\nexport interface ActionTitleChanged {\n readonly type: 'title_changed'\n\n /** New group name */\n readonly title: string\n}\n\n/** Group photo was changed */\nexport interface ActionPhotoChanged {\n readonly type: 'photo_changed'\n\n /** New group photo */\n readonly photo: Photo\n}\n\n/** Group photo was deleted */\nexport interface ActionPhotoDeleted {\n readonly type: 'photo_deleted'\n}\n\n/** Users were added to the chat */\nexport interface ActionUsersAdded {\n readonly type: 'users_added'\n\n /** IDs of the users that were added */\n readonly users: number[]\n}\n\n/** User has left the group */\nexport interface ActionUserLeft {\n readonly type: 'user_left'\n}\n\n/** User was removed from the group */\nexport interface ActionUserRemoved {\n readonly type: 'user_removed'\n\n /** ID of the user that was removed from the group */\n readonly user: number\n}\n\n/** User has joined the group via an invite link */\nexport interface ActionUserJoinedLink {\n readonly type: 'user_joined_link'\n\n /** ID of the user who created the link */\n readonly inviter: number\n}\n\n/**\n * User has joined the group via an invite link\n * and was approved by an administrator\n */\nexport interface ActionUserJoinedApproved {\n readonly type: 'user_joined_approved'\n}\n\n/** A payment was received from a user (bot) */\nexport interface ActionPaymentReceived {\n readonly type: 'payment_received'\n\n /** Three-letter ISO 4217 currency code */\n readonly currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n readonly amount: tl.Long\n\n /** Bot specified invoice payload */\n readonly payload: Uint8Array\n\n /** Order information provided by the user */\n readonly info?: tl.TypePaymentRequestedInfo\n\n /** ID of the shipping option chosen by the user */\n readonly shippingOptionId?: string\n\n /** Payment provider ID */\n readonly charge?: tl.TypePaymentCharge\n}\n\n/** A payment was sent to a user */\nexport interface ActionPaymentSent {\n readonly type: 'payment_sent'\n\n /** Three-letter ISO 4217 currency code */\n readonly currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n readonly amount: tl.Long\n}\n\n/** A phone call */\nexport interface ActionCall {\n readonly type: 'call'\n\n /** Call ID */\n readonly id: tl.Long\n\n /** Whether this is a video call */\n readonly isVideo: boolean\n\n /** Duration if the call in seconds (0 if not available) */\n readonly duration: number\n\n /** Call discard reason, if available */\n readonly reason?: CallDiscardReason\n}\n\n/** A screenshot was taken */\nexport interface ActionScreenshotTaken {\n readonly type: 'screenshot_taken'\n}\n\n/** User has authorized via the bot */\nexport interface ActionBotAllowed {\n readonly type: 'bot_allowed'\n\n /** Domain where the user has logged in */\n readonly domain?: string\n}\n\n/**\n * A user is in proximity of another user\n * (see [Proximity alerts](https://core.telegram.org/api/live-location#proximity-alert))\n */\nexport interface ActionGeoProximity {\n readonly type: 'geo_proximity'\n\n /** ID of the user who sent the geolocation with proximity alerts */\n readonly targetId: number\n\n /** ID of the user who has approached `targetId` */\n readonly userId: number\n\n /** Distance between them in meters */\n readonly distance: number\n}\n\n/** Group call has started */\nexport interface ActionGroupCallStarted {\n readonly type: 'group_call_started'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n}\n\n/** Group call has ended */\nexport interface ActionGroupCallEnded {\n readonly type: 'group_call_ended'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** Duration of the call */\n readonly duration: number\n}\n\n/** Group call has been scheduled */\nexport interface ActionGroupCallScheduled {\n readonly type: 'group_call_scheduled'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** Date when the call will start */\n readonly date: Date\n}\n\n/** Group call has ended */\nexport interface ActionGroupInvite {\n readonly type: 'group_call_invite'\n\n /** TL object representing the call */\n readonly call: tl.TypeInputGroupCall\n\n /** IDs of the users invited to the call */\n readonly userIds: number[]\n}\n\n/** Messages TTL changed */\nexport interface ActionTtlChanged {\n readonly type: 'ttl_changed'\n\n /** New TTL period */\n readonly period: number\n}\n\n/** Forum topic was created */\nexport interface ActionTopicCreated {\n readonly type: 'topic_created'\n\n /** Title of the topic */\n title: string\n\n /** Icon color of the topic */\n iconColor: number\n\n /** Icon emoji of the topic */\n iconCustomEmoji?: tl.Long\n}\n\n/** Forum topic was modified */\nexport interface ActionTopicEdited {\n readonly type: 'topic_edited'\n\n /** New title of the topic */\n title?: string\n\n /** New icon emoji of the topic (may be empty) */\n iconCustomEmoji?: tl.Long\n\n /** Whether the topic was opened/closed */\n closed?: boolean\n\n /** Whether the topic was (un-)hidden - only for \"General\" topic (`id=1`) */\n hidden?: boolean\n}\n\n/** A non-standard action has happened in the chat */\nexport interface ActionCustom {\n readonly type: 'custom'\n\n /** Text to be shown in the interface */\n action: string\n}\n\n/** Chat theme was changed */\nexport interface ActionThemeChanged {\n readonly type: 'theme_changed'\n\n /** Emoji representing the new theme */\n emoji: string\n}\n\n/** Data was sent from a WebView (user-side action) */\nexport interface ActionWebviewDataSent {\n readonly type: 'webview_sent'\n\n /** Text of the button that was pressed to open the WebView */\n text: string\n}\n\n/** Data was received from a WebView (bot-side action) */\nexport interface ActionWebviewDataReceived {\n readonly type: 'webview_received'\n\n /** Text of the button that was pressed to open the WebView */\n text: string\n\n /** Data received from the WebView */\n data: string\n}\n\n/** Premium subscription was gifted */\nexport interface ActionPremiumGifted {\n readonly type: 'premium_gifted'\n\n /**\n * Currency in which it was paid for.\n * Three-letter ISO 4217 currency code)\n */\n currency: string\n\n /**\n * Price of the product in the smallest units of the currency\n * (integer, not float/double). For example, for a price of\n * `US$ 1.45`, `amount = 145`\n */\n amount: number\n\n /** Duration of the gifted subscription in months */\n months: number\n\n /** If the subscription was bought with crypto, information about it */\n crypto?: {\n /** Crypto currency name */\n currency: string\n /** Price in the smallest units */\n amount: number\n }\n}\n\n/** A photo has been suggested as a profile photo */\nexport interface ActionPhotoSuggested {\n readonly type: 'photo_suggested'\n\n /** Photo that was suggested */\n photo: Photo\n}\n\n/**\n * A peer was chosen by the user after clicking on a RequestPeer button.\n * The user-side version of {@link ActionPeerChosen}\n */\nexport interface ActionPeerSent {\n readonly type: 'peer_sent'\n\n /** ID of the button passed earlier by the bot */\n buttonId: number\n\n /** Brief information about the chosen peers */\n peers: tl.TypeRequestedPeer[]\n}\n\n/**\n * A peer was chosen by the user after clicking on a RequestPeer button\n * The bot-side version of {@link ActionPeerSent}\n */\nexport interface ActionPeerChosen {\n readonly type: 'peer_chosen'\n\n /** ID of the button passed earlier by the bot */\n buttonId: number\n\n /** Chosen peers */\n peers: Peer[]\n}\n\n/** A wallpaper of the chathas been changed */\nexport interface ActionWallpaperChanged {\n readonly type: 'wallpaper_changed'\n\n /**\n * Whether the user has applied the same wallpaper\n * as the other party previously set in the chat\n */\n same: boolean\n\n /**\n * Whether the wallpaper was forcefully applied for\n * both sides, without explicit confirmation from the other\n * side.\n */\n forBoth: boolean\n\n /** TL object representing the new wallpaper */\n wallpaper: tl.TypeWallPaper\n}\n\n/** A Telergam Premium gift code was received */\nexport interface ActionGiftCode {\n readonly type: 'gift_code'\n\n /** Information about the gift code */\n raw: tl.RawMessageActionGiftCode\n}\n\n/** A Telergam Premium giveaway was started */\nexport interface ActionGiveawayStarted {\n readonly type: 'giveaway_started'\n}\n\n/** A Telergam Premium giveaway was ended and results are available */\nexport interface ActionGiveawayEnded {\n readonly type: 'giveaway_ended'\n\n /** Number of winners in the giveaway */\n winners: number\n\n /** Number of undistributed prizes */\n undistributed: number\n}\n\n/** Boosts were applied to the group */\nexport interface ActionBoostApply {\n readonly type: 'boost_apply'\n\n /** Number of boosts applied */\n count: number\n}\n\n/** A payment was refunded */\nexport interface ActionPaymentRefunded {\n readonly type: 'payment_refunded'\n\n /** Three-letter ISO 4217 currency code */\n currency: string\n\n /** Marked ID of the peer where the stars were refunded (?) */\n peerId: number\n\n /** Number of `currency` refunded, in the smallest unit */\n amount: tl.Long\n\n /** Payload defined by the bot */\n payload?: Uint8Array\n\n /** Information about the charge */\n charge: tl.TypePaymentCharge\n}\n\nexport type MessageAction =\n | ActionChatCreated\n | ActionChannelCreated\n | ActionChatMigrateTo\n | ActionChannelMigrateFrom\n | ActionMessagePinned\n | ActionHistoryCleared\n | ActionGameScore\n | ActionContactJoined\n | ActionTitleChanged\n | ActionPhotoChanged\n | ActionPhotoDeleted\n | ActionUsersAdded\n | ActionUserLeft\n | ActionUserRemoved\n | ActionUserJoinedLink\n | ActionPaymentReceived\n | ActionPaymentSent\n | ActionCall\n | ActionScreenshotTaken\n | ActionBotAllowed\n | ActionGeoProximity\n | ActionGroupCallStarted\n | ActionGroupCallEnded\n | ActionGroupCallScheduled\n | ActionGroupInvite\n | ActionTtlChanged\n | ActionTopicCreated\n | ActionTopicEdited\n | ActionCustom\n | ActionThemeChanged\n | ActionUserJoinedApproved\n | ActionWebviewDataSent\n | ActionWebviewDataReceived\n | ActionPremiumGifted\n | ActionPhotoSuggested\n | ActionPeerSent\n | ActionPeerChosen\n | ActionWallpaperChanged\n | ActionGiftCode\n | ActionGiveawayStarted\n | ActionGiveawayEnded\n | ActionBoostApply\n | ActionPaymentRefunded\n | null\n\n/** @internal */\nexport function _messageActionFromTl(this: Message, act: tl.TypeMessageAction): MessageAction {\n // todo - passport\n // messageActionSecureValuesSentMe#1b287353 values:Vector<SecureValue> credentials:SecureCredentialsEncrypted\n // messageActionSecureValuesSent#d95c6154 types:Vector<SecureValueType>\n\n switch (act._) {\n case 'messageActionChatCreate':\n return {\n type: 'chat_created',\n title: act.title,\n users: act.users,\n }\n case 'messageActionChannelCreate':\n return {\n type: 'channel_created',\n title: act.title,\n }\n case 'messageActionChatMigrateTo':\n return {\n type: 'chat_migrate_to',\n id: act.channelId,\n }\n case 'messageActionChannelMigrateFrom':\n return {\n type: 'channel_migrate_from',\n id: act.chatId,\n title: act.title,\n }\n case 'messageActionPinMessage':\n return {\n type: 'message_pinned',\n }\n case 'messageActionHistoryClear':\n return {\n type: 'history_cleared',\n }\n case 'messageActionGameScore':\n return {\n type: 'game_score',\n gameId: act.gameId,\n score: act.score,\n }\n case 'messageActionContactSignUp':\n return {\n type: 'contact_joined',\n }\n case 'messageActionChatEditTitle':\n return {\n type: 'title_changed',\n title: act.title,\n }\n case 'messageActionChatEditPhoto':\n return {\n type: 'photo_changed',\n photo: new Photo(act.photo as tl.RawPhoto),\n }\n case 'messageActionChatDeletePhoto':\n return {\n type: 'photo_deleted',\n }\n case 'messageActionChatAddUser':\n return {\n type: 'users_added',\n users: act.users,\n }\n case 'messageActionChatDeleteUser':\n if (this.raw.fromId?._ === 'peerUser' && act.userId === this.raw.fromId.userId) {\n return {\n type: 'user_left',\n }\n }\n\n return {\n type: 'user_removed',\n user: act.userId,\n }\n\n case 'messageActionChatJoinedByLink':\n return {\n type: 'user_joined_link',\n inviter: act.inviterId,\n }\n case 'messageActionPaymentSentMe':\n return {\n type: 'payment_received',\n currency: act.currency,\n amount: act.totalAmount,\n payload: act.payload,\n info: act.info,\n shippingOptionId: act.shippingOptionId,\n charge: act.charge,\n }\n case 'messageActionPaymentSent':\n return {\n type: 'payment_sent',\n currency: act.currency,\n amount: act.totalAmount,\n }\n case 'messageActionPhoneCall':\n return {\n type: 'call',\n id: act.callId,\n isVideo: Boolean(act.video),\n reason: act.reason ? _callDiscardReasonFromTl(act.reason) : undefined,\n duration: act.duration ?? 0,\n }\n case 'messageActionScreenshotTaken':\n return {\n type: 'screenshot_taken',\n }\n case 'messageActionBotAllowed':\n return {\n type: 'bot_allowed',\n domain: act.domain,\n }\n case 'messageActionGeoProximityReached':\n if (act.fromId._ !== 'peerUser' || act.toId._ !== 'peerUser') {\n return null\n }\n\n return {\n type: 'geo_proximity',\n targetId: act.toId.userId,\n userId: act.fromId.userId,\n distance: act.distance,\n }\n\n case 'messageActionGroupCall':\n if (act.duration) {\n return {\n type: 'group_call_ended',\n call: act.call,\n duration: act.duration,\n }\n }\n\n return {\n type: 'group_call_started',\n call: act.call,\n }\n case 'messageActionGroupCallScheduled':\n return {\n type: 'group_call_scheduled',\n call: act.call,\n date: new Date(act.scheduleDate * 1000),\n }\n case 'messageActionInviteToGroupCall':\n return {\n type: 'group_call_invite',\n call: act.call,\n userIds: act.users,\n }\n case 'messageActionSetMessagesTTL':\n return {\n type: 'ttl_changed',\n period: act.period,\n }\n case 'messageActionTopicCreate':\n return {\n type: 'topic_created',\n title: act.title,\n iconColor: act.iconColor,\n iconCustomEmoji: act.iconEmojiId,\n }\n case 'messageActionTopicEdit':\n return {\n type: 'topic_edited',\n title: act.title,\n iconCustomEmoji: act.iconEmojiId,\n closed: act.closed,\n hidden: act.hidden,\n }\n case 'messageActionCustomAction':\n return {\n type: 'custom',\n action: act.message,\n }\n case 'messageActionSetChatTheme':\n return {\n type: 'theme_changed',\n emoji: act.emoticon,\n }\n case 'messageActionChatJoinedByRequest':\n return {\n type: 'user_joined_approved',\n }\n case 'messageActionWebViewDataSent':\n return {\n type: 'webview_sent',\n text: act.text,\n }\n case 'messageActionWebViewDataSentMe':\n return {\n type: 'webview_received',\n text: act.text,\n data: act.data,\n }\n case 'messageActionGiftPremium':\n return {\n type: 'premium_gifted',\n currency: act.currency,\n amount: act.amount.toNumber(),\n months: act.months,\n crypto: act.cryptoAmount ?\n {\n currency: act.cryptoCurrency!,\n amount: act.cryptoAmount.toNumber(),\n } :\n undefined,\n }\n case 'messageActionSuggestProfilePhoto':\n return {\n type: 'photo_suggested',\n photo: new Photo(act.photo as tl.RawPhoto),\n }\n case 'messageActionRequestedPeerSentMe':\n return {\n type: 'peer_sent',\n buttonId: act.buttonId,\n peers: act.peers,\n }\n case 'messageActionRequestedPeer':\n return {\n type: 'peer_chosen',\n buttonId: act.buttonId,\n peers: act.peers.map((it) => parsePeer(it, this._peers)),\n }\n case 'messageActionSetChatWallPaper':\n return {\n type: 'wallpaper_changed',\n same: act.same!,\n forBoth: act.forBoth!,\n wallpaper: act.wallpaper,\n }\n case 'messageActionGiftCode':\n return {\n type: 'gift_code',\n raw: act,\n }\n case 'messageActionGiveawayLaunch':\n return {\n type: 'giveaway_started',\n }\n case 'messageActionGiveawayResults':\n return {\n type: 'giveaway_ended',\n winners: act.winnersCount,\n undistributed: act.unclaimedCount,\n }\n case 'messageActionBoostApply':\n return {\n type: 'boost_apply',\n count: act.boosts,\n }\n case 'messageActionPaymentRefunded':\n return {\n type: 'payment_refunded',\n currency: act.currency,\n peerId: getMarkedPeerId(act.peer),\n amount: act.totalAmount,\n payload: act.payload,\n charge: act.charge,\n }\n default:\n return null\n }\n}\n"]}
|
|
@@ -76,6 +76,8 @@ export declare class FullChat extends Chat {
|
|
|
76
76
|
* Number of boosts required for the user to be unrestricted in this chat.
|
|
77
77
|
*/
|
|
78
78
|
get boostsForUnrestrict(): number;
|
|
79
|
+
/** Whether the current user can view Telegram Stars revenue for this chat */
|
|
80
|
+
get canViewStarsRevenue(): boolean;
|
|
79
81
|
/**
|
|
80
82
|
* Chat members count, for groups, supergroups and channels only.
|
|
81
83
|
*/
|
|
@@ -172,6 +172,10 @@ class FullChat extends chat_js_1.Chat {
|
|
|
172
172
|
return 0;
|
|
173
173
|
return this.fullPeer?.boostsUnrestrict ?? 0;
|
|
174
174
|
}
|
|
175
|
+
/** Whether the current user can view Telegram Stars revenue for this chat */
|
|
176
|
+
get canViewStarsRevenue() {
|
|
177
|
+
return this.fullPeer._ === 'channelFull' && this.fullPeer.canViewStats;
|
|
178
|
+
}
|
|
175
179
|
/**
|
|
176
180
|
* Chat members count, for groups, supergroups and channels only.
|
|
177
181
|
*/
|