Explorar el Código

Fix tl generation (bytes vs getBytes)
Fix error logging
add sender export
Fix cast bug
Fix flood sleep bug

painor hace 5 años
padre
commit
afc4482bec

+ 1 - 1
gramjs/Utils.js

@@ -63,7 +63,7 @@ function getInputPeer(entity, allowSelf = true, checkHash = true) {
         return new types.InputPeerChat({ chatId: entity.id })
     }
     if (entity instanceof types.Channel) {
-        if ((entity.accessHash !== undefined && !entity.min) || checkHash) {
+        if ((entity.accessHash !== undefined && !entity.min) || !checkHash) {
             return new types.InputPeerChannel({ channelId: entity.id, accessHash: entity.accessHash })
         } else {
             throw new TypeError('Channel without access_hash or min info cannot be input')

+ 39 - 3
gramjs/client/TelegramClient.js

@@ -31,7 +31,7 @@ class TelegramClient {
         retryDelay: 1,
         autoReconnect: true,
         sequentialUpdates: false,
-        FloodSleepLimit: 60,
+        floodSleepLimit: 60,
         deviceModel: null,
         systemVersion: null,
         appVersion: null,
@@ -121,6 +121,7 @@ class TelegramClient {
 
         })
         this.phoneCodeHashes = []
+        this._borrowedSenders = {}
     }
 
 
@@ -213,7 +214,9 @@ class TelegramClient {
         if (request.CONSTRUCTOR_ID in this._floodWaitedRequests) {
             const due = this._floodWaitedRequests[request.CONSTRUCTOR_ID]
             const diff = Math.round(due - new Date().getTime() / 1000)
-            if (diff <= 3) {
+            console.log('diff is ', diff)
+            console.log('limit is ', this.floodSleepLimit)
+            if (diff <= 3) { // Flood waits below 3 seconds are 'ignored'
                 delete this._floodWaitedRequests[request.CONSTRUCTOR_ID]
             } else if (diff <= this.floodSleepLimit) {
                 this._log.info(`Sleeping early for ${diff}s on flood wait`)
@@ -241,7 +244,7 @@ class TelegramClient {
                     this._log.warn(`Telegram is having internal issues ${e.constructor.name}`)
                     await sleep(2000)
                 } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {
-                    this._floodWaitedRequests = new Date().getTime() / 1000 + e.seconds
+                    this._floodWaitedRequests[request.CONSTRUCTOR_ID] = new Date().getTime() / 1000 + e.seconds
                     if (e.seconds <= this.floodSleepLimit) {
                         this._log.info(`Sleeping for ${e.seconds}s on flood wait`)
                         await sleep(e.seconds * 1000)
@@ -378,6 +381,7 @@ class TelegramClient {
                         })
                         break
                     } catch (e) {
+                        console.log(e)
                         console.log('Invalid password. Please try again')
                     }
                 }
@@ -811,6 +815,38 @@ class TelegramClient {
     async signUp() {
 
     }
+
+    // export region
+
+    async _borrowExportedSender(dcId) {
+        let sender = this._borrowedSenders(dcId)
+        if (!sender) {
+            sender = await this._createExportedSender(dcId)
+            sender.dcId = dcId
+            this._borrowedSenders[dcId] = sender
+        }
+        return sender
+    }
+
+    async _createExportedSender(dcId) {
+        const dc = await this._getDC(dcId)
+        const sender = new MTProtoSender(null, { logger: this._log })
+        await sender.connect(new this._connection(
+            dc.ipAddress,
+            dc.port,
+            dcId,
+            this._log,
+        ))
+        this._log.info(`Exporting authorization for data center ${dc.ipAddress}`)
+        const auth = await this.invoke(new functions.auth.ExportAuthorizationRequest({ dcId: dcId }))
+        const req = this._initWith(new functions.auth.ImportAuthorizationRequest({
+                id: auth.id, bytes: auth.bytes,
+            },
+        ))
+        await sender.send(req)
+        return sender
+    }
+
 }
 
 module.exports = TelegramClient

+ 3 - 3
gramjs/network/Authenticator.js

@@ -62,7 +62,7 @@ async function doAuthentication(sender, log) {
     let cipherText = null
     let targetFingerprint = null
     for (const fingerprint of resPQ.serverPublicKeyFingerprints) {
-        cipherText = RSA.encrypt(fingerprint.toString(), pqInnerData.bytes)
+        cipherText = RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes())
         if (cipherText !== null && cipherText !== undefined) {
             targetFingerprint = fingerprint
             break
@@ -135,12 +135,12 @@ async function doAuthentication(sender, log) {
     const gab = Helpers.modExp(ga, b, dhPrime)
 
     // Prepare client DH Inner Data
-    const { bytes: clientDhInner } = new ClientDHInnerData({
+    const clientDhInner = new ClientDHInnerData({
         nonce: resPQ.nonce,
         serverNonce: resPQ.serverNonce,
         retryId: 0, // TODO Actual retry ID
         gB: getByteArray(gb, false),
-    })
+    }).getBytes()
 
     const clientDdhInnerHashed = Buffer.concat([Helpers.sha1(clientDhInner), clientDhInner])
     // Encryption

+ 1 - 1
gramjs/network/MTProtoPlainSender.js

@@ -28,7 +28,7 @@ class MTProtoPlainSender {
      * @param request
      */
     async send(request) {
-        let body = request.bytes
+        let body = request.getBytes()
         let msgId = this._state._getNewMsgId()
         const res = Buffer.concat([struct.pack('<qqi', [0, msgId.toString(), body.length]), body])
 

+ 0 - 1
gramjs/network/MTProtoSender.js

@@ -732,7 +732,6 @@ class MTProtoSender {
                 await Helpers.sleep(this._delay)
             }
         }
-        process.exit()
     }
 }
 

+ 1 - 1
gramjs/network/RequestState.js

@@ -3,7 +3,7 @@ class RequestState {
         this.containerId = null
         this.msgId = null
         this.request = request
-        this.data = request.bytes
+        this.data = request.getBytes()
         this.after = after
         this.result = null
         this.promise = new Promise((resolve, reject) => {

+ 10 - 1
gramjs_generator/generators/errors.js

@@ -42,11 +42,20 @@ const generateErrors = (errors, f) => {
 
         if (error.hasCaptures) {
             f.write(`super(format('${capture}', {${error.captureName}})`)
+            f.write(' + RPCError._fmtRequest(args.request));\n')
+
+            f.write(`this.message = format('${capture}', {${error.captureName}})`)
+            f.write(' + RPCError._fmtRequest(args.request);\n')
+
         } else {
             f.write(`super('${capture}'`)
+            f.write(' + RPCError._fmtRequest(args.request));\n')
+
+            f.write(`this.message = '${capture}'`)
+            f.write(' + RPCError._fmtRequest(args.request);\n')
+
         }
 
-        f.write(' + RPCError._fmtRequest(args.request));\n')
 
         if (error.hasCaptures) {
             f.write(`        this.${error.captureName} = ${error.captureName};\n`)

+ 2 - 2
gramjs_generator/generators/tlobject.js

@@ -434,7 +434,7 @@ const writeResolve = (tlobject, builder) => {
 };
  */
 const writeToBytes = (tlobject, builder) => {
-    builder.writeln('get bytes() {')
+    builder.writeln('getBytes() {')
 
     // Some objects require more than one flag parameter to be set
     // at the same time. In this case, add an assertion.
@@ -615,7 +615,7 @@ const writeArgToBytes = (builder, arg, args, name = null) => {
         builder.write('TLObject.serializeDatetime(%s)', name)
     } else {
         // Else it may be a custom type
-        builder.write('%s.bytes', name)
+        builder.write('%s.getBytes()', name)
 
         // If the type is not boxed (i.e. starts with lowercase) we should
         // not serialize the constructor ID (so remove its first 4 bytes).