Commit a676a83d authored by tug's avatar tug

Create Tg Client NodeJS

parent 5e4e4945
......@@ -2,3 +2,4 @@ node_modules/
*.log
_td*
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
const http = require('http')
// const tgclient = require('./tgclient')
// const logger = require('./logger')
const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon')
var path = require('path');
const tgclient = new Client(new TDLib(path.join(__dirname, 'td/build/libtdjson.so')), {
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd'
})
const url = require('url')
const process = require('process')
// const TGClient = require('./tgc')
var path = require('path')
const pm2 = require('pm2')
var allClients = {};
var pm2Connected = false;
var myNumber = 1;
const host = '192.168.130.10'
const port = 51000
tgclient.on('error', console.error)
tgclient.on('update', update => {
console.log('Received update:', update)
})
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
};
}
async function main () {
await tgclient.connectAndLogin()
function list(cbk){
if(pm2Connected){
pm2.list((err, list) => {
var processes = [];
if(typeof list != 'undefined' && list){
var pnn = 1;
list.forEach(function(app){
console.log("-= PM2 Listing processes EACH: ", app);
var currProcc = {
pm_id: app.pm_id,
pm_name: app.name,
pm_monit: app.monit,
pm_status: (app.pm2_env && app.pm2_env.status && app.pm2_env.status=="online")
};
if(app.name.substring(0,4)=="tgc_"){
var currClNumber = app.name.substring(4);
if(!allClients[currClNumber]){
allClients[currClNumber] = {
name: app.name,
pm_id: app.pm_id,
status: currProcc.pm_status
}
}
else {
allClients[currClNumber]['status'] = currProcc.pm_status
}
}
processes.push(currProcc);
if(pnn==list.length){
if(typeof cbk != 'undefined'){
cbk(processes);
}
}
else {
pnn = pnn+1;
}
})
}
});
}
}
console.log(await tgclient.invoke({ _: 'getMe' }))
function state(clientNumber){
console.log("-= Starting TGClient for allClients: ", allClients);
console.log("-= Starting TGClient for allClients NUM: ", allClients[clientNumber]);
return { result: (allClients[clientNumber] && allClients[clientNumber]['status']) ? true : false };
}
// ...
function start(clientNumber){
console.log("-= Starting TGClient for NUMBER: ", clientNumber);
allClients[clientNumber] = {}
if(pm2Connected){
list(function(){
if(!allClients[clientNumber]['status']){
pm2.start({
script : 'tgc.js',
name : 'tgc_'+clientNumber,
args : clientNumber
}, function(err, startedApp) {
if (err) {
console.error(err)
return pm2.disconnect()
}
if(startedApp) {
startedApp.forEach(function(app){
if(app.name=='tgc_'+clientNumber){
allClients[clientNumber]['name'] = app.name
allClients[clientNumber]['pm_id'] = app.pm_id
}
})
}
console.log("-= Starting for startedApp: ", startedApp);
senddata(clientNumber, {cmd:'startClient'})
})
}
})
}
// const tclient = new TGClient(clientNumber);
// tclient.start();
// allClients[clientNumber]['tgclient'] = tclient;
// console.log('---=======- CLIENT CNT [ '+Object.keys(allClients).length+' ] ---------')
return {result:true};
}
main().catch(console.error)
function stop(clientNumber){
console.log("--== STOPing COMMAND: ", pm2Connected, clientNumber, allClients);
// allClients[clientNumber]['tgclient'].stop();
if(pm2Connected){
console.log("--== STOPing pm ID: ", allClients[clientNumber]);
var pmIden = (allClients[clientNumber] && allClients[clientNumber]['pm_id']) ? allClients[clientNumber]['pm_id'] : 'tgc_'+clientNumber;
pm2.stop(pmIden,
function(err, stopedApp) {
if (err) {
console.error(err)
return pm2.disconnect()
}
console.log("-= Starting for stopedApp: ", stopedApp);
if(typeof stopedApp.status != 'undefined' && stopedApp.status=='stopped'){
allClients[clientNumber]['status'] = false;
}
else if(typeof stopedApp.pm2_env != 'undefined' && typeof stopedApp.pm2_env.status != 'undefined' && stopedApp.status=='stopped'){
allClients[clientNumber]['pm_id'] = stopedApp.pm_id;
allClients[clientNumber]['status'] = false;
}
})
}
return {result:true};
}
function restart(clientNumber){
console.log("--== RESTARTing COMMAND: ", clientNumber);
if(pm2Connected && allClients[clientNumber] && allClients[clientNumber]['pm_id']){
pm2.restart(allClients[clientNumber]['pm_id'], {},
function(err, restartedApp) {
if (err) {
console.error(err)
return pm2.disconnect()
}
console.log("-= Starting for restartedApp: ", restartedApp);
})
}
return {result:true};
}
var myNumber = 1;
function senddata(clientNumber, data){
console.log("--== SENDing Data to: ", clientNumber, data);
if(pm2Connected && allClients[clientNumber] && allClients[clientNumber]['pm_id']){
pm2.sendDataToProcessId({
// id of procces from "pm2 list" command or from pm2.list(errback) method
id : allClients[clientNumber]['pm_id'],
// process:msg will be send as 'message' on target process
type : 'process:msg',
const host = '192.168.130.10'
const port = 51000
// Data to be sent
data : data,
topic: true
}, function(err, res) {
console.log("-= SendData ERROR: ", err, res);
})
}
}
function notFound(res) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.end('Not found\n')
var getString = (o) => {
if (o !== null) {
if (typeof o === 'string') {
return o;
} else {
return JSON.stringify(o);
}
} else {
return null;
}
}
const server = http.createServer((req, res) => {
//getAuthorizationState
// let url=req.url.parse(req.originalUrl);
// let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';
const path = url.parse(req.url).path.split('/');
var allMethods = ['start','stop','restart','state','list'];
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 URL:' + url)
console.log('This is the path:', path)
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': {
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 '/': {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello main\n')
break
}
default: {
notFound(res)
break
}
}
break
}
case 'POST': {
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
}
default: {
notFound(res)
break
}
}
var param = (path[2] && path[2].length) ? path[2].replace(/\D/g, '') : false;
console.log('This is the PARAM:', param)
if(path[1] && path[1].length && allMethods.indexOf(path[1])!='-1'){
break
console.log(' ')
console.log(' --------======== COMMAND ['+path[1]+'] =======-----------')
console.log("--== CLIENTS: ", allClients);
console.log(' ')
if(param){
var result = eval(path[1])(param);
console.log(' -= Cmd Params:', param)
}
default: {
notFound(res)
break
else {
var result = eval(path[1]);
}
console.log(' --------======== COMMAND RES:', result)
if(result){
var resStr = getString(result)
console.log(' --------======== COMMAND RES TEXT:', resStr)
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(resStr)
}
}
else {
res.statusCode = 404
res.setHeader('Content-Type', 'text/plain')
res.end('Command not found\n')
}
})
server.listen(port, host, () => {
console.log(`Server listens http://${host}:${port}`)
})
\ No newline at end of file
console.log(`Server listens http://${host}:${port}`)
pm2.connect(function(err) {
if (err) {
pm2Connected = false
console.error(err)
process.exit(2)
}
pm2Connected = true
console.log('-= PM2 connected!')
pm2.launchBus(function(err, pm2_bus) {
console.log("-= PM2 incom LaunchBUS Started!",err)
pm2_bus.on('process:msg', function(packet) {
console.log("-= PM2 incom PACKET:",packet)
})
})
list();
});
})
// server.listen(port, host, () => {
// console.log(`Server listens http://${host}:${port}`)
// })
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 @@
"pm2": "^5.2.0",
"tdl": "^7.1.0",
"tdl-tdlib-addon": "^1.2.1",
"url": "^0.11.0",
"winston": "^2.4.6"
},
"devDependencies": {
......@@ -2477,6 +2478,15 @@
"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": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
......@@ -3164,6 +3174,20 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
......@@ -5240,6 +5264,11 @@
"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": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
......@@ -5746,6 +5775,22 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
......
......@@ -26,6 +26,7 @@
"pm2": "^5.2.0",
"tdl": "^7.1.0",
"tdl-tdlib-addon": "^1.2.1",
"url": "^0.11.0",
"winston": "^2.4.6"
},
"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 { 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')), {
apiId: 234569,
apiHash: 'ee77bf549e61d3de158916126c8ef7dd'
})
console.log("--======== TG Client Process ARGV:", process.argv )
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)
tgclient.on('update', update => {
console.log('Received update:', update)
if (!fs.existsSync(clienDirectory)){
fs.mkdirSync(clienDirectory, { recursive: true });
}
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 () {
await tgclient.connectAndLogin()
console.log(" ")
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
\ No newline at end of file
function startClient() {
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