tgc.js 21.4 KB
Newer Older
Azizov Aziz 's avatar
Azizov Aziz committed
1
const { getString, getFromJson, parseUrl, getBinarySize, rlog } = require('./tools'); 
tug's avatar
tug committed
2 3 4 5 6
const http = require('http')
const net = require('net')
const fs = require('fs')
const path = require('path')
const process = require('process')
Azizov Aziz 's avatar
Azizov Aziz committed
7
// import dateFormat, { masks } from "dateformat";
tug's avatar
tug committed
8
const Handler = require('./handler')
Azizov Aziz 's avatar
Azizov Aziz committed
9 10 11
const DB = require('./models')
// const Domains = require('./models/domains')
// const Accounts = require('./models/accounts')
tug's avatar
tug committed
12 13
const { Client } = require('tdl')
const { TDLib } = require('tdl-tdlib-addon')
tug's avatar
tug committed
14
const prefix = '_tg';
Azizov Aziz 's avatar
Azizov Aziz committed
15 16 17 18 19 20
// const Sequelize = require('sequelize');
const BXAPI = require('./bx24'); 
// const { getBinarySize } = require('./tools'); 
var moment = require('moment');
var currDate = moment().format("YY_DD_MM")
//getFromJson parseUrl getBinarySize
tug's avatar
tug committed
21 22 23
console.log("--======== TG Client Process ARGV:",  process.argv )

var clientNumber = process.argv[2];
Azizov Aziz 's avatar
Azizov Aziz committed
24 25 26 27 28 29 30 31

if(!clientNumber || clientNumber.length<9){
	//	ll("--======== TG Client STOP, Bad Phone Number: ", clientNumber )
	process.exit(0);
}

var DBC = {};
var B24 = false;
tug's avatar
tug committed
32
var TGID = 0;
Azizov Aziz 's avatar
Azizov Aziz committed
33 34 35 36 37 38
var account = false;
var domain = false;
var domainName = false;
var domainId = false;
var TGAuthSmsCode = false;
var TGAuthPassword = false;
tug's avatar
tug committed
39
var clienDirectory = path.join(__dirname, 'clients/'+clientNumber)
Azizov Aziz 's avatar
Azizov Aziz committed
40 41 42 43 44
var clienDirectoryDb = path.join(__dirname, 'clients/'+clientNumber+'/_td_database')
var clienDirectoryFiles = path.join(__dirname, 'clients/'+clientNumber+'/_td_files')
var logStream = false;
var tgclient = false;
var tgHandler = false;
tug's avatar
tug committed
45 46
var SHUTDOWN = false;
var tgServer;
Azizov Aziz 's avatar
Azizov Aziz committed
47 48
var connections = {};
var tgTdlibPath = path.join(__dirname, 'td/libtdjson.so')
tug's avatar
tug committed
49

tug's avatar
tug committed
50 51 52
if (!fs.existsSync(clienDirectory)){
    fs.mkdirSync(clienDirectory, { recursive: true });
}
Azizov Aziz 's avatar
Azizov Aziz committed
53 54 55 56 57 58
if (!fs.existsSync(clienDirectoryDb)){
    fs.mkdirSync(clienDirectoryDb, { recursive: true });
}
if (!fs.existsSync(clienDirectoryFiles)){
    fs.mkdirSync(clienDirectoryFiles, { recursive: true });
}
tug's avatar
tug committed
59

Azizov Aziz 's avatar
Azizov Aziz committed
60
var tgClientParams = {
tug's avatar
tug committed
61 62
	apiId: 234569,
	apiHash: 'ee77bf549e61d3de158916126c8ef7dd',
Azizov Aziz 's avatar
Azizov Aziz committed
63 64
	databaseDirectory: clienDirectoryDb, // Relative path (default is '_td_database')
	filesDirectory: clienDirectoryFiles, // Relative path (default is '_td_files')
tug's avatar
tug committed
65 66 67 68 69
	tdlibParameters: {
		application_version: '1.0',
		device_model: 'TgClient',
		system_version: 'TgOS',
	}
Azizov Aziz 's avatar
Azizov Aziz committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
}
var SOCKETFILE = path.join(clienDirectory, 'tgclient.sock')
	//
ll("--======== TG Client ["+clientNumber+"] INITED run...",)

// var dbc = mysql.createConnection({
  // host     : 'localhost',
  // user     : 'tug',
  // password : 'mteam',
  // database : 'tgc_dev'
// });

// const dbc = new Sequelize(
   // 'tgc_dev',
   // 'tug',
   // 'mteam',
    // {
		// host: 'localhost',
		// dialect: 'mysql'
    // }
// );


async function processIncom(msg){
	return new Promise((resolve, reject) => {
		msg = JSON.parse( msg.toString()); 

		ll("--===== INCOM MSG:", msg);

		switch (msg.cmd) {
			case 'getTest':
				getTest(msg).then(resolve)
				return
			case 'getTests':
				getTests(msg).then(resolve)
				return
				
			case 'getId':
				getId().then(resolve)
				return	
				
			case 'getState':
				getState().then(resolve)
				return
				
			case 'getAuth':
				getAuth().then(resolve)
				return
				
			case 'getFileById':
				getFileById(msg).then(resolve)
				return
				
			case 'getFilePath':
				getFilePath(msg).then(resolve)
				return

			case 'getRemoteFile':
				getRemoteFile(msg).then(resolve)
				return
				
			// case 'startClient':
				// startClient().then(resolve)
				// return
				
			case 'stopClient':
				stopClient(msg).then(resolve)
				return	
				
			case 'setAuthSmscode':
				setAuthSmscode(msg).then(resolve)
				return	
			case 'startHanler':
				
				tgHandler.start(msg.lineid).then(function () {
					resolve(true)
				})
				return
			case 'stopHanler':
				tgHandler.stop().then(function () {
					resolve(true)
				})
				return
			case 'removeAccount':
				tgHandler.remove()
				resolve(true)
				return
			case 'setAuthPassword':
				setAuthPassword(msg).then(resolve)
				return
			case 'test':
				return resolve('TGID  ---->>>' + tgHandler.TGID)
				
			default:
				ping(msg).then(resolve)
				return
		}
		
	});
}

async function ping() {
	return new Promise((resolve, reject) => {
		resolve( {result:true} );
	});
}

async function getTests() {
	return new Promise((resolve, reject) => {
		resolve( {result:"Tests ok1"} );
	});
	// return {result:"ok"};
}
async function getTest() {
	return new Promise((resolve, reject) => {
		setTimeout(function(){
			resolve( {result:"Test ok"} );
		},3000)
	});
	// return {result:"ok"};
}

// async function initingDbTables() {
	
	// console.log('--== INIT initingDbTables..');
tug's avatar
tug committed
195
	
Azizov Aziz 's avatar
Azizov Aziz committed
196 197 198 199 200 201
	// await Domains.init(dbc)
	// await Accounts.init(dbc)
	// await Chats.init(dbc)
	// console.log('--== INIT initED Tables..');
// }

tug's avatar
tug committed
202

Azizov Aziz 's avatar
Azizov Aziz committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
async function prepareDatabases() {
	// DBC = datatables
	ll('--== Preparing DB For Account: ['+clientNumber+']');
	return new Promise((resolve, reject) => {
		if(!clientNumber){
			reject({result:'No Client Number'});
			return;
		}

		DBC.Accounts.findOne({ where: { phone_number: clientNumber } })
			.then(async function(oaccount){
				account = oaccount
				ll("--= DB Account Found: ", oaccount.dataValues.id, clientNumber)
				
				if(oaccount && oaccount.domain_id){
					account = oaccount;
					domainId = oaccount.domain_id;
					var dWr = { id:domainId }
					
						ll("-= Domain srch id: ", dWr)
					
					// DBC.Domains.find	//All({where:dWr})
						// .then(function(ressss){
							//	// ll("-= Domains WR LIST: ", ressss)
						// })
					
					// DBC.Domains.findOne({ where: dWr })
					DBC.Domains.findOne({where:dWr})
						// .then(o => o[0])
						.then(function(odomain){
							//	ll("--= DB Domain GET by account: ", odomain)
							if(odomain && odomain.id){
								domain = odomain;
								domainId = odomain.id;
								domainName = odomain.name;
								
								B24 = new BXAPI()

								ll("--= B24 before init: ", domainName)
								B24.init(DBC, domainName)
									.then(function(BXDOMAIN){
										domain = BXDOMAIN
											ll("--= Bitrix INITED Tgc: ",domain)
										resolve();
									})
									.catch(function(e){
										//	ll("--= Bitrix24 INIT Error: ",e)
										reject({result:'Bitrix for Domain not inited'});
										ll('EXITING: ', e)
										// TODO UPDATE TOCKEN
										process.exit(0)
										return;
									}); 
					
									
							}
							
							
						})
						.catch(function(e){
							//	ll("--= DB Account Found: eorroooorrr ", e)
							reject({result:'Domain of Account not found'});
							return;
						})
						
											
					// new BXAPI('edo.4u.uz').then(function(B24){
				
					
					// B24.init().then(function(){
						// console.log("--= Bitrix TEST: ",B24.domain)
						// // console.log("--= Bitrix TEST: ",BXO.options.test_domain)
					// }); 
					
					
					
				}
				
			}).catch(function(e){
				console.log(e)
				reject({result:'Account not found'});
				return;
			})
	})
}
tug's avatar
tug committed
288

