Advertisement
Guest User

echo

a guest
Oct 24th, 2017
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 161.49 KB | None | 0 0
  1. /*
  2. Initalizing packages
  3. */
  4. var SteamUser = require('steam-user');
  5. var TradeOfferManager = require('steam-tradeoffer-manager');
  6. var SteamTotp = require('steam-totp');
  7. var SteamCommunity = require('steamcommunity');
  8. var fs = require('fs');
  9. var request = require('request');
  10. var config = require('./config.json');
  11. var crypto = require('crypto');
  12. var log4js = require('log4js');
  13.  
  14. const community = {
  15. bot1: new SteamCommunity(),
  16. bot2: new SteamCommunity(),
  17. bot3: new SteamCommunity()
  18. };
  19. const client = {
  20. bot1: new SteamUser(),
  21. bot2: new SteamUser(),
  22. bot3: new SteamUser()
  23. };
  24. const manager = {
  25. bot1: new TradeOfferManager({
  26. steam: client.bot1,
  27. domain: 'localhost',
  28. language: 'en'
  29. }),
  30. bot2: new TradeOfferManager({
  31. steam: client.bot2,
  32. domain: 'localhost',
  33. language: 'en'
  34. }),
  35. bot3: new TradeOfferManager({
  36. steam: client.bot3,
  37. domain: 'localhost',
  38. language: 'en'
  39. })
  40. };
  41.  
  42. //SSL INIT
  43. var express = require('express');
  44. var options = {
  45. key: fs.readFileSync('kingdom-csgo.com.key'),
  46. cert: fs.readFileSync('kingdom-csgo.com.crt'),
  47. requestCert: false
  48. };
  49. var app = express();
  50. var server = require('https').createServer(options, app);
  51. var io = require('socket.io').listen(server);
  52. server.listen(2096, "0.0.0.0");
  53. //SSL END
  54.  
  55.  
  56. log4js.configure({
  57. appenders: {
  58. console: {
  59. type: 'console'
  60. },
  61. default: {
  62. type: 'file',
  63. filename: 'logs/cf_'+time()+'.log'
  64. }
  65. },
  66. categories: {
  67. default: {
  68. appenders: ['default', 'console'],
  69. level: 'trace'
  70. }
  71. }
  72. });
  73.  
  74. var logger = log4js.getLogger();
  75.  
  76. var mysql = require('mysql');
  77. var db_config = {
  78. //debug: true,
  79. host: config.options.sql['host'],
  80. user: config.options.sql['username'],
  81. password: f.config.options.sql['password'],
  82. database: config.options.sql['database']
  83. };
  84. var pool;
  85. handleDisconnect();
  86.  
  87. process.on('uncaughtException', function (err) {
  88. logger.error('Strange error');
  89. logger.error(err);
  90. });
  91.  
  92. //GAME INFO
  93. var AppID = 740;
  94. var ContextID = 2;
  95. var minDep = config.options.minDeposit;
  96. var percentRake = 5;
  97. var maximumBots = 1;
  98.  
  99. var coolDown = {};
  100. var sendTradeCoolDown = {};
  101.  
  102. var proxies = config.proxies;
  103.  
  104. var deletingTrades = [];
  105.  
  106. var inventoryTimer = {};
  107. var socketBySteam = {};
  108.  
  109. var tradingRequests = {};
  110.  
  111. var loadGames = [];
  112. var timerGame = {};
  113. var timer11Game = {};
  114.  
  115. //PIN SYSTEM
  116. var pinSystem = false;
  117. var pinnedMessages = [];
  118. //PIN SYSTEM
  119.  
  120. var gamesPending = {};
  121.  
  122. var antiFlood = {};
  123. var timesFlooding = {};
  124.  
  125. var inventoryUser = {};
  126.  
  127. //CHAT FUNCTIONS
  128. var chatMessages = [];
  129. var usersOnline = {};
  130. var antiSpamChat = {};
  131. //CHAT FUNCTIONS
  132.  
  133. //JACKPOT'
  134. var jackpotHash = "";
  135. var jackpotSecret = "";
  136. var jackpotRound = -1;
  137. var jackpotBot = 0;
  138. var jackpotState = 'NONE';
  139. var jackpotTickets = 0;
  140. var jackpotTotalTickets = [];
  141. var totalJackpotItems = 0;
  142. var totalJackpotValue = 0;
  143. var totalSecondsJackpot = 0;
  144. var usersPrices = {};
  145. var checkJackpotEnd;
  146. var JackpotUsers = [];
  147. var JinventoryUser = {};
  148. var jackpotInt;
  149. var jackpotNextRoundTime;
  150.  
  151. var CoinfliprecentGames = [];
  152.  
  153. /*
  154. Polling Steam and Logging On
  155. */
  156. client.bot1.logOn({
  157. accountName: config.bots[0].username,
  158. password: config.bots[0].password,
  159. twoFactorCode: SteamTotp.generateAuthCode(config.bots[0].sharedSecret)
  160. });
  161. client.bot2.logOn({
  162. accountName: config.bots[1].username,
  163. password: config.bots[1].password,
  164. twoFactorCode: SteamTotp.generateAuthCode(config.bots[1].sharedSecret)
  165. });
  166. client.bot3.logOn({
  167. accountName: config.bots[2].username,
  168. password: config.bots[2].password,
  169. twoFactorCode: SteamTotp.generateAuthCode(config.bots[2].sharedSecret)
  170. });
  171.  
  172.  
  173. nextJackpotRound();
  174. function nextJackpotRound()
  175. {
  176. var secret = makeSecret();
  177. var hash = makeHash();
  178. var botAles = Math.floor(Math.random() * (maximumBots - 1 + 1)) + 1;
  179. var botul = 'bot' + botAles;
  180.  
  181. pool.query('INSERT INTO jgames SET hash = ' + pool.escape(hash) + ', secret = ' + pool.escape(secret) + ', pot = 0.00, items = 0, tickets = 0, bot = ' + pool.escape(botul), function(er, ro) {
  182. if(er) throw er;
  183. jackpotRound = ro.insertId;
  184. jackpotState = 'WAITING';
  185. jackpotHash = hash;
  186. jackpotSecret = secret;
  187.  
  188. JackpotUsers = [];
  189. jackpotTotalTickets = [];
  190. jackpotTickets = 0;
  191. totalJackpotItems = 0;
  192. totalSecondsJackpot = 0;
  193. usersPrices = {};
  194. jackpotBot = botul;
  195.  
  196. io.sockets.emit('message', {
  197. type: 'newJackpotRound',
  198. hash: hash
  199. });
  200.  
  201. if(jackpotQueueBets.length > 0)
  202. {
  203. for(var i in jackpotQueueBets)
  204. {
  205. if(jackpotQueueBets[i]['removed'] != 1)
  206. {
  207. if(jackpotState == 'WAITING') jackpotState = 'BETTING';
  208.  
  209. var minTicket = parseInt(jackpotTickets+1);
  210. var maxTicket = parseInt(minTicket+(jackpotQueueBets[i]['totalPrice']*100)-1);
  211. for(var a = minTicket; a < maxTicket; a++)
  212. {
  213. jackpotTotalTickets.push({
  214. 'user': jackpotQueueBets[i]['user'],
  215. 'ticket': parseInt(a)
  216. });
  217. }
  218. jackpotTickets += parseInt(jackpotQueueBets[i]['totalPrice']*100);
  219.  
  220. var assetidsSS = jackpotQueueBets[i]['receivedItems'].join('/');
  221. pool.query('INSERT INTO jbets SET user = ' + pool.escape(jackpotQueueBets[i]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(jackpotQueueBets[i]['totalPrice']) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(jackpotQueueBets[i]['totalSkins']) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(jackpotQueueBets[i]['offerID']));
  222. setTimeout(function() {
  223. addJackpotBet(jackpotQueueBets[i]['user'], jackpotQueueBets[i]['skinImages'], jackpotQueueBets[i]['skinImages'], jackpotQueueBets[i]['skinPrices'], jackpotQueueBets[i]['totalSkins'], jackpotQueueBets[i]['totalPrice'], jackpotQueueBets[i]['itemsData']);
  224. jackpotQueueBets[i]['removed'] = 1;
  225. }, 8000);
  226. }
  227. }
  228. }
  229. });
  230. }
  231.  
  232. function checkTrades()
  233. {
  234. pool.query('SELECT * FROM trades WHERE expired < ' + pool.escape(time()) + ' AND status = ' + pool.escape('PendingAccept'), function(err, row) {
  235. if(err) throw err;
  236. if(row.length == 0) return;
  237.  
  238. for(var i in row)
  239. {
  240. if(row[i].action == 'winning')
  241. {
  242. var defBot = pickBot(row[i].bot);
  243. defBot.getOffer(parseInt(row[i].tid), function(abra, offer) {
  244. setTimeout(function() {
  245. if(abra) throw abra;
  246. if(offer.state == 2)
  247. {
  248. declineOffer(offer);
  249. logger.trace('Tradeoffer #' + offer.id + ' (winning) was cancelled due to expire.');
  250.  
  251. if(socketBySteam.hasOwnProperty(row[i].user))
  252. {
  253. if(io.sockets.connected[socketBySteam[row[i].user]['info']])
  254. {
  255. io.sockets.connected[socketBySteam[row[i].user]['info']].emit('message', {
  256. type: 'msg',
  257. tip: 'error',
  258. msg: 'Tradeoffer #' + offer.id + ' was cancelled due to expire.'
  259. });
  260. }
  261. }
  262. }
  263. else if(offer.state == 3)
  264. {
  265. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE id = ' + pool.escape(row[i].id));
  266. }
  267. }, 2500);
  268. });
  269. }
  270. else if(row[i].action == 'newGame')
  271. {
  272. var defBot = pickBot(row[i].bot);
  273. defBot.getOffer(parseInt(row[i].tid), function(abra, offer) {
  274. setTimeout(function() {
  275. if(abra) throw abra;
  276. if(offer.state == 2)
  277. {
  278. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE id = ' + pool.escape(row[i].id), function(e, ree) {
  279. if(e) throw e;
  280. if(ree.length == 0) return;
  281.  
  282. declineOffer(offer);
  283. logger.trace('Tradeoffer #' + offer.id + ' (newGame) was cancelled due to expire.');
  284.  
  285. if(socketBySteam.hasOwnProperty(row[i].user))
  286. {
  287. if(io.sockets.connected[socketBySteam[row[i].user]['info']])
  288. {
  289. io.sockets.connected[socketBySteam[row[i].user]['info']].emit('message', {
  290. type: 'msg',
  291. tip: 'error',
  292. msg: 'Tradeoffer #' + offer.id + ' was cancelled due to expire.'
  293. });
  294. }
  295. }
  296. });
  297. }
  298. }, 2500);
  299. });
  300. }
  301. else if(row[i].action == 'joingame')
  302. {
  303. var defBot = pickBot(row[i].bot);
  304. defBot.getOffer(parseInt(row[i].tid), function(abra, offer) {
  305. setTimeout(function() {
  306. if(abra) throw abra;
  307. if(offer.state == 2)
  308. {
  309. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE id = ' + pool.escape(row[i].id), function(e, ree) {
  310. if(e) throw e;
  311. if(ree.length == 0) return;
  312.  
  313. pool.query('SELECT id FROM games WHERE trade_token = ' + pool.escape(row[i].tid), function(cece, mece) {
  314. if(cece) throw cece;
  315. if(mece.length == 0) return;
  316.  
  317. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(row[i].tid), function(aaa,bbb) {
  318. if(err) throw err;
  319.  
  320. loadAllGames();
  321. sendGames(mece[0].id);
  322. declineOffer(offer);
  323. logger.trace('Tradeoffer #' + offer.id + ' (joingame) was cancelled due to expire.');
  324.  
  325. {
  326. io.sockets.connected[socketBySteam[row[i].user]['info']].emit('message', {
  327. type: 'msg',
  328. tip: 'error',
  329. msg: 'Tradeoffer #' + offer.id + ' was cancelled due to expire.'
  330. });
  331. }
  332. }
  333. });
  334. });
  335. });
  336. }
  337. }, 2500);
  338. });
  339. }
  340. }
  341. });
  342. }
  343.  
  344.  
  345. setTradingRequests();
  346. function setTradingRequests()
  347. {
  348. pool.query('SELECT * FROM trades WHERE status = ' + pool.escape('PendingAccept'), function(err, row) {
  349. if(err) throw err;
  350. if(row.length == 0) return;
  351.  
  352. for(var i in row)
  353. {
  354. logger.debug('Trade #' + row[i].tid + ' added --> ' + row[i].action + ' + ' + row[i].user);
  355.  
  356. var timpExpire = time()+20;
  357.  
  358. tradingRequests[row[i].tid] = {
  359. action: row[i].action,
  360. user: row[i].user,
  361. created: parseInt(row[i].created),
  362. expired: timpExpire
  363. };
  364.  
  365. pool.query('UPDATE trades SET expired = ' + pool.escape(timpExpire) + ' WHERE id = ' + pool.escape(row[i].id));
  366. }
  367. });
  368. }
  369.  
  370. loadAllGames();
  371. function loadAllGames()
  372. {
  373. pool.query('SELECT * FROM games WHERE `ended` = 0', function(err, res, fields) {
  374. if(err) throw err;
  375.  
  376. loadGames = [];
  377.  
  378. for(var i in res)
  379. {
  380. loadGames.push({
  381. 'id': res[i].id,
  382. 'csteamid': res[i].csteamid,
  383. 'cavatar': res[i].cavatar,
  384. 'cskinsurl': res[i].cskinsurl,
  385. 'cskinsnames': res[i].cskinsnames,
  386. 'cskinsprices': res[i].cskinsprices,
  387. 'cskins': res[i].cskins,
  388. 'ctp': res[i].ctp,
  389. 'psteamid': res[i].psteamid,
  390. 'pname': res[i].pname,
  391. 'pavatar': res[i].pavatar,
  392. 'pskins': res[i].pskins,
  393. 'ptp': res[i].ptp,
  394. 'hash': res[i].hash,
  395. 'secret': res[i].secret,
  396. 'cpick': res[i].cpick,
  397. 'winnerPercentage': res[i].winnerPercentage,
  398. 'timer11': res[i].timer11
  399. });
  400. }
  401. });
  402. }
  403.  
  404.  
  405. io.on('connection', function(socket) {
  406. socket.on('hash', function(m) {
  407. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  408. addHistory(socket);
  409. socket.emit('pinsSystem', pinSystem, pinnedMessages);
  410.  
  411. if(!usersOnline[address])
  412. {
  413. usersOnline[address] = 1;
  414. }
  415.  
  416. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  417. if(err) throw err;
  418.  
  419. if(row.length == 0)
  420. {
  421. socket.emit('message', {
  422. type: 'newJackpotRound',
  423. hash: jackpotHash
  424. });
  425. {
  426. for(var i in JackpotUsers)
  427. {
  428. socket.emit('message', {
  429. type: 'addJackpotBet',
  430. userInfo: {
  431. avatar: JackpotUsers[i]['userInfo'].avatar,
  432. name: JackpotUsers[i]['userInfo'].name,
  433. steamid: JackpotUsers[i]['userInfo'].steamid,
  434. level: JackpotUsers[i]['userInfo'].level
  435. },
  436. itemsInfo: JackpotUsers[i]['itemsInfo']
  437. });
  438. }
  439. socket.emit('message', {
  440. type: 'jackpotSet',
  441. totalUsers: JackpotUsers.length,
  442. potItemsValue: totalJackpotValue,
  443. potValue: totalJackpotItems,
  444. });
  445. }
  446. }
  447.  
  448. if(row.length > 0)
  449. {
  450. getInv(row[0].steamid, socket);
  451.  
  452. if(socketBySteam.hasOwnProperty(row[0].steamid))
  453. {
  454. delete socketBySteam[row[0].steamid];
  455. socketBySteam[row[0].steamid] = {
  456. 'info': socket.id
  457. };
  458. }
  459. else
  460. {
  461. socketBySteam[row[0].steamid] = {
  462. 'info': socket.id
  463. };
  464. }
  465.  
  466. socket.emit('message', {
  467. type: 'newJackpotRound',
  468. hash: jackpotHash
  469. });
  470.  
  471. if(jackpotState == 'BETTING')
  472. {
  473. JackpotUsers.forEach(function (i) {
  474. if(i['userInfo'].steamid == row[0].steamid)
  475. {
  476. var yourValue = 0;
  477. for(var z in i['itemsInfo'])
  478. {
  479. yourValue += parseFloat(i['itemsInfo'][z].price);
  480. }
  481.  
  482.  
  483. socket.emit('message', {
  484. type: 'standingQueue',
  485. totalItems: i['itemsInfo'].length,
  486. yourChance: chance
  487. });
  488. }
  489. });
  490. for(var i in JackpotUsers)
  491. {
  492. socket.emit('message', {
  493. type: 'addJackpotBet',
  494. userInfo: {
  495. avatar: JackpotUsers[i]['userInfo'].avatar,
  496. name: JackpotUsers[i]['userInfo'].name,
  497. },
  498. itemsInfo: JackpotUsers[i]['itemsInfo']
  499. });
  500. }
  501. socket.emit('message', {
  502. type: 'jackpotSet',
  503. totalUsers: JackpotUsers.length,
  504. potItemsValue: totalJackpotValue,
  505. potValue: totalJackpotItems,
  506. timpul: totalSecondsJackpot-time()
  507. });
  508. }
  509. }
  510. });
  511.  
  512. loadStatistics(socket);
  513.  
  514. io.sockets.emit('message', {
  515. type: 'connections',
  516. total: Object.keys(usersOnline).length
  517. });
  518.  
  519. loadGames.forEach(function(itm) {
  520. socket.emit('message', {
  521. type: 'addGame',
  522. games: {
  523. 'id': itm.id,
  524. 'csteamid': itm.csteamid,
  525. 'cname': itm.cname,
  526. 'cavatar': itm.cavatar,
  527. 'cskinsurl': itm.cskinsurl,
  528. 'cskinsnames': itm.cskinsnames,
  529. 'cskinsprices': itm.cskinsprices,
  530. 'cskins': itm.cskins,
  531. 'ctp': itm.ctp,
  532. 'psteamid': itm.psteamid,
  533. 'pname': itm.pname,
  534. 'pavatar': itm.pavatar,
  535. 'pskinsurl': itm.pskinsurl,
  536. 'pskinsnames': itm.pskinsnames,
  537. 'pskinsprices': itm.pskinsprices,
  538. 'pskins': itm.pskins,
  539. 'winner': itm.winner,
  540. 'cpick': itm.cpick,
  541. 'ppick': itm.ppick,
  542. 'timer': timerGame[itm.id]-time(),
  543. 'timer11': itm.timer11,
  544. 'ttimer11': timer11Game[itm.id]-time()
  545. }
  546. });
  547. });
  548. });
  549.  
  550.  
  551.  
  552. socket.on('sendTrade', function(m) {
  553. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  554. var tradeID = m.tradeID;
  555.  
  556. if(!tradeID)
  557. {
  558. if(socketBySteam.hasOwnProperty(row[0].user))
  559. {
  560. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  561. {
  562. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  563. type: 'msg',
  564. tip: 'error',
  565. msg: 'You need to enter a tradeid.'
  566. });
  567. }
  568. }
  569. return;
  570. }
  571.  
  572. pool.query('SELECT status,action,user,items,code,bot FROM trades WHERE tid = ' + pool.escape(tradeID), function(err, row) {
  573. if(err) throw err;
  574. if(row.length == 0) return;
  575.  
  576. if(row[0].status == 'PendingAccept' && row[0].action == 'winning')
  577. {
  578. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(row[0].user), function(er, ro) {
  579. if(er) throw er;
  580. if(ro.length == 0)
  581. {
  582. if(socketBySteam.hasOwnProperty(row[0].user))
  583. {
  584. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  585. {
  586. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  587. type: 'msg',
  588. tip: 'error',
  589. msg: 'User does not exists in db.'
  590. });
  591. }
  592. }
  593. return;
  594. }
  595.  
  596. if(sendTradeCoolDown[address]-time() >= 1) {
  597. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  598. type: 'msg',
  599. tip: 'error',
  600. msg: 'You need to wait ' + (sendTradeCoolDown[address]-time()) + ' more seconds to click it again.'
  601. });
  602. return;
  603. } else {
  604. sendTradeCoolDown[address] = time()+60;
  605. }
  606.  
  607. if(!ro[0].tradelink.includes('://'))
  608. {
  609. if(socketBySteam.hasOwnProperty(row[0].user))
  610. {
  611. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  612. {
  613. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  614. type: 'msg',
  615. tip: 'error',
  616. msg: 'You need to add your tradelink before requesting a tradeoffer.'
  617. });
  618. sendTradeCoolDown[address] = time();
  619. }
  620. }
  621. return;
  622. }
  623.  
  624. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].user) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(ca, ma) {
  625. if(ca) throw ca;
  626. if(ma.length == 0) return;
  627.  
  628. if(ma[0].tTrades != 0)
  629. {
  630. if(socketBySteam.hasOwnProperty(row[0].user))
  631. {
  632. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  633. {
  634. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  635. type: 'msg',
  636. tip: 'error',
  637. msg: 'You isset an active tradeoffer.'
  638. });
  639. sendTradeCoolDown[address] = time();
  640. }
  641. }
  642. return;
  643. }
  644.  
  645. var Items = row[0].items.split('/');
  646. var defBot = pickBot(row[0].bot);
  647. var create = defBot.createOffer(row[0].user, ro[0].tradelink.split('token=')[1]);
  648. defBot.loadInventory(AppID, ContextID, true, function(err, inv, curr) {
  649. if(err) throw err;
  650. if(inv.length == 0)
  651. {
  652. logger.info('An error ocurred while loading bot inventory. Status of trade #' + tradeID + ' has been changed to <Accepted>.');
  653. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(tradeID));
  654. sendTradeCoolDown[address] = time();
  655. return;
  656. }
  657.  
  658. for(var i in Items)
  659. {
  660. for(var z in inv)
  661. {
  662. if(Items[i] == inv[z].assetid && Items[i] != 1)
  663. {
  664. Items[i] = 1;
  665. create.addMyItem({
  666. "appid": AppID,
  667. "contextid": ContextID,
  668. "assetid": inv[z].assetid
  669. });
  670. }
  671. }
  672. }
  673.  
  674. create.setMessage('Your winnings are here. Security code: ' + row[0].code);
  675. create.send(function(err2, status) {
  676. if(err2)
  677. {
  678. if(err2.toString() == 'Error: Cannot send an empty trade offer')
  679. {
  680. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(tradeID));
  681. logger.info('Trade #' + tradeID + ' has been already accepted, so the trade will not be send.');
  682. if(socketBySteam.hasOwnProperty(row[0].user))
  683. {
  684. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  685. {
  686. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  687. type: 'msg',
  688. tip: 'error',
  689. msg: 'This trade was accepted in the past. Status changed to "Accepted".'
  690. });
  691. sendTradeCoolDown[address] = time();
  692. }
  693. }
  694. }
  695. else
  696. {
  697. throw err2;
  698. }
  699. return;
  700. }
  701.  
  702. var timpExpire = time()+90;
  703.  
  704. tradingRequests[create.id] = {
  705. action: 'winning',
  706. user: row[0].user,
  707. };
  708.  
  709. pool.query('UPDATE trades SET tid = ' + pool.escape(create.id) + ', expired = ' + pool.escape(timpExpire) + ' WHERE tid = ' + pool.escape(tradeID));
  710.  
  711. if(socketBySteam.hasOwnProperty(row[0].user))
  712. {
  713. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  714. {
  715. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  716. type: 'modals',
  717. tip: 'trade',
  718. result: 'offerSend',
  719. code: row[0].code,
  720. tid: create.id
  721. });
  722. }
  723. }
  724.  
  725. logger.debug('Winnings from tradeid #' + tradeID + ' were sent again to winner ' + row[0].user + ' new tradeoffer #' + create.id);
  726. sendTradeCoolDown[address] = time();
  727. });
  728. });
  729. });
  730. });
  731. }
  732. });
  733. });
  734.  
  735.  
  736.  
  737. //JACKPOT PLAYER GETINV
  738. socket.on('jwantInv', function(m) {
  739. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  740. if(coolDown[address]+2 >= time()) {
  741. socket.emit('message', {
  742. type: 'msg',
  743. tip: 'error',
  744. msg: 'Please, stop flooding!'
  745. });
  746. return;
  747. } else {
  748. coolDown[address] = time();
  749. }
  750. if(m.hash)
  751. {
  752. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  753. if(err) throw err;
  754.  
  755. if(row.length == 0) return;
  756.  
  757. if(row.length > 0 && !JinventoryTimer.hasOwnProperty(row[0].steamid))
  758. {
  759. jgetInv(row[0].steamid, socket);
  760. JinventoryTimer[row[0].steamid] = {
  761. 'timer': time()+45
  762. };
  763. }
  764. else if(row.length > 0 && JinventoryTimer.hasOwnProperty(row[0].steamid))
  765. {
  766. if(JinventoryUser.hasOwnProperty(row[0].steamid) && JinventoryTimer[row[0].steamid]['timer']-time() > 0)
  767. {
  768.  
  769. socket.emit('message', {
  770. type: 'jgetInventory',
  771. id: id,
  772. name: name,
  773. price: price,
  774. img: img
  775. });
  776.  
  777. socket.emit('message', {
  778. type: 'msg',
  779. tip: 'jInv',
  780. seconds: JinventoryTimer[row[0].steamid]['timer']-time()
  781. });
  782. }
  783. else if(JinventoryTimer[row[0].steamid]['timer']-time() <= 0)
  784. {
  785. JinventoryTimer[row[0].steamid] = {
  786. 'timer': time()+45
  787. };
  788.  
  789. jgetInv(row[0].steamid, socket);
  790.  
  791. socket.emit('message', {
  792. type: 'msg',
  793. tip: 'jInv',
  794. seconds: JinventoryTimer[row[0].steamid]['timer']-time()
  795. });
  796. }
  797. }
  798. });
  799. }
  800. });
  801.  
  802. //JACKPOT DEPOSIT BUTTON
  803. socket.on('jDeposit', function(m) {
  804. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  805. if(coolDown[address]+2 >= time()) {
  806. socket.emit('message', {
  807. type: 'msg',
  808. tip: 'error',
  809. msg: 'Please, stop flooding!'
  810. });
  811. return;
  812. } else {
  813. coolDown[address] = time();
  814. }
  815. if(antiFlood[socket]+2 >= time()) {
  816. timesFlooding[socket] += 1;
  817. if(timesFlooding[socket] == 3)
  818. {
  819. delete timesFlooding[socket];
  820. socket.disconnect();
  821. return;
  822. }
  823. return;
  824. } else {
  825. antiFlood[socket] = time();
  826. }
  827. if(m.hash)
  828. {
  829. pool.query('SELECT steamid,tradelink,rank FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  830. if(err) throw err;
  831. if(row.length == 0)
  832. {
  833. logger.debug('Error [1]');
  834. return;
  835. }
  836.  
  837. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(er, ro) {
  838. if(er) throw er;
  839. if(ro.length == 0) return;
  840.  
  841. if(ro[0].tTrades != 0)
  842. {
  843. socket.emit('message', {
  844. type: 'msg',
  845. tip: 'alert',
  846. msg: 'Error: You isset an active tradeoffer.'
  847. });
  848. return;
  849. }
  850.  
  851. if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
  852. {
  853. socket.emit('message', {
  854. type: 'msg',
  855. tip: 'alert',
  856. msg: 'Error: Tradelink wrong.'
  857. });
  858. return;
  859. }
  860.  
  861. var joinedJackpot = 0;
  862.  
  863. JackpotUsers.forEach(function (i) {
  864. if(i['userInfo'].steamid == row[0].steamid && row[0].rank != 69)
  865. {
  866. joinedJackpot = 1;
  867. }
  868. });
  869.  
  870. if(joinedJackpot == 1)
  871. {
  872. socket.emit('message', {
  873. });
  874. return;
  875. }
  876.  
  877. if(jackpotRound == -1)
  878. {
  879. socket.emit('message', {
  880. type: 'msg',
  881. tip: 'alert',
  882. msg: 'Error: The game is not open.'
  883. });
  884. return;
  885. }
  886.  
  887. if(jackpotState == 'NONE')
  888. {
  889. socket.emit('message', {
  890. type: 'msg',
  891. tip: 'alert',
  892. msg: 'Error: The game did not start. (state: ' + jackpotState + ')'
  893. });
  894. return;
  895. }
  896.  
  897. var Items = m.assets.split('/');
  898. var pretul = require('./prices.json');
  899. var itemsToReceive = [];
  900. var create = defBot.createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
  901. defBot.getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
  902. if(e) throw e;
  903. if(inv.length == 0)
  904. {
  905. logger.debug('Error [4]');
  906. return;
  907. }
  908.  
  909. for(var i in Items)
  910. {
  911. for(var z in inv)
  912. {
  913. if(Items[i] == inv[z].assetid && Items[i].ss != 1)
  914. {
  915. Items[i].ss = 1;
  916. ItemsToReceived++;
  917. ItemsPriceValue += parseFloat(pretul[inv[z].market_hash_name]);
  918. itemsToReceive.push(inv[z].assetid);
  919. }
  920. }
  921. }
  922.  
  923. if(ItemsToReceived + totalJackpotItems > 50)
  924. {
  925. socket.emit('message', {
  926. type: 'msg',
  927. tip: 'alert',
  928. msg: 'Error: You exceeded the maximum items in this pot!'
  929. });
  930. return;
  931. }
  932.  
  933. if(ItemsToReceived > 25)
  934. {
  935. socket.emit('message', {
  936. type: 'msg',
  937. tip: 'alert',
  938. msg: 'Error: Maximum items per user is 25!'
  939. });
  940. return;
  941. }
  942.  
  943. if(itemsToReceive.length == 0)
  944. {
  945. socket.emit('message', {
  946. type: 'msg',
  947. tip: 'alert',
  948. msg: 'Error: You need to select items.'
  949. });
  950. return;
  951. }
  952.  
  953. for(var i in itemsToReceive)
  954. {
  955. create.addTheirItem({
  956. "appid": AppID,
  957. "contextid": ContextID,
  958. "assetid": itemsToReceive[i]
  959. });
  960. }
  961.  
  962. socket.emit('message', {
  963. type: 'modals',
  964. tip: 'trade',
  965. result: 'offerProcessing'
  966. });
  967.  
  968.  
  969. var cod = makeCode();
  970. create.setMessage('Security code: ' + cod);
  971.  
  972. create.send(function(ab, status) {
  973.  
  974. if(ab)
  975. {
  976. socket.emit('message', {
  977. type: 'modals',
  978. tip: 'trade',
  979. result: 'offerError',
  980. msg: ab.toString()
  981. });
  982. logger.trace('Line: 1078' + ab.toString());
  983. return;
  984. }
  985.  
  986. var timpCreat = time();
  987. var timpExpired = time()+90;
  988.  
  989.  
  990. logger.debug('Tradeoffer #' + create.id + ' (' + status + ' - joinJackpot) with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
  991.  
  992. tradingRequests[create.id] = {
  993. action: 'joinJackpot',
  994. user: row[0].steamid,
  995. created: timpCreat,
  996. expired: timpExpired
  997. }
  998.  
  999. pool.query('INSERT INTO trades SET user = ' + pool.escape(row[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('joinJackpot') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpired) + ', bot = ' + pool.escape(defBot2));
  1000.  
  1001. socket.emit('message', {
  1002. type: 'modals',
  1003. tip: 'trade',
  1004. result: 'offerSend',
  1005. tid: create.id,
  1006. code: cod
  1007. });
  1008. });
  1009. });
  1010. });
  1011. });
  1012. }
  1013. });
  1014.  
  1015. //INVENTORY TIMER
  1016. socket.on('wantInv', function(m) {
  1017. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1018. if(coolDown[address]+2 >= time()) {
  1019. socket.emit('message', {
  1020. type: 'msg',
  1021. tip: 'error',
  1022. msg: 'Please, stop flooding!'
  1023. });
  1024. return;
  1025. } else {
  1026. coolDown[address] = time();
  1027. }
  1028. if(m.hash)
  1029. {
  1030. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  1031. if(err) throw err;
  1032.  
  1033. if(row.length == 0) return;
  1034.  
  1035. if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
  1036. {
  1037. getInv(row[0].steamid, socket);
  1038. inventoryTimer[row[0].steamid] = {
  1039. 'timer': time()+45
  1040. };
  1041. }
  1042. else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
  1043. {
  1044. if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
  1045. {
  1046. var id = inventoryUser[row[0].steamid]['id'];
  1047. var name = inventoryUser[row[0].steamid]['name'];
  1048. var price = inventoryUser[row[0].steamid]['price'];
  1049. var img = inventoryUser[row[0].steamid]['img'];
  1050.  
  1051. socket.emit('message', {
  1052. type: 'getInventory',
  1053. id: id,
  1054. name: name,
  1055. price: price,
  1056. img: img
  1057. });
  1058.  
  1059. socket.emit('message', {
  1060. type: 'msg',
  1061. tip: 'Inv',
  1062. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  1063. });
  1064. }
  1065. else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
  1066. {
  1067. inventoryTimer[row[0].steamid] = {
  1068. 'timer': time()+45
  1069. };
  1070.  
  1071. getInv(row[0].steamid, socket);
  1072.  
  1073. socket.emit('message', {
  1074. type: 'msg',
  1075. tip: 'Inv',
  1076. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  1077. });
  1078. }
  1079. }
  1080. });
  1081. }
  1082. });
  1083.  
  1084.  
  1085. socket.on('wantInv2', function(m) {
  1086. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1087. if(coolDown[address]+2 >= time()) {
  1088. socket.emit('message', {
  1089. type: 'msg',
  1090. tip: 'error',
  1091. msg: 'Please, stop flooding!'
  1092. });
  1093. return;
  1094. } else {
  1095. coolDown[address] = time();
  1096. }
  1097. if(m.hash)
  1098. {
  1099. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  1100. if(err) throw err;
  1101.  
  1102. if(row.length == 0) return;
  1103.  
  1104. if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
  1105. {
  1106. getInv2(row[0].steamid, socket);
  1107. inventoryTimer[row[0].steamid] = {
  1108. 'timer': time()+45
  1109. };
  1110. }
  1111. else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
  1112. {
  1113. if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
  1114. {
  1115. var id = inventoryUser[row[0].steamid]['id'];
  1116. var name = inventoryUser[row[0].steamid]['name'];
  1117. var price = inventoryUser[row[0].steamid]['price'];
  1118. var img = inventoryUser[row[0].steamid]['img'];
  1119.  
  1120. socket.emit('message', {
  1121. type: 'getInventory2',
  1122. id: id,
  1123. name: name,
  1124. price: price,
  1125. img: img
  1126. });
  1127.  
  1128. socket.emit('message', {
  1129. type: 'msg',
  1130. tip: 'Inv2',
  1131. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  1132. });
  1133. }
  1134. else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
  1135. {
  1136. inventoryTimer[row[0].steamid] = {
  1137. 'timer': time()+45
  1138. };
  1139.  
  1140. getInv2(row[0].steamid, socket);
  1141.  
  1142. socket.emit('message', {
  1143. type: 'msg',
  1144. tip: 'Inv2',
  1145. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  1146. });
  1147. }
  1148. }
  1149. });
  1150. }
  1151. });
  1152.  
  1153. socket.on('jackpotWinnings', function(m) {
  1154. if(m.hash && m.bot)
  1155. {
  1156. pool.query('SELECT steamid, tradelink FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  1157. if(err) throw err;
  1158. if(row.length == 0) return;
  1159.  
  1160. var botull = 'bot' + m.bot;
  1161. var defBot = pickBot(botull);
  1162.  
  1163. var create = defBot.createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
  1164. defBot.loadInventory(AppID, ContextID, true, function(er, inv, curr) {
  1165. for(var i in inv)
  1166. {
  1167. create.addMyItem({
  1168. 'assetid': inv[i].assetid,
  1169. 'appid': AppID,
  1170. 'contextid': ContextID
  1171. });
  1172. }
  1173.  
  1174. create.setMessage('Your winnings from jackpot game #' + jackpotRound);
  1175. create.send(function(e, status) {
  1176. if(e) throw e;
  1177. });
  1178. });
  1179. });
  1180. }
  1181. });
  1182.  
  1183. socket.on('newGame', function(m) {
  1184. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1185. if(coolDown[address]+2 >= time()) {
  1186. socket.emit('message', {
  1187. type: 'msg',
  1188. tip: 'error',
  1189. msg: 'Please, stop flooding!'
  1190. });
  1191. return;
  1192. } else {
  1193. coolDown[address] = time();
  1194. }
  1195. if(antiFlood[socket]+2 >= time()) {
  1196. timesFlooding[socket] += 1;
  1197. if(timesFlooding[socket] == 3)
  1198. {
  1199. delete timesFlooding[socket];
  1200. socket.disconnect();
  1201. return;
  1202. }
  1203. return;
  1204. } else {
  1205. antiFlood[socket] = time();
  1206. }
  1207. if(m.hash)
  1208. {
  1209. pool.query('SELECT steamid,tradelink FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  1210. if(err) throw err;
  1211. if(row.length == 0)
  1212. {
  1213. logger.debug('Error [1]');
  1214. return;
  1215. }
  1216.  
  1217. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(er, ro) {
  1218. if(er) throw er;
  1219. if(ro.length == 0) return;
  1220.  
  1221. if(ro[0].tTrades != 0)
  1222. {
  1223. socket.emit('message', {
  1224. type: 'msg',
  1225. tip: 'error',
  1226. msg: 'Error: You isset an active tradeoffer.'
  1227. });
  1228. return;
  1229. }
  1230.  
  1231. if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
  1232. {
  1233. socket.emit('message', {
  1234. type: 'msg',
  1235. tip: 'error',
  1236. msg: 'Error: Update your tradelink in the "my profile" page.'
  1237. });
  1238. return;
  1239. }
  1240.  
  1241. var botAles = Math.floor(Math.random() * (maximumBots - 1 + 1)) + 1;
  1242. var botull = 'bot' + botAles;
  1243. var defBot = pickBot(botull);
  1244.  
  1245. var Items = m.assets.split('/');
  1246. var itemsToReceive = [];
  1247. var create = defBot.createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
  1248. defBot.getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
  1249. if(e) throw e;
  1250. if(inv.length == 0)
  1251. {
  1252. logger.debug('Error [4]');
  1253. return;
  1254. }
  1255.  
  1256. for(var i in Items)
  1257. {
  1258. for(var z in inv)
  1259. {
  1260. if(Items[i] == inv[z].assetid && inv[z].ss != 1)
  1261. {
  1262. inv[z].ss = 1;
  1263.  
  1264. itemsToReceive.push(inv[z].assetid);
  1265. }
  1266. }
  1267. }
  1268.  
  1269. if(itemsToReceive.length == 0)
  1270. {
  1271. socket.emit('message', {
  1272. type: 'msg',
  1273. tip: 'error',
  1274. msg: 'Error: You need to select items.'
  1275. });
  1276. return;
  1277. }
  1278.  
  1279. for(var i in itemsToReceive)
  1280. {
  1281. create.addTheirItem({
  1282. "appid": AppID,
  1283. "contextid": ContextID,
  1284. "assetid": itemsToReceive[i]
  1285. });
  1286. }
  1287.  
  1288. socket.emit('message', {
  1289. type: 'modals',
  1290. tip: 'trade',
  1291. result: 'offerProcessing'
  1292. });
  1293.  
  1294.  
  1295. var cod = makeCode();
  1296. create.setMessage('Security code: ' + cod);
  1297.  
  1298. create.send(function(ab, status) {
  1299.  
  1300. if(ab)
  1301. {
  1302. socket.emit('message', {
  1303. type: 'modals',
  1304. tip: 'trade',
  1305. result: 'offerError',
  1306. msg: ab.toString()
  1307. });
  1308. logger.trace('Line: 1359 ' + ab.toString());
  1309. return;
  1310. }
  1311.  
  1312. var timpCreat = time();
  1313. var timpExpire = time()+90;
  1314.  
  1315. var expireIn = 0;
  1316. if(m.expire == 1)
  1317. {
  1318. expireIn = 10;
  1319. }
  1320. else if(m.expire == 2)
  1321. {
  1322. expireIn = 30;
  1323. }
  1324. else
  1325. {
  1326. expireIn = 30;
  1327. }
  1328.  
  1329. logger.debug('Tradeoffer #' + create.id + ' (' + status + '; expire in: ' + expireIn + 'm) with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
  1330.  
  1331. tradingRequests[create.id] = {
  1332. action: 'newGame',
  1333. user: row[0].steamid,
  1334. created: timpCreat,
  1335. expire: timpExpire,
  1336. side: m.side,
  1337. gameExpire: expireIn,
  1338. botulAles: botull
  1339. }
  1340.  
  1341. pool.query('INSERT INTO trades SET user = ' + pool.escape(row[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('newGame') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(botull));
  1342.  
  1343. socket.emit('message', {
  1344. type: 'modals',
  1345. tip: 'trade',
  1346. result: 'offerSend',
  1347. tid: create.id,
  1348. code: cod
  1349. });
  1350. });
  1351. });
  1352. });
  1353. });
  1354. }
  1355. });
  1356.  
  1357.  
  1358. socket.on('recentGames', function(m) {
  1359. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1360. if(coolDown[address]+2 >= time()) {
  1361. socket.emit('message', {
  1362. type: 'msg',
  1363. tip: 'error',
  1364. msg: 'Please, stop flooding!'
  1365. });
  1366. return;
  1367. } else {
  1368. coolDown[address] = time();
  1369. }
  1370. if(m.hash)
  1371. {
  1372. socket.emit('message', {
  1373. type: 'updateRecentGames',
  1374. games: CoinfliprecentGames
  1375. });
  1376. }
  1377. });
  1378.  
  1379. //PIN FUNCTION
  1380. socket.on('addPin', function(m) {
  1381. var mesaj = m.message;
  1382. var utilizator = m.user;
  1383. pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level`,`tradelink` FROM `users` WHERE `hash` = ' + pool.escape(utilizator), function(err, res) {
  1384. if(err) throw err;
  1385. if(res.length == 0) return;
  1386.  
  1387. var row = res;
  1388. if(row[0].rank == 69)
  1389. {
  1390. pinnedMessages.push({
  1391. name: row[0].name,
  1392. avatar: row[0].avatar,
  1393. steamid: row[0].steamid,
  1394. rank: row[0].rank,
  1395. level: row[0].level,
  1396. message: mesaj
  1397. });
  1398. socket.emit('pinsSystem', pinSystem, pinnedMessages);
  1399. }
  1400. });
  1401. });
  1402.  
  1403.  
  1404. //CHAT FUNCTIONS
  1405. socket.on('nMsg', function(m)  {
  1406. var mesaj = escapeHtml(m.message);
  1407. var utilizator = m.user;
  1408. var hide = m.hide;
  1409. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1410.  
  1411. pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level`,`tradelink` FROM `users` WHERE `hash` = ' + pool.escape(utilizator), function(err, res) {
  1412. if (err) throw err;
  1413. var row = res;
  1414.  
  1415. if (!res[0]) return err;
  1416.  
  1417. if (mesaj.length >= 128 || mesaj.length < 2 && res[0].rank != 69) {
  1418. if(mesaj.length >= 128)
  1419. {
  1420. socket.emit('message', {
  1421. type: 'msg',
  1422. tip: 'error',
  1423. msg: 'You have exceeded the maximum characters in chat.'
  1424. });
  1425. }
  1426. else if(mesaj.length < 2)
  1427. {
  1428. socket.emit('message', {
  1429. type: 'msg',
  1430. tip: 'error',
  1431. msg: 'Your message is very short to send in chat.'
  1432. });
  1433. }
  1434. return;
  1435. } else {
  1436. if (antiSpamChat[res[0].steamid] + 2 >= time() && res[0].rank != 69) {
  1437. socket.emit('message', {
  1438. type: 'msg',
  1439. tip: 'error',
  1440. msg: 'Error: You need to wait before sending another message.'
  1441. });
  1442. return;
  1443. } else {
  1444. antiSpamChat[res[0].steamid] = time();
  1445. }
  1446.  
  1447. var caca = null;
  1448. if (caca = /^\/clear/.exec(mesaj)) {
  1449. if (row[0].rank == 69 || row[0].rank == 92) {
  1450. io.sockets.emit('message', {
  1451. type: 'addMessage',
  1452. tip: 'clear',
  1453. name: 'Alert',
  1454. rank: '0',
  1455. avatar: 'favicon.ico',
  1456. hide: true,
  1457. msg: 'Chat was cleared by Admin ' + row[0].name + '.'
  1458. });
  1459.  
  1460. chatMessages = [];
  1461. logger.trace('Chat: Cleared by Admin ' + row[0].name + '.');
  1462. }
  1463. } else if (caca = /^\/jwinner/.exec(mesaj)) {
  1464. if (row[0].rank == 69) {
  1465. pickJackpotWinner();
  1466. }
  1467. } else if (caca = /^\/spooky ([0-9]*)/.exec(mesaj)) {
  1468. if (row[0].rank == 69) {
  1469. if(caca[1])
  1470. {
  1471. if(socketBySteam.hasOwnProperty(caca[1]))
  1472. {
  1473. if(io.sockets.connected[socketBySteam[caca[1]]['info']])
  1474. {
  1475. io.sockets.connected[socketBySteam[caca[1]]['info']].emit('spooky');
  1476. }
  1477. }
  1478. }
  1479. }
  1480. } else if (caca = /^\/mute ([0-9]*) ([0-9]*)/.exec(mesaj)) {
  1481. if (row[0].rank == 69 || row[0].rank == 92) {
  1482. var t = time();
  1483. pool.query('UPDATE `users` SET `mute` = ' + pool.escape(parseInt(t) + parseInt(caca[2])) + ' WHERE `steamid` = ' + pool.escape(caca[1]), function(err2, row2) {
  1484. if (err2) throw err2;
  1485. if (row2.affectedRows == 0) {
  1486. socket.emit('message', {
  1487. type: 'msg',
  1488. tip: 'error',
  1489. msg: 'Steamid not found in database.'
  1490. });
  1491. logger.trace('Mute: Steamid not found in database (' + caca[1] + ').');
  1492. return;
  1493. }
  1494.  
  1495. socket.emit('message', {
  1496. type: 'msg',
  1497. tip: 'alert',
  1498. msg: 'You have muted user for ' + caca[2] + ' seconds.'
  1499. });
  1500. logger.trace('Mute: Steamid ' + caca[1] + ' has been muted for ' + caca[2] + ' seconds by ' + row[0].name + ' (' + row[0].steamid + ').');
  1501. });
  1502. }
  1503. } else if (caca = /^\/hidegame ([0-9]*)/.exec(mesaj)) {
  1504. if (row[0].rank == 69) {
  1505. hideGame(caca[1]);
  1506. socket.emit('message', {
  1507. type: 'msg',
  1508. tip: 'alert',
  1509. msg: 'Successfully hided game #' + caca[1] + '!'
  1510. });
  1511. logger.trace('Hide: Admin ' + row[0].name + ' hided game #' + caca[1]);
  1512. }
  1513. } else if (caca = /^\/spin ([0-9]*)/.exec(mesaj)) {
  1514. if (row[0].rank == 69) {
  1515. if(caca[1] == 1)
  1516. {
  1517. pinSystem = true;
  1518. socket.emit('pinsSystem', pinSystem, pinnedMessages);
  1519. }
  1520. else if(caca[1] == 0)
  1521. {
  1522. pinSystem = false;
  1523. socket.emit('pinsSystem', pinSystem, pinnedMessages);
  1524. }
  1525. socket.emit('message', {
  1526. type: 'msg',
  1527. tip: 'alert',
  1528. msg: 'Successfully changed the pin system to ' + caca[1]
  1529. });
  1530. logger.trace('Chat: Admin ' + row[0].name + ' changed the pin system to ' + caca[1]);
  1531. }
  1532. } else if (caca = /^\/dpin/.exec(mesaj)) {
  1533. if (row[0].rank == 69) {
  1534. pinSystem = false;
  1535. pinnedMessages = [];
  1536. socket.emit('pinsSystem', pinSystem, pinnedMessages);
  1537. socket.emit('message', {
  1538. type: 'msg',
  1539. tip: 'alert',
  1540. msg: 'Successfully deleted the pins'
  1541. });
  1542. logger.trace('Chat: Admin ' + row[0].name + ' deleted the pins.');
  1543. }
  1544. } else {
  1545.  
  1546. if (row[0].mute > time() && row[0].mute != 0) {
  1547. socket.emit('message', {
  1548. type: 'msg',
  1549. tip: 'error',
  1550. msg: 'You are muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').'
  1551. });
  1552. logger.trace('Mute: ' + row[0].name + ' (' + row[0].steamid + ') tried to speak (' + mesaj + ') while muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').');
  1553. return;
  1554. }
  1555.  
  1556. if (chatMessages.length > 20) {
  1557. chatMessages.shift();
  1558. }
  1559.  
  1560. chatMessages.push({
  1561. name: res[0].name,
  1562. avatar: res[0].avatar,
  1563. steamid: res[0].steamid,
  1564. rank: res[0].rank,
  1565. hide: hide,
  1566. level: res[0].level,
  1567. message: mesaj
  1568. });
  1569.  
  1570. io.sockets.emit('message', {
  1571. type: 'addMessage',
  1572. msg: mesaj,
  1573. avatar: res[0].avatar,
  1574. steamid: res[0].steamid,
  1575. rank: res[0].rank,
  1576. hide: hide,
  1577. level: res[0].level,
  1578. name: res[0].name
  1579. });
  1580. logger.trace('Chat: Message from ' + row[0].name + ' (SID: ' + row[0].steamid + ', IP: ' + address + ', hide: ' + hide + ') --> ' + mesaj);
  1581. }
  1582. }
  1583. });
  1584. });
  1585.  
  1586. socket.on('disconnect', function(m) {
  1587. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1588. if(usersOnline[address])
  1589. {
  1590. delete usersOnline[address];
  1591. }
  1592. io.sockets.emit('message', {
  1593. type: 'connections',
  1594. total: Object.keys(usersOnline).length
  1595. });
  1596. });
  1597.  
  1598. socket.on('setTlink', function(m) {
  1599. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1600. if(coolDown[address]+2 >= time()) {
  1601. socket.emit('message', {
  1602. type: 'msg',
  1603. tip: 'error',
  1604. msg: 'Please, stop flooding!'
  1605. });
  1606. return;
  1607. } else {
  1608. coolDown[address] = time();
  1609. }
  1610. if(m.hash)
  1611. {
  1612. if(m.tradelink.includes('://') && m.tradelink.includes('token=') && m.tradelink.includes('partner='))
  1613. {
  1614. pool.query('UPDATE users SET tradelink = ' + pool.escape(m.tradelink) + ' WHERE hash = ' + pool.escape(m.hash));
  1615. socket.emit('message', {
  1616. type: 'msg',
  1617. tip: 'alert',
  1618. msg: 'Your tradelink has been updated!'
  1619. });
  1620. }
  1621. else
  1622. {
  1623. socket.emit('message', {
  1624. type: 'msg',
  1625. tip: 'error',
  1626. msg: 'You need to type a correct tradelink!'
  1627. });
  1628. }
  1629. }
  1630. });
  1631.  
  1632. //CHAT FUNCTIONS
  1633. socket.on('watchGame', function(m) {
  1634. pool.query('SELECT * FROM games WHERE id = ' + pool.escape(m.gameid), function(error, results) {
  1635. if(error) throw error;
  1636.  
  1637. socket.emit('message', {
  1638. type: 'watchCF',
  1639. id: results[0].id,
  1640. cname: results[0].cname,
  1641. cavatar: results[0].cavatar,
  1642. cskinsurl: results[0].cskinsurl,
  1643. cskinsnames: results[0].cskinsnames,
  1644. cskinsprices: results[0].cskinsprices,
  1645. cskins: results[0].cskins,
  1646. ctp: results[0].ctp,
  1647. pname: results[0].pname,
  1648. pavatar: results[0].pavatar,
  1649. pskinsurl: results[0].pskinsurl,
  1650. pskinsnames: results[0].pskinsnames,
  1651. pskinsprices: results[0].pskinsprices,
  1652. pskins: results[0].pskins,
  1653. ptp: results[0].ptp,
  1654. hash: results[0].hash,
  1655. secret: results[0].secret,
  1656. winner: results[0].winner,
  1657. cpick: results[0].cpick,
  1658. ppick: results[0].ppick,
  1659. timer: timerGame[results[0].id]-time(),
  1660. timer11: results[0].timer11,
  1661. ttimer11: timer11Game[results[0].id]-time(),
  1662. winnerPercentage: results[0].winnerPercentage,
  1663. gameNumber: m.gameid,
  1664. expire: results[0].expire-time()
  1665. });
  1666. });
  1667. });
  1668.  
  1669. socket.on('joingame', function(m) {
  1670. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  1671. if(coolDown[address]+2 >= time()) {
  1672. socket.emit('message', {
  1673. type: 'msg',
  1674. tip: 'error',
  1675. msg: 'Please, stop flooding!'
  1676. });
  1677. return;
  1678. } else {
  1679. coolDown[address] = time();
  1680. }
  1681. if(antiFlood[socket]+2 >= time()) {
  1682. timesFlooding[socket] += 1;
  1683. if(timesFlooding[socket] == 3)
  1684. {
  1685. delete timesFlooding[socket];
  1686. socket.disconnect();
  1687. return;
  1688. }
  1689. return;
  1690. } else {
  1691. antiFlood[socket] = time();
  1692. }
  1693. if(!m.game)
  1694. {
  1695. return;
  1696. }
  1697.  
  1698. var assetids = m.assetids.split('/');
  1699. var gameID = m.game;
  1700. var user_hash = m.hash;
  1701.  
  1702.  
  1703. pool.query('SELECT id,trade_token,csteamid,cpick,expire,bot FROM games WHERE id = ' + pool.escape(gameID), function(error, results) {
  1704. if(error) throw errorl
  1705.  
  1706. if(results[0].trade_token)
  1707. {
  1708. socket.emit('message', {
  1709. type: 'msg',
  1710. tip: 'error',
  1711. msg: 'Error: Someone already joined in this game!'
  1712. });
  1713. return;
  1714. }
  1715.  
  1716. /*if(results[0].expire-time() <= 20)
  1717. {
  1718. socket.emit('message', {
  1719. type: 'msg',
  1720. tip: 'error',
  1721. msg: 'This game will expire in ~20 seconds. You cannot join!'
  1722. });
  1723. return;
  1724. }*/
  1725.  
  1726.  
  1727. if(results[0].id)
  1728. {
  1729. pool.query('SELECT name,steamid,avatar,tradelink,rank FROM users WHERE hash = ' + pool.escape(user_hash), function(error1, results1) {
  1730. if(error1) throw error1;
  1731.  
  1732. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(results1[0].steamid) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(ca, ma) {
  1733. if(ca) throw ca;
  1734. if(ma.length == 0) return;
  1735.  
  1736. if(ma[0].tTrades != 0)
  1737. {
  1738. socket.emit('message', {
  1739. type: 'msg',
  1740. tip: 'error',
  1741. msg: 'You isset an active tradeoffer.'
  1742. });
  1743. return;
  1744. }
  1745.  
  1746. if(!results[0] || !results1[0])
  1747. {
  1748. socket.emit('message', {
  1749. type: 'msg',
  1750. tip: 'error',
  1751. msg: 'Error: Unexpected error, contact an administrator!'
  1752. });
  1753. return;
  1754. }
  1755.  
  1756. if(results[0].csteamid == results1[0].steamid && results1[0].rank != 69)
  1757. {
  1758. socket.emit('message', {
  1759. type: 'msg',
  1760. tip: 'error',
  1761. msg: 'Error: You cannot join your own game!'
  1762. });
  1763. return;
  1764. }
  1765.  
  1766. if(results1[0].name || results1[0].steamid || results1[0].avatar)
  1767. {
  1768. var totalAmount = 0;
  1769. var totalItems = 0;
  1770.  
  1771. //ITEMS INFO
  1772. var skinImages = [];
  1773. var skinNames = [];
  1774. var skinPrices = [];
  1775. //ITEMS INFO
  1776.  
  1777. var minPriceDet = 0;
  1778.  
  1779.  
  1780. if(!results1[0].tradelink.includes('://') || !results1[0].tradelink.includes('steamcommunity.com') || !results1[0].tradelink.includes('partner') || !results1[0].tradelink.includes('token'))
  1781. {
  1782. socket.emit('message', {
  1783. type: 'msg',
  1784. tip: 'error',
  1785. msg: 'Error: Update your tradelink in the "my profile" page.'
  1786. });
  1787. return;
  1788. }
  1789.  
  1790. var toContinue = 0;
  1791.  
  1792. var defBot = pickBot(results[0].bot);
  1793. var defBot2 = results[0].bot;
  1794.  
  1795. var create = defBot.createOffer(results1[0].steamid, results1[0].tradelink.split('token=')[1]);
  1796. var itemsLength = [];
  1797. defBot.getUserInventoryContents(results1[0].steamid, AppID, ContextID, true, function(err, inv, currencies) {
  1798. for(i = 0; i < inv.length; i++) {
  1799. for(a=0; a < assetids.length; a++)
  1800. {
  1801. if(minPriceDet == 0)
  1802. {
  1803. if(inv[i].assetid == assetids[a] && inv[i].ss != 1)
  1804. {
  1805. inv[i].ss = 1;
  1806. skinImages.push(inv[i].icon_url);
  1807. skinNames.push(inv[i].market_hash_name);
  1808. skinPrices.push(getPriceItem(inv[i].market_hash_name));
  1809.  
  1810.  
  1811. if(getPriceItem(inv[i].market_hash_name) < minDep)
  1812. {
  1813. socket.emit('message', {
  1814. type: 'msg',
  1815. tip: 'error',
  1816. msg: 'Error: Do not force system [min price $' + minDep + '].'
  1817. });
  1818.  
  1819. minPriceDet = 1;
  1820. toContinue = 1;
  1821. return;
  1822. }
  1823. else
  1824. {
  1825. totalItems++;
  1826.  
  1827. totalAmount += getPriceItem(inv[i].market_hash_name);
  1828.  
  1829. itemsLength.push(inv[i].assetid);
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835.  
  1836. if(totalItems == 0 || totalItems > 25)
  1837. {
  1838. socket.emit('message', {
  1839. type: 'msg',
  1840. tip: 'error',
  1841. msg: 'Error: Min. items per trade: 1 and max. items per trade: 25!'
  1842. });
  1843. return;
  1844. }
  1845.  
  1846. pool.query('SELECT `ctp` FROM games WHERE id = ' + pool.escape(gameID), function(eroare, resultate) {
  1847. if(eroare) throw eroare;
  1848.  
  1849. if(resultate[0].ctp)
  1850. {
  1851. var calculare = 10/100*resultate[0].ctp;
  1852. var Gap01 = parseFloat(resultate[0].ctp - calculare).toFixed(2);
  1853. var Gap02 = parseFloat(resultate[0].ctp + calculare).toFixed(2);
  1854.  
  1855. if(totalAmount < Gap01 || totalAmount > Gap02)
  1856. {
  1857. toContinue = 1;
  1858. socket.emit('message', {
  1859. type: 'msg',
  1860. tip: 'error',
  1861. msg: 'Error: Minimum amount required: $' + Gap01 + ' or total amount required: $' + Gap02 + '. Your amount: $' + totalAmount
  1862. });
  1863. return;
  1864. }
  1865. }
  1866. else
  1867. {
  1868. toContinue = 1;
  1869. socket.emit('message', {
  1870. type: 'msg',
  1871. tip: 'error',
  1872. msg: 'Error: Invalid game!'
  1873. });
  1874. return;
  1875. }
  1876.  
  1877. if(toContinue == 0)
  1878. {
  1879. for(var b = 0; b < itemsLength.length; b++)
  1880. {
  1881. create.addTheirItem({
  1882. "appid": AppID,
  1883. "contextid": ContextID,
  1884. "assetid": itemsLength[b]
  1885. });
  1886. }
  1887.  
  1888. socket.emit('message', {
  1889. type: 'modals',
  1890. tip: 'trade',
  1891. result: 'offerProcessing'
  1892. });
  1893.  
  1894. var cod = makeCode();
  1895. create.setMessage("Security code: " + cod);
  1896. pool.query('UPDATE games SET scode = ' + pool.escape(cod) + ' WHERE id = ' + pool.escape(gameID));
  1897.  
  1898. create.send(function(err, status) {
  1899. if(err)
  1900. {
  1901. socket.emit('message', {
  1902. type: 'modals',
  1903. tip: 'trade',
  1904. result: 'offerError',
  1905. msg: err.toString()
  1906. });
  1907. return;
  1908. }
  1909. else
  1910. {
  1911. //INFO ITEMS
  1912. var Skinimages = skinImages.join('/');
  1913. var Skinnames = skinNames.join('/');
  1914. var Skinprices = skinPrices.join('/');
  1915.  
  1916. var timpCreat = time();
  1917. var timpExpire = time()+90;
  1918.  
  1919. gamesPending[create.id] = results1[0].steamid;
  1920.  
  1921. tradingRequests[create.id] = {
  1922. action: 'joingame',
  1923. user: results1[0].steamid,
  1924. created: timpCreat,
  1925. expire: timpExpire,
  1926. gameExpire: results[0].expire,
  1927. gameID: results[0].id
  1928. }
  1929.  
  1930. socket.emit('message', {
  1931. type: 'modals',
  1932. tip: 'trade',
  1933. result: 'offerSend',
  1934. tid: create.id,
  1935. code: cod
  1936. });
  1937.  
  1938. pool.query('INSERT INTO trades SET user = ' + pool.escape(results1[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('joingame') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(defBot2));
  1939.  
  1940.  
  1941. var ppick = '';
  1942.  
  1943. if(results[0].cpick == 'ct')
  1944. {
  1945. ppick = 't';
  1946. }
  1947. else if(results[0].cpick == 't')
  1948. {
  1949. ppick = 'ct';
  1950. }
  1951.  
  1952. pool.query('SELECT hash FROM games WHERE id = ' + pool.escape(gameID), function(err1, res1) {
  1953. if(err1) throw err1;
  1954. logger.info('Joined game #' + gameID + ', player steamid: ' + results1[0].steamid + ' (' + results1[0].name + ')');
  1955. pool.query('UPDATE `games` SET `psteamid` = ' + pool.escape(results1[0].steamid) + ', `pname` = ' + pool.escape(results1[0].name) + ', `pavatar` = ' + pool.escape(results1[0].avatar) + ', `pskinsurl` = ' + pool.escape(Skinimages) + ', `pskinsnames` = ' + pool.escape(Skinnames) + ', `pskinsprices` = ' + pool.escape(Skinprices) + ', `pskins` = ' + pool.escape(totalItems) + ', `ppick` = ' + pool.escape(ppick) + ', `ptp` = ' + pool.escape(totalAmount) + ', `trade_token` = ' + pool.escape(create.id) + ' WHERE `id` = ' + pool.escape(gameID));
  1956. loadAllGames();
  1957. sendGames(gameID);
  1958. });
  1959. }
  1960. });
  1961. }
  1962. });
  1963. });
  1964. }
  1965. else
  1966. {
  1967. socket.emit('message', {
  1968. type: 'msg',
  1969. tip: 'error',
  1970. msg: 'Error: User_id not found! Hacked.'
  1971. });
  1972. }
  1973. });
  1974. });
  1975. }
  1976. else
  1977. {
  1978. socket.emit('message', {
  1979. type: 'msg',
  1980. tip: 'error',
  1981. msg: 'Error: This game does not exists!'
  1982. });
  1983. }
  1984. });
  1985. });
  1986. });
  1987.  
  1988. function hideGame(gameID)
  1989. {
  1990. pool.query('UPDATE games SET `ended` = 1 WHERE `id` = ' + pool.escape(gameID), function(err, row) {
  1991. if(err) throw err;
  1992. if(row.length == 0) return;
  1993.  
  1994. pool.query('SELECT * FROM games WHERE id = ' + pool.escape(gameID), function(aaa, bbb) {
  1995. if(aaa) throw aaa;
  1996. if(bbb.length == 0) return;
  1997.  
  1998. CoinfliprecentGames.unshift(bbb[0]);
  1999. CoinfliprecentGames.pop();
  2000. });
  2001. });
  2002. loadAllGames();
  2003. setTimeout(function() {
  2004. io.sockets.emit('message', {
  2005. type: 'removeGame',
  2006. id: gameID
  2007. });
  2008. }, 1000);
  2009. }
  2010.  
  2011.  
  2012.  
  2013. function getPriceItem(name)
  2014. {
  2015. var priceItem = 0;
  2016. if (name) {
  2017. var prices = require('./prices.json');
  2018. priceItem = prices[name];
  2019. }
  2020. return priceItem;
  2021. }
  2022.  
  2023.  
  2024.  
  2025. /*
  2026. Getting prices
  2027. */
  2028. var priceUrl = 'https://api.csgofast.com/price/all';
  2029.  
  2030. function getPriceList() {
  2031. request(priceUrl, function(dataAndEvents, r, actual) {
  2032. ok = JSON.parse(actual);
  2033. if (200 != r.statusCode) {
  2034. if (fs.existsSync("/var/Bot/prices.json")) {
  2035. ok = JSON.parse(fs.readFileSync("/var/Bot/prices.json"));
  2036. ok = JSON.parse(fs.readFileSync("/var/www/prices.json"));
  2037. logger.trace("[SERVER] Loading Prices - Server sided prices loaded!");
  2038. }
  2039. } else {
  2040. fs.writeFileSync("/var/Bot/prices.json", actual);
  2041. fs.writeFileSync("/var/www/prices.json", actual);
  2042. logger.trace("[SERVER] Loading Prices - API prices loaded!");
  2043. }
  2044. });
  2045. }
  2046.  
  2047. function PriceOfItem(offer)
  2048. {
  2049. var priceItem = 0;
  2050. if (offer) {
  2051. var prices = require('./prices.json');
  2052. priceItem = prices[offer.market_hash_name];
  2053. }
  2054. return priceItem;
  2055. }
  2056.  
  2057. getPriceList();
  2058. setInterval(getPriceList, config.options.priceRefreshInterval * 1000);
  2059.  
  2060. /*
  2061. Offer handling
  2062. */
  2063. function isInArray(value, array) {
  2064. return array.indexOf(value) > -1;
  2065. }
  2066. function acceptOffer(offer) {
  2067. offer.accept((err) => {
  2068. if (err) logger.error('Unable to accept offer: ' + err);
  2069. community.bot1.checkConfirmations();
  2070. community.bot2.checkConfirmations();
  2071. community.bot3.checkConfirmations();
  2072. logger.info('Trade offer #' + offer.id + ' accepted.');
  2073. });
  2074. }
  2075.  
  2076. function declineOffer(offer) {
  2077. offer.decline((err) => {
  2078. if (err) return logger.error('Unable to decline offer: ' + err);
  2079. logger.info('Trade offer #' + offer.id + ' declined.');
  2080. });
  2081. }
  2082.  
  2083. //VERIFICARE ACCEPTARE TRADE:
  2084. manager.bot1.on('sentOfferChanged', function(offer, oldState) {
  2085. managers.bot1(offer, oldState);
  2086. });
  2087. manager.bot2.on('sentOfferChanged', function(offer, oldState) {
  2088. managers.bot2(offer, oldState);
  2089. });
  2090. manager.bot3.on('sentOfferChanged', function(offer, oldState) {
  2091. managers.bot3(offer, oldState);
  2092. });
  2093.  
  2094.  
  2095.  
  2096. function pickJackpotWinner()
  2097. {
  2098. setTimeout(function() {
  2099. var wooble = Math.floor(Math.random() * (9510 - 9420 + 1)) + 9420;
  2100. var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
  2101. var winnerTicket = Math.floor((jackpotTickets - 0.0000000001) * (winnerPercentage / 100));
  2102. var secondsRotate = Math.floor(Math.random() * (13000 - 8900 + 1)) + 8900;
  2103. var winSteamid;
  2104. var avatarWin;
  2105. var nameWin;
  2106. var isAdded = [];
  2107. var winnerInfo = [];
  2108.  
  2109. jackpotNextRoundTime = time()+(secondsRotate/1000)+12;
  2110.  
  2111. jackpotInt = setInterval(function() {
  2112. if(jackpotNextRoundTime-time() <= 0)
  2113. {
  2114. nextJackpotRound();
  2115. logger.trace('JACKPOT -> new round started!');
  2116. clearInterval(jackpotInt);
  2117. }
  2118. });
  2119.  
  2120. logger.trace('JACKPOT -> winner percentage: ' + winnerPercentage + '; winner ticket: ' + winnerTicket);
  2121. jackpotTotalTickets.forEach(function (i) {
  2122. logger.trace('JACKPOT -> ticket number: ' + i['ticket'] + ' and user ' + i['user']);
  2123. if(i['ticket'] == winnerTicket)
  2124. {
  2125. logger.info('JACKPOT -> ticket number won: ' + i['ticket'] + ' and user ' + i['user']);
  2126. winSteamid = i['user'];
  2127. pool.query('SELECT name, avatar FROM users WHERE steamid = ' + pool.escape(winSteamid), function(e, r) {
  2128. if(e) {logger.error(e); return;}
  2129. //if(r.length == 0) {logger.error('SELECT ticketname.'); return;}
  2130.  
  2131. avatarWin = r[0].avatar;
  2132. nameWin = r[0].name;
  2133.  
  2134. winnerInfo.push({
  2135. "avatar": avatarWin,
  2136. "name": nameWin,
  2137. "steamid": winSteamid,
  2138. "chance": parseFloat(100 - ((totalJackpotValue-usersPrices[winSteamid])/totalJackpotValue)*100).toFixed(2),
  2139. "pot": totalJackpotValue,
  2140. "secret": jackpotSecret,
  2141. "winnerPercentage": winnerPercentage
  2142. });
  2143.  
  2144.  
  2145. var users_avatars_pot = [];
  2146. var users_names_pot = [];
  2147.  
  2148. for(var i = 0; i < 103; i++)
  2149. {
  2150. var randomUser = Math.floor(Math.random() * (jackpotTotalTickets.length-1 - 1 + 1)) + 1;
  2151. for(var z in JackpotUsers)
  2152. {
  2153. if(jackpotTotalTickets[randomUser]['user'] == JackpotUsers[z]['userInfo']['steamid'] && isAdded[i] != 1)
  2154. {
  2155. isAdded[i] = 1;
  2156. if(i == 92)
  2157. {
  2158. users_avatars_pot.push(avatarWin);
  2159. users_names_pot.push(nameWin);
  2160. continue;
  2161. }
  2162. users_avatars_pot.push(JackpotUsers[z]['userInfo']['avatar']);
  2163. users_names_pot.push(JackpotUsers[z]['userInfo']['name']);
  2164. }
  2165. }
  2166. }
  2167.  
  2168. pool.query('UPDATE jgames SET pot = ' + pool.escape(parseFloat(totalJackpotValue).toFixed(2)) + ', items = ' + pool.escape(totalJackpotItems) + ', tickets = ' + pool.escape(jackpotTickets) + ', winnerTicket = ' + pool.escape(winnerTicket) + ', ended = 1 WHERE id = ' + pool.escape(jackpotRound));
  2169. setTimeout(function() {
  2170. io.sockets.emit('message', {
  2171. type: 'spinJackpot',
  2172. seconds: secondsRotate,
  2173. wooble: wooble,
  2174. users_avatars: users_avatars_pot.join('|'),
  2175. users_names: users_names_pot.join('|'),
  2176. winner: winnerInfo
  2177. });
  2178.  
  2179. setTimeout(function() {
  2180. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(winSteamid), function(a, b) {
  2181. if(a) {logger.error(a); return;}
  2182. if(b.length == 0) {logger.error('Error inv [tradelinkSteamid]'); return;}
  2183. var itemsToSend = [];
  2184. for(var i in JackpotUsers)
  2185. {
  2186. for(var z in JackpotUsers[i]['itemsInfo'])
  2187. {
  2188. itemsToSend.push(JackpotUsers[i]['itemsInfo'][z]['id']);
  2189. }
  2190. }
  2191.  
  2192. sendJackpotItems(winSteamid, b[0].tradelink, itemsToSend, nameWin);
  2193. logger.trace('JACKPOT -> Winner got trade');
  2194. });
  2195. }, secondsRotate+1000);
  2196. }, 2000);
  2197. });
  2198. }
  2199. });
  2200. }, 2500);
  2201. }
  2202.  
  2203. function sendJackpotItems(steamid, tradelink, items, name)
  2204. {
  2205. var defBot = pickBot(jackpotBot);
  2206. var defBot2 = jackpotBot;
  2207. var create = defBot.createOffer(steamid, tradelink.split('token=')[1]);
  2208. var cod = makeCode();
  2209. create.setMessage('Your winnings from jackpot round #' + jackpotRound + '. Security code: ' + cod);
  2210.  
  2211. var totalPrice = 0;
  2212. var itemss = items;
  2213. var Items = [];
  2214.  
  2215. defBot.loadInventory(AppID, ContextID, true, function(err, inv, curr) {
  2216. if(err) {logger.error(err); return;}
  2217. if(inv.length == 0) {logger.error('Error inv [jackpot]'); return;}
  2218.  
  2219. var pretul = require('./prices.json');
  2220. var itemsDB = [];
  2221.  
  2222. for(var i in inv)
  2223. {
  2224. for(var z in itemss)
  2225. {
  2226. if(inv[i].assetid == itemss[z] && itemss[z].ss != 1)
  2227. {
  2228. itemss[z].ss = 1;
  2229. totalPrice += parseFloat(pretul[inv[i].market_hash_name]);
  2230. Items.push({
  2231. 'name': inv[i].market_hash_name,
  2232. 'price': pretul[inv[i].market_hash_name],
  2233. 'assetid': inv[i].assetid
  2234. });
  2235. }
  2236. }
  2237. }
  2238.  
  2239. var maxComission = jackpotPRake/100*(totalPrice.toFixed(2));
  2240. var currComission = 0.00;
  2241.  
  2242. if(/(KINGDOM-CSGO.com|kingdom-csgo.com|KINGDOM-CSGO.COM)/.exec(name))
  2243. {
  2244. maxComission = (jackpotPRake - 2)/100*(totalPrice.toFixed(2));
  2245. }
  2246.  
  2247. for(var i in Items)
  2248. {
  2249. if(Items[i].price <= maxComission && ((currComission+Items[i].price) <= maxComission))
  2250. {
  2251. currComission += parseFloat(Items[i].price);
  2252. Items[i].remove = 1;
  2253. //logger.trace('[Script check nr. 1] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') removed from Items array.');
  2254. }
  2255. else
  2256. {
  2257. Items[i].added = 1;
  2258. //logger.trace('[Script check nr. 1] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') added to Items array.');
  2259. }
  2260. }
  2261.  
  2262.  
  2263. for(var i in Items)
  2264. {
  2265. if(Items[i].added == 1)
  2266. {
  2267. itemsDB.push(Items[i].assetid);
  2268. //logger.trace('[Script check nr. 2] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') added to itemsDB array.');
  2269. }
  2270. else if(Items[i].remove == 1)
  2271. {
  2272. //logger.trace('[Script check nr. 2] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') removed from itemsDB array.');
  2273. }
  2274. }
  2275.  
  2276. for(var i in itemsDB)
  2277. {
  2278. create.addMyItem({
  2279. "appid": AppID,
  2280. "contextid": ContextID,
  2281. "assetid": itemsDB[i]
  2282. });
  2283. }
  2284.  
  2285. create.send(function(cc, sts) {
  2286. if(cc)
  2287. {
  2288. logger.error(cc);
  2289. return;
  2290. }
  2291. else
  2292. {
  2293. logger.trace('[Winner-jackpot: ' + steamid + ' (' + name + ') ] Offer #' + create.id + " " + sts);
  2294.  
  2295. var timpCreat = time();
  2296. var timpExpired = time()+90;
  2297.  
  2298. tradingRequests[create.id] = {
  2299. action: 'winning',
  2300. user: steamid,
  2301. created: timpCreat,
  2302. expired: timpExpired
  2303. };
  2304.  
  2305. pool.query('INSERT INTO trades SET user = ' + pool.escape(steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpired) + ', bot = ' + pool.escape(defBot2));
  2306. }
  2307. });
  2308. });
  2309. }
  2310.  
  2311.  
  2312. function sendItemsTrade(offer, items, winner, numeleItm, idsItm, priceItm)
  2313. {
  2314. pool.query('SELECT id,cskinsnames,winner,csteamid,psteamid,cname,pname,cskinsprices,ctp,ptp,cassetids,cpick,ppick,bot FROM games WHERE trade_token = ' + pool.escape(offer), function(err, res) {
  2315. if(err) throw err;
  2316.  
  2317. setTimeout(function() {
  2318. hideGame(res[0].id);
  2319. }, 60000);
  2320.  
  2321. var ItemsRake = [];
  2322.  
  2323. var Skins1Names = res[0].cskinsnames.split('/');
  2324. var Skins2Names = numeleItm;
  2325. var TotalSkinsNames = Skins1Names.concat(Skins2Names);
  2326.  
  2327. var Skins1 = res[0].cassetids.split('/');
  2328. var Skins2 = idsItm;
  2329. var allSkins = Skins1.concat(Skins2);
  2330.  
  2331. var Prices1 = res[0].cskinsprices.split('/');
  2332. var Prices2 = priceItm;
  2333. var allPrices = Prices1.concat(Prices2);
  2334.  
  2335. var itemsDB = [];
  2336.  
  2337. var maxComission = percentRake/100*(res[0].ctp+res[0].ptp);
  2338. var currComission = 0.00;
  2339.  
  2340. var partner;
  2341. var numele;
  2342. if(winner == 'ct' && res[0].cpick == 'ct')
  2343. {
  2344. partner = res[0].csteamid;
  2345. numele = res[0].cname;
  2346. }
  2347. else if(winner == 't' && res[0].ppick == 't')
  2348. {
  2349. partner = res[0].psteamid;
  2350. numele = res[0].pname;
  2351. }
  2352. else if(winner == 'ct' && res[0].ppick == 'ct')
  2353. {
  2354. partner = res[0].psteamid;
  2355. numele = res[0].pname;
  2356. }
  2357. else if(winner == 't' && res[0].cpick == 't')
  2358. {
  2359. partner = res[0].csteamid;
  2360. numele = res[0].cname;
  2361. }
  2362.  
  2363. if(/(KINGDOM-CSGO.com|kingdom-csgo.com|KINGDOWM-CSGO.COM)/.exec(numele))
  2364. {
  2365. maxComission = (percentRake - 2)/100*(res[0].ctp+res[0].ptp);
  2366. }
  2367.  
  2368. for(var i in allSkins)
  2369. {
  2370. ItemsRake.push({
  2371. assetid: allSkins[i],
  2372. price: allPrices[i],
  2373. name: TotalSkinsNames[i]
  2374. });
  2375. }
  2376.  
  2377.  
  2378. for(var i in ItemsRake)
  2379. {
  2380. if(ItemsRake[i].price <= maxComission && ((currComission+ItemsRake[i].price) <= maxComission))
  2381. {
  2382. currComission += parseFloat(ItemsRake[i].price);
  2383. ItemsRake[i].remove = 1;
  2384. //logger.trace('[Script check nr. 1] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') removed from ItemsRake array.');
  2385. }
  2386. else
  2387. {
  2388. ItemsRake[i].added = 1;
  2389. //logger.trace('[Script check nr. 1] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') added to ItemsRake array.');
  2390. }
  2391. }
  2392.  
  2393.  
  2394. for(var i in ItemsRake)
  2395. {
  2396. if(ItemsRake[i].added == 1)
  2397. {
  2398. itemsDB.push(ItemsRake[i].assetid);
  2399. //logger.trace('[Script check nr. 2] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') added to itemsDB array.');
  2400. }
  2401. else if(ItemsRake[i].remove == 1)
  2402. {
  2403. //logger.trace('[Script check nr. 2] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') removed from itemsDB array.');
  2404. }
  2405. }
  2406.  
  2407. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(partner), function(eroare, success) {
  2408. if(eroare) throw eroare;
  2409. if(success.length == 0) return;
  2410.  
  2411. var defBot = pickBot(res[0].bot);
  2412. var defBot2 = res[0].bot;
  2413. var create = defBot.createOffer(partner, success[0].tradelink.split('token=')[1]);
  2414. for(var i in itemsDB)
  2415. {
  2416. create.addMyItem({
  2417. "appid": AppID,
  2418. "contextid": ContextID,
  2419. "assetid": itemsDB[i]
  2420. });
  2421. }
  2422.  
  2423. var cod = makeCode();
  2424. create.setMessage('Security code: ' + cod);
  2425. create.send(function(err, status) {
  2426. if(err)
  2427. {
  2428. logger.error(err);
  2429. var WSteamid;
  2430. var WName;
  2431. pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
  2432. if(winner == 'ct' && res[0].cpick == 'ct')
  2433. {
  2434. WSteamid = res[0].csteamid;
  2435. WName = res[0].cname;
  2436. }
  2437. else if(winner == 't' && res[0].ppick == 't')
  2438. {
  2439. WSteamid = res[0].psteamid;
  2440. WName = res[0].pname;
  2441. }
  2442. else if(winner == 'ct' && res[0].ppick == 'ct')
  2443. {
  2444. WSteamid = res[0].psteamid;
  2445. WName = res[0].pname;
  2446. }
  2447. else if(winner == 't' && res[0].cpick == 't')
  2448. {
  2449. WSteamid = res[0].csteamid;
  2450. WName = res[0].cname;
  2451. }
  2452.  
  2453. var timpCreat = time();
  2454. var timpExpire = time()+90;
  2455.  
  2456. logger.trace('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
  2457. pool.query('INSERT INTO trades SET user = ' + pool.escape(WSteamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(defBot2), function(abc, cba) {
  2458. if(abc) throw abc;
  2459. if(cba.length == 0) return;
  2460.  
  2461. logger.info('Trade #' + create.id + ' has been added to database!');
  2462. });
  2463. return;
  2464. }
  2465. else
  2466. {
  2467.  
  2468. var WSteamid;
  2469. var WName;
  2470. pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
  2471. if(winner == 'ct' && res[0].cpick == 'ct')
  2472. {
  2473. WSteamid = res[0].csteamid;
  2474. WName = res[0].cname;
  2475. }
  2476. else if(winner == 't' && res[0].ppick == 't')
  2477. {
  2478. WSteamid = res[0].psteamid;
  2479. WName = res[0].pname;
  2480. }
  2481. else if(winner == 'ct' && res[0].ppick == 'ct')
  2482. {
  2483. WSteamid = res[0].psteamid;
  2484. WName = res[0].pname;
  2485. }
  2486. else if(winner == 't' && res[0].cpick == 't')
  2487. {
  2488. WSteamid = res[0].csteamid;
  2489. WName = res[0].cname;
  2490. }
  2491.  
  2492. logger.trace('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
  2493.  
  2494. var timpCreat = time();
  2495. var timpExpire = time()+90;
  2496.  
  2497. tradingRequests[create.id] = {
  2498. action: 'winning',
  2499. user: WSteamid,
  2500. created: timpCreat,
  2501. expire: timpExpire
  2502. };
  2503.  
  2504. pool.query('INSERT INTO trades SET user = ' + pool.escape(WSteamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(defBot2), function(abc, cba) {
  2505. if(abc) throw abc;
  2506. if(cba.length == 0) return;
  2507.  
  2508. logger.info('Trade #' + create.id + ' has been added to database!');
  2509. });
  2510.  
  2511. if(gamesPending.hasOwnProperty(offer.id))
  2512. {
  2513. delete gamesPending[offer.id];
  2514. }
  2515. }
  2516. });
  2517.  
  2518. loadAllGames();
  2519. sendGames(res[0].id);
  2520.  
  2521. setTimeout(function() {
  2522. loadStatistics();
  2523. }, 5000);
  2524. });
  2525. });
  2526. }
  2527.  
  2528. //Refresh polldata.json
  2529. manager.bot1.on('pollData', function(pollData) {
  2530. fs.writeFile('polldata-bot1.json', JSON.stringify(pollData));
  2531. });
  2532. if (fs.existsSync('polldata-bot1.json')) {
  2533. manager.bot1.pollData = JSON.parse(fs.readFileSync('polldata-bot1.json'));
  2534. }
  2535. manager.bot2.on('pollData', function(pollData) {
  2536. fs.writeFile('polldata-bot2.json', JSON.stringify(pollData));
  2537. });
  2538. if (fs.existsSync('polldata-bot2.json')) {
  2539. manager.bot2.pollData = JSON.parse(fs.readFileSync('polldata-bot2.json'));
  2540. }
  2541. manager.bot3.on('pollData', function(pollData) {
  2542. fs.writeFile('polldata-bot3.json', JSON.stringify(pollData));
  2543. });
  2544. if (fs.existsSync('polldata-bot3.json')) {
  2545. manager.bot3.pollData = JSON.parse(fs.readFileSync('polldata-bot3.json'));
  2546. }
  2547. //
  2548.  
  2549. //BOTS LOG
  2550. client.bot1.on('loggedOn', function(details) {
  2551. client.bot1.setPersona(SteamUser.Steam.EPersonaState.Online, config.bots[0].botname);
  2552. client.bot1.gamesPlayed([730]);
  2553. });
  2554. client.bot2.on('loggedOn', function(details) {
  2555. client.bot2.setPersona(SteamUser.Steam.EPersonaState.Online, config.bots[1].botname);
  2556. client.bot2.gamesPlayed([730]);
  2557. });
  2558. client.bot3.on('loggedOn', function(details) {
  2559. client.bot3.setPersona(SteamUser.Steam.EPersonaState.Online, config.bots[2].botname);
  2560. client.bot3.gamesPlayed([730]);
  2561. });
  2562.  
  2563. client.bot1.on('webSession', function(sessionID, cookies) {
  2564. manager.bot1.setCookies(cookies, function(err) {
  2565. if (err) {
  2566. logger.info('Bot 1 -> err: ' + err);
  2567. process.exit(1);
  2568. return;
  2569. }
  2570. logger.info('Bot 1 -> got api key: ' + manager.bot1.apiKey);
  2571. });
  2572.  
  2573. community.bot1.setCookies(cookies);
  2574. community.bot1.startConfirmationChecker(config.options.confirmationInterval, config.bots[0].identitySecret);
  2575. });
  2576. client.bot2.on('webSession', function(sessionID, cookies) {
  2577. manager.bot2.setCookies(cookies, function(err) {
  2578. if (err) {
  2579. logger.info('Bot 2 -> err: ' + err);
  2580. process.exit(1);
  2581. return;
  2582. }
  2583. logger.info('Bot 2 -> got api key: ' + manager.bot2.apiKey);
  2584. });
  2585.  
  2586. community.bot2.setCookies(cookies);
  2587. community.bot2.startConfirmationChecker(config.options.confirmationInterval, config.bots[1].identitySecret);
  2588. });
  2589. client.bot3.on('webSession', function(sessionID, cookies) {
  2590. manager.bot3.setCookies(cookies, function(err) {
  2591. if (err) {
  2592. logger.info('Bot 3 -> err: ' + err);
  2593. process.exit(1);
  2594. return;
  2595. }
  2596. logger.info('Bot 3 -> got api key: ' + manager.bot3.apiKey);
  2597. });
  2598.  
  2599. community.bot3.setCookies(cookies);
  2600. community.bot3.startConfirmationChecker(config.options.confirmationInterval, config.bots[2].identitySecret);
  2601. });
  2602. //BOTS LOG
  2603.  
  2604.  
  2605.  
  2606.  
  2607. function time()
  2608. {
  2609. return parseInt(new Date().getTime()/1000);
  2610. }
  2611.  
  2612. function addHistory(socket)
  2613. {
  2614. chatMessages.forEach(function(itm) {
  2615. socket.emit('message', {
  2616. type: 'addMessage',
  2617. msg: itm.message,
  2618. avatar: itm.avatar,
  2619. steamid: itm.steamid,
  2620. rank: itm.rank,
  2621. hide: itm.hide,
  2622. level: itm.level,
  2623. name: itm.name
  2624. });
  2625. })
  2626. }
  2627.  
  2628. function makeCode() {
  2629. var text = "";
  2630. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  2631.  
  2632. for(var i=0; i < 6; i++)
  2633. text += possible.charAt(Math.floor(Math.random() * possible.length));
  2634.  
  2635. return text;
  2636. }
  2637.  
  2638. function makeHash()
  2639. {
  2640. var text = "";
  2641. var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
  2642.  
  2643. for(var i=0; i < 32; i++)
  2644. text += possible.charAt(Math.floor(Math.random() * possible.length));
  2645.  
  2646. return text;
  2647. }
  2648.  
  2649. function makeSecret()
  2650. {
  2651. var data = 'CSGO-' + time() + '-' + Math.floor(Math.random() * 500);
  2652. var hashess = crypto.createHash('md5').update(data).digest("hex");
  2653.  
  2654. return hashess;
  2655. }
  2656.  
  2657. function getProxy()
  2658. {
  2659. return "http://" + proxies[random(0,proxies.length-1)];
  2660. }
  2661.  
  2662. function random(min, max) {
  2663. return Math.floor(Math.random() * (max - min + 1)) + min;
  2664. }
  2665.  
  2666. function getInv(user, socket)
  2667. {
  2668. var pret = require('./prices.json');
  2669.  
  2670. var reqOpts = {
  2671. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
  2672. };
  2673.  
  2674. request(reqOpts, function(err, response, body) {
  2675. if(err) throw err;
  2676. if(response && response.statusCode == 200)
  2677. {
  2678. var bodiul = JSON.parse(body);
  2679.  
  2680. var assets = bodiul['assets'];
  2681. var descriptions = bodiul['descriptions'];
  2682.  
  2683. var counter = 0;
  2684.  
  2685. var idss = [];
  2686. var namess = [];
  2687. var pricess = [];
  2688. var imgss = [];
  2689.  
  2690. var Ids = '';
  2691. var Names = '';
  2692. var Prices = '';
  2693. var Imgs = '';
  2694.  
  2695. if(!assets) return;
  2696.  
  2697. assets.forEach(function(valuey, y) {
  2698. descriptions.forEach(function(valuez, z) {
  2699. if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
  2700. {
  2701. var isTradable = valuez['tradable'];
  2702. if(isTradable == 1)
  2703. {
  2704. var id = valuey['assetid'];
  2705.  
  2706. var name = valuez['market_hash_name'];
  2707. var price = pret[valuez['market_hash_name']];
  2708. var img = valuez['icon_url'];
  2709.  
  2710. if(price >= minDep)
  2711. {
  2712. idss.push(id);
  2713. namess.push(name);
  2714. pricess.push(price);
  2715. imgss.push(img);
  2716. }
  2717. }
  2718. }
  2719. });
  2720. });
  2721.  
  2722. Ids = idss.join('/');
  2723. Names = namess.join('/');
  2724. Prices = pricess.join('/');
  2725. Imgs = imgss.join('/');
  2726.  
  2727. socket.emit('message', {
  2728. type: 'getInventory',
  2729. id: Ids,
  2730. name: Names,
  2731. price: Prices,
  2732. img: Imgs
  2733. });
  2734.  
  2735. inventoryUser[user] = {
  2736. id: Ids,
  2737. name: Names,
  2738. price: Prices,
  2739. img: Imgs
  2740. }
  2741. }
  2742. else
  2743. {
  2744.  
  2745. }
  2746. });
  2747. }
  2748.  
  2749.  
  2750. function getInv2(user, socket)
  2751. {
  2752. var pret = require('./prices.json');
  2753.  
  2754. var reqOpts = {
  2755. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
  2756. };
  2757.  
  2758. request(reqOpts, function(err, response, body) {
  2759. if(err) throw err;
  2760. if(response && response.statusCode == 200)
  2761. {
  2762. var bodiul = JSON.parse(body);
  2763.  
  2764. var assets = bodiul['assets'];
  2765. var descriptions = bodiul['descriptions'];
  2766.  
  2767. var counter = 0;
  2768.  
  2769. var idss = [];
  2770. var namess = [];
  2771. var pricess = [];
  2772. var imgss = [];
  2773.  
  2774. var Ids = '';
  2775. var Names = '';
  2776. var Prices = '';
  2777. var Imgs = '';
  2778.  
  2779. var Gamess = [];
  2780.  
  2781. if(!assets) return;
  2782.  
  2783. assets.forEach(function(valuey, y) {
  2784. descriptions.forEach(function(valuez, z) {
  2785. if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
  2786. {
  2787. var isTradable = valuez['tradable'];
  2788. if(isTradable == 1)
  2789. {
  2790. var id = valuey['assetid'];
  2791.  
  2792. var name = valuez['market_hash_name'];
  2793. var price = pret[valuez['market_hash_name']];
  2794. var img = valuez['icon_url'];
  2795.  
  2796. if(price >= minDep)
  2797. {
  2798. idss.push(id);
  2799. imgss.push(img);
  2800. }
  2801. }
  2802. }
  2803. });
  2804. });
  2805.  
  2806. Ids = idss.join('/');
  2807. Names = namess.join('/');
  2808. Prices = pricess.join('/');
  2809. Imgs = imgss.join('/');
  2810.  
  2811. socket.emit('message', {
  2812. type: 'getInventory2',
  2813. id: Ids,
  2814. name: Names,
  2815. price: Prices,
  2816. img: Imgs
  2817. });
  2818.  
  2819. inventoryUser[user] = {
  2820. id: Ids,
  2821. name: Names,
  2822. price: Prices,
  2823. img: Imgs
  2824. }
  2825. }
  2826. else
  2827. {
  2828.  
  2829. }
  2830. });
  2831. }
  2832.  
  2833. function jgetInv(user, socket)
  2834. {
  2835. var pret = require('./prices.json');
  2836.  
  2837. if(config['proxyON'] == true)
  2838. {
  2839. var reqOpts = {
  2840. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000',
  2841. proxy: getProxy()
  2842. };
  2843. }
  2844. else
  2845. {
  2846. var reqOpts = {
  2847. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
  2848. };
  2849. }
  2850.  
  2851. request(reqOpts, function(err, response, body) {
  2852. if(err) throw err;
  2853. if(response && response.statusCode == 200)
  2854. {
  2855. var bodiul = JSON.parse(body);
  2856.  
  2857. var assets = bodiul['assets'];
  2858. var descriptions = bodiul['descriptions'];
  2859.  
  2860. var counter = 0;
  2861.  
  2862. var idss = [];
  2863. var namess = [];
  2864. var pricess = [];
  2865. var imgss = [];
  2866.  
  2867. var Ids = '';
  2868. var Names = '';
  2869. var Prices = '';
  2870. var Imgs = '';
  2871.  
  2872. if(!assets) return;
  2873.  
  2874. assets.forEach(function(valuey, y) {
  2875. descriptions.forEach(function(valuez, z) {
  2876. if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
  2877. {
  2878. var isTradable = valuez['tradable'];
  2879. if(isTradable == 1)
  2880. {
  2881. var id = valuey['assetid'];
  2882. var name = valuez['market_hash_name'];
  2883. var price = pret[valuez['market_hash_name']];
  2884. var img = valuez['icon_url'];
  2885.  
  2886. if(price >= minDep)
  2887. {
  2888. idss.push(id);
  2889. namess.push(name);
  2890. pricess.push(price);
  2891. imgss.push(img);
  2892. }
  2893. }
  2894. }
  2895. });
  2896. });
  2897.  
  2898. Ids = idss.join('/');
  2899. Names = namess.join('/');
  2900. Prices = pricess.join('/');
  2901. Imgs = imgss.join('/');
  2902.  
  2903. socket.emit('message', {
  2904. type: 'jgetInventory',
  2905. id: Ids,
  2906. name: Names,
  2907. price: Prices,
  2908. img: Imgs
  2909. });
  2910.  
  2911. JinventoryUser[user] = {
  2912. id: Ids,
  2913. name: Names,
  2914. price: Prices,
  2915. img: Imgs
  2916. }
  2917. }
  2918. else
  2919. {
  2920.  
  2921. }
  2922. });
  2923. }
  2924.  
  2925. function loadStatistics(socket)
  2926. {
  2927. var totalAmount = 0;
  2928. var totalItems = 0;
  2929. var activeGames = 0;
  2930.  
  2931. pool.query('SELECT SUM(`ctp`) AS `totalAmount`, SUM(`cskins`) AS `totalItems`, COUNT(`id`) AS `activeGames` FROM games WHERE `winner` = -1', function(error, res) {
  2932. if(error) throw error;
  2933.  
  2934. if(res.length == 0)
  2935. {
  2936. totalAmount = 0;
  2937. totalItems = 0;
  2938. activeGames = 0;
  2939.  
  2940. if(!socket)
  2941. {
  2942. io.sockets.emit('message', {
  2943. type: 'loadStatistics',
  2944. totalAmount: totalAmount,
  2945. totalItems: totalItems,
  2946. activeGames: activeGames
  2947. });
  2948. }
  2949. else
  2950. {
  2951. socket.emit('message', {
  2952. type: 'loadStatistics',
  2953. totalAmount: totalAmount,
  2954. totalItems: totalItems,
  2955. activeGames: activeGames
  2956. });
  2957. }
  2958. }
  2959.  
  2960. if(res.length > 0)
  2961. {
  2962. totalAmount = res[0].totalAmount;
  2963. totalItems = res[0].totalItems;
  2964. activeGames = res[0].activeGames;
  2965.  
  2966. if(totalAmount == null)
  2967. {
  2968. totalAmount = 0;
  2969. }
  2970. if(totalItems == null)
  2971. {
  2972. totalItems = 0;
  2973. }
  2974. if(activeGames == null)
  2975. {
  2976. activeGames = 0;
  2977. }
  2978.  
  2979. if(!socket)
  2980. {
  2981. io.sockets.emit('message', {
  2982. type: 'loadStatistics',
  2983. totalAmount: totalAmount,
  2984. totalItems: totalItems,
  2985. activeGames: activeGames
  2986. });
  2987. }
  2988. else
  2989. {
  2990. socket.emit('message', {
  2991. type: 'loadStatistics',
  2992. totalAmount: totalAmount,
  2993. totalItems: totalItems,
  2994. activeGames: activeGames
  2995. });
  2996. }
  2997. }
  2998. });
  2999. }
  3000.  
  3001. function sendGames(gameID)
  3002. {
  3003. setTimeout(function() {
  3004. for(var i in loadGames)
  3005. {
  3006. if(loadGames[i].id == gameID)
  3007. {
  3008. timerGame[loadGames[i].id] = time()+90;
  3009.  
  3010. io.sockets.emit('message', {
  3011. type: 'editGame',
  3012. games: {
  3013. 'id': loadGames[i].id,
  3014. 'csteamid': loadGames[i].csteamid,
  3015. 'cname': loadGames[i].cname,
  3016. 'cavatar': loadGames[i].cavatar,
  3017. 'cskinsurl': loadGames[i].cskinsurl,
  3018. 'cskinsnames': loadGames[i].cskinsnames,
  3019. 'cskinsprices': loadGames[i].cskinsprices,
  3020. 'cskins': loadGames[i].cskins,
  3021. 'ctp': loadGames[i].ctp,
  3022. 'psteamid': loadGames[i].psteamid,
  3023. 'pname': loadGames[i].pname,
  3024. 'pavatar': loadGames[i].pavatar,
  3025. 'pskinsurl': loadGames[i].pskinsurl,
  3026. 'pskinsnames': loadGames[i].pskinsnames,
  3027. 'pskinsprices': loadGames[i].pskinsprices,
  3028. 'pskins': loadGames[i].pskins,
  3029. 'ptp': loadGames[i].ptp,
  3030. 'hash': loadGames[i].hash,
  3031. 'secret': loadGames[i].secret,
  3032. 'winnerPercentage': loadGames[i].winnerPercentage,
  3033. 'cpick': loadGames[i].cpick,
  3034. 'ppick': loadGames[i].ppick,
  3035. 'timer': timerGame[loadGames[i].id]-time(),
  3036. 'timer11': loadGames[i].timer11,
  3037. 'ttimer11': timer11Game[loadGames[i].id]-time(),
  3038. }
  3039. });
  3040.  
  3041. io.sockets.emit('message', {
  3042. type: 'watchCF',
  3043. id: loadGames[i].id,
  3044. csteamid: loadGames[i].csteamid,
  3045. cname: loadGames[i].cname,
  3046. cavatar: loadGames[i].cavatar,
  3047. cskinsurl: loadGames[i].cskinsurl,
  3048. cskinsnames: loadGames[i].cskinsnames,
  3049. cskinsprices: loadGames[i].cskinsprices,
  3050. cskins: loadGames[i].cskins,
  3051. ctp: loadGames[i].ctp,
  3052. psteamid: loadGames[i].psteamid,
  3053. pname: loadGames[i].pname,
  3054. pskins: loadGames[i].pskins,
  3055. ptp: loadGames[i].ptp,
  3056. hash: loadGames[i].hash,
  3057. secret: loadGames[i].secret,
  3058. winner: loadGames[i].winner,
  3059. cpick: loadGames[i].cpick,
  3060. ppick: loadGames[i].ppick,
  3061. timer: timerGame[loadGames[i].id]-time(),
  3062. timer11: loadGames[i].timer11,
  3063. ttimer11: timer11Game[loadGames[i].id]-time(),
  3064. winnerPercentage: loadGames[i].winnerPercentage,
  3065. gameNumber: loadGames[i].id
  3066. });
  3067. }
  3068. }
  3069. }, 1000);
  3070. }
  3071.  
  3072. function LevelCalculate(user)
  3073. {
  3074. pool.query('SELECT xp,level FROM users WHERE steamid = ' + pool.escape(user), function(err, row) {
  3075. if(err) throw err;
  3076. if(row.length == 0) return;
  3077.  
  3078. var currentLevel = row[0].level;
  3079.  
  3080. var currentXp = row[0].xp;
  3081. var xpNeeded = 0;
  3082. var xpMinus = 0;
  3083.  
  3084. for(var i = 1; i < 500; i++)
  3085. {
  3086. xpNeeded += 40 * i;
  3087. xpMinus = xpNeeded - (40 * i-1);
  3088. if(currentXp >= xpMinus && currentXp <= xpNeeded)
  3089. {
  3090. pool.query('UPDATE users SET level = ' + pool.escape(i) + ' WHERE steamid = ' + pool.escape(user));
  3091. }
  3092. }
  3093. });
  3094. }
  3095.  
  3096. function pickBot(text)
  3097. {
  3098. var definire;
  3099. if(text == 'bot1')
  3100. {
  3101. definire = manager.bot1;
  3102. }
  3103. else if(text == 'bot2')
  3104. {
  3105. definire = manager.bot2;
  3106. }
  3107. else if(text == 'bot3')
  3108. {
  3109. definire = manager.bot3;
  3110. }
  3111. return definire;
  3112. }
  3113.  
  3114. const managers = {
  3115. bot1: function(offer, oldState) {
  3116. if(offer)
  3117. {
  3118. logger.info('Offer #' + offer.id + ' | oldState: ' + oldState + ' | newState: ' + offer.state);
  3119.  
  3120. if(offer.isOurOffer && offer.itemsToReceive.length > 0)
  3121. {
  3122. if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  3123. {
  3124. pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  3125. if(err) throw err;
  3126. if(res[0].winner == -1)
  3127. {
  3128. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  3129. {
  3130. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  3131. {
  3132. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  3133. type: 'modals',
  3134. tip: 'trade',
  3135. result: 'offerDeclined'
  3136. });
  3137. }
  3138. }
  3139.  
  3140. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(offer.id), function(err2, res2) {
  3141. if(err2) throw err2;
  3142.  
  3143. loadAllGames();
  3144. sendGames(res[0].id);
  3145.  
  3146. logger.info('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
  3147. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3148. });
  3149. }
  3150. });
  3151. }
  3152. else if(oldState == 2 && offer.state == 3)
  3153. {
  3154. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
  3155. {
  3156. var receivedItems = [];
  3157. var assetiddsss = [];
  3158.  
  3159. offer.getReceivedItems(true, function(err, maca) {
  3160. if(err) throw err;
  3161.  
  3162. for(var i in maca)
  3163. {
  3164. receivedItems.push(maca[i]);
  3165. assetiddsss.push(maca[i].assetid);
  3166. }
  3167.  
  3168. var pretul = require('./prices.json');
  3169.  
  3170. var totalSkins = 0;
  3171. var skinImages = [];
  3172. var skinNames = [];
  3173. var skinPrices = [];
  3174. var totalPrice = 0;
  3175.  
  3176. for(var i in receivedItems)
  3177. {
  3178. totalSkins++;
  3179. totalPrice += pretul[receivedItems[i].market_hash_name];
  3180. skinImages.push(receivedItems[i].icon_url);
  3181. skinNames.push(receivedItems[i].market_hash_name);
  3182. skinPrices.push(pretul[receivedItems[i].market_hash_name]);
  3183. }
  3184.  
  3185. //SMECHERIE
  3186. var Skinimages = "";
  3187. var Skinnames = "";
  3188. var Skinprices = "";
  3189. Skinimages = skinImages.join('/');
  3190. Skinnames = skinNames.join('/');
  3191. Skinprices = skinPrices.join('/');
  3192.  
  3193. var timp = new Date();
  3194. var timpCalc = timp.getTime()/1000;
  3195.  
  3196. var name;
  3197. var avatar;
  3198. var steamid = tradingRequests[offer.id]['user'];
  3199. var botAles = tradingRequests[offer.id]['botulAles'];
  3200.  
  3201. pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(steamid), function(error, results) {
  3202. if(error) throw error;
  3203.  
  3204. //GENERATE a SECRET
  3205. var hashul = creatusHash('CSGO-' + time() + '-' + results[0].name);
  3206.  
  3207. function creatusHash(datahere)
  3208. {
  3209. var data = datahere;
  3210. var hashess = crypto.createHash('md5').update(data).digest("hex");
  3211.  
  3212. return hashess;
  3213. }
  3214.  
  3215. if(socketBySteam.hasOwnProperty(tradingRequests[offer.id]['user']))
  3216. {
  3217. if(io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']])
  3218. {
  3219. io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']].emit('message', {
  3220. type: 'modals',
  3221. tip: 'trade',
  3222. result: 'offerAccepted'
  3223. });
  3224. }
  3225. }
  3226.  
  3227.  
  3228. pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  3229. if(haha) throw haha;
  3230. if(huhu.length == 0) return;
  3231.  
  3232. LevelCalculate(steamid);
  3233. });
  3234.  
  3235. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3236.  
  3237. var nume = results[0].name;
  3238. var avatarul = results[0].avatar;
  3239.  
  3240.  
  3241. pool.query('INSERT INTO games SET expire = ' + pool.escape((time() + tradingRequests[offer.id]['gameExpire']*60)) + ', cassetids = ' + pool.escape(assetiddsss.join('/')) + ', csteamid = ' + pool.escape(steamid) + ', cname = ' + pool.escape(nume) + ', cavatar = ' + pool.escape(avatarul) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', cpick = ' + pool.escape(tradingRequests[offer.id]['side']) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul) + ', bot = ' + pool.escape(botAles), function(arr, ass) {
  3242. if(arr) throw arr;
  3243.  
  3244. pool.query('SELECT MAX(id) AS cacat FROM games', function(caca, rara) {
  3245. if(caca) throw caca;
  3246.  
  3247. loadAllGames();
  3248. loadStatistics();
  3249. setTimeout(function() {
  3250. loadGames.forEach(function(itm) {
  3251. if(itm.id == rara[0].cacat)
  3252. {
  3253. io.sockets.emit('message', {
  3254. type: 'addGame',
  3255. games: {
  3256. 'id': itm.id,
  3257. 'csteamid': itm.csteamid,
  3258. 'cname': itm.cname,
  3259. 'cavatar': itm.cavatar,
  3260. 'cskinsurl': itm.cskinsurl,
  3261. 'cskinsnames': itm.cskinsnames,
  3262. 'cskinsprices': itm.cskinsprices,
  3263. 'cskins': itm.cskins,
  3264. 'ctp': itm.ctp,
  3265. 'psteamid': itm.psteamid,
  3266. 'pname': itm.pname,
  3267. 'pavatar': itm.pavatar,
  3268. 'pskinsurl': itm.pskinsurl,
  3269. 'pskinsnames': itm.pskinsnames,
  3270. 'pskinsprices': itm.pskinsprices,
  3271. 'pskins': itm.pskins,
  3272. 'ptp': itm.ptp,
  3273. 'hash': itm.hash,
  3274. 'secret': itm.secret,
  3275. 'winner': itm.winner,
  3276. 'cpick': itm.cpick,
  3277. 'ppick': itm.ppick,
  3278. 'timer': timerGame[itm.id]-time(),
  3279. 'timer11': itm.timer11,
  3280. 'winnerPercentage': itm.winnerPercentage,
  3281. 'ttimer11': timer11Game[itm.id]-time()
  3282. }
  3283. });
  3284. }
  3285. });
  3286. }, 1200);
  3287. });
  3288. });
  3289. });
  3290. });
  3291. }
  3292. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  3293. {
  3294. pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  3295. if(err) throw err;
  3296. var receivedItems = [];
  3297.  
  3298. var skinsnames = [];
  3299. var skinsids = [];
  3300. var skinsprices = [];
  3301. var pretul = require('./prices.json');
  3302.  
  3303. offer.getReceivedItems(true, function(err, caca) {
  3304. if(err) throw err;
  3305.  
  3306. for(var i in caca)
  3307. {
  3308. receivedItems.push(caca[i].assetid);
  3309. skinsprices.push(pretul[caca[i].market_hash_name]);
  3310. }
  3311.  
  3312. pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id), function(caca, maca) {
  3313. if(caca) throw caca;
  3314. if(maca.length == 0) return;
  3315.  
  3316. //GENERATE a SECRET
  3317. var TotalNumberOfTickets = (res[0].ctp+res[0].ptp)*100;
  3318. var winner;
  3319. var secret = createSecret();
  3320. var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
  3321. var winnerTicket = Math.floor((TotalNumberOfTickets - 0.0000000001) * (winnerPercentage / 100));
  3322.  
  3323. if(winnerTicket >= 0 && winnerTicket <= res[0].ctp*100)
  3324. {
  3325. winner = 'ct';
  3326. logger.trace('Ticket #' + winnerTicket + ' - winner ct');
  3327. }
  3328. else if(winnerTicket >= (res[0].ctp+0.01)*100 && winnerTicket <= (res[0].ctp+res[0].ptp)*100)
  3329. {
  3330. winner = 't';
  3331. logger.trace('Ticket #' + winnerTicket + ' - winner t');
  3332. }
  3333. var secret = createSecret();
  3334. function createSecret() {
  3335. var text = "";
  3336. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
  3337.  
  3338. for(var i=0; i < 8; i++)
  3339. text += possible.charAt(Math.floor(Math.random() * possible.length));
  3340.  
  3341. return text;
  3342. }
  3343. var hashul = res[0].hash;
  3344.  
  3345. var secretsihash = secret.concat(hashul);
  3346.  
  3347. var steamid = res[0].psteamid;
  3348.  
  3349. pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ', ticketWon = ' + pool.escape(winnerTicket) + ', ticketsTotal = ' + pool.escape(parseFloat(res[0].ctp+res[0].ptp)*100) + ', winnerPercentage = ' + pool.escape(winnerPercentage) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
  3350. if(aaa) throw aaa;
  3351.  
  3352. pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  3353. if(haha) throw haha;
  3354. if(huhu.length == 0) return;
  3355.  
  3356. LevelCalculate(steamid);
  3357. });
  3358.  
  3359. loadAllGames();
  3360. sendGames(res[0].id);
  3361. });
  3362.  
  3363. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3364.  
  3365. timer11Game[res[0].id] = time()+10;
  3366.  
  3367. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  3368. {
  3369. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  3370. {
  3371. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  3372. type: 'modals',
  3373. tip: 'trade',
  3374. result: 'offerAccepted'
  3375. });
  3376. }
  3377. }
  3378.  
  3379. setTimeout(function() {
  3380. pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
  3381. if(errr) throw errr;
  3382.  
  3383. sendItemsTrade(offer.id, receivedItems.join('/'), winner, skinsnames, skinsids, skinsprices);
  3384. });
  3385. }, 9500);
  3386. });
  3387. });
  3388. });
  3389. }
  3390. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joinJackpot')
  3391. {
  3392. var receivedItems = [];
  3393. var items = [];
  3394.  
  3395. offer.getReceivedItems(true, function(err, maca) {
  3396. if(err) throw err;
  3397.  
  3398. for(var i in maca)
  3399. {
  3400. items.push(maca[i]);
  3401. receivedItems.push(maca[i].assetid);
  3402. }
  3403.  
  3404. var pretul = require('./prices.json');
  3405.  
  3406. if(jackpotState == 'WAITING') jackpotState = 'BETTING';
  3407.  
  3408. var itemsData = [];
  3409.  
  3410. var totalSkins = 0;
  3411. var skinImages = [];
  3412. var skinNames = [];
  3413. var skinPrices = [];
  3414. var totalPrice = 0;
  3415.  
  3416. for(var i in items)
  3417. {
  3418. totalSkins++;
  3419. totalPrice += pretul[items[i].market_hash_name];
  3420. skinImages.push(items[i].icon_url);
  3421. skinNames.push(items[i].market_hash_name);
  3422. skinPrices.push(pretul[items[i].market_hash_name]);
  3423.  
  3424. itemsData.push({
  3425. 'id': items[i].assetid,
  3426. 'price': pretul[items[i].market_hash_name],
  3427. 'name': items[i].market_hash_name,
  3428. 'icon_url': items[i].icon_url
  3429. });
  3430. }
  3431. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3432.  
  3433. if(jackpotState == 'BETTING')
  3434. {
  3435. var minTicket = parseInt(jackpotTickets+1);
  3436. var maxTicket = parseInt(minTicket+(totalPrice*100)-1);
  3437. for(var a = minTicket; a < maxTicket; a++)
  3438. {
  3439. jackpotTotalTickets.push({
  3440. 'user': tradingRequests[offer.id]['user'],
  3441. 'ticket': parseInt(a)
  3442. });
  3443. }
  3444. jackpotTickets += parseInt(totalPrice*100);
  3445. var assetidsSS = receivedItems.join('/');
  3446. pool.query('INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(totalPrice) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(totalSkins) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(offer.id));
  3447. addJackpotBet(tradingRequests[offer.id]['user'], skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData);
  3448. }
  3449. else
  3450. {
  3451. jackpotQueueBets.push({
  3452. 'user': tradingRequests[offer.id]['user'],
  3453. 'offerID': offer.id,
  3454. 'skinImages': skinImages,
  3455. 'skinNames': skinNames,
  3456. 'skinPrices': skinPrices,
  3457. 'totalSkins': totalSkins,
  3458. 'totalPrice': totalPrice,
  3459. 'itemsData': itemsData,
  3460. 'receivedItems': receivedItems
  3461. });
  3462. logger.info('Jackpot round #' + jackpotRound + ' added to queue trade offer #' + offer.id);
  3463. }
  3464. });
  3465. }
  3466. }
  3467. else if(oldState == 2 && offer.state == 7)
  3468. {
  3469. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3470. if(caca) throw caca;
  3471. if(maca.length == 0) return;
  3472.  
  3473. if(maca[0].action == 'winning') return;
  3474. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  3475. if(socketBySteam.hasOwnProperty(maca[0].user))
  3476. {
  3477. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3478. {
  3479. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3480. type: 'modals',
  3481. tip: 'trade',
  3482. result: 'offerDeclined'
  3483. });
  3484. }
  3485. }
  3486. });
  3487. }
  3488. else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  3489. {
  3490. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3491. if(caca) throw caca;
  3492. if(maca.length == 0) return;
  3493.  
  3494. if(maca[0].action == 'winning') return;
  3495. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3496. });
  3497. }
  3498. }
  3499. else if(offer.isOurOffer && offer.itemsToGive.length > 0)
  3500. {
  3501. if((oldState == 2 || oldState == 9) && offer.state == 3)
  3502. {
  3503. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
  3504. {
  3505. pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3506. if(caca) throw caca;
  3507. if(maca.length == 0) return;
  3508.  
  3509. if(socketBySteam.hasOwnProperty(maca[0].user))
  3510. {
  3511. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3512. {
  3513. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3514. type: 'modals',
  3515. tip: 'trade',
  3516. result: 'offerAccepted'
  3517. });
  3518. }
  3519. }
  3520. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3521. });
  3522. }
  3523. }
  3524. else if((oldState == 2 || oldState == 9) && offer.state == 7)
  3525. {
  3526. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3527. if(caca) throw caca;
  3528. if(maca.length == 0) return;
  3529.  
  3530. if(maca[0].action == 'winning') return;
  3531. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  3532. if(socketBySteam.hasOwnProperty(maca[0].user))
  3533. {
  3534. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3535. {
  3536. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3537. type: 'modals',
  3538. tip: 'trade',
  3539. result: 'offerDeclined'
  3540. });
  3541. }
  3542. }
  3543. });
  3544. }
  3545. else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  3546. {
  3547. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3548. if(caca) throw caca;
  3549. if(maca.length == 0) return;
  3550.  
  3551. if(maca[0].action == 'winning') return;
  3552. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3553. });
  3554. }
  3555. }
  3556. }
  3557. },
  3558. bot2: function(offer, oldState) {
  3559. if(offer)
  3560. {
  3561.  
  3562. if(offer.isOurOffer && offer.itemsToReceive.length > 0)
  3563. {
  3564. if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  3565. {
  3566. pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  3567. if(err) throw err;
  3568. if(res[0].winner == -1)
  3569. {
  3570. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  3571. {
  3572. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  3573. {
  3574. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  3575. type: 'modals',
  3576. tip: 'trade',
  3577. result: 'offerDeclined'
  3578. });
  3579. }
  3580. }
  3581.  
  3582. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(offer.id), function(err2, res2) {
  3583. if(err2) throw err2;
  3584.  
  3585. loadAllGames();
  3586. sendGames(res[0].id);
  3587.  
  3588. logger.info('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
  3589. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3590. });
  3591. }
  3592. });
  3593. }
  3594. else if(oldState == 2 && offer.state == 3)
  3595. {
  3596. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
  3597. {
  3598. var receivedItems = [];
  3599. var assetiddsss = [];
  3600.  
  3601. offer.getReceivedItems(true, function(err, maca) {
  3602. if(err) throw err;
  3603.  
  3604. for(var i in maca)
  3605. {
  3606. receivedItems.push(maca[i]);
  3607. assetiddsss.push(maca[i].assetid);
  3608. }
  3609.  
  3610. var pretul = require('./prices.json');
  3611.  
  3612. var totalSkins = 0;
  3613. var skinImages = [];
  3614. var skinNames = [];
  3615. var skinPrices = [];
  3616. var totalPrice = 0;
  3617.  
  3618. for(var i in receivedItems)
  3619. {
  3620. totalSkins++;
  3621. totalPrice += pretul[receivedItems[i].market_hash_name];
  3622. skinImages.push(receivedItems[i].icon_url);
  3623. skinNames.push(receivedItems[i].market_hash_name);
  3624. skinPrices.push(pretul[receivedItems[i].market_hash_name]);
  3625. }
  3626.  
  3627. //SMECHERIE
  3628. var Skinimages = "";
  3629. var Skinnames = "";
  3630. var Skinprices = "";
  3631. Skinimages = skinImages.join('/');
  3632. Skinnames = skinNames.join('/');
  3633. Skinprices = skinPrices.join('/');
  3634.  
  3635. var timp = new Date();
  3636. var timpCalc = timp.getTime()/1000;
  3637.  
  3638. var name;
  3639. var avatar;
  3640. var steamid = tradingRequests[offer.id]['user'];
  3641. var botAles = tradingRequests[offer.id]['botulAles'];
  3642.  
  3643. pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(steamid), function(error, results) {
  3644. if(error) throw error;
  3645.  
  3646. //GENERATE a SECRET
  3647. var hashul = creatusHash('CSGO-' + time() + '-' + results[0].name);
  3648.  
  3649. function creatusHash(datahere)
  3650. {
  3651. var data = datahere;
  3652. var hashess = crypto.createHash('md5').update(data).digest("hex");
  3653.  
  3654. return hashess;
  3655. }
  3656.  
  3657. if(socketBySteam.hasOwnProperty(tradingRequests[offer.id]['user']))
  3658. {
  3659. if(io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']])
  3660. {
  3661. io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']].emit('message', {
  3662. type: 'modals',
  3663. tip: 'trade',
  3664. result: 'offerAccepted'
  3665. });
  3666. }
  3667. }
  3668.  
  3669.  
  3670. pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  3671. if(haha) throw haha;
  3672. if(huhu.length == 0) return;
  3673.  
  3674. LevelCalculate(steamid);
  3675. });
  3676.  
  3677. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3678.  
  3679. var nume = results[0].name;
  3680. var avatarul = results[0].avatar;
  3681.  
  3682.  
  3683. pool.query('INSERT INTO games SET expire = ' + pool.escape((time() + tradingRequests[offer.id]['gameExpire']*60)) + ', cassetids = ' + pool.escape(assetiddsss.join('/')) + ', csteamid = ' + pool.escape(steamid) + ', cname = ' + pool.escape(nume) + ', cavatar = ' + pool.escape(avatarul) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', cpick = ' + pool.escape(tradingRequests[offer.id]['side']) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul) + ', bot = ' + pool.escape(botAles), function(arr, ass) {
  3684. if(arr) throw arr;
  3685.  
  3686. pool.query('SELECT MAX(id) AS cacat FROM games', function(caca, rara) {
  3687. if(caca) throw caca;
  3688.  
  3689. loadAllGames();
  3690. loadStatistics();
  3691. setTimeout(function() {
  3692. loadGames.forEach(function(itm) {
  3693. if(itm.id == rara[0].cacat)
  3694. {
  3695. io.sockets.emit('message', {
  3696. type: 'addGame',
  3697. games: {
  3698. 'id': itm.id,
  3699. 'csteamid': itm.csteamid,
  3700. 'cname': itm.cname,
  3701. 'cavatar': itm.cavatar,
  3702. 'cskinsurl': itm.cskinsurl,
  3703. 'cskinsnames': itm.cskinsnames,
  3704. 'cskinsprices': itm.cskinsprices,
  3705. 'cskins': itm.cskins,
  3706. 'ctp': itm.ctp,
  3707. 'psteamid': itm.psteamid,
  3708. 'pname': itm.pname,
  3709. 'pavatar': itm.pavatar,
  3710. 'pskinsurl': itm.pskinsurl,
  3711. 'pskinsnames': itm.pskinsnames,
  3712. 'pskinsprices': itm.pskinsprices,
  3713. 'pskins': itm.pskins,
  3714. 'ptp': itm.ptp,
  3715. 'hash': itm.hash,
  3716. 'secret': itm.secret,
  3717. 'winner': itm.winner,
  3718. 'cpick': itm.cpick,
  3719. 'ppick': itm.ppick,
  3720. 'timer': timerGame[itm.id]-time(),
  3721. 'timer11': itm.timer11,
  3722. 'winnerPercentage': itm.winnerPercentage,
  3723. 'ttimer11': timer11Game[itm.id]-time()
  3724. }
  3725. });
  3726. }
  3727. });
  3728. }, 1200);
  3729. });
  3730. });
  3731. });
  3732. });
  3733. }
  3734. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  3735. {
  3736. pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  3737. if(err) throw err;
  3738. var receivedItems = [];
  3739.  
  3740. var skinsnames = [];
  3741. var skinsids = [];
  3742. var skinsprices = [];
  3743. var pretul = require('./prices.json');
  3744.  
  3745. offer.getReceivedItems(true, function(err, caca) {
  3746. if(err) throw err;
  3747.  
  3748. for(var i in caca)
  3749. {
  3750. receivedItems.push(caca[i].assetid);
  3751. skinsnames.push(caca[i].market_hash_name);
  3752. }
  3753.  
  3754. pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id), function(caca, maca) {
  3755. if(caca) throw caca;
  3756. if(maca.length == 0) return;
  3757.  
  3758. //GENERATE a SECRET
  3759. var TotalNumberOfTickets = (res[0].ctp+res[0].ptp)*100;
  3760. var winner;
  3761. var secret = createSecret();
  3762. var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
  3763. var winnerTicket = Math.floor((TotalNumberOfTickets - 0.0000000001) * (winnerPercentage / 100));
  3764.  
  3765. if(winnerTicket >= 0 && winnerTicket <= res[0].ctp*100)
  3766. {
  3767. winner = 'ct';
  3768. logger.trace('Ticket #' + winnerTicket + ' - winner ct');
  3769. }
  3770. else if(winnerTicket >= (res[0].ctp+0.01)*100 && winnerTicket <= (res[0].ctp+res[0].ptp)*100)
  3771. {
  3772. winner = 't';
  3773. logger.trace('Ticket #' + winnerTicket + ' - winner t');
  3774. }
  3775. var secret = createSecret();
  3776. function createSecret() {
  3777. var text = "";
  3778. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
  3779.  
  3780. for(var i=0; i < 8; i++)
  3781. text += possible.charAt(Math.floor(Math.random() * possible.length));
  3782.  
  3783. return text;
  3784. }
  3785. var hashul = res[0].hash;
  3786.  
  3787. var secretsihash = secret.concat(hashul);
  3788.  
  3789. var steamid = res[0].psteamid;
  3790.  
  3791. pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ', ticketWon = ' + pool.escape(winnerTicket) + ', ticketsTotal = ' + pool.escape(parseFloat(res[0].ctp+res[0].ptp)*100) + ', winnerPercentage = ' + pool.escape(winnerPercentage) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
  3792. if(aaa) throw aaa;
  3793.  
  3794. pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  3795. if(haha) throw haha;
  3796. if(huhu.length == 0) return;
  3797.  
  3798. LevelCalculate(steamid);
  3799. });
  3800.  
  3801. loadAllGames();
  3802. sendGames(res[0].id);
  3803. });
  3804.  
  3805. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3806.  
  3807. timer11Game[res[0].id] = time()+10;
  3808.  
  3809. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  3810. {
  3811. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  3812. {
  3813. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  3814. type: 'modals',
  3815. tip: 'trade',
  3816. result: 'offerAccepted'
  3817. });
  3818. }
  3819. }
  3820.  
  3821. setTimeout(function() {
  3822. pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
  3823. if(errr) throw errr;
  3824.  
  3825. sendItemsTrade(offer.id, receivedItems.join('/'), winner, skinsnames, skinsids, skinsprices);
  3826. });
  3827. }, 9500);
  3828. });
  3829. });
  3830. });
  3831. }
  3832. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joinJackpot')
  3833. {
  3834. var receivedItems = [];
  3835. var items = [];
  3836.  
  3837. offer.getReceivedItems(true, function(err, maca) {
  3838. if(err) throw err;
  3839.  
  3840. for(var i in maca)
  3841. {
  3842. items.push(maca[i]);
  3843. receivedItems.push(maca[i].assetid);
  3844. }
  3845.  
  3846. var pretul = require('./prices.json');
  3847.  
  3848. if(jackpotState == 'WAITING') jackpotState = 'BETTING';
  3849.  
  3850. var itemsData = [];
  3851.  
  3852. var totalSkins = 0;
  3853. var skinImages = [];
  3854. var totalPrice = 0;
  3855.  
  3856. for(var i in items)
  3857. {
  3858. totalSkins++;
  3859. totalPrice += pretul[items[i].market_hash_name];
  3860. skinImages.push(items[i].icon_url);
  3861. skinNames.push(items[i].market_hash_name);
  3862. skinPrices.push(pretul[items[i].market_hash_name]);
  3863.  
  3864. itemsData.push({
  3865. 'id': items[i].assetid,
  3866. 'price': pretul[items[i].market_hash_name],
  3867. 'name': items[i].market_hash_name,
  3868. 'icon_url': items[i].icon_url
  3869. });
  3870. }
  3871. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3872.  
  3873. if(jackpotState == 'BETTING')
  3874. {
  3875. var minTicket = parseInt(jackpotTickets+1);
  3876. var maxTicket = parseInt(minTicket+(totalPrice*100)-1);
  3877. for(var a = minTicket; a < maxTicket; a++)
  3878. {
  3879. jackpotTotalTickets.push({
  3880. 'user': tradingRequests[offer.id]['user'],
  3881. 'ticket': parseInt(a)
  3882. });
  3883. }
  3884. jackpotTickets += parseInt(totalPrice*100);
  3885. var assetidsSS = receivedItems.join('/');
  3886. pool.query('INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(totalPrice) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(totalSkins) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(offer.id));
  3887. addJackpotBet(tradingRequests[offer.id]['user'], skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData);
  3888. }
  3889. else
  3890. {
  3891. jackpotQueueBets.push({
  3892. 'user': tradingRequests[offer.id]['user'],
  3893. 'offerID': offer.id,
  3894. 'skinImages': skinImages,
  3895. 'skinNames': skinNames,
  3896. 'skinPrices': skinPrices,
  3897. 'itemsData': itemsData,
  3898. 'receivedItems': receivedItems
  3899. });
  3900. logger.info('Jackpot round #' + jackpotRound + ' added to queue trade offer #' + offer.id);
  3901. }
  3902. });
  3903. }
  3904. }
  3905. else if(oldState == 2 && offer.state == 7)
  3906. {
  3907. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3908. if(caca) throw caca;
  3909. if(maca.length == 0) return;
  3910.  
  3911. if(maca[0].action == 'winning') return;
  3912. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  3913. if(socketBySteam.hasOwnProperty(maca[0].user))
  3914. {
  3915. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3916. {
  3917. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3918. type: 'modals',
  3919. tip: 'trade',
  3920. result: 'offerDeclined'
  3921. });
  3922. }
  3923. }
  3924. });
  3925. }
  3926. else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  3927. {
  3928. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3929. if(caca) throw caca;
  3930. if(maca.length == 0) return;
  3931.  
  3932. if(maca[0].action == 'winning') return;
  3933. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3934. });
  3935. }
  3936. }
  3937. else if(offer.isOurOffer && offer.itemsToGive.length > 0)
  3938. {
  3939. if((oldState == 2 || oldState == 9) && offer.state == 3)
  3940. {
  3941. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
  3942. {
  3943. pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3944. if(caca) throw caca;
  3945. if(maca.length == 0) return;
  3946.  
  3947. if(socketBySteam.hasOwnProperty(maca[0].user))
  3948. {
  3949. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3950. {
  3951. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3952. type: 'modals',
  3953. tip: 'trade',
  3954. result: 'offerAccepted'
  3955. });
  3956. }
  3957. }
  3958. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  3959. });
  3960. }
  3961. }
  3962. else if((oldState == 2 || oldState == 9) && offer.state == 7)
  3963. {
  3964. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3965. if(caca) throw caca;
  3966. if(maca.length == 0) return;
  3967.  
  3968. if(maca[0].action == 'winning') return;
  3969. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  3970. if(socketBySteam.hasOwnProperty(maca[0].user))
  3971. {
  3972. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  3973. {
  3974. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  3975. type: 'modals',
  3976. tip: 'trade',
  3977. result: 'offerDeclined'
  3978. });
  3979. }
  3980. }
  3981. });
  3982. }
  3983. else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  3984. {
  3985. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  3986. if(caca) throw caca;
  3987. if(maca.length == 0) return;
  3988.  
  3989. if(maca[0].action == 'winning') return;
  3990. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  3991. });
  3992. }
  3993. }
  3994. }
  3995. },
  3996. bot3: function(offer, oldState) {
  3997. if(offer)
  3998. {
  3999. logger.info('Offer #' + offer.id + ' | oldState: ' + oldState + ' | newState: ' + offer.state);
  4000.  
  4001. if(offer.isOurOffer && offer.itemsToReceive.length > 0)
  4002. {
  4003. if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  4004. {
  4005. pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  4006. if(err) throw err;
  4007. if(res[0].winner == -1)
  4008. {
  4009. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  4010. {
  4011. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  4012. {
  4013. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  4014. type: 'modals',
  4015. tip: 'trade',
  4016. result: 'offerDeclined'
  4017. });
  4018. }
  4019. }
  4020.  
  4021. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(offer.id), function(err2, res2) {
  4022. if(err2) throw err2;
  4023.  
  4024. loadAllGames();
  4025. sendGames(res[0].id);
  4026.  
  4027. logger.info('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
  4028. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  4029. });
  4030. }
  4031. });
  4032. }
  4033. else if(oldState == 2 && offer.state == 3)
  4034. {
  4035. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
  4036. {
  4037. var receivedItems = [];
  4038. var assetiddsss = [];
  4039.  
  4040. offer.getReceivedItems(true, function(err, maca) {
  4041. if(err) throw err;
  4042.  
  4043. for(var i in maca)
  4044. {
  4045. receivedItems.push(maca[i]);
  4046. assetiddsss.push(maca[i].assetid);
  4047. }
  4048.  
  4049. var pretul = require('./prices.json');
  4050.  
  4051. var totalSkins = 0;
  4052. var skinImages = [];
  4053. var totalPrice = 0;
  4054.  
  4055. for(var i in receivedItems)
  4056. {
  4057. totalSkins++;
  4058. totalPrice += pretul[receivedItems[i].market_hash_name];
  4059. skinImages.push(receivedItems[i].icon_url);
  4060. skinNames.push(receivedItems[i].market_hash_name);
  4061. skinPrices.push(pretul[receivedItems[i].market_hash_name]);
  4062. }
  4063.  
  4064. //SMECHERIE
  4065. var Skinimages = "";
  4066. var Skinnames = "";
  4067. var Skinprices = "";
  4068. Skinimages = skinImages.join('/');
  4069. Skinnames = skinNames.join('/');
  4070. Skinprices = skinPrices.join('/');
  4071.  
  4072. var timp = new Date();
  4073. var timpCalc = timp.getTime()/1000;
  4074.  
  4075. var name;
  4076. var avatar;
  4077. var steamid = tradingRequests[offer.id]['user'];
  4078. var botAles = tradingRequests[offer.id]['botulAles'];
  4079.  
  4080. pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(steamid), function(error, results) {
  4081. if(error) throw error;
  4082.  
  4083. //GENERATE a SECRET
  4084. var hashul = creatusHash('CSGO-' + time() + '-' + results[0].name);
  4085.  
  4086. function creatusHash(datahere)
  4087. {
  4088. var data = datahere;
  4089. var hashess = crypto.createHash('md5').update(data).digest("hex");
  4090.  
  4091. return hashess;
  4092. }
  4093.  
  4094. if(socketBySteam.hasOwnProperty(tradingRequests[offer.id]['user']))
  4095. {
  4096. if(io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']])
  4097. {
  4098. io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']].emit('message', {
  4099. type: 'modals',
  4100. tip: 'trade',
  4101. result: 'offerAccepted'
  4102. });
  4103. }
  4104. }
  4105.  
  4106.  
  4107. pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  4108. if(haha) throw haha;
  4109. if(huhu.length == 0) return;
  4110.  
  4111. LevelCalculate(steamid);
  4112. });
  4113.  
  4114. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  4115.  
  4116. var nume = results[0].name;
  4117. var avatarul = results[0].avatar;
  4118.  
  4119.  
  4120. pool.query('INSERT INTO games SET expire = ' + pool.escape((time() + tradingRequests[offer.id]['gameExpire']*60)) + ', cassetids = ' + pool.escape(assetiddsss.join('/')) + ', csteamid = ' + pool.escape(steamid) + ', cname = ' + pool.escape(nume) + ', cavatar = ' + pool.escape(avatarul) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', cpick = ' + pool.escape(tradingRequests[offer.id]['side']) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul) + ', bot = ' + pool.escape(botAles), function(arr, ass) {
  4121. if(arr) throw arr;
  4122.  
  4123. pool.query('SELECT MAX(id) AS cacat FROM games', function(caca, rara) {
  4124. if(caca) throw caca;
  4125.  
  4126. loadAllGames();
  4127. loadStatistics();
  4128. setTimeout(function() {
  4129. loadGames.forEach(function(itm) {
  4130. if(itm.id == rara[0].cacat)
  4131. {
  4132. io.sockets.emit('message', {
  4133. type: 'addGame',
  4134. games: {
  4135. 'id': itm.id,
  4136. 'csteamid': itm.csteamid,
  4137. 'cname': itm.cname,
  4138. 'cavatar': itm.cavatar,
  4139. 'cskinsurl': itm.cskinsurl,
  4140. 'cskinsnames': itm.cskinsnames,
  4141. 'cskinsprices': itm.cskinsprices,
  4142. 'cskins': itm.cskins,
  4143. 'ctp': itm.ctp,
  4144. 'psteamid': itm.psteamid,
  4145. 'pname': itm.pname,
  4146. 'pavatar': itm.pavatar,
  4147. 'pskinsurl': itm.pskinsurl,
  4148. 'pskinsnames': itm.pskinsnames,
  4149. 'pskinsprices': itm.pskinsprices,
  4150. 'pskins': itm.pskins,
  4151. 'ptp': itm.ptp,
  4152. 'hash': itm.hash,
  4153. 'secret': itm.secret,
  4154. 'winner': itm.winner,
  4155. 'cpick': itm.cpick,
  4156. 'ppick': itm.ppick,
  4157. 'timer': timerGame[itm.id]-time(),
  4158. 'timer11': itm.timer11,
  4159. 'winnerPercentage': itm.winnerPercentage,
  4160. 'ttimer11': timer11Game[itm.id]-time()
  4161. }
  4162. });
  4163. }
  4164. });
  4165. }, 1200);
  4166. });
  4167. });
  4168. });
  4169. });
  4170. }
  4171. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  4172. {
  4173. pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  4174. if(err) throw err;
  4175. var receivedItems = [];
  4176.  
  4177. var skinsnames = [];
  4178. var skinsids = [];
  4179. var skinsprices = [];
  4180. var pretul = require('./prices.json');
  4181.  
  4182. offer.getReceivedItems(true, function(err, caca) {
  4183. if(err) throw err;
  4184.  
  4185. for(var i in caca)
  4186. {
  4187. receivedItems.push(caca[i].assetid);
  4188. skinsnames.push(caca[i].market_hash_name);
  4189. skinsids.push(caca[i].assetid);
  4190. skinsprices.push(pretul[caca[i].market_hash_name]);
  4191. }
  4192.  
  4193. pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id), function(caca, maca) {
  4194. if(caca) throw caca;
  4195. if(maca.length == 0) return;
  4196.  
  4197. //GENERATE a SECRET
  4198. var TotalNumberOfTickets = (res[0].ctp+res[0].ptp)*100;
  4199. var winner;
  4200. var secret = createSecret();
  4201. var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
  4202. var winnerTicket = Math.floor((TotalNumberOfTickets - 0.0000000001) * (winnerPercentage / 100));
  4203.  
  4204. if(winnerTicket >= 0 && winnerTicket <= res[0].ctp*100)
  4205. {
  4206. winner = 'ct';
  4207. logger.trace('Ticket #' + winnerTicket + ' - winner ct');
  4208. }
  4209. else if(winnerTicket >= (res[0].ctp+0.01)*100 && winnerTicket <= (res[0].ctp+res[0].ptp)*100)
  4210. {
  4211. winner = 't';
  4212. logger.trace('Ticket #' + winnerTicket + ' - winner t');
  4213. }
  4214. var secret = createSecret();
  4215. function createSecret() {
  4216. var text = "";
  4217. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
  4218.  
  4219. for(var i=0; i < 8; i++)
  4220. text += possible.charAt(Math.floor(Math.random() * possible.length));
  4221.  
  4222. return text;
  4223. }
  4224. var hashul = res[0].hash;
  4225.  
  4226. var secretsihash = secret.concat(hashul);
  4227.  
  4228. var steamid = res[0].psteamid;
  4229. pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ', ticketWon = ' + pool.escape(winnerTicket) + ', ticketsTotal = ' + pool.escape(parseFloat(res[0].ctp+res[0].ptp)*100) + ', winnerPercentage = ' + pool.escape(winnerPercentage) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
  4230. if(aaa) throw aaa;
  4231.  
  4232. pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
  4233. if(haha) throw haha;
  4234. if(huhu.length == 0) return;
  4235.  
  4236. LevelCalculate(steamid);
  4237. });
  4238.  
  4239. loadAllGames();
  4240. sendGames(res[0].id);
  4241. });
  4242.  
  4243. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  4244.  
  4245. timer11Game[res[0].id] = time()+10;
  4246.  
  4247. if(socketBySteam.hasOwnProperty(res[0].psteamid))
  4248. {
  4249. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  4250. {
  4251. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  4252. type: 'modals',
  4253. tip: 'trade',
  4254. result: 'offerAccepted'
  4255. });
  4256. }
  4257. }
  4258.  
  4259. setTimeout(function() {
  4260. pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
  4261. if(errr) throw errr;
  4262.  
  4263. sendItemsTrade(offer.id, receivedItems.join('/'), winner, skinsnames, skinsids, skinsprices);
  4264. });
  4265. }, 9500);
  4266. });
  4267. });
  4268. });
  4269. }
  4270. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joinJackpot')
  4271. {
  4272. var receivedItems = [];
  4273. var items = [];
  4274.  
  4275. offer.getReceivedItems(true, function(err, maca) {
  4276. if(err) throw err;
  4277.  
  4278. for(var i in maca)
  4279. {
  4280. items.push(maca[i]);
  4281. receivedItems.push(maca[i].assetid);
  4282. }
  4283.  
  4284. var pretul = require('./prices.json');
  4285.  
  4286. if(jackpotState == 'WAITING') jackpotState = 'BETTING';
  4287.  
  4288. var itemsData = [];
  4289.  
  4290. var totalSkins = 0;
  4291. var skinImages = [];
  4292. var skinNames = [];
  4293. var skinPrices = [];
  4294. var totalPrice = 0;
  4295.  
  4296. for(var i in items)
  4297. {
  4298. totalSkins++;
  4299. totalPrice += pretul[items[i].market_hash_name];
  4300. skinImages.push(items[i].icon_url);
  4301. skinNames.push(items[i].market_hash_name);
  4302. skinPrices.push(pretul[items[i].market_hash_name]);
  4303.  
  4304. itemsData.push({
  4305. 'id': items[i].assetid,
  4306. 'price': pretul[items[i].market_hash_name],
  4307. 'name': items[i].market_hash_name,
  4308. 'icon_url': items[i].icon_url
  4309. });
  4310. }
  4311. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  4312.  
  4313. if(jackpotState == 'BETTING')
  4314. {
  4315. var minTicket = parseInt(jackpotTickets+1);
  4316. var maxTicket = parseInt(minTicket+(totalPrice*100)-1);
  4317. for(var a = minTicket; a < maxTicket; a++)
  4318. {
  4319. jackpotTotalTickets.push({
  4320. 'user': tradingRequests[offer.id]['user'],
  4321. 'ticket': parseInt(a)
  4322. });
  4323. }
  4324. jackpotTickets += parseInt(totalPrice*100);
  4325. var assetidsSS = receivedItems.join('/');
  4326. pool.query('INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(totalPrice) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(totalSkins) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(offer.id));
  4327. addJackpotBet(tradingRequests[offer.id]['user'], skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData);
  4328. }
  4329. else
  4330. {
  4331. jackpotQueueBets.push({
  4332. 'user': tradingRequests[offer.id]['user'],
  4333. 'offerID': offer.id,
  4334. 'skinImages': skinImages,
  4335. 'skinNames': skinNames,
  4336. 'skinPrices': skinPrices,
  4337. 'totalSkins': totalSkins,
  4338. 'totalPrice': totalPrice,
  4339. 'itemsData': itemsData,
  4340. 'receivedItems': receivedItems
  4341. });
  4342. logger.info('Jackpot round #' + jackpotRound + ' added to queue trade offer #' + offer.id);
  4343. }
  4344. });
  4345. }
  4346. }
  4347. else if(oldState == 2 && offer.state == 7)
  4348. {
  4349. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  4350. if(caca) throw caca;
  4351. if(maca.length == 0) return;
  4352.  
  4353. if(maca[0].action == 'winning') return;
  4354. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  4355. if(socketBySteam.hasOwnProperty(maca[0].user))
  4356. {
  4357. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  4358. {
  4359. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  4360. type: 'modals',
  4361. tip: 'trade',
  4362. result: 'offerDeclined'
  4363. });
  4364. }
  4365. }
  4366. });
  4367. }
  4368. else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  4369. {
  4370. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  4371. if(caca) throw caca;
  4372. if(maca.length == 0) return;
  4373.  
  4374. if(maca[0].action == 'winning') return;
  4375. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  4376. });
  4377. }
  4378. }
  4379. else if(offer.isOurOffer && offer.itemsToGive.length > 0)
  4380. {
  4381. if((oldState == 2 || oldState == 9) && offer.state == 3)
  4382. {
  4383. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
  4384. {
  4385. pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  4386. if(caca) throw caca;
  4387. if(maca.length == 0) return;
  4388.  
  4389. if(socketBySteam.hasOwnProperty(maca[0].user))
  4390. {
  4391. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  4392. {
  4393. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  4394. type: 'modals',
  4395. tip: 'trade',
  4396. result: 'offerAccepted'
  4397. });
  4398. }
  4399. }
  4400. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  4401. });
  4402. }
  4403. }
  4404. else if((oldState == 2 || oldState == 9) && offer.state == 7)
  4405. {
  4406. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  4407. if(caca) throw caca;
  4408. if(maca.length == 0) return;
  4409.  
  4410. if(maca[0].action == 'winning') return;
  4411. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  4412. if(socketBySteam.hasOwnProperty(maca[0].user))
  4413. {
  4414. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  4415. {
  4416. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  4417. type: 'modals',
  4418. tip: 'trade',
  4419. result: 'offerDeclined'
  4420. });
  4421. }
  4422. }
  4423. });
  4424. }
  4425. else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  4426. {
  4427. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  4428. if(caca) throw caca;
  4429. if(maca.length == 0) return;
  4430.  
  4431. if(maca[0].action == 'winning') return;
  4432. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  4433. });
  4434. }
  4435. }
  4436. }
  4437. }
  4438. };
  4439.  
  4440.  
  4441.  
  4442. function addJackpotBet(userBet, skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData)
  4443. {
  4444. //SMECHERIE
  4445. var Skinimages = "";
  4446. var Skinnames = "";
  4447. var Skinprices = "";
  4448. Skinimages = skinImages.join('/');
  4449. Skinnames = skinNames.join('/');
  4450. Skinprices = skinPrices.join('/');
  4451.  
  4452. var timp = new Date();
  4453. var timpCalc = timp.getTime()/1000;
  4454.  
  4455. var name;
  4456. var avatar;
  4457.  
  4458. totalJackpotItems += totalSkins;
  4459. totalJackpotValue += totalPrice;
  4460.  
  4461. pool.query('SELECT tradelink,name,avatar,level FROM users WHERE steamid = ' + pool.escape(userBet), function(error, results) {
  4462. if(error) throw error;
  4463.  
  4464. JackpotUsers.push({
  4465. 'userInfo': {
  4466. 'avatar': results[0].avatar,
  4467. 'name': results[0].name,
  4468. 'steamid': userBet,
  4469. 'level': results[0].level
  4470. },
  4471. 'itemsInfo': itemsData
  4472. });
  4473.  
  4474. pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(userBet), function(haha, huhu) {
  4475. if(haha) throw haha;
  4476. if(huhu.length == 0) return;
  4477.  
  4478. LevelCalculate(userBet);
  4479. });
  4480.  
  4481. if(JackpotUsers.length == 2)
  4482. {
  4483. totalSecondsJackpot = time()+60;
  4484. checkJackpotEnd = setInterval(function() {
  4485. if(totalSecondsJackpot-time() <= 0)
  4486. {
  4487. jackpotState = 'PICKING_WINNER';
  4488. pickJackpotWinner();
  4489. clearInterval(checkJackpotEnd);
  4490. }
  4491. }, 1000);
  4492. }
  4493.  
  4494. io.sockets.emit('message', {
  4495. type: 'addJackpotBet',
  4496. userInfo: {
  4497. avatar: results[0].avatar,
  4498. name: results[0].name,
  4499. steamid: userBet,
  4500. level: results[0].level
  4501. },
  4502. itemsInfo: itemsData
  4503. });
  4504.  
  4505. io.sockets.emit('message', {
  4506. type: 'jackpotSet',
  4507. totalUsers: JackpotUsers.length,
  4508. potItemsValue: totalJackpotValue,
  4509. potValue: totalJackpotItems,
  4510. timpul: totalSecondsJackpot-time()
  4511. });
  4512.  
  4513.  
  4514. for(var c in JackpotUsers)
  4515. {
  4516. var value = 0;
  4517. for(var z in JackpotUsers[c]['itemsInfo'])
  4518. {
  4519. value += parseFloat(JackpotUsers[c]['itemsInfo'][z]['price']);
  4520. }
  4521. var chance = 100 - ((totalJackpotValue-value)/totalJackpotValue)*100;
  4522. usersPrices[JackpotUsers[c]['userInfo']['steamid']] = value;
  4523.  
  4524. if(socketBySteam.hasOwnProperty(JackpotUsers[c]['userInfo']['steamid']))
  4525. {
  4526. if(io.sockets.connected[socketBySteam[JackpotUsers[c]['userInfo']['steamid']]['info']])
  4527. {
  4528. io.sockets.connected[socketBySteam[JackpotUsers[c]['userInfo']['steamid']]['info']].emit('message', {
  4529. type: 'standingQueue',
  4530. totalItems: JackpotUsers[c]['itemsInfo'].length,
  4531. yourChance: chance
  4532. });
  4533. }
  4534. }
  4535. }
  4536.  
  4537. if(totalJackpotItems >= 50)
  4538. {
  4539. jackpotState = 'PICKING_WINNER';
  4540. pickJackpotWinner();
  4541. }
  4542. });
  4543. }
  4544.  
  4545. function getRandomFloat(min, max) {
  4546. return (Math.random() * (max - min) + min).toFixed(10);
  4547. }
  4548.  
  4549. function handleDisconnect() {
  4550. pool = mysql.createConnection(db_config);
  4551.  
  4552. pool.connect(function(err) {
  4553. if(err) {
  4554. logger.trace('Error: Connecting to database: ', err);
  4555. setTimeout(handleDisconnect, 2000);
  4556. }
  4557. });
  4558.  
  4559. pool.on('error', function(err) {
  4560. logger.trace('Error: Database error: ', err);
  4561. if(err.code === 'PROTOCOL_CONNECTION_LOST') {
  4562. handleDisconnect();
  4563. } else {
  4564. throw err;
  4565. }
  4566. });
  4567. }
  4568.  
  4569. function escapeHtml(text) {
  4570. var map = {
  4571. '&': '&amp;',
  4572. '<': '&lt;',
  4573. '>': '&gt;',
  4574. '"': '&quot;',
  4575. "'": '&#039;'
  4576. };
  4577.  
  4578. return text.replace(/[&<>"']/g, function(m) { return map[m]; });
  4579. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement