Skip to content

Instantly share code, notes, and snippets.

@rahman541
Created February 4, 2019 09:46
Show Gist options
  • Save rahman541/c3b5ca6b510cf7735c0accd210b849db to your computer and use it in GitHub Desktop.
Save rahman541/c3b5ca6b510cf7735c0accd210b849db to your computer and use it in GitHub Desktop.
TDLib in Javascript
const ref = require('ref-napi')
const ffi = require('ffi-napi')
const win = require('./win')
const rs = require('readline-sync')
win.SetDllDirectoryA('../tdlib')
tdlib = ffi.Library('tdjson.dll', {
'td_json_client_create': ['pointer', []],
'td_json_client_send': ['void', ['pointer', 'string']],
'td_json_client_receive': ['string', ['pointer', 'double']],
'td_json_client_execute': ['string', ['pointer', 'string']],
'td_json_client_destroy': ['void', ['pointer']],
'td_set_log_file_path': ['int', ['string']],
'td_set_log_verbosity_level': ['void', ['int']],
'td_set_log_fatal_error_callback': ['void', ['pointer']]
});
function buildQuery(query) {
const buffer = Buffer.from(JSON.stringify(query) + '\0', 'utf-8')
buffer.type = ref.types.CString
return buffer
}
// Create client
tdlib.td_set_log_verbosity_level(1)
const client = tdlib.td_json_client_create()
function send(query) {
tdlib.td_json_client_send(client, buildQuery(query))
}
function execute(query) {
return JSON.parse(
tdlib.td_json_client_execute(client, buildQuery(query))
)
}
function receive() {
const timeout = 5
let obj = JSON.parse(
tdlib.td_json_client_receive(client, timeout)
)
checkAuthenticationError(obj)
return obj
}
function destroy() {
tdlib.td_json_client_destroy(client)
}
authorized = false
needRestart = false
authState = {}
function loop() {
while (true) {
if (!authorized) {
processResponse(receive())
} else {
action = rs.question('Enter action [q] quit [u] update [l] logout: ')
if (action == 'q') return
else if (action == 'l') {
send({'@type': 'logOut'})
}
}
}
}
function processResponse(res) {
if (res == null) return
processUpdate(res)
}
function processUpdate(res) {
console.log('processUpdate', res['@type'])
if (res['@type'] == 'updateAuthorizationState') {
onAuthorizationStateUpdate(authState = res.authorization_state)
}
}
function onAuthorizationStateUpdate() {
state = authState['@type']
if (state == 'authorizationStateReady') {
authorized = true
console.log('Got Authorized..\n')
} else if (state == 'authorizationStateLoggingOut') {
authorized = false
console.log('Logging out..')
} else if (state == 'authorizationStateClosing') {
console.log('Closing..')
} else if (state == 'authorizationStateClosed') {
} else if (state == 'authorizationStateWaitCode') {
let first_name = '', last_name = '';
if (!authState.is_registered) {
console.log('\nNew user')
first_name = rs.question('First Name: ')
last_name = rs.question('Last Name: ')
}
code = rs.question('Enter authentication code: ')
send({ '@type': 'checkAuthenticationCode', code, first_name, last_name })
} else if (state == 'authorizationStateWaitEncryptionKey') {
let key = rs.question('Enter encryption key: ');
send({'@type': 'checkDatabaseEncryptionKey','key': key})
} else if (state == 'authorizationStateWaitPhoneNumber') {
let num = rs.question('Enter phone number: ');
send({ '@type': 'setAuthenticationPhoneNumber', 'phone_number': num, 'allow_flash_call_': false, 'is_current_phone_number': false })
} else if (state == 'authorizationStateWaitTdlibParameters') {
send({
'@type': 'setTdlibParameters',
'parameters': {
"database_directory": "db",
"use_message_database": true,
"use_secret_chats": false,
"api_id": 11111,
"api_hash": "aaaaaa",
"system_language_code": "en",
"device_model": "Windows",
"system_version": "10.0",
"application_version": "0.1",
"enable_storage_optimizer": true
}
})
}
}
function checkAuthenticationError(res) {
if (res && res['@type'] == 'error') {
console.log('\n', 'ERROR ' + res['code'] + ': ' + res['message'],'\n')
onAuthorizationStateUpdate()
}
}
loop()
// Destroy client
destroy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment