Kaynağa Gözat

add some examples

painor 5 yıl önce
ebeveyn
işleme
a9d93bb480

+ 2 - 0
.gitignore

@@ -21,3 +21,5 @@ example.js
 .env
 .env
 
 
 settings
 settings
+
+/browser/

Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
browser/gramjs.js


+ 38 - 0
examples/betterLogging.js

@@ -0,0 +1,38 @@
+rewireLoggingToElement(
+  () => document.getElementById("log"),
+  () => document.getElementById("log-container"),
+  true
+);
+
+function rewireLoggingToElement(eleLocator, eleOverflowLocator, autoScroll) {
+  fixLoggingFunc("log");
+
+  function fixLoggingFunc(name) {
+      console.old = console.log
+    console.log = function(...arg) {
+      const output = produceOutput(name, arg);
+      const eleLog = eleLocator();
+
+      if (autoScroll) {
+        const eleContainerLog = eleOverflowLocator();
+        const isScrolledToBottom =
+          eleContainerLog.scrollHeight - eleContainerLog.clientHeight <=
+          eleContainerLog.scrollTop + 1;
+        eleLog.innerHTML += output + "<br>";
+        if (isScrolledToBottom) {
+          eleContainerLog.scrollTop =
+            eleContainerLog.scrollHeight - eleContainerLog.clientHeight;
+        }
+      } else {
+        eleLog.innerHTML += output + "<br>";
+      }
+
+    };
+  }
+
+  function produceOutput(name, args) {
+      arg =  args[0].replace("%c","")
+    return '<span style="'+ args[1]+'">'+arg+"</span>&nbsp;"
+    
+  }
+}

+ 1 - 2
examples/main.js

@@ -1,6 +1,5 @@
 const { TelegramClient } = require('../gramjs')
 const { TelegramClient } = require('../gramjs')
-const logger = require('log4js').getLogger()
-logger.level = 'debug';
+
 
 
 (async () => {
 (async () => {
     console.log('Loading interactive example...')
     console.log('Loading interactive example...')

+ 44 - 0
examples/simpleLogin.html

@@ -0,0 +1,44 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Telegram Login</title>
+    <style>
+        #log-container {
+            overflow: auto;
+            height: 150px;
+            width: 20%;
+            resize: both;
+        }
+    </style>
+</head>
+
+<body>
+    <form>
+        <div id="phoneDiv">
+            <label>phone number</label> <input disabled type="text" id="phone"> <button type="button" disabled id="phoneSend">Send</button>
+        </div>
+        <div id="codeDiv" style="visibility: hidden;">
+            <label>code you recieved</label> <input type="text" id="code"> <button type="button" id="codeSend">Send</button>
+        </div>
+        <div id="passDiv" style="visibility: hidden;">
+            <label>password</label> <input type="text" id="pass"> <button type="button" id="passSend">Send</button>
+        </div>
+        <div id="log-container">
+            <pre id="log"></pre>
+        </div>
+
+
+    </form>
+</body>
+<script src="../browser/gramjs.js"></script>
+<!--Loading the library-->
+<script src="betterLogging.js"></script>
+<!--beautifies the ouput (this rewrites console.log)-->
+
+<script src="simpleLogin.js"></script>
+
+</html>

+ 75 - 0
examples/simpleLogin.js

@@ -0,0 +1,75 @@
+const phoneDiv = document.getElementById('phoneDiv')
+const phone = document.getElementById('phone')
+const phoneSend = document.getElementById('phoneSend')
+const codeDiv = document.getElementById('codeDiv')
+const code = document.getElementById('code')
+const codeSend = document.getElementById('codeSend')
+const passDiv = document.getElementById('passDiv')
+const pass = document.getElementById('pass')
+const passSend = document.getElementById('passSend')
+const logger = document.getElementById('log')
+
+function phoneCallback() {
+    phone.disabled = false
+    phoneSend.disabled = false
+
+    return new Promise(resolve => {
+        phoneSend.addEventListener('click', function() {
+            phone.disabled = true
+            phoneSend.disabled = true
+            resolve(phone.value)
+        })
+    })
+}
+
+
+function passwordCallback() {
+    passDiv.style.visibility = 'visible'
+
+    return new Promise(resolve => {
+        passSend.addEventListener('click', function() {
+            code.disabled = true
+            codeSend.disabled = true
+
+            resolve(pass.value)
+            alert('welcome')
+
+        })
+    })
+}
+
+function codeCallback() {
+    code.disabled = false
+    codeSend.disabled = false
+
+    codeDiv.style.visibility = 'visible'
+
+    return new Promise(resolve => {
+        codeSend.addEventListener('click', function() {
+            code.disabled = true
+            codeSend.disabled = true
+            resolve(code.value)
+        })
+    })
+}
+
+
+const { TelegramClient } = gramjs
+const { StringSession } = gramjs.session
+const apiId = // put your api id here
+const apiHash = // put your api hash here
+
+const client = new TelegramClient(new StringSession(''), apiId, apiHash)
+// If you want to run this example in the test servers uncomment this line
+//client.session.setDC(2, '149.154.167.40', 80)
+
+client.start({
+    phone: phoneCallback,
+    password: passwordCallback,
+    code: codeCallback,
+}).then(() => {
+    console.log('%c you should now be connected', 'color:#B54128')
+})
+
+
+

+ 40 - 12
gramjs/client/TelegramClient.js

@@ -14,7 +14,6 @@ const { functions, types } = require('../tl')
 const { computeCheck } = require('../Password')
 const { computeCheck } = require('../Password')
 const MTProtoSender = require('../network/MTProtoSender')
 const MTProtoSender = require('../network/MTProtoSender')
 const { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')
 const { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')
-const { ConnectionTCPFull } = require('../network/connection/TCPFull')
 
 
 const DEFAULT_DC_ID = 4
 const DEFAULT_DC_ID = 4
 const DEFAULT_IPV4_IP = '149.154.167.51'
 const DEFAULT_IPV4_IP = '149.154.167.51'
@@ -273,6 +272,7 @@ class TelegramClient {
         return me
         return me
     }
     }
 
 
+
     async start(args = {
     async start(args = {
         phone: null,
         phone: null,
         code: null,
         code: null,
@@ -284,16 +284,27 @@ class TelegramClient {
         maxAttempts: 5,
         maxAttempts: 5,
     }) {
     }) {
         args.maxAttempts = args.maxAttempts || 5
         args.maxAttempts = args.maxAttempts || 5
-
         if (!this.isConnected()) {
         if (!this.isConnected()) {
             await this.connect()
             await this.connect()
         }
         }
         if (await this.isUserAuthorized()) {
         if (await this.isUserAuthorized()) {
             return this
             return this
         }
         }
-        let phone
+        if (args.code == null && !args.botToken) {
+            throw new Error('Please pass a promise to the code arg')
+        }
+        if (!args.botToken && !args.phone) {
+            throw new Error('Please provide either a phone or a bot token')
+        }
         if (!args.botToken) {
         if (!args.botToken) {
-            phone = utils.parsePhone(args.phone) || args.phone
+            while (typeof args.phone == 'function') {
+                const value = await args.phone()
+                if (value.indexOf(':') !== -1) {
+                    args.botToken = value
+                    break
+                }
+                args.phone = utils.parsePhone(value) || args.phone
+            }
         }
         }
         if (args.botToken) {
         if (args.botToken) {
             await this.signIn({
             await this.signIn({
@@ -306,17 +317,18 @@ class TelegramClient {
         let attempts = 0
         let attempts = 0
         let twoStepDetected = false
         let twoStepDetected = false
 
 
-        await this.sendCodeRequest(phone, args.forceSMS)
+        await this.sendCodeRequest(args.phone, args.forceSMS)
 
 
         let signUp = false
         let signUp = false
         while (attempts < args.maxAttempts) {
         while (attempts < args.maxAttempts) {
             try {
             try {
-                const value = args.code
+                const value = await args.code()
                 if (!value) {
                 if (!value) {
                     throw new errors.PhoneCodeEmptyError({
                     throw new errors.PhoneCodeEmptyError({
                         request: null,
                         request: null,
                     })
                     })
                 }
                 }
+
                 if (signUp) {
                 if (signUp) {
                     me = await this.signUp({
                     me = await this.signUp({
                         code: value,
                         code: value,
@@ -326,7 +338,7 @@ class TelegramClient {
                 } else {
                 } else {
                     // this throws SessionPasswordNeededError if 2FA enabled
                     // this throws SessionPasswordNeededError if 2FA enabled
                     me = await this.signIn({
                     me = await this.signIn({
-                        phone: phone,
+                        phone: args.phone,
                         code: value,
                         code: value,
                     })
                     })
                 }
                 }
@@ -358,13 +370,29 @@ class TelegramClient {
                 throw new Error('Two-step verification is enabled for this account. ' +
                 throw new Error('Two-step verification is enabled for this account. ' +
                     'Please provide the \'password\' argument to \'start()\'.')
                     'Please provide the \'password\' argument to \'start()\'.')
             }
             }
-            me = await this.signIn({
-                phone: phone,
-                password: args.password,
-            })
+            if (typeof args.password == 'function') {
+                for (let i = 0; i < args.maxAttempts; i++) {
+                    try {
+                        const pass = await args.password()
+                        me = await this.signIn({
+                            phone: args.phone,
+                            password: pass,
+                        })
+                        break
+                    } catch (e) {
+                        console.log('Invalid password. Please try again')
+                    }
+                }
+            } else {
+                me = await this.signIn({
+                    phone: args.phone,
+                    password: args.password,
+                })
+            }
+
         }
         }
         const name = utils.getDisplayName(me)
         const name = utils.getDisplayName(me)
-        console.log('Signed in successfully as', name)
+        console.log('Signed in successfully as'+ name)
         return this
         return this
     }
     }
 
 

+ 1 - 1
gramjs/extensions/PromisedWebSockets.js

@@ -49,7 +49,7 @@ class PromisedWebSockets {
 
 
     getWebSocketLink(ip, port) {
     getWebSocketLink(ip, port) {
         if (port === 443) {
         if (port === 443) {
-            return 'wss://' + ip + '/apiws'
+            return 'ws://' + ip + '/apiws'
         } else {
         } else {
             return 'ws://' + ip + '/apiws'
             return 'ws://' + ip + '/apiws'
         }
         }

+ 2 - 0
gramjs/extensions/index.js

@@ -0,0 +1,2 @@
+const Logger = require('./Logger')
+const BinaryWriter = require()

+ 2 - 3
gramjs/network/MTProtoSender.js

@@ -217,7 +217,6 @@ class MTProtoSender {
      * @private
      * @private
      */
      */
     async _connect() {
     async _connect() {
-
         this._log.info('Connecting to {0}...'.replace('{0}', this._connection))
         this._log.info('Connecting to {0}...'.replace('{0}', this._connection))
         await this._connection.connect()
         await this._connection.connect()
         this._log.debug('Connection success!')
         this._log.debug('Connection success!')
@@ -503,10 +502,10 @@ class MTProtoSender {
     async _handleUpdate(message) {
     async _handleUpdate(message) {
         if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {
         if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {
             // crc32(b'Updates')
             // crc32(b'Updates')
-            logger.warn(`Note: ${message.obj.constructor.name} is not an update, not dispatching it`)
+            this._log.warn(`Note: ${message.obj.constructor.name} is not an update, not dispatching it`)
             return
             return
         }
         }
-        this._log.debug('Handling update %s', message.obj.constructor.name)
+        this._log.debug('Handling update ' + message.obj.constructor.name)
         if (this._updateCallback) {
         if (this._updateCallback) {
             this._updateCallback(message.obj)
             this._updateCallback(message.obj)
         }
         }

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor