painor 3 anni fa
parent
commit
26323f67ef

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.8.12";
+export const version = "1.8.13";

+ 27 - 3
gramjs/client/TelegramClient.ts

@@ -145,12 +145,37 @@ export class TelegramClient extends TelegramBaseClient {
     /**
      * logs the user using a QR code to be scanned.<br/>
      * this function generates the QR code that needs to be scanned by mobile.
+     * @example
+     * '''ts
+     * await client.connect();
+     * const user = await client.signInUserWithQrCode({ apiId, apiHash },
+     * {
+     *       onError: async function(p1: Error) {
+     *           console.log("error", p1);
+     *           // true = stop the authentication processes
+     *           return true;
+     *       },
+     *       qrCode: async (code) => {
+     *           console.log("Convert the next string to a QR code and scan it");
+     *           console.log(
+     *               `tg://login?token=${code.token.toString("base64url")}`
+     *           );
+     *       },
+     *       password: async (hint) => {
+     *           // password if needed
+     *           return "1111";
+     *       }
+     *   }
+     * );
+     * console.log("user is", user);
+     *
+     * '''
      * @param apiCredentials - credentials to be used.
      * @param authParams - user auth params.
      */
     signInUserWithQrCode(
         apiCredentials: authMethods.ApiCredentials,
-        authParams: authMethods.UserAuthParams
+        authParams: authMethods.QrCodeAuthParams
     ) {
         return authMethods.signInUserWithQrCode(
             this,
@@ -196,7 +221,7 @@ export class TelegramClient extends TelegramBaseClient {
      */
     signInWithPassword(
         apiCredentials: authMethods.ApiCredentials,
-        authParams: authMethods.UserAuthParams
+        authParams: authMethods.UserPasswordAuthParams
     ) {
         return authMethods.signInWithPassword(this, apiCredentials, authParams);
     }
@@ -800,7 +825,6 @@ export class TelegramClient extends TelegramBaseClient {
         return updateMethods.on(this, event);
     }
 
-
     /**
      * Registers a new event handler callback.<br/>
      * <br/>

+ 33 - 10
gramjs/client/auth.ts

@@ -30,9 +30,28 @@ export interface UserAuthParams {
     forceSMS?: boolean;
 }
 
+export interface UserPasswordAuthParams {
+    /** optional string or callback that should return the 2FA password if present.<br/>
+     *  the password hint will be sent in the hint param */
+    password?: (hint?: string) => Promise<string>;
+    /** when an error happens during auth this function will be called with the error.<br/>
+     *  if this returns true the auth operation will stop. */
+    onError: (err: Error) => Promise<boolean> | void;
+}
+
+export interface QrCodeAuthParams extends UserPasswordAuthParams {
+    /** a qrCode token for login through qrCode.<br/>
+     *  this would need a QR code that you should scan with another app to login with. */
+    qrCode?: (qrCode: { token: Buffer; expires: number }) => Promise<void>;
+    /** when an error happens during auth this function will be called with the error.<br/>
+     *  if this returns true the auth operation will stop. */
+    onError: (err: Error) => Promise<boolean> | void;
+}
+
 interface ReturnString {
     (): string;
 }
+
 /**
  * For when you want as a normal bot created by https://t.me/Botfather.<br/>
  * Logging in as bot is simple and requires no callbacks
@@ -78,6 +97,7 @@ export async function start(
 
     await _authFlow(client, apiCredentials, authParams);
 }
+
 /** @hidden */
 export async function checkAuthorization(client: TelegramClient) {
     try {
@@ -87,6 +107,7 @@ export async function checkAuthorization(client: TelegramClient) {
         return false;
     }
 }
+
 /** @hidden */
 export async function signInUser(
     client: TelegramClient,
@@ -238,7 +259,7 @@ export async function signInUser(
 export async function signInUserWithQrCode(
     client: TelegramClient,
     apiCredentials: ApiCredentials,
-    authParams: UserAuthParams
+    authParams: QrCodeAuthParams
 ): Promise<Api.TypeUser> {
     const inputPromise = (async () => {
         while (1) {
@@ -261,6 +282,7 @@ export async function signInUserWithQrCode(
                     sleep(QR_CODE_TIMEOUT),
                 ]);
             }
+            await sleep(QR_CODE_TIMEOUT);
         }
     })();
 
@@ -275,10 +297,6 @@ export async function signInUserWithQrCode(
     try {
         await Promise.race([updatePromise, inputPromise]);
     } catch (err) {
-        if (err.errorMessage === "RESTART_AUTH") {
-            return client.signInUser(apiCredentials, authParams);
-        }
-
         throw err;
     }
 
@@ -290,7 +308,6 @@ export async function signInUserWithQrCode(
                 exceptIds: [],
             })
         );
-
         if (
             result2 instanceof Api.auth.LoginTokenSuccess &&
             result2.authorization instanceof Api.auth.Authorization
@@ -318,7 +335,7 @@ export async function signInUserWithQrCode(
     }
 
     await authParams.onError(new Error("QR auth failed"));
-    return client.signInUser(apiCredentials, authParams);
+    throw new Error("QR auth failed");
 }
 
 /** @hidden */
@@ -375,15 +392,17 @@ export async function sendCode(
 export async function signInWithPassword(
     client: TelegramClient,
     apiCredentials: ApiCredentials,
-    authParams: UserAuthParams
+    authParams: UserPasswordAuthParams
 ): Promise<Api.TypeUser> {
+    let emptyPassword = false;
     while (1) {
         try {
             const passwordSrpResult = await client.invoke(
                 new Api.account.GetPassword()
             );
             if (!authParams.password) {
-                throw new Error("Account has 2FA enabled.");
+                emptyPassword = true;
+                break;
             }
 
             const password = await authParams.password(passwordSrpResult.hint);
@@ -409,9 +428,12 @@ export async function signInWithPassword(
             }
         }
     }
-
+    if (emptyPassword) {
+        throw new Error("Account has 2FA enabled.");
+    }
     return undefined!; // Never reached (TypeScript fix)
 }
+
 /** @hidden */
 export async function signInBot(
     client: TelegramClient,
@@ -443,6 +465,7 @@ export async function signInBot(
     )) as Api.auth.Authorization;
     return user;
 }
+
 /** @hidden */
 export async function _authFlow(
     client: TelegramClient,

+ 5 - 1
gramjs/client/updates.ts

@@ -116,7 +116,11 @@ export async function _dispatchUpdate(
         let event = args.update;
         if (event) {
             if (!client._selfInputPeer) {
-                await client.getMe(true);
+                try {
+                    await client.getMe(true);
+                } catch (e) {
+                    // we don't care about this.
+                }
             }
             if (!(event instanceof UpdateConnectionState)) {
                 // TODO fix me

+ 0 - 1
gramjs/client/uploads.ts

@@ -473,7 +473,6 @@ export async function sendFile(
         supportsStreaming: supportsStreaming,
         workers: workers,
     });
-    console.log({ fileHandle, media, image })
     if (media == undefined) {
         throw new Error(`Cannot use ${file} as file.`);
     }

+ 12 - 19
gramjs/client/users.ts

@@ -83,27 +83,20 @@ export async function getMe(
     if (inputPeer && client._selfInputPeer) {
         return client._selfInputPeer;
     }
-    try {
-        const me = (
-            await client.invoke(
-                new Api.users.GetUsers({ id: [new Api.InputUserSelf()] })
-            )
-        )[0] as Api.User;
-        client._bot = me.bot;
+    const me = (
+        await client.invoke(
+            new Api.users.GetUsers({ id: [new Api.InputUserSelf()] })
+        )
+    )[0] as Api.User;
+    client._bot = me.bot;
 
-        if (!client._selfInputPeer) {
-            client._selfInputPeer = utils.getInputPeer(
-                me,
-                false
-            ) as Api.InputPeerUser;
-        }
-        return inputPeer ? client._selfInputPeer : me;
-    } catch (e) {
-        if (client._log.canSend("error")) {
-            console.error(e);
-        }
-        throw new Error("Could not get me");
+    if (!client._selfInputPeer) {
+        client._selfInputPeer = utils.getInputPeer(
+            me,
+            false
+        ) as Api.InputPeerUser;
     }
+    return inputPeer ? client._selfInputPeer : me;
 }
 
 /** @hidden */

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "telegram",
-  "version": "1.8.12",
+  "version": "1.8.13",
   "lockfileVersion": 2,
   "requires": true,
   "packages": {
     "": {
       "name": "telegram",
-      "version": "1.8.12",
+      "version": "1.8.13",
       "license": "MIT",
       "dependencies": {
         "@cryptography/aes": "^0.1.1",

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "telegram",
-  "version": "1.8.12",
+  "version": "1.8.13",
   "description": "NodeJS/Browser MTProto API Telegram client library,",
   "main": "index.js",
   "types": "index.d.ts",