Azizov Aziz 's avatar
Azizov Aziz committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
async function startClient() {
	return new Promise((resolve, reject) => {
		if(tgclient && tgHandler && tgHandler.getAuthorizationState()) {
			resolve({result:true});
			return;
		}
		
		ll('--== Begin Starting client: ['+clientNumber+']');
		
		// ll('--== TESt Text SIZE: ', getBinarySize('kdsjf ghksdjfhg валопварывралпдо dhfkgjsh dkfjghskdjf ghksdjf '));
		
		
		prepareDatabases()
			.then(() => ll('--== Begin Starting client2'))
			.then(() => B24.isInited || Promise.reject(new Error('B24 is not inited')))
			.then(() => B24.call('app.info', {}))
			.then(() => {
				tgclient = new Client(new TDLib(tgTdlibPath), tgClientParams)
				
				tgHandler = new Handler(clientNumber,tgclient,{ domain,account, DBC, B24 })

				tgclient.on('error', console.error)
				tgclient.on('update', (...args) => tgHandler.listen(...args))

				return tgclient.connect()
			})
			.then(() => tgclient.login(() => ({
				getPhoneNumber: getClientPhoneNumber,
				getAuthCode: getClientAuthCode,
				getPassword: getClientPassword,
				// getName: () => Promise.resolve({ firstName: 'John', lastName: 'Doe' })
			})))
			.catch(e => {
				console.error('startClient ERROR', e)
				ll('ERROR: ', e)
				throw e
			})

		resolve({result:true})	
	})
}
tug's avatar
tug committed
330

Azizov Aziz 's avatar
Azizov Aziz committed
331 332 333
function errLog(...data) {
	// console.error(data)
	ll(" !!! ERROR: ", data)
tug's avatar
tug committed
334 335
}

Azizov Aziz 's avatar
Azizov Aziz committed
336 337 338 339 340 341 342
async function stopClient() {

	if(!tgclient) return {result:true};
	
	return new Promise((resolve, reject) => {
		tgclient.close()
		tgclient = false;
tug's avatar
tug committed
343

Azizov Aziz 's avatar
Azizov Aziz committed
344 345
		resolve({result:true});
	})
tug's avatar
tug committed
346
}
Azizov Aziz 's avatar
Azizov Aziz committed
347 348

async function getMe() {
tug's avatar
tug committed
349
	
Azizov Aziz 's avatar
Azizov Aziz committed
350
	if(!tgclient) return {result:false};
tug's avatar
tug committed
351
	
Azizov Aziz 's avatar
Azizov Aziz committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
	var me = await tgclient.invoke({ _: 'getMe' })
	//	ll("--== getMe RES ["+clientNumber+"]:", me)
	return me;
}

async function getUserInfo(chat_id) {
	if(!tgclient) return {result:false};
	return tgclient.invoke({ _: 'getChat', chat_id })
}

async function getState() {
	if(!tgclient) return {result:false};
	
	return new Promise((resolve, reject) => {
		var authState = (tgHandler) ? tgHandler.getAuthorizationState() : false;

tug's avatar
tug committed
368
		
Azizov Aziz 's avatar
Azizov Aziz committed
369 370 371 372 373 374 375 376 377 378 379
		// var tgAuth = await tgclient.invoke({
		  // _: 'getAuthorizationState',
		  // chat_id: 124987160,
		// })
		
		// console.log("--== getAuthorizationState RES ["+clientNumber+"]:", tgAuth)
		
		resolve( {result:authState} );
	});
	
}
tug's avatar
tug committed
380

Azizov Aziz 's avatar
Azizov Aziz committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
async function getAuth() {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	
	return new Promise((resolve, reject) => {
		var tgId = tgHandler.getId();
		if(!tgId){
			resolve( {result:false} );
		}
		
		var tgAuth = tgclient.invoke({
			_: 'getAuthorizationState',
			chat_id: tgId,
		})
		
		//	ll("--== getAuthorizationState RES ["+clientNumber+"]:", tgAuth)
		
		resolve( {result:tgAuth} );
	});
	
}
tug's avatar
tug committed
402

Azizov Aziz 's avatar
Azizov Aziz committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
async function getFilePath(p) {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	if(typeof p.file_id == 'undefined' && typeof p.file_remote_id == 'undefined') return {result:false};
	
	
	try {
		
		if(typeof p.file_remote_id != 'undefined'){
			//	ll("--== getFilePath Begin remoteCatching ["+clientNumber+"]:", p.file_remote_id)
			var resRemote =  await getRemoteFile({remote_id:p.file_remote_id})
			
			//	ll("--== getRemoteFile RES ["+clientNumber+"]:", resRemote)
			
			if(typeof resRemote.result != 'undefined' && typeof resRemote.result.local != 'undefined' && resRemote.result.local.is_downloading_completed){
				return {result:resRemote.result.local.path};
			}
			
			if(typeof resRemote.result != 'undefined' && typeof resRemote.result.id != 'undefined'){
				p.file_id = resRemote.result.id
			}
			
			
		}
		
		if(typeof p.file_id != 'undefined'){
			//	ll("--== getFileById Begin downloading ["+clientNumber+"]:", p.file_id)
			var resDown =  await getFileById({file_id:p.file_id})
			
			//	ll("--== getFileById RES ["+clientNumber+"]:", resDown)
		}
		
		return resDown;
	} catch (error) {
		console.error(error)
		return {result:false}
	}
	
}

async function getFileById(p) {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	if(typeof p.file_id == 'undefined') return {result:false};
	
	try {
		//	ll("--== getFileById Begin downloading ["+clientNumber+"]:", p.file_id)
		var resFile =  await tgclient.invoke({
			_: 'downloadFile',
			file_id: p.file_id,
			priority: 1,
		})
		
		//	ll("--== getFileById RES ["+clientNumber+"]:", resFile)
		return {result:resFile};
	} catch (error) {
		console.error(error)
		return false
	}
	
	// return new Promise((resolve, reject) => {
		// var oFile = tgHandler.downloadFile(p.file_id);
	
		// console.log("--== getFileById RES ["+clientNumber+"]:", oFile)
		
		// resolve( {result:oFile} );
	// });
	
}
tug's avatar
tug committed
472

Azizov Aziz 's avatar
Azizov Aziz committed
473 474 475 476 477 478 479 480 481 482 483 484 485
async function getFileDownStatus(p) {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	if(typeof p.file_id == 'undefined') return {result:false};
	
	try {
		//	ll("--== getRemoteFile Begin downloading ["+clientNumber+"]:", p.remote_id)
		//updateFile
	} catch (error){
		console.error(error)
		return false
	}
}
tug's avatar
tug committed
486

Azizov Aziz 's avatar
Azizov Aziz committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
async function getRemoteFile(p) {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	if(typeof p.remote_id == 'undefined') return {result:false,msg:'No remote Id'};
	
	try {
		//	ll("--== getRemoteFile Begin downloading ["+clientNumber+"]:", p.remote_id)
		var resRemFile =  await tgclient.invoke({
			_: 'getRemoteFile',
			remote_file_id: p.remote_id
		})
		
		//	ll("--== getRemoteFile RES ["+clientNumber+"]:", resRemFile)
		
		if(typeof resRemFile.local != "undefined" && typeof resRemFile.local.path != "undefined" && resRemFile.local.path.length){
			return {result:resRemFile.local.path};
		}
		else if(typeof resRemFile._ != "undefined" && resRemFile._=="file" && resRemFile.id){
			
			var resFileDown = await getFileById({file_id:resRemFile.id})
			
			if(typeof resFileDown.local != "undefined" && typeof resFileDown.local.path != "undefined" && resFileDown.local.path.length){
				return { result: resFileDown.local.path }
			}
		}
		return {result:false};
	} catch (error) {
		console.error(error)
		return false
	}
	
	// return new Promise((resolve, reject) => {
		// var oFile = tgHandler.downloadFile(p.file_id);
	
		// console.log("--== getFileById RES ["+clientNumber+"]:", oFile)
		
		// resolve( {result:oFile} );
	// });
	
}
tug's avatar
tug committed
527

Azizov Aziz 's avatar
Azizov Aziz committed
528 529 530 531 532 533 534 535 536 537 538 539
async function getId() {
	if(!tgclient) return {result:false};
	if(!tgHandler) return {result:false};
	
	try {
		var tgId = tgHandler.getId()
		return {result:tgId};
	} catch (error) {
		console.error(error)
		return { result:false }
	}
}
tug's avatar
tug committed
540 541 542



Azizov Aziz 's avatar
Azizov Aziz committed
543 544
async function setAuthSmscode(p) {
	if(!tgHandler) return {result:false};
tug's avatar
tug committed
545

Azizov Aziz 's avatar
Azizov Aziz committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
	ll('setAuthSmscode: START', p)
	return new Promise((resolve, reject) => {
		if(typeof p != 'undefined' && typeof p.code != 'undefined' && p.code){
			tgHandler.clearResAnswer();
			TGAuthSmsCode = p.code;
		}
		var timeOutSecs = 60;
		const id = setInterval(() => {
			var resAns = tgHandler.getResAnswer();
			ll('setAuthSmscode: resAns', resAns)

			if (!resAns) {
				return
			}
			
			clearInterval(id);
			
			if (resAns._ === 'authorizationStateWaitPassword') {
				resolve({ auth: false })
				return
			}
			// if (resAns._ === '56030341230296') {
			if (resAns._ === 'authorizationStateReady') {
				resolve({ auth: true })
				return
			}
			resolve({ result: resAns });
		}, 300)
		
	});
}
tug's avatar
tug committed
577

Azizov Aziz 's avatar
Azizov Aziz committed
578 579 580 581 582 583 584
async function setAuthPassword(p) {
	return new Promise((resolve, reject) => {
		ll("- setting ClientPassword: ", p);
		if(typeof p != 'undefined' && typeof p.pass != 'undefined' && p.pass){
			tgHandler.clearResAnswer();
			TGAuthPassword = p.pass;
		}
tug's avatar
tug committed
585
		
Azizov Aziz 's avatar
Azizov Aziz committed
586 587 588 589 590 591 592 593 594 595 596 597 598
		const id = setInterval(() => {
			var resAns = tgHandler.getResAnswer();
			ll("- resAns ClientPassword: ", resAns);
			if (!resAns) {
				return
			}
			
			clearInterval(id);
			resolve( {result:resAns} );
			
		}, 300)
	});
}
tug's avatar
tug committed
599

Azizov Aziz 's avatar
Azizov Aziz committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
function getClientPhoneNumber(r) {
	//	ll("- getting Phone NUMBER: ", clientNumber, r);
	return clientNumber;
}


// function getClientAuthCode(r) {
	// return await getClientAuthCodePromice(r);
// }
async function getClientAuthCode(r) {
	//	ll("- getting ClientPassword: ", r);
	return new Promise((resolve, reject) => {
		var timeOutSecs = 60 * 10;
		const id = setInterval(() => {
			if (!TGAuthSmsCode) {
				timeOutSecs = timeOutSecs-1;
				if(timeOutSecs<1){
					clearInterval(id);
					//	ll("-- wait 2FA Password  Timed OUT! ["+timeOutSecs+"]");
					process.exit(0);
				}
				return
			}
			
			clearInterval(id);
			var currCode = TGAuthSmsCode;
			TGAuthSmsCode = false
			//	ll("-- resolving current SmsCODE ["+timeOutSecs+"]: ", currCode);
			resolve(currCode);
		}, 1000)
	})
}
tug's avatar
tug committed
632

Azizov Aziz 's avatar
Azizov Aziz committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
// function getClientPassword(r) {
	// return await getClientPasswordPromice(r);
// }
async function getClientPassword(passwordHint, r) {
	//	ll("- getting ClientPassword: passwordHint: ", passwordHint, "  r:", r);

	return new Promise((resolve, reject) => {
		var timeOutSecs = 60 * 10;
		const id = setInterval(() => {
			//	ll("-- wait 2FA Password  ["+timeOutSecs+"]: ", TGAuthPassword);
			if (!TGAuthPassword) {
				timeOutSecs = timeOutSecs-1;
				if(timeOutSecs<1){
					clearInterval(id);
					//	ll("-- wait 2FA Password  Timed OUT! ["+timeOutSecs+"]");
					process.exit(0);
				}
				return
			}
			
			clearInterval(id);
			var currPass = TGAuthPassword;
			TGAuthPassword = false
			
			console.log("-- resolving current 2FA Password ["+timeOutSecs+"]: ", currPass);
			resolve(currPass);
		}, 1000)
	})
}

function tgServerToListen(cbk){
tug's avatar
tug committed
664 665

    // check for failed cleanup
Azizov Aziz 's avatar
Azizov Aziz committed
666
   	ll('--=== BEGIN to listening SOCKET...');
tug's avatar
tug committed
667 668 669
    fs.stat(SOCKETFILE, function (err, stats) {
        if (err) {
            // start server
Azizov Aziz 's avatar
Azizov Aziz committed
670 671
           	ll('No leftover socket found.');
            tgServer = createServer(SOCKETFILE, cbk); return;
tug's avatar
tug committed
672 673
        }
        // remove file then start server
Azizov Aziz 's avatar
Azizov Aziz committed
674
       	ll('Removing leftover socket.', SOCKETFILE)
tug's avatar
tug committed
675
        fs.unlink(SOCKETFILE, function(err){
Azizov Aziz 's avatar
Azizov Aziz committed
676
						ll('ERROR: Removing leftover socket.', err)
tug's avatar
tug committed
677
            if(err){
Azizov Aziz 's avatar
Azizov Aziz committed
678
              console.error(err); process.exit(0);
tug's avatar
tug committed
679
            }
Azizov Aziz 's avatar
Azizov Aziz committed
680 681
						ll('leftover SOCKETFILE.')
            tgServer = createServer(SOCKETFILE, cbk); return;
tug's avatar
tug committed
682 683 684 685 686 687
        });  
    });

    // close all connections when the user does CTRL-C
    function cleanup(){
        if(!SHUTDOWN){ SHUTDOWN = true;
Azizov Aziz 's avatar
Azizov Aziz committed
688
           	// ll('\n',"Terminating.",'\n');
tug's avatar
tug committed
689 690 691 692
            if(Object.keys(connections).length){
                let clients = Object.keys(connections);
                while(clients.length){
                    let client = clients.pop();
Azizov Aziz 's avatar
Azizov Aziz committed
693
                    // connections[client].write('__disconnect');
tug's avatar
tug committed
694 695 696 697 698 699 700 701 702
                    connections[client].end(); 
                }
            }
            tgServer.close();
            process.exit(0);
        }
    }
	
    process.on('SIGINT', cleanup);
Azizov Aziz 's avatar
Azizov Aziz committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
	
	process.on('message', function(packet) {
		//	ll("- 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
			}
		});
	});
tug's avatar
tug committed
723

Azizov Aziz 's avatar
Azizov Aziz committed
724
	process.send('ready')
tug's avatar
tug committed
725 726
}

Azizov Aziz 's avatar
Azizov Aziz committed
727 728
function createServer(socket, cbk){
   	ll('Creating server on socket: '+socket);
tug's avatar
tug committed
729 730
	
    var server = net.createServer(function(stream) {
Azizov Aziz 's avatar
Azizov Aziz committed
731
       	// ll('Connection acknowledged: '+socket);
tug's avatar
tug committed
732 733 734 735 736

        // 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);
Azizov Aziz 's avatar
Azizov Aziz committed
737 738 739
        stream.on('listening', function() {
           	// ll('Client begin listening.. ');
        });
tug's avatar
tug committed
740
        stream.on('end', function() {
Azizov Aziz 's avatar
Azizov Aziz committed
741
           	// ll('Client disconnected: '+socket);
tug's avatar
tug committed
742 743 744 745 746
            delete connections[self];
        });

        // Messages are buffers. use toString
        stream.on('data', function(msg) {
Azizov Aziz 's avatar
Azizov Aziz committed
747 748 749 750
			processIncom(msg).then(function(resultMsg){
				ll("--===== INCOM RESULT: ", msg, resultMsg);
				stream.write(JSON.stringify(resultMsg));
			})
tug's avatar
tug committed
751 752 753
        });
    })
    .listen(socket)
Azizov Aziz 's avatar
Azizov Aziz committed
754 755
    .on('connection', function(socket, t){
       	// ll('Client connected.');
tug's avatar
tug committed
756
    })
Azizov Aziz 's avatar
Azizov Aziz committed
757 758 759 760 761 762
	.on('error', errLog);

	if(typeof cbk == 'function'){
		cbk();
	}
	
tug's avatar
tug committed
763 764 765
    return server;
}

Azizov Aziz 's avatar
Azizov Aziz committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
// dbc.authenticate().then(() => {
	// console.log('DB Connection has been established successfully.');
	tgServerToListen(function(){
		DB(async function(datatables){
			DBC = datatables
			//	ll("-= TG Begin DB INITED done!", Object.keys(datatables));
		})
		.then(startClient)
		.catch(function(err){
			console.error("--== DB Error:", err);
			ll("--== DB Error:", err)
			process.exit(2)
		})
		
		
		// DB().then(startClient)
		
		// DB().then(function(datatables){
			// console.log("-= Begin DB Testing...");
			// DBC = datatables
			// initingDbTables().then(startClient);
		// })
	})
tug's avatar
tug committed
789
	
Azizov Aziz 's avatar
Azizov Aziz committed
790 791 792 793 794
   
// }).catch((error) => {
   // console.error('Unable to connect to the database: ', error);
   // process.exit(0)
// });
tug's avatar
tug committed
795

Azizov Aziz 's avatar
Azizov Aziz committed
796 797
function ll(...datas){
	console.log(...datas)
tug's avatar
tug committed
798
	
Azizov Aziz 's avatar
Azizov Aziz committed
799 800 801 802 803 804 805 806
	var currTime = moment().format("HH:mm:ss")
	var nowDate = moment().format("YY_DD_MM")
	var logdir = 'logs/'+currDate+'/';
	if(currDate != nowDate){
		logdir = 'logs/'+nowDate+'/';
		if(logStream){
			logStream.close()
			logStream=false
tug's avatar
tug committed
807 808 809
		}
	}
	
Azizov Aziz 's avatar
Azizov Aziz committed
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
	var ldir = path.join(__dirname, logdir)
	
	if (!fs.existsSync(ldir)){
		fs.mkdirSync(ldir, { recursive: true });
	}
	
	var logFileName = path.join(ldir, 'tgc_'+clientNumber+'.log');
	
	// if(!logStream){
		// logStream = fs.createWriteStream(path.join(ldir, 'tgc_'+clientNumber+'.log'))
	// }

	var logline = (typeof datas != "string") ? getString(datas) : datas;
	// var time = Math.floor(Date.now() / 1000);

	// logStream.write("\n--==["+currTime+"]__"+logline);
	
	fs.appendFile(logFileName, "\n--==["+currTime+"]__"+logline, (err) => {
        if(err) throw err;
        // console.log('Data has been added!');
    });
	
}

process.on('exit', () => {
	ll('exit: process')
})
process.on('unhandledRejection', (...args) => {
	ll('unhandledRejection: process ', ...args)
})

// setInterval(() => {
// 	B24.call(domain, 'app.info')
// }, 60 * 1e3);