Commit a676a83d authored by tug's avatar tug

Create Tg Client NodeJS

parent 5e4e4945
...@@ -2,3 +2,4 @@ node_modules/ ...@@ -2,3 +2,4 @@ node_modules/
*.log *.log
_td* _td*
test test
clients
const fs = require('fs');
const path = require('path');
var getString = (o) => {
if (o !== null) {
if (typeof o === 'string') {
return o;
} else {
return JSON.stringify(o);
}
} else {
return null;
}
}
module.exports = class Handler {
constructor(clientNumber,tgclient) {
this.clientNumber = clientNumber;
this.TGID = 0;
this.prefix = '_tg';
this.tgc = tgclient;
this.logStream = fs.createWriteStream(path.join(__dirname, 'logs/handler_'+this.clientNumber+'.log'), {flags: 'a'});
// this.logStream = fs.createWriteStream('/var/www/tgc/logs/handler_'+this.clientNumber+'.log', {flags: 'a'});
}
listen(update) {
if(update._ && typeof this[update._] == 'function'){
var myFunc = this[update._].bind(this);
myFunc(update);
}
else {
this.ll("\n--== "+getString(update));
return;
}
}
updateOption (update){
this.ll('__updateOption ['+this.TGID+'] :'+getString(update))
// console.log();
if(update.name && update.value.value && update.name=="my_id"){
this.TGID = update.value.value;
}
}
updateAuthorizationState (update){
this.ll('__updateAuthorizationState ['+this.TGID+']['+this.clientNumber+'] :'+getString(update))
}
updateUserStatus(update){
this.ll('__updateUserStatus ['+this.TGID+'] :'+getString(update))
// console.log('-- updateUserStatus ['+this.TGID+'] :', update);
}
updateChatAction(update){
this.ll('__updateChatAction ['+this.TGID+'] :'+getString(update))
// console.log('-- updateChatAction ['+this.TGID+'] :', update);
}
ll(log){
var logline = (typeof tog != "string") ? getString(log) : log;
var time = Math.floor(Date.now() / 1000);
this.logStream.write("\n--==["+time+"]"+logline);
}
};
\ No newline at end of file
This diff is collapsed.
const http = require('http')
const process = require('process')
// const tgclient = require('./tgclient')
// const logger = require('./logger')
const Handler = require('./handler')
const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon')
var path = require('path');
var allClients = {};
var clientNumber = process.argv[2];
allClients[clientNumber] = {
number: clientNumber
};
function getClientPhoneNumber(r) {
console.log("- getting Phone NUMBER: ", clientNumber, r);
return clientNumber;
}
function getClientAuthCode(r) {
console.log("- getting AuthCode: ", r);
return false;
}
function getClientPassword(passwordHint, r) {
console.log("- getting ClientPassword: ", passwordHint, r);
return false;
}
async function startTgclient() {
console.log("-= Starting TGClient for NUMBER Inside: ", clientNumber);
const tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd',
tdlibParameters: {
application_version: '1.0',
device_model: 'TgClient',
system_version: 'TgOS',
}
})
const tgHandler = new Handler(clientNumber,tgclient);
tgclient.on('error', console.error)
// tgclient.on('update', tgHandler.listen);
tgclient.on('update', (...args) => tgHandler.listen(...args));
tgclient.connect().then(function(){
console.log("--= CONNECTED! Begin loggin in...")
tgclient.login(() => ({
getPhoneNumber: getClientPhoneNumber,
getAuthCode: getClientAuthCode,
getPassword: getClientPassword,
// getName: () => Promise.resolve({ firstName: 'John', lastName: 'Doe' })
}))
.then(function(){
console.log("--= LOGGED IN!")
});
})
// await tgclient.connectAndLogin()
// var meInfo = await tgclient.invoke({ _: 'getMe' }))
// console.log("--= ME: ",meInfo)
}
console.log("-= Begin Client for NUMBER: ", clientNumber);
startTgclient().catch(console.error)
var myNumber = 1;
const host = '192.168.130.10'
const port = 51000
function notFound(res) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.end('Not found\n')
}
function parseUrl(url)
{
var split = /^.*\/(getAuth|getMe|getUser|getUserFullInfo)_([^?]*)\??(.*)$/gi.exec(url);
var final_params = {};
split[3].split('&').forEach(function(pair){
var ps = pair.split('=');
final_params[ps[0]] = ps[1];
});
return {
name: split[1],
value: split[2],
params: final_params
};
}
const server = http.createServer((req, res) => {
//getAuthorizationState
myNumber = myNumber+1;
console.log(' ')
console.log(' ')
console.log('---=======- [ '+myNumber+' ] ---------')
console.log('This is the METHOD:' + req.method)
console.log('This is the URL:' + req.url)
console.log('This is the REQUEST Hdrs:')
console.log(req.headers)
switch (req.method) {
case 'GET': {
switch (req.url) {
case '/home': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Home page\n')
break
}
case '/about': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('About page\n')
break
}
case '/test': {
const chats = tgclient.invoke({
_: 'sendMessage',
chat_id: 124987160,
input_message_content: {
_: 'inputMessageText',
text: {
_: 'formattedText',
text: '👻 Test 123'
}
}
})
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('About page\n')
break
}
case '/getAuth': {
var tgAuth = tgclient.invoke({
_: 'getAuthorizationState',
chat_id: 124987160,
})
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end(tgAuth)
break
}
case '/': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello main\n')
break
}
default: {
notFound(res)
break
}
}
break
}
case 'POST': {
const reuqest = req.body;
const headers = req.headers;
console.log('-= REQUEST:', reuqest)
console.log('-= HEADERS:', headers)
switch (req.url) {
case '/api/admin': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Create admin request\n')
break
}
case '/api/user': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Create user request\n')
break
}
case '/sendMessage': {
const sentMessage = tgclient.invoke({
_: 'sendMessage',
chat_id: 124987160,
input_message_content: {
_: 'inputMessageText',
text: {
_: 'formattedText',
text: '👻 Test 123'
}
}
})
console.log('-=-=-= SENT MESSAGE: ')
console.log(sentMessage)
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Sent')
break
}
default: {
notFound(res)
break
}
}
break
}
default: {
notFound(res)
break
}
}
})
server.listen(port, host, () => {
console.log(`Server listens http://${host}:${port}`)
})
// server.listen(port, host, () => {
// console.log(`Server listens http://${host}:${port}`)
// })
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
"pm2": "^5.2.0", "pm2": "^5.2.0",
"tdl": "^7.1.0", "tdl": "^7.1.0",
"tdl-tdlib-addon": "^1.2.1", "tdl-tdlib-addon": "^1.2.1",
"url": "^0.11.0",
"winston": "^2.4.6" "winston": "^2.4.6"
}, },
"devDependencies": { "devDependencies": {
...@@ -2477,6 +2478,15 @@ ...@@ -2477,6 +2478,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/querystring": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz",
"integrity": "sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g==",
"deprecated": "The querystring API is considered Legacy. new code should use the URLSearchParams API instead.",
"engines": {
"node": ">=0.4.x"
}
},
"node_modules/range-parser": { "node_modules/range-parser": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
...@@ -3164,6 +3174,20 @@ ...@@ -3164,6 +3174,20 @@
"punycode": "^2.1.0" "punycode": "^2.1.0"
} }
}, },
"node_modules/url": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz",
"integrity": "sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ==",
"dependencies": {
"punycode": "1.3.2",
"querystring": "0.2.0"
}
},
"node_modules/url/node_modules/punycode": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz",
"integrity": "sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw=="
},
"node_modules/utils-merge": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
...@@ -5240,6 +5264,11 @@ ...@@ -5240,6 +5264,11 @@
"side-channel": "^1.0.4" "side-channel": "^1.0.4"
} }
}, },
"querystring": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz",
"integrity": "sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g=="
},
"range-parser": { "range-parser": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
...@@ -5746,6 +5775,22 @@ ...@@ -5746,6 +5775,22 @@
"punycode": "^2.1.0" "punycode": "^2.1.0"
} }
}, },
"url": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz",
"integrity": "sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ==",
"requires": {
"punycode": "1.3.2",
"querystring": "0.2.0"
},
"dependencies": {
"punycode": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz",
"integrity": "sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw=="
}
}
},
"utils-merge": { "utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
"pm2": "^5.2.0", "pm2": "^5.2.0",
"tdl": "^7.1.0", "tdl": "^7.1.0",
"tdl-tdlib-addon": "^1.2.1", "tdl-tdlib-addon": "^1.2.1",
"url": "^0.11.0",
"winston": "^2.4.6" "winston": "^2.4.6"
}, },
"devDependencies": { "devDependencies": {
......
// const tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
// apiId: 234569,
// apiHash: 'ee77bf549e61d3de158916126c8ef7dd',
// tdlibParameters: {
// application_version: '1.0',
// device_model: 'TgClient',
// system_version: 'TgOS',
// }
// })
// const tgHandler = new Handler(tgclient);
// tgclient.on('error', console.error)
// tgclient.on('update', tgHandler.listen);
// tgclient.on('update', update => {
// console.log('Received update:', update)
// })
\ No newline at end of file
const http = require('http')
const net = require('net')
const fs = require('fs')
const path = require('path')
const process = require('process')
const Handler = require('./handler')
const { Client } = require('tdl') const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon') const { TDLib } = require('tdl-tdlib-addon')
var path = require('path'); const prefix = '_tg';
const tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), { console.log("--======== TG Client Process ARGV:", process.argv )
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd' var clientNumber = process.argv[2];
}) var TGID = 0;
var clienDirectory = path.join(__dirname, 'clients/'+clientNumber)
var SOCKETFILE = path.join(clienDirectory, 'tgclient.sock')
var SHUTDOWN = false;
var tgServer;
connections = {};
tgclient.on('error', console.error) if (!fs.existsSync(clienDirectory)){
tgclient.on('update', update => { fs.mkdirSync(clienDirectory, { recursive: true });
console.log('Received update:', update) }
var logStream = fs.createWriteStream(path.join(__dirname, 'logs/handler_'+clientNumber+'.log'), {flags: 'a'});
var tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd',
tdlibParameters: {
application_version: '1.0',
device_model: 'TgClient',
system_version: 'TgOS',
}
}) })
const tgHandler = new Handler(clientNumber,tgclient);
async function main () { console.log(" ")
await tgclient.connectAndLogin() console.log("--======== TG Client ["+clientNumber+"] INITED!",)
tgHandler.ll(" ")
tgHandler.ll("--======== TG Client ["+clientNumber+"] INITED!")
console.log(await tgclient.invoke({ _: 'getMe' })) tgHandler.ll(" ")
tgHandler.ll("--======== TG clienDirectory ["+clienDirectory+"]")
tgHandler.ll("--======== TG SOCKETFILE ["+SOCKETFILE+"]")
// ... function processIncom(msg){
console.log("--===== INCOM MSG: "+msg);
// msg = msg.toString();
return '';
} }
main().catch(console.error)
module.exports = tgclient function startClient() {
\ No newline at end of file tgHandler.ll(" ")
tgHandler.ll("--======== TG Client CMD: [startClient]-------")
}
// function startClient() {
// tgclient.on('error', console.error)
// tgclient.on('update', (...args) => tgHandler.listen(...args));
// tgclient.connect().then(function(){
// console.log("--= CONNECTEDS! Begin loggin in...")
// tgclient.login(() => ({
// getPhoneNumber: getClientPhoneNumber,
// getAuthCode: getClientAuthCode,
// getPassword: getClientPassword,
// // getName: () => Promise.resolve({ firstName: 'John', lastName: 'Doe' })
// }))
// .then(function(){
// console.log("--= ["+clientNumber+"] LOGGEDS IN!")
// });
// })
// }
// function stop() {
// tgclient.close()
// }
// // getAuth() {
// // var tgAuth = tgclient.invoke({
// // _: 'getAuthorizationState',
// // chat_id: 124987160,
// // })
// // }
// function getClientPhoneNumber(r) {
// console.log("- getting Phone NUMBER: ", clientNumber, r);
// return clientNumber;
// }
// function getClientAuthCode(r) {
// console.log("- getting AuthCode: ", r);
// return false;
// }
// function getClientPassword(passwordHint, r) {
// console.log("- getting ClientPassword: ", passwordHint, r);
// return false;
// }
// console.log("--= Client Process for ["+clientNumber+"] INITed!")
// var myNumber = 0;
// const tgServer = http.createServer((req, res) => {
// // const path = url.parse(req.url).path.split('/');
// // var allMethods = ['start','stop','restart','state'];
// myNumber = myNumber+1;
// console.log(' ')
// console.log(' ')
// console.log('---=======- [ '+clientNumber+' ] ('+myNumber+') ---------')
// console.log('This is the REQ:' + req)
// console.log('This is the RES:' + res)
// });
// tgServer.on('error', (e) => {
// if (e.code === 'EADDRINUSE') {
// console.log('Address in use, retrying...', tgServer.listening);
// setTimeout(() => {
// if(tgServer.listening){
// tgServer.close();
// tgServerToListen();
// }
// else {
// fs.unlink(clienSocketFile, function(err) {
// if (err) {
// throw err
// } else {
// console.log("Successfully deleted the socket file:",clienSocketFile)
// tgServerToListen();
// }
// })
// }
// }, 1000);
// }
// });
function tgServerToListen(){
// check for failed cleanup
console.log('--=== BEGIN to listening SOCKET...');
fs.stat(SOCKETFILE, function (err, stats) {
if (err) {
// start server
console.log('No leftover socket found.');
tgServer = createServer(SOCKETFILE); return;
}
// remove file then start server
console.log('Removing leftover socket.')
fs.unlink(SOCKETFILE, function(err){
if(err){
// This should never happen.
console.error(err); process.exit(0);
}
tgServer = createServer(SOCKETFILE); return;
});
});
// close all connections when the user does CTRL-C
function cleanup(){
if(!SHUTDOWN){ SHUTDOWN = true;
console.log('\n',"Terminating.",'\n');
if(Object.keys(connections).length){
let clients = Object.keys(connections);
while(clients.length){
let client = clients.pop();
connections[client].write('__disconnect');
connections[client].end();
}
}
tgServer.close();
process.exit(0);
}
}
process.on('SIGINT', cleanup);
}
function createServer(socket){
console.log('Creating server on socket: '+socket);
var server = net.createServer(function(stream) {
console.log('Connection acknowledged: '+socket);
// Store all connections so we can terminate them if the server closes.
// An object is better than an array for these.
var self = Date.now();
connections[self] = (stream);
stream.on('end', function() {
console.log('Client disconnected: '+socket);
delete connections[self];
});
// Messages are buffers. use toString
stream.on('data', function(msg) {
var resultMsg = processIncom(msg);
console.log("--===== INCOM RESULT: "+resultMsg);
stream.write(resultMsg);
// msg = msg.toString(); console.log("--===== INCOM MSG: "+msg);
// if(msg === '__snootbooped'){
// console.log("Client's snoot confirmed booped: "+socket);
// return;
// }
// console.log('Client:', msg);
// if(msg === 'foo'){
// stream.write('bar');
// }
// if(msg === 'baz'){
// stream.write('qux');
// }
// if(msg === 'here come dat boi'){
// stream.write('Kill yourself.');
// }
});
})
.listen(socket)
.on('connection', function(socket){
console.log('Client connected.');
console.log('Sending boop.');
socket.write('__boop');
//console.log(Object.keys(socket));
})
;
return server;
}
// function tgServerToListen(){
// console.log(`--===== BEGIN TgServer listening: ${clienSocketFile}`)
// tgServer.listen(clienSocketFile, 50, () => {
// console.log(`--===== TgServer listens: ${clienSocketFile}`)
// startClient();
// });
// }
tgServerToListen();
process.on('message', function(packet) {
console.log("- PM2 ON_MESSAGE: ", packet)
if(typeof packet.data == 'object'){
if(typeof packet.data.cmd != 'undefined' && typeof tgHandler[packet.data.cmd] == 'function'){
var myFunc = tgHandler[packet.data.cmd].bind(tgHandler);
myFunc(packet.data);
}
}
process.send({
type : 'process:msg',
data : {
success : true
}
});
});
\ No newline at end of file
const http = require('http')
const fs = require('fs')
const path = require('path')
const process = require('process')
const Handler = require('./handler')
const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon')
var clientNumber = process.argv[2];
module.exports = class TGClient {
constructor(clientNumbers) {
console.log("-= Constructing TGClient for NUMBER Inside: ", clientNumber);
this.clientNumber = clientNumber;
this.TGID = 0;
this.prefix = '_tg';
this.logStream = fs.createWriteStream(path.join(__dirname, 'logs/handler_'+this.clientNumber+'.log'), {flags: 'a'});
this.tgc = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd',
tdlibParameters: {
application_version: '1.0',
device_model: 'TgClient',
system_version: 'TgOS',
}
})
}
// getAuth() {
// var tgAuth = tgclient.invoke({
// _: 'getAuthorizationState',
// chat_id: 124987160,
// })
// }
start() {
const self = this
const clientNumber = this.clientNumber
const tgclient = this.tgc
const tgHandler = new Handler(clientNumber,tgclient);
tgclient.on('error', console.error)
tgclient.on('update', (...args) => tgHandler.listen(...args));
tgclient.connect().then(function(){
console.log("--= CONNECTED! Begin loggin in...")
tgclient.login(() => ({
getPhoneNumber: getClientPhoneNumber,
getAuthCode: getClientAuthCode,
getPassword: getClientPassword,
// getName: () => Promise.resolve({ firstName: 'John', lastName: 'Doe' })
}))
.then(function(){
console.log("--= ["+clientNumber+"] LOGGED IN!")
});
})
}
stop() {
const self = this
const clientNumber = this.clientNumber
this.tgc.close()
}
}
function getClientPhoneNumber(r) {
console.log("- getting Phone NUMBER: ", clientNumber, r);
return clientNumber;
}
function getClientAuthCode(r) {
console.log("- getting AuthCode: ", r);
return false;
}
function getClientPassword(passwordHint, r) {
console.log("- getting ClientPassword: ", passwordHint, r);
return false;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment