Advertisement
Guest User

Untitled

a guest
Feb 27th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 69.48 KB | None | 0 0
  1. var fs = require('fs');
  2. var sslOptions = {
  3. key: fs.readFileSync('ssl/privkey.pem'),
  4. cert: fs.readFileSync('ssl/cert.pem'),
  5. requestCert: true,
  6. rejectUnauthorized: false
  7. };
  8. var SteamUser = require('steam-user');
  9. var TradeOfferManager = require('steam-tradeoffer-manager');
  10. var SteamTotp = require('steam-totp');
  11. var SteamCommunity = require('steamcommunity');
  12. var io = require('socket.io')(server);
  13. var https = require('https');
  14. var http = require('http');
  15. var request = require('request');
  16. var config = require('./config.json');
  17. var CryptoJS = require("crypto-js");
  18. var log4js = require('log4js');
  19. var express = require('express');
  20. var app = express();
  21. var server = https.createServer(sslOptions, app).listen(3001);
  22. var community = new SteamCommunity();
  23. var client = new SteamUser();
  24. var manager = new TradeOfferManager({
  25. steam: client,
  26. domain: 'localhost',
  27. language: 'en'
  28. });
  29.  
  30.  
  31. updateLog(time());
  32. function updateLog(time) {
  33. log4js.configure({
  34. appenders: [
  35. { type: 'console' },
  36. { type: 'file', filename: 'logs/site_'+time+'.log' }
  37. ]
  38. });
  39. }
  40.  
  41. var logger = log4js.getLogger();
  42.  
  43. var mysql = require('mysql');
  44. var db_config = {
  45. //debug: true,
  46. host: config.options.sql['host'],
  47. user: config.options.sql['username'],
  48. password: config.options.sql['password'],
  49. database: config.options.sql['database']
  50. };
  51. var pool;
  52. handleDisconnect();
  53.  
  54. process.on('uncaughtException', function (err) {
  55. logger.error('Strange error');
  56. logger.error(err);
  57. });
  58.  
  59. //GAME INFO
  60. var AppID = 730;
  61. var ContextID = 2;
  62. var minDep = config.options.minDeposit;
  63.  
  64.  
  65. var proxies = config.proxies;
  66.  
  67. var deletingTrades = [];
  68.  
  69. var inventoryTimer = {};
  70. var socketBySteam = {};
  71.  
  72. var tradingRequests = {};
  73.  
  74. var loadGames = [];
  75. var timerGame = {};
  76. var timer11Game = {};
  77.  
  78. var depositTrades = [];
  79. var depositSteamTrades = [];
  80.  
  81. var gamesPending = {};
  82.  
  83. var antiFlood = {};
  84. var timesFlooding = {};
  85.  
  86. var inventoryUser = {};
  87.  
  88. //CHAT FUNCTIONS
  89. var chatMessages = [];
  90. var usersOnline = {};
  91. var antiSpamChat = {};
  92. //CHAT FUNCTIONS
  93.  
  94.  
  95. /*
  96. Polling Steam and Logging On
  97. */
  98. client.logOn({
  99. accountName: config.bots[0].username,
  100. password: config.bots[0].password,
  101. twoFactorCode: SteamTotp.generateAuthCode(config.bots[0].sharedSecret)
  102. });
  103.  
  104. community.on('sessionExpired', function(err) {
  105. client.logOn({
  106. accountName: config.bots[0].username,
  107. password: config.bots[0].password,
  108. twoFactorCode: SteamTotp.generateAuthCode(config.bots[0].sharedSecret)
  109. });
  110. });
  111.  
  112. app.get('/sendTrade', function(req, res) {
  113. var tradeID = req.query['tid'];
  114.  
  115. if(!tradeID)
  116. {
  117. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  118. {
  119. }
  120. return;
  121. }
  122.  
  123. pool.query('SELECT status,action,user,items,code FROM trades WHERE tid = ' + pool.escape(tradeID), function(err, row) {
  124. if(err) throw err;
  125. if(row.length == 0)
  126. {
  127. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  128. {
  129. }
  130. return;
  131. }
  132.  
  133. if(row[0].status == 'PendingAccept' && row[0].action == 'winning')
  134. {
  135. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(row[0].user), function(er, ro) {
  136. if(er) throw er;
  137. if(ro.length == 0)
  138. {
  139. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  140. {
  141. }
  142. return;
  143. }
  144.  
  145. if(!ro[0].tradelink.includes('://'))
  146. {
  147. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  148. {
  149. }
  150. return;
  151. }
  152.  
  153. 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) {
  154. if(ca) throw ca;
  155. if(ma.length == 0) return;
  156.  
  157. if(ma[0].tTrades != 0)
  158. {
  159. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  160. {
  161. }
  162. return;
  163. }
  164.  
  165. var Items = row[0].items.split('/');
  166. var create = manager.createOffer(row[0].user, ro[0].tradelink.split('token=')[1]);
  167. manager.loadInventory(AppID, ContextID, true, function(err, inv, curr) {
  168. if(err) throw err;
  169. if(inv.length == 0) return;
  170.  
  171. for(var i in Items)
  172. {
  173. for(var z in inv)
  174. {
  175. if(Items[i] == inv[z].assetid && Items[i] != 1)
  176. {
  177. Items[i] = 1;
  178. create.addMyItem({
  179. "appid": AppID,
  180. "contextid": ContextID,
  181. "assetid": inv[z].assetid
  182. });
  183. }
  184. }
  185. }
  186.  
  187. create.setMessage('Your winnings are here. Code: ' + row[0].code);
  188. create.send(function(err, status) {
  189. if(err) throw err;
  190.  
  191. tradingRequests[create.id] = {
  192. action: 'winning',
  193. user: row[0].user
  194. };
  195.  
  196. pool.query('UPDATE trades SET tid = ' + pool.escape(create.id) + ' WHERE tid = ' + pool.escape(tradeID));
  197.  
  198. if(io.sockets.connected[socketBySteam[row[0].user]['info']])
  199. {
  200. io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
  201. type: 'modals',
  202. tip: 'trade',
  203. result: 'offerSend',
  204. code: row[0].code,
  205. tid: create.id
  206. });
  207. }
  208.  
  209. setTimeout(function() {
  210. declineOffer(create);
  211. }, 90000);
  212.  
  213. logger.debug('Winnings from tradeid #' + tradeID + ' were sent again to winner ' + row[0].user + ' new tradeoffer #' + create.id);
  214. });
  215. });
  216. });
  217. });
  218. }
  219. });
  220. });
  221.  
  222. setTradingRequests();
  223. function setTradingRequests()
  224. {
  225. pool.query('SELECT * FROM trades WHERE status = ' + pool.escape('PendingAccept'), function(err, row) {
  226. if(err) throw err;
  227. if(row.length == 0) return;
  228.  
  229. for(var i in row)
  230. {
  231. logger.debug('Trade #' + row[i].tid + ' added --> ' + row[i].action + ' + ' + row[i].user);
  232.  
  233. tradingRequests[row[i].tid] = {
  234. action: row[i].action,
  235. user: row[i].user
  236. };
  237. }
  238. });
  239. }
  240.  
  241. loadAllGames();
  242. function loadAllGames()
  243. {
  244. pool.query('SELECT * FROM games WHERE `ended` = 0', function(err, res, fields) {
  245. if(err) throw err;
  246.  
  247. loadGames = [];
  248.  
  249. for(var i in res)
  250. {
  251. loadGames.push({
  252. 'id': res[i].id,
  253. 'csteamid': res[i].csteamid,
  254. 'cname': res[i].cname,
  255. 'cavatar': res[i].cavatar,
  256. 'cskinsurl': res[i].cskinsurl,
  257. 'cskinsnames': res[i].cskinsnames,
  258. 'cskinsprices': res[i].cskinsprices,
  259. 'cskins': res[i].cskins,
  260. 'ctp': res[i].ctp,
  261. 'psteamid': res[i].psteamid,
  262. 'pname': res[i].pname,
  263. 'pavatar': res[i].pavatar,
  264. 'pskinsurl': res[i].pskinsurl,
  265. 'pskinsnames': res[i].pskinsnames,
  266. 'pskinsprices': res[i].pskinsprices,
  267. 'pskins': res[i].pskins,
  268. 'ptp': res[i].ptp,
  269. 'hash': res[i].hash,
  270. 'secret': res[i].secret,
  271. 'winner': res[i].winner,
  272. 'timer11': res[i].timer11
  273. });
  274. }
  275. });
  276. }
  277.  
  278.  
  279. io.on('connection', function(socket) {
  280. socket.on('hash', function(m) {
  281. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  282. addHistory(socket);
  283.  
  284. if(!usersOnline[address])
  285. {
  286. usersOnline[address] = 1;
  287. }
  288.  
  289. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  290. if(err) throw err;
  291.  
  292. if(row.length == 0) return;
  293.  
  294. if(row.length > 0)
  295. {
  296. getInv(row[0].steamid, socket);
  297.  
  298. if(socketBySteam.hasOwnProperty(row[0].steamid))
  299. {
  300. delete socketBySteam[row[0].steamid];
  301. socketBySteam[row[0].steamid] = {
  302. 'info': socket.id
  303. };
  304. }
  305. else
  306. {
  307. socketBySteam[row[0].steamid] = {
  308. 'info': socket.id
  309. };
  310. }
  311. }
  312. });
  313.  
  314. loadStatistics(socket);
  315.  
  316. io.sockets.emit('message', {
  317. type: 'connections',
  318. total: Object.keys(usersOnline).length
  319. });
  320. //console.log('a user connected.');
  321.  
  322. loadGames.forEach(function(itm) {
  323. socket.emit('message', {
  324. type: 'addGame',
  325. games: {
  326. 'id': itm.id,
  327. 'csteamid': itm.csteamid,
  328. 'cname': itm.cname,
  329. 'cavatar': itm.cavatar,
  330. 'cskinsurl': itm.cskinsurl,
  331. 'cskinsnames': itm.cskinsnames,
  332. 'cskinsprices': itm.cskinsprices,
  333. 'cskins': itm.cskins,
  334. 'ctp': itm.ctp,
  335. 'psteamid': itm.psteamid,
  336. 'pname': itm.pname,
  337. 'pavatar': itm.pavatar,
  338. 'pskinsurl': itm.pskinsurl,
  339. 'pskinsnames': itm.pskinsnames,
  340. 'pskinsprices': itm.pskinsprices,
  341. 'pskins': itm.pskins,
  342. 'ptp': itm.ptp,
  343. 'hash': itm.hash,
  344. 'secret': itm.secret,
  345. 'winner': itm.winner,
  346. 'timer': timerGame[itm.id]-time(),
  347. 'timer11': itm.timer11,
  348. 'ttimer11': timer11Game[itm.id]-time()
  349. }
  350. });
  351. });
  352. });
  353.  
  354.  
  355. //BOT INVENTORY
  356.  
  357. socket.on('getBotInv', function(m) {
  358. if(m.hash)
  359. {
  360. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  361. if(err) throw err;
  362. if(row.length == 0) return;
  363.  
  364. manager.loadInventory(AppID, ContextID, true, function(er, inv, curr) {
  365. if(er) throw er;
  366. if(inv.length == 0)
  367. {
  368. return;
  369. }
  370.  
  371. var skins = [];
  372. var price = require('./prices.json');
  373.  
  374. var ids = [];
  375. var names = [];
  376. var prices = [];
  377. var images = [];
  378.  
  379.  
  380.  
  381. for(var i in inv)
  382. {
  383. skins.push({
  384. id: inv[i].assetid,
  385. name: inv[i].market_hash_name,
  386. price: price[inv[i].market_hash_name],
  387. image: inv[i].icon_url
  388. });
  389. }
  390.  
  391.  
  392. setTimeout(function() {
  393. for(var z in inv)
  394. {
  395. socket.emit('bot', {
  396. type: 'botInv',
  397. ids: skins[z].id,
  398. names: skins[z].name,
  399. prices: skins[z].price,
  400. images: skins[z].image
  401. });
  402. }
  403. }, 2000);
  404.  
  405. });
  406.  
  407. });
  408. }
  409. });
  410.  
  411.  
  412. socket.on('wantsInvBot', function(m) {
  413. if(m.hash && m.link)
  414. {
  415. pool.query('SELECT steamid,rank FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  416. if(err) throw err;
  417. if(row.length == 0) return;
  418.  
  419. var assets = m.assets;
  420. var itemsToSend = [];
  421.  
  422. var create = manager.createOffer(m.link);
  423. manager.loadInventory(AppID, ContextID, true, function(er, inv, curr) {
  424. if(er) throw er;
  425. if(inv.length == 0) return;
  426.  
  427.  
  428. for(var i in assets)
  429. {
  430. for(var z in inv)
  431. {
  432. if(assets[i] == inv[z].assetid && assets[i].ss != 1)
  433. {
  434. assets[i].ss = 1;
  435.  
  436. itemsToSend.push(inv[z].assetid);
  437. }
  438. }
  439. }
  440.  
  441. if(itemsToSend.length == 0)
  442. {
  443. return;
  444. }
  445.  
  446. for(var i in itemsToSend)
  447. {
  448. create.addMyItem({
  449. "appid": AppID,
  450. "contextid": ContextID,
  451. "assetid": itemsToSend[i]
  452. });
  453. }
  454.  
  455. create.send(function(e, status) {
  456. if(e) throw e;
  457.  
  458.  
  459. logger.debug('Tradeoffer #' + create.id + ' (' + status + ') to user ' + row[0].steamid + ' [getBotItems]');
  460. });
  461. });
  462.  
  463. });
  464. }
  465. });
  466.  
  467.  
  468. //INVENTORY TIMER
  469. socket.on('wantInv', function(m) {
  470. if(m.hash)
  471. {
  472. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  473. if(err) throw err;
  474.  
  475. if(row.length == 0) return;
  476.  
  477. if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
  478. {
  479. getInv(row[0].steamid, socket);
  480. inventoryTimer[row[0].steamid] = {
  481. 'timer': time()+45
  482. };
  483. }
  484. else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
  485. {
  486. if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
  487. {
  488. var id = inventoryUser[row[0].steamid]['id'].split('/');
  489. var name = inventoryUser[row[0].steamid]['name'].split('/');
  490. var price = inventoryUser[row[0].steamid]['price'].split('/');
  491. var img = inventoryUser[row[0].steamid]['img'].split('/');
  492.  
  493. for(var i = 0; i < id.length; i++)
  494. {
  495. socket.emit('message', {
  496. type: 'getInventory',
  497. id: id[i],
  498. name: name[i],
  499. price: price[i],
  500. img: img[i]
  501. });
  502. }
  503.  
  504. socket.emit('message', {
  505. type: 'msg',
  506. tip: 'Inv',
  507. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  508. });
  509. }
  510. else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
  511. {
  512. inventoryTimer[row[0].steamid] = {
  513. 'timer': time()+45
  514. };
  515.  
  516. getInv(row[0].steamid, socket);
  517.  
  518. socket.emit('message', {
  519. type: 'msg',
  520. tip: 'Inv',
  521. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  522. });
  523. }
  524. }
  525. });
  526. }
  527. });
  528.  
  529.  
  530. socket.on('wantInv2', function(m) {
  531. if(m.hash)
  532. {
  533. pool.query('SELECT steamid FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  534. if(err) throw err;
  535.  
  536. if(row.length == 0) return;
  537.  
  538. if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
  539. {
  540. getInv2(row[0].steamid, socket);
  541. inventoryTimer[row[0].steamid] = {
  542. 'timer': time()+45
  543. };
  544. }
  545. else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
  546. {
  547. if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
  548. {
  549. var id = inventoryUser[row[0].steamid]['id'].split('/');
  550. var name = inventoryUser[row[0].steamid]['name'].split('/');
  551. var price = inventoryUser[row[0].steamid]['price'].split('/');
  552. var img = inventoryUser[row[0].steamid]['img'].split('/');
  553.  
  554. for(var i = 0; i < id.length; i++)
  555. {
  556. socket.emit('message', {
  557. type: 'getInventory2',
  558. id: id[i],
  559. name: name[i],
  560. price: price[i],
  561. img: img[i]
  562. });
  563. }
  564.  
  565. socket.emit('message', {
  566. type: 'msg',
  567. tip: 'Inv2',
  568. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  569. });
  570. }
  571. else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
  572. {
  573. inventoryTimer[row[0].steamid] = {
  574. 'timer': time()+45
  575. };
  576.  
  577. getInv2(row[0].steamid, socket);
  578.  
  579. socket.emit('message', {
  580. type: 'msg',
  581. tip: 'Inv2',
  582. seconds: inventoryTimer[row[0].steamid]['timer']-time()
  583. });
  584. }
  585. }
  586. });
  587. }
  588. });
  589.  
  590. socket.on('newGame', function(m) {
  591. if(antiFlood[socket]+2 >= time()) {
  592. timesFlooding[socket] += 1;
  593. if(timesFlooding[socket] == 3)
  594. {
  595. delete timesFlooding[socket];
  596. socket.disconnect();
  597. return;
  598. }
  599. return;
  600. } else {
  601. antiFlood[socket] = time();
  602. }
  603. if(m.hash)
  604. {
  605. pool.query('SELECT steamid,tradelink FROM users WHERE hash = ' + pool.escape(m.hash), function(err, row) {
  606. if(err) throw err;
  607. if(row.length == 0)
  608. {
  609. logger.debug('Error [1]');
  610. return;
  611. }
  612.  
  613. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(er, ro) {
  614. if(er) throw er;
  615. if(ro.length == 0) return;
  616.  
  617. if(ro[0].tTrades != 0)
  618. {
  619. return;
  620. }
  621.  
  622. if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
  623. {
  624. return;
  625. }
  626.  
  627. var Items = m.assets.split('/');
  628. var itemsToReceive = [];
  629. var create = manager.createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
  630. manager.getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
  631. if(e) throw e;
  632. if(inv.length == 0)
  633. {
  634. logger.debug('Error [4]');
  635. return;
  636. }
  637.  
  638. for(var i in Items)
  639. {
  640. for(var z in inv)
  641. {
  642. if(Items[i] == inv[z].assetid && Items[i].ss != 1)
  643. {
  644. Items[i].ss = 1;
  645.  
  646. itemsToReceive.push(inv[z].assetid);
  647. }
  648. }
  649. }
  650.  
  651. if(itemsToReceive.length == 0)
  652. {
  653. return;
  654. }
  655.  
  656. for(var i in itemsToReceive)
  657. {
  658. create.addTheirItem({
  659. "appid": AppID,
  660. "contextid": ContextID,
  661. "assetid": itemsToReceive[i]
  662. });
  663. }
  664.  
  665. socket.emit('message', {
  666. type: 'modals',
  667. tip: 'trade',
  668. result: 'offerProcessing'
  669. });
  670.  
  671.  
  672. var cod = makeCode();
  673. create.setMessage('Code: ' + cod);
  674.  
  675. create.send(function(ab, status) {
  676.  
  677. if(ab) throw ab;
  678.  
  679. depositTrades.push(create.id);
  680. depositSteamTrades.push(row[0].steamid);
  681.  
  682.  
  683. logger.debug('Tradeoffer #' + create.id + ' (' + status + ') with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
  684.  
  685. deletingTrades[create.id] = setTimeout(function() {
  686. deleteTrade(create.id, socket, create);
  687. }, 92000);
  688.  
  689. tradingRequests[create.id] = {
  690. action: 'newGame',
  691. user: row[0].steamid
  692. }
  693.  
  694. 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));
  695.  
  696. socket.emit('message', {
  697. type: 'modals',
  698. tip: 'trade',
  699. result: 'offerSend',
  700. tid: create.id,
  701. code: cod
  702. });
  703. });
  704. });
  705. });
  706. });
  707. }
  708. });
  709.  
  710.  
  711. //CHAT FUNCTIONS
  712. socket.on('nMsg', function(m)  {
  713. var mesaj = m.message;
  714. var utilizator = m.user;
  715. var hide = m.hide;
  716. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  717.  
  718. pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level` FROM `users` WHERE `hash` = ' + pool.escape(utilizator), function(err, res) {
  719. if (err) throw err;
  720. var row = res;
  721.  
  722. if (!res[0]) return err;
  723.  
  724. if (mesaj.length > 128 || mesaj.length < 6 && res[0].rank != 69) {
  725. return;
  726. } else {
  727. if (antiSpamChat[res[0].steamid] + 2 >= time() && res[0].rank != 69) {
  728. return;
  729. } else {
  730. antiSpamChat[res[0].steamid] = time();
  731. }
  732.  
  733. var caca = null;
  734. if (caca = /^\/clear/.exec(mesaj)) {
  735. if (row[0].rank == 69 || row[0].rank == 92) {
  736. io.sockets.emit('message', {
  737. type: 'addMessage',
  738. tip: 'clear',
  739. name: '',
  740. rank: '',
  741. avatar: '',
  742. hide: true,
  743. msg: ''
  744. });
  745. chatMessages = [];
  746. //logger.trace('Chat: Cleared by Admin ' + row[0].name + '.');
  747. }
  748. } else if (caca = /^\/mute ([0-9]*) ([0-9]*)/.exec(mesaj)) {
  749. if (row[0].rank == 69 || row[0].rank == 92) {
  750. var t = time();
  751. pool.query('UPDATE `users` SET `mute` = ' + pool.escape(parseInt(t) + parseInt(caca[2])) + ' WHERE `steamid` = ' + pool.escape(caca[1]), function(err2, row2) {
  752. if (err2) throw err2;
  753. if (row2.affectedRows == 0) {
  754. //logger.trace('Mute: Steamid not found in database (' + caca[1] + ').');
  755. return;
  756. }
  757. //logger.trace('Mute: Steamid ' + caca[1] + ' has been muted for ' + caca[2] + ' seconds by ' + row[0].name + ' (' + row[0].steamid + ').');
  758. });
  759. }
  760. } else {
  761.  
  762. if (row[0].mute > time() && row[0].mute != 0) {
  763. //logger.trace('Mute: ' + row[0].name + ' (' + row[0].steamid + ') tried to speak (' + mesaj + ') while muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').');
  764. return;
  765. }
  766.  
  767. if (chatMessages.length > 20) {
  768. chatMessages.shift();
  769. }
  770.  
  771.  
  772. chatMessages.push({
  773. name: res[0].name,
  774. avatar: res[0].avatar,
  775. steamid: res[0].steamid,
  776. rank: res[0].rank,
  777. hide: hide,
  778. level: res[0].level,
  779. message: mesaj
  780. });
  781.  
  782. io.sockets.emit('message', {
  783. type: 'addMessage',
  784. msg: mesaj,
  785. avatar: res[0].avatar,
  786. steamid: res[0].steamid,
  787. rank: res[0].rank,
  788. hide: hide,
  789. level: res[0].level,
  790. name: res[0].name
  791. });
  792. //logger.trace('Chat: Message from ' + row[0].name + ' (SID: ' + row[0].steamid + ', IP: ' + address + ', hide: ' + hide + ') --> ' + mesaj);
  793. }
  794. }
  795. });
  796. });
  797.  
  798. socket.on('disconnect', function(m) {
  799. var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
  800. if(usersOnline[address])
  801. {
  802. delete usersOnline[address];
  803. }
  804. io.sockets.emit('message', {
  805. type: 'connections',
  806. total: Object.keys(usersOnline).length
  807. });
  808. //console.log('a user disconnected.');
  809. });
  810.  
  811. //CHAT FUNCTIONS
  812. socket.on('watchGame', function(m) {
  813. pool.query('SELECT * FROM games WHERE id = ' + pool.escape(m.gameid), function(error, results) {
  814. if(error) throw error;
  815.  
  816. socket.emit('message', {
  817. type: 'watchCF',
  818. id: results[0].id,
  819. cname: results[0].cname,
  820. cavatar: results[0].cavatar,
  821. cskinsurl: results[0].cskinsurl,
  822. cskinsnames: results[0].cskinsnames,
  823. cskinsprices: results[0].cskinsprices,
  824. cskins: results[0].cskins,
  825. ctp: results[0].ctp,
  826. pname: results[0].pname,
  827. pavatar: results[0].pavatar,
  828. pskinsurl: results[0].pskinsurl,
  829. pskinsnames: results[0].pskinsnames,
  830. pskinsprices: results[0].pskinsprices,
  831. pskins: results[0].pskins,
  832. ptp: results[0].ptp,
  833. hash: results[0].hash,
  834. secret: results[0].secret,
  835. winner: results[0].winner,
  836. timer: timerGame[results[0].id]-time(),
  837. timer11: results[0].timer11,
  838. ttimer11: timer11Game[results[0].id]-time(),
  839. gameNumber: m.gameid
  840. });
  841. });
  842. });
  843.  
  844. socket.on('joingame', function(m) {
  845. if(antiFlood[socket]+2 >= time()) {
  846. timesFlooding[socket] += 1;
  847. if(timesFlooding[socket] == 3)
  848. {
  849. delete timesFlooding[socket];
  850. socket.disconnect();
  851. return;
  852. }
  853. return;
  854. } else {
  855. antiFlood[socket] = time();
  856. }
  857. if(!m.game)
  858. {
  859. return;
  860. }
  861.  
  862. var assetids = m.assetids.split('/');
  863. var gameID = m.game;
  864. var user_hash = m.hash;
  865.  
  866.  
  867. pool.query('SELECT id,trade_token,csteamid FROM games WHERE id = ' + pool.escape(gameID), function(error, results) {
  868. if(error) throw errorl
  869.  
  870. if(results[0].trade_token)
  871. {
  872. socket.emit('message', {
  873. type: 'msg',
  874. tip: 'error',
  875. msg: 'Error: Someone already joined in this game!'
  876. });
  877. return;
  878. }
  879.  
  880.  
  881. if(results[0].id)
  882. {
  883. pool.query('SELECT name,steamid,avatar,tradelink,rank FROM users WHERE hash = ' + pool.escape(user_hash), function(error1, results1) {
  884. if(error1) throw error1;
  885.  
  886. pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(results1[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(ca, ma) {
  887. if(ca) throw ca;
  888. if(ma.length == 0) return;
  889.  
  890. if(ma[0].tTrades != 0)
  891. {
  892. socket.emit('message', {
  893. type: 'msg',
  894. tip: 'error',
  895. msg: 'You isset an active tradeoffer.'
  896. });
  897. return;
  898. }
  899.  
  900. if(!results[0] || !results1[0])
  901. {
  902. socket.emit('message', {
  903. type: 'msg',
  904. tip: 'error',
  905. msg: 'Error: Unexpected error, contact an administrator!'
  906. });
  907. return;
  908. }
  909.  
  910. if(results[0].csteamid == results1[0].steamid && results1[0].rank != 69)
  911. {
  912. socket.emit('message', {
  913. type: 'msg',
  914. tip: 'error',
  915. msg: 'Error: You cannot join your own game!'
  916. });
  917. return;
  918. }
  919.  
  920. if(results1[0].name || results1[0].steamid || results1[0].avatar)
  921. {
  922. var totalAmount = 0;
  923. var totalItems = 0;
  924.  
  925. //ITEMS INFO
  926. var skinImages = [];
  927. var skinNames = [];
  928. var skinPrices = [];
  929. //ITEMS INFO
  930.  
  931. var minPriceDet = 0;
  932.  
  933.  
  934. if(!results1[0].tradelink.includes('://') || !results1[0].tradelink.includes('steamcommunity.com') || !results1[0].tradelink.includes('partner') || !results1[0].tradelink.includes('token'))
  935. {
  936. return;
  937. }
  938.  
  939. var toContinue = 0;
  940.  
  941. var create = manager.createOffer(results1[0].steamid, results1[0].tradelink.split('token=')[1]);
  942. var itemsLength = [];
  943. manager.getUserInventoryContents(results1[0].steamid, AppID, ContextID, true, function(err, inv, currencies) {
  944. for(i = 0; i < inv.length; i++) {
  945. for(a=0; a < assetids.length; a++)
  946. {
  947. if(minPriceDet == 0)
  948. {
  949. if(inv[i].assetid == assetids[a])
  950. {
  951. skinImages.push(inv[i].icon_url);
  952. skinNames.push(inv[i].market_hash_name);
  953. skinPrices.push(getPriceItem(inv[i].market_hash_name));
  954.  
  955.  
  956. if(getPriceItem(inv[i].market_hash_name) < minDep)
  957. {
  958. socket.emit('message', {
  959. type: 'msg',
  960. tip: 'error',
  961. msg: 'Error: Do not force system [min price $' + minDep + '].'
  962. });
  963.  
  964. minPriceDet = 1;
  965. toContinue = 1;
  966. return;
  967. }
  968. else
  969. {
  970. totalItems++;
  971.  
  972. totalAmount += getPriceItem(inv[i].market_hash_name);
  973.  
  974. itemsLength.push(inv[i].assetid);
  975. }
  976. }
  977. }
  978. }
  979. }
  980.  
  981. if(totalItems == 0 || totalItems > 12)
  982. {
  983. socket.emit('message', {
  984. type: 'msg',
  985. tip: 'error',
  986. msg: 'Error: Min. items per trade: 1 and max. items per trade: 12!'
  987. });
  988. return;
  989. }
  990.  
  991. pool.query('SELECT `ctp` FROM games WHERE id = ' + pool.escape(gameID), function(eroare, resultate) {
  992. if(eroare) throw eroare;
  993.  
  994. if(resultate[0].ctp)
  995. {
  996. var calculare = 10/100*resultate[0].ctp;
  997. var Gap01 = parseFloat(resultate[0].ctp - calculare).toFixed(2);
  998. var Gap02 = parseFloat(resultate[0].ctp + calculare).toFixed(2);
  999.  
  1000. if(totalAmount < Gap01 || totalAmount > Gap02)
  1001. {
  1002. toContinue = 1;
  1003. socket.emit('message', {
  1004. type: 'msg',
  1005. tip: 'error',
  1006. msg: 'Error: Minimum amount required: $' + Gap01 + ' or total amount required: $' + Gap02 + '. Your amount: $' + totalAmount
  1007. });
  1008. return;
  1009. }
  1010. }
  1011. else
  1012. {
  1013. toContinue = 1;
  1014. socket.emit('message', {
  1015. type: 'msg',
  1016. tip: 'error',
  1017. msg: 'Error: Invalid game!'
  1018. });
  1019. return;
  1020. }
  1021.  
  1022. if(toContinue == 0)
  1023. {
  1024. for(var b = 0; b < itemsLength.length; b++)
  1025. {
  1026. create.addTheirItem({
  1027. "appid": AppID,
  1028. "contextid": ContextID,
  1029. "assetid": itemsLength[b]
  1030. });
  1031. }
  1032.  
  1033. socket.emit('message', {
  1034. type: 'modals',
  1035. tip: 'trade',
  1036. result: 'offerProcessing'
  1037. });
  1038.  
  1039. var cod = makeCode();
  1040. create.setMessage("C: " + cod);
  1041. pool.query('UPDATE games SET scode = ' + pool.escape(cod) + ' WHERE id = ' + pool.escape(gameID));
  1042.  
  1043. create.send(function(err, status) {
  1044. if(err)
  1045. {
  1046. console.log(err);
  1047. return;
  1048. }
  1049. else
  1050. {
  1051. //INFO ITEMS
  1052. var Skinimages = skinImages.join('/');
  1053. var Skinnames = skinNames.join('/');
  1054. var Skinprices = skinPrices.join('/');
  1055.  
  1056. deletingTrades[create.id] = setTimeout(function() {
  1057. deleteTrade(create.id, socket, create);
  1058. }, 92000);
  1059.  
  1060. gamesPending[create.id] = results1[0].steamid;
  1061.  
  1062. tradingRequests[create.id] = {
  1063. action: 'joingame',
  1064. user: results1[0].steamid
  1065. }
  1066.  
  1067. socket.emit('message', {
  1068. type: 'modals',
  1069. tip: 'trade',
  1070. result: 'offerSend',
  1071. tid: create.id,
  1072. code: cod
  1073. });
  1074.  
  1075. 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));
  1076.  
  1077.  
  1078. pool.query('SELECT hash FROM games WHERE id = ' + pool.escape(gameID), function(err1, res1) {
  1079. if(err1) throw err1;
  1080. console.log('Joined game #' + gameID + ', player steamid: ' + results1[0].steamid + ' (' + results1[0].name + ')');
  1081. 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) + ', `ptp` = ' + pool.escape(totalAmount) + ', `trade_token` = ' + pool.escape(create.id) + ' WHERE `id` = ' + pool.escape(gameID));
  1082. loadAllGames();
  1083. sendGames(gameID);
  1084. });
  1085. }
  1086. });
  1087. }
  1088. });
  1089. });
  1090. }
  1091. else
  1092. {
  1093. socket.emit('message', {
  1094. type: 'msg',
  1095. tip: 'error',
  1096. msg: 'Error: User_id not found! Hacked.'
  1097. });
  1098. }
  1099. });
  1100. });
  1101. }
  1102. else
  1103. {
  1104. socket.emit('message', {
  1105. type: 'msg',
  1106. tip: 'error',
  1107. msg: 'Error: This game does not exists!'
  1108. });
  1109. }
  1110. });
  1111. });
  1112. });
  1113.  
  1114.  
  1115. function deleteTrade(trade_token, socket, offer)
  1116. {
  1117. if(socket)
  1118. {
  1119. pool.query('SELECT id,winner FROM games WHERE trade_token = ' + pool.escape(trade_token), function(err, res) {
  1120. if(err) throw err;
  1121.  
  1122. if(!res[0])
  1123. {
  1124. declineOffer(offer);
  1125. return;
  1126. }
  1127.  
  1128. if(res[0].winner == -1)
  1129. {
  1130. manager.getOffer(trade_token, function(err, offer) {
  1131. setTimeout(function() {
  1132. if(offer.status != 3 || offer.status != 8 || offer.status != 7 || offer.status != 6 || offer.status != 5 || offer.status != 4 || offer.status != 1 || offer.status != 10)
  1133. {
  1134. pool.query('SELECT action FROM trades WHERE tid = ' + pool.escape(trade_token), function(er, ro) {
  1135. if(er) throw er;
  1136. if(ro.length == 0) return;
  1137.  
  1138. if(ro[0].action == 'winning') return;
  1139.  
  1140. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(trade_token));
  1141. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(trade_token));
  1142.  
  1143. loadAllGames();
  1144. sendGames(res[0].id);
  1145.  
  1146. socket.emit('message', {
  1147. type: 'msg',
  1148. tip: 'error',
  1149. msg: 'Error: You did not accept the trade in time, your entry were cancelled!'
  1150. });
  1151. declineOffer(offer);
  1152. });
  1153. }
  1154. }, 2500);
  1155. });
  1156. }
  1157. });
  1158. }
  1159. else
  1160. {
  1161. pool.query('SELECT id,winner FROM games WHERE trade_token = ' + pool.escape(trade_token), function(err, res) {
  1162. if(err) throw err;
  1163.  
  1164. if(!res[0])
  1165. {
  1166. declineOffer(offer);
  1167. return;
  1168. }
  1169.  
  1170. if(res[0].winner == -1)
  1171. {
  1172. manager.getOffer(trade_token, function(err, offer) {
  1173. setTimeout(function() {
  1174. if(offer.status != 3 || offer.status != 8 || offer.status != 7 || offer.status != 6 || offer.status != 5 || offer.status != 4 || offer.status != 1 || offer.status != 10)
  1175. {
  1176. pool.query('SELECT action FROM trades WHERE tid = ' + pool.escape(trade_token), function(er, ro) {
  1177. if(er) throw er;
  1178. if(ro.length == 0) return;
  1179.  
  1180. if(ro[0].action == 'winning') return;
  1181.  
  1182. pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(trade_token));
  1183. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(trade_token));
  1184.  
  1185. loadAllGames();
  1186. sendGames(res[0].id);
  1187. declineOffer(offer);
  1188. });
  1189. }
  1190. }, 2500);
  1191. });
  1192. }
  1193. });
  1194. }
  1195. }
  1196.  
  1197. function hideGame(gameID)
  1198. {
  1199. pool.query('UPDATE games SET `ended` = 1 WHERE `id` = ' + pool.escape(gameID));
  1200. loadAllGames();
  1201. setTimeout(function() {
  1202. io.sockets.emit('message', {
  1203. type: 'removeGame',
  1204. id: gameID
  1205. });
  1206. }, 1000);
  1207. }
  1208.  
  1209.  
  1210.  
  1211. function getPriceItem(name)
  1212. {
  1213. var priceItem = 0;
  1214. if (name) {
  1215. var prices = require('./prices.json');
  1216. priceItem = prices[name];
  1217. }
  1218. return priceItem;
  1219. }
  1220.  
  1221.  
  1222.  
  1223. /*
  1224. Getting prices
  1225. */
  1226. var priceUrl = 'https://api.csgofast.com/price/all';
  1227.  
  1228. function getPriceList() {
  1229. request(priceUrl, function(dataAndEvents, r, actual) {
  1230. ok = JSON.parse(actual);
  1231. if (200 != r.statusCode) {
  1232. if (fs.existsSync("/var/Bot/prices.json")) {
  1233. ok = JSON.parse(fs.readFileSync("/var/Bot/prices.json"));
  1234. ok = JSON.parse(fs.readFileSync("/var/www/html/prices.json"));
  1235. console.log("[SERVER] Loading Prices - Server sided prices loaded!");
  1236. }
  1237. } else {
  1238. fs.writeFileSync("/var/Bot/prices.json", actual);
  1239. fs.writeFileSync("/var/www/html/prices.json", actual);
  1240. console.log("[SERVER] Loading Prices - API prices loaded!");
  1241. }
  1242. });
  1243. }
  1244.  
  1245. function PriceOfItem(offer)
  1246. {
  1247. var priceItem = 0;
  1248. if (offer) {
  1249. var prices = require('./prices.json');
  1250. priceItem = prices[offer.market_hash_name];
  1251. }
  1252. return priceItem;
  1253. }
  1254.  
  1255. getPriceList();
  1256. setInterval(getPriceList, config.options.priceRefreshInterval * 1000);
  1257.  
  1258.  
  1259. //OFFER SENDING
  1260. function offerItems(steamID)
  1261. {
  1262. var create = manager.createOffer(steamID);
  1263. var itemsToSend = [];
  1264. manager.loadInventory(AppID, ContextID, true, function(err, myItems) {
  1265. for(i = 0; i < myItems.length; i++) {
  1266. create.addMyItem({
  1267. "appid": AppID,
  1268. "contextid": ContextID,
  1269. "assetid": myItems[i].assetid
  1270. });
  1271. }
  1272. create.send(function(err, status) {
  1273. if(err)
  1274. {
  1275. console.log(err);
  1276. return;
  1277. }
  1278. else
  1279. {
  1280. console.log('Offer #' + create.id + " " + status);
  1281. }
  1282. });
  1283. });
  1284. }
  1285.  
  1286.  
  1287.  
  1288. /*
  1289. Offer handling
  1290. */
  1291. function isInArray(value, array) {
  1292. return array.indexOf(value) > -1;
  1293. }
  1294. function acceptOffer(offer) {
  1295. offer.accept((err) => {
  1296. if (err) console.log('Unable to accept offer: ' + err);
  1297. community.checkConfirmations();
  1298. });
  1299. }
  1300.  
  1301. function declineOffer(offer) {
  1302. offer.decline((err) => {
  1303. if (err) return console.log('Unable to decline offer: ' + err);
  1304. });
  1305. }
  1306.  
  1307.  
  1308.  
  1309. //VERIFICARE ACCEPTARE TRADE:
  1310. manager.on('sentOfferChanged', function(offer, oldState) {
  1311. if(offer)
  1312. {
  1313. console.log('Offer #' + offer.id + ' | oldState: ' + oldState + ' | newState: ' + offer.state);
  1314.  
  1315. if(offer.isOurOffer && offer.itemsToReceive.length > 0)
  1316. {
  1317. if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  1318. {
  1319. pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  1320. if(err) throw err;
  1321. if(res[0].winner == -1)
  1322. {
  1323. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  1324. {
  1325. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  1326. type: 'modals',
  1327. tip: 'trade',
  1328. result: 'offerDeclined'
  1329. });
  1330. }
  1331.  
  1332. 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) {
  1333. if(err2) throw err2;
  1334.  
  1335. loadAllGames();
  1336. sendGames(res[0].id);
  1337.  
  1338. console.log('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
  1339. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  1340. });
  1341. }
  1342. });
  1343. }
  1344. else if(oldState == 2 && offer.state == 3)
  1345. {
  1346. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
  1347. {
  1348. var receivedItems = [];
  1349.  
  1350. offer.getReceivedItems(true, function(err, maca) {
  1351. if(err) throw err;
  1352.  
  1353. for(var i in maca)
  1354. {
  1355. receivedItems.push(maca[i].assetid);
  1356. }
  1357.  
  1358. var items = offer.itemsToReceive;
  1359. /*console.log(offer.itemsToReceive);*/
  1360.  
  1361. var totalSkins = 0;
  1362. var skinImages = [];
  1363. var skinNames = [];
  1364. var skinPrices = [];
  1365. var totalPrice = 0;
  1366.  
  1367. for(var i = 0; i < items.length; i++)
  1368. {
  1369. if(items.length == 1)
  1370. {
  1371. totalSkins = 1;
  1372. totalPrice = PriceOfItem(items[i]);
  1373. }
  1374. else
  1375. {
  1376. totalSkins++;
  1377. totalPrice += PriceOfItem(items[i]);
  1378. }
  1379. skinImages.push(items[i].icon_url);
  1380. skinNames.push(items[i].market_hash_name);
  1381. skinPrices.push(PriceOfItem(items[i]));
  1382. }
  1383.  
  1384. //SMECHERIE
  1385. var Skinimages = "";
  1386. var Skinnames = "";
  1387. var Skinprices = "";
  1388. Skinimages = skinImages.join('/');
  1389. Skinnames = skinNames.join('/');
  1390. Skinprices = skinPrices.join('/');
  1391.  
  1392. var timp = new Date();
  1393. var timpCalc = timp.getTime()/1000;
  1394.  
  1395. var name;
  1396. var avatar;
  1397.  
  1398. pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]), function(error, results) {
  1399. if(error) throw error;
  1400.  
  1401. //GENERATE a SECRET
  1402. var hashul = createHash();
  1403.  
  1404. function createHash() {
  1405. var text = "";
  1406. var possible = "0123456789";
  1407.  
  1408. for(var i=0; i < 16; i++)
  1409. text += possible.charAt(Math.floor(Math.random() * possible.length));
  1410.  
  1411. return text;
  1412. }
  1413.  
  1414. if(io.sockets.connected[socketBySteam[depositSteamTrades[depositTrades.indexOf(offer.id)]]['info']])
  1415. {
  1416. io.sockets.connected[socketBySteam[depositSteamTrades[depositTrades.indexOf(offer.id)]]['info']].emit('message', {
  1417. type: 'modals',
  1418. tip: 'trade',
  1419. result: 'offerAccepted'
  1420. });
  1421. }
  1422.  
  1423.  
  1424. pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]), function(haha, huhu) {
  1425. if(haha) throw haha;
  1426. if(huhu.length == 0) return;
  1427.  
  1428. LevelCalculate(depositSteamTrades[depositTrades.indexOf(offer.id)]);
  1429. });
  1430.  
  1431. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  1432.  
  1433. pool.query('INSERT INTO games SET cassetids = ' + pool.escape(receivedItems.join('/')) + ', csteamid = ' + pool.escape(depositSteamTrades[depositTrades.indexOf(offer.id)]) + ', cname = ' + pool.escape(results[0].name) + ', cavatar = ' + pool.escape(results[0].avatar) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul), function(arr, ass) {
  1434. if(arr) throw arr;
  1435.  
  1436. pool.query('SELECT MAX(id) AS cacat FROM games', function(caca, rara) {
  1437. if(caca) throw caca;
  1438.  
  1439. loadAllGames();
  1440. loadStatistics();
  1441. setTimeout(function() {
  1442. loadGames.forEach(function(itm) {
  1443. if(itm.id == rara[0].cacat)
  1444. {
  1445. io.sockets.emit('message', {
  1446. type: 'addGame',
  1447. games: {
  1448. 'id': itm.id,
  1449. 'csteamid': itm.csteamid,
  1450. 'cname': itm.cname,
  1451. 'cavatar': itm.cavatar,
  1452. 'cskinsurl': itm.cskinsurl,
  1453. 'cskinsnames': itm.cskinsnames,
  1454. 'cskinsprices': itm.cskinsprices,
  1455. 'cskins': itm.cskins,
  1456. 'ctp': itm.ctp,
  1457. 'psteamid': itm.psteamid,
  1458. 'pname': itm.pname,
  1459. 'pavatar': itm.pavatar,
  1460. 'pskinsurl': itm.pskinsurl,
  1461. 'pskinsnames': itm.pskinsnames,
  1462. 'pskinsprices': itm.pskinsprices,
  1463. 'pskins': itm.pskins,
  1464. 'ptp': itm.ptp,
  1465. 'hash': itm.hash,
  1466. 'secret': itm.secret,
  1467. 'winner': itm.winner,
  1468. 'timer': timerGame[itm.id]-time(),
  1469. 'timer11': itm.timer11,
  1470. 'ttimer11': timer11Game[itm.id]-time()
  1471. }
  1472. });
  1473. }
  1474. });
  1475. }, 1200);
  1476. });
  1477. });
  1478. });
  1479. });
  1480. }
  1481. else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
  1482. {
  1483. pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  1484. if(err) throw err;
  1485.  
  1486. if(!res[0])
  1487. {
  1488. declineOffer(offer);
  1489. return;
  1490. }
  1491.  
  1492. var receivedItems = [];
  1493.  
  1494. offer.getReceivedItems(true, function(err, caca) {
  1495. if(err) throw err;
  1496.  
  1497. for(var i in caca)
  1498. {
  1499. receivedItems.push(caca[i].assetid);
  1500. }
  1501.  
  1502. pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id));
  1503.  
  1504. //GENERATE a SECRET
  1505. var winner;
  1506. var secret = createSecret();
  1507. var forWinner = (Math.random() * ((res[0].ctp+res[0].ptp) - 0.01) + 0.01).toFixed(2);
  1508.  
  1509. if(forWinner >= 0.01 && forWinner <= res[0].ctp)
  1510. {
  1511. winner = 1;
  1512. logger.info(forWinner + 'winner 1');
  1513. }
  1514. else if(forWinner >= (res[0].ctp+0.01) && forWinner <= (res[0].ctp+res[0].ptp))
  1515. {
  1516. winner = 2;
  1517. logger.info(forWinner + 'winner 2');
  1518. }
  1519. var secret = createSecret();
  1520. function createSecret() {
  1521. var text = "";
  1522. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
  1523.  
  1524. for(var i=0; i < 8; i++)
  1525. text += possible.charAt(Math.floor(Math.random() * possible.length));
  1526.  
  1527. return text;
  1528. }
  1529. var hashul = res[0].hash;
  1530.  
  1531. var secretsihash = secret.concat(hashul);
  1532. pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
  1533. if(aaa) throw aaa;
  1534.  
  1535. pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(res[0].psteamid), function(haha, huhu) {
  1536. if(haha) throw haha;
  1537. if(huhu.length == 0) return;
  1538.  
  1539. LevelCalculate(res[0].psteamid);
  1540. });
  1541.  
  1542. loadAllGames();
  1543. sendGames(res[0].id);
  1544. });
  1545.  
  1546. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  1547.  
  1548. timer11Game[res[0].id] = time()+10;
  1549.  
  1550. if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
  1551. {
  1552. io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
  1553. type: 'modals',
  1554. tip: 'trade',
  1555. result: 'offerAccepted'
  1556. });
  1557. }
  1558.  
  1559. setTimeout(function() {
  1560. pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
  1561. if(errr) throw errr;
  1562.  
  1563. if(winner == 1)
  1564. {
  1565. pool.query('SELECT csteamid AS steamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(arr, ass) {
  1566. if(arr) throw arr;
  1567.  
  1568. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(ass[0].steamid), function(arr2, ass2) {
  1569. if(arr2) throw arr2;
  1570. sendItemsTrade(offer, ass2[0].tradelink, winner);
  1571. });
  1572. });
  1573. }
  1574. else if(winner == 2)
  1575. {
  1576.  
  1577. pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(gamesPending[offer.id]), function(arr2, ass2) {
  1578. if(arr2) throw arr2;
  1579. sendItemsTrade(offer, ass2[0].tradelink, winner);
  1580. });
  1581. }
  1582. });
  1583. }, 11000);
  1584. });
  1585. });
  1586. }
  1587. }
  1588. else if(oldState == 2 && offer.state == 7)
  1589. {
  1590. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  1591. if(caca) throw caca;
  1592. if(maca.length == 0) return;
  1593.  
  1594. if(maca[0].action == 'winning') return;
  1595. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  1596. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  1597. {
  1598. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  1599. type: 'modals',
  1600. tip: 'trade',
  1601. result: 'offerDeclined'
  1602. });
  1603. }
  1604. });
  1605. }
  1606. else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  1607. {
  1608. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  1609. if(caca) throw caca;
  1610. if(maca.length == 0) return;
  1611.  
  1612. if(maca[0].action == 'winning') return;
  1613. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  1614. });
  1615. }
  1616. }
  1617. else if(offer.isOurOffer && offer.itemsToGive.length > 0)
  1618. {
  1619. if((oldState == 2 || oldState == 9) && offer.state == 3)
  1620. {
  1621. if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
  1622. {
  1623. pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  1624. if(caca) throw caca;
  1625. if(maca.length == 0) return;
  1626.  
  1627. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  1628. {
  1629. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  1630. type: 'modals',
  1631. tip: 'trade',
  1632. result: 'offerAccepted'
  1633. });
  1634. }
  1635. pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
  1636. });
  1637. }
  1638. }
  1639. else if((oldState == 2 || oldState == 9) && offer.state == 7)
  1640. {
  1641. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  1642. if(caca) throw caca;
  1643. if(maca.length == 0) return;
  1644.  
  1645. if(maca[0].action == 'winning') return;
  1646. pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
  1647. if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
  1648. {
  1649. io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
  1650. type: 'modals',
  1651. tip: 'trade',
  1652. result: 'offerDeclined'
  1653. });
  1654. }
  1655. });
  1656. }
  1657. else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
  1658. {
  1659. pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
  1660. if(caca) throw caca;
  1661. if(maca.length == 0) return;
  1662.  
  1663. if(maca[0].action == 'winning') return;
  1664. pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
  1665. });
  1666. }
  1667. }
  1668. }
  1669. });
  1670.  
  1671. function sendItemsTrade(offer, link, winner)
  1672. {
  1673. pool.query('SELECT id,cskinsnames,pskinsnames,winner,csteamid,psteamid,cname,pname,cskinsprices,pskinsprices,ctp,ptp,cassetids,passetids FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
  1674. if(err) throw err;
  1675.  
  1676. setTimeout(function() {
  1677. hideGame(res[0].id);
  1678. }, 60000);
  1679.  
  1680. var ItemsRake = [];
  1681.  
  1682. var Skins1Names = res[0].cskinsnames.split('/');
  1683. var Skins2Names = res[0].pskinsnames.split('/');
  1684. var TotalSkinsNames = Skins1Names.concat(Skins2Names);
  1685.  
  1686. var Skins1 = res[0].cassetids.split('/');
  1687. var Skins2 = res[0].passetids.split('/');
  1688. var allSkins = Skins1.concat(Skins2);
  1689.  
  1690. var Prices1 = res[0].cskinsprices.split('/');
  1691. var Prices2 = res[0].pskinsprices.split('/');
  1692. var allPrices = Prices1.concat(Prices2);
  1693.  
  1694. var itemsDB = [];
  1695.  
  1696. for(var i in allSkins)
  1697. {
  1698. ItemsRake.push({
  1699. assetid: allSkins[i],
  1700. price: allPrices[i]
  1701. });
  1702. }
  1703.  
  1704. ItemsRake.sort(compare);
  1705.  
  1706. function compare(a,b) {
  1707. if (a.price < b.price)
  1708. return -1;
  1709. if (a.price > b.price)
  1710. return 1;
  1711. return 0;
  1712. }
  1713.  
  1714. if(ItemsRake.length == 4)
  1715. {
  1716. if(res[0].ctp+res[0].ptp >= 7)
  1717. {
  1718. ItemsRake.shift();
  1719. }
  1720. }
  1721. if(ItemsRake.length >= 5 && ItemsRake.length <= 7)
  1722. {
  1723. if(res[0].ctp+res[0].ptp >= 7)
  1724. {
  1725. ItemsRake.shift();
  1726. }
  1727. else
  1728. {
  1729. ItemsRake.shift();
  1730. ItemsRake.shift();
  1731. }
  1732. }
  1733. else if(ItemsRake.length >= 8 && ItemsRake.length <= 12)
  1734. {
  1735. if(res[0].ctp+res[0].ptp >= 7)
  1736. {
  1737. ItemsRake.shift();
  1738. }
  1739. else
  1740. {
  1741. ItemsRake.shift();
  1742. ItemsRake.shift();
  1743. }
  1744. }
  1745. else if(ItemsRake.length >= 13 && ItemsRake.length <= 17)
  1746. {
  1747. if(res[0].ctp+res[0].ptp >= 7)
  1748. {
  1749. ItemsRake.shift();
  1750. }
  1751. else
  1752. {
  1753. ItemsRake.shift();
  1754. ItemsRake.shift();
  1755. }
  1756. }
  1757. else if(ItemsRake.length >= 18)
  1758. {
  1759. if(res[0].ctp+res[0].ptp >= 7)
  1760. {
  1761. ItemsRake.shift();
  1762. }
  1763. else
  1764. {
  1765. ItemsRake.shift();
  1766. ItemsRake.shift();
  1767. }
  1768. }
  1769.  
  1770. for(var i in ItemsRake)
  1771. {
  1772. itemsDB.push(ItemsRake[i].assetid);
  1773. }
  1774.  
  1775. var partner;
  1776. if(winner == 1)
  1777. {
  1778. partner = res[0].csteamid;
  1779. }
  1780. else if(winner == 2)
  1781. {
  1782. partner = res[0].psteamid;
  1783. }
  1784.  
  1785. var create = manager.createOffer(partner, link.split('token=')[1]);
  1786. for(var i in itemsDB)
  1787. {
  1788. create.addMyItem({
  1789. "appid": AppID,
  1790. "contextid": ContextID,
  1791. "assetid": itemsDB[i]
  1792. });
  1793. }
  1794.  
  1795. var cod = makeCode();
  1796. create.setMessage('W: ' + cod);
  1797. create.send(function(err, status) {
  1798. if(err)
  1799. {
  1800. console.log(err);
  1801. return;
  1802. }
  1803. else
  1804. {
  1805. var WSteamid;
  1806. var WName;
  1807. pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
  1808. if(winner == 1)
  1809. {
  1810. WSteamid = res[0].csteamid;
  1811. WName = res[0].cname;
  1812. }
  1813. else if(winner == 2)
  1814. {
  1815. WSteamid = res[0].psteamid;
  1816. WName = res[0].pname;
  1817. }
  1818. console.log('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
  1819.  
  1820. tradingRequests[create.id] = {
  1821. action: 'winning',
  1822. user: WSteamid
  1823. };
  1824.  
  1825. 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('/')));
  1826.  
  1827. if(gamesPending.hasOwnProperty(offer.id))
  1828. {
  1829. delete gamesPending[offer.id];
  1830. }
  1831. }
  1832. });
  1833.  
  1834. loadAllGames();
  1835. sendGames(res[0].id);
  1836.  
  1837. setTimeout(function() {
  1838. loadStatistics();
  1839. }, 5000);
  1840. });
  1841. }
  1842.  
  1843. //Refresh polldata.json
  1844. manager.on('pollData', function(pollData) {
  1845. fs.writeFile('polldata.json', JSON.stringify(pollData));
  1846. });
  1847.  
  1848. if (fs.existsSync('polldata.json')) {
  1849. manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
  1850. }
  1851.  
  1852. /*client.on('loggedOn', function(details) {
  1853. console.log('Logged into Steam as ' + client.steamID.getSteam3RenderedID());
  1854. client.setPersona(SteamUser.Steam.EPersonaState.Online,config.botname);
  1855. client.gamesPlayed([AppID])
  1856. });*/
  1857.  
  1858. client.on('webSession', function(sessionID, cookies) {
  1859. manager.setCookies(cookies, function(err) {
  1860. if (err) return console.log(err);
  1861. console.log('Got API key: ' + manager.apiKey);
  1862. app.listen(3030);
  1863. });
  1864.  
  1865. community.setCookies(cookies);
  1866. community.startConfirmationChecker(config.options.confirmationInterval, config.bots[0].identitySecret);
  1867. });
  1868.  
  1869.  
  1870.  
  1871. function time()
  1872. {
  1873. return parseInt(new Date().getTime()/1000);
  1874. }
  1875.  
  1876. function addHistory(socket)
  1877. {
  1878. chatMessages.forEach(function(itm) {
  1879. socket.emit('message', {
  1880. type: 'addMessage',
  1881. msg: itm.message,
  1882. avatar: itm.avatar,
  1883. steamid: itm.steamid,
  1884. rank: itm.rank,
  1885. hide: itm.hide,
  1886. level: itm.level,
  1887. name: itm.name
  1888. });
  1889. })
  1890. }
  1891.  
  1892. function makeCode() {
  1893. var text = "";
  1894. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  1895.  
  1896. for(var i=0; i < 6; i++)
  1897. text += possible.charAt(Math.floor(Math.random() * possible.length));
  1898.  
  1899. return text;
  1900. }
  1901.  
  1902. function getProxy()
  1903. {
  1904. return "http://" + proxies[random(0,proxies.length-1)];
  1905. }
  1906.  
  1907. function random(min, max) {
  1908. return Math.floor(Math.random() * (max - min + 1)) + min;
  1909. }
  1910.  
  1911. function getInv(user, socket)
  1912. {
  1913. var pret = require('./prices.json');
  1914.  
  1915. var reqOpts = {
  1916. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
  1917. };
  1918.  
  1919. request(reqOpts, function(err, response, body) {
  1920. if(err) throw err;
  1921. if(response && response.statusCode == 200)
  1922. {
  1923. var bodiul = JSON.parse(body);
  1924.  
  1925. var assets = bodiul['assets'];
  1926. var descriptions = bodiul['descriptions'];
  1927.  
  1928. var counter = 0;
  1929.  
  1930. var idss = [];
  1931. var namess = [];
  1932. var pricess = [];
  1933. var imgss = [];
  1934.  
  1935. var Ids = '';
  1936. var Names = '';
  1937. var Prices = '';
  1938. var Imgs = '';
  1939.  
  1940. if(!assets) return;
  1941.  
  1942. assets.forEach(function(valuey, y) {
  1943. descriptions.forEach(function(valuez, z) {
  1944. if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
  1945. {
  1946. var isTradable = valuez['tradable'];
  1947. if(isTradable == 1)
  1948. {
  1949. if(/(Souvenir)/.exec(valuez['market_hash_name'])) return;
  1950.  
  1951. var id = valuey['assetid'];
  1952.  
  1953. var name = valuez['market_hash_name'];
  1954. var price = pret[valuez['market_hash_name']];
  1955. var img = valuez['icon_url'];
  1956.  
  1957. if(price >= minDep)
  1958. {
  1959. idss.push(id);
  1960. namess.push(name);
  1961. pricess.push(price);
  1962. imgss.push(img);
  1963. }
  1964. }
  1965. }
  1966. });
  1967. });
  1968.  
  1969. Ids = idss.join('/');
  1970. Names = namess.join('/');
  1971. Prices = pricess.join('/');
  1972. Imgs = imgss.join('/');
  1973.  
  1974. socket.emit('message', {
  1975. type: 'getInventory',
  1976. id: Ids,
  1977. name: Names,
  1978. price: Prices,
  1979. img: Imgs
  1980. });
  1981.  
  1982. inventoryUser[user] = {
  1983. id: Ids,
  1984. name: Names,
  1985. price: Prices,
  1986. img: Imgs
  1987. }
  1988. }
  1989. else
  1990. {
  1991.  
  1992. }
  1993. });
  1994. }
  1995.  
  1996.  
  1997. function getInv2(user, socket)
  1998. {
  1999. var pret = require('./prices.json');
  2000.  
  2001. var reqOpts = {
  2002. url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
  2003. };
  2004.  
  2005. request(reqOpts, function(err, response, body) {
  2006. if(err) throw err;
  2007. if(response && response.statusCode == 200)
  2008. {
  2009. var bodiul = JSON.parse(body);
  2010.  
  2011. var assets = bodiul['assets'];
  2012. var descriptions = bodiul['descriptions'];
  2013.  
  2014. var counter = 0;
  2015.  
  2016. var idss = [];
  2017. var namess = [];
  2018. var pricess = [];
  2019. var imgss = [];
  2020.  
  2021. var Ids = '';
  2022. var Names = '';
  2023. var Prices = '';
  2024. var Imgs = '';
  2025.  
  2026. var Gamess = [];
  2027.  
  2028. if(!assets) return;
  2029.  
  2030. assets.forEach(function(valuey, y) {
  2031. descriptions.forEach(function(valuez, z) {
  2032. if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
  2033. {
  2034. var isTradable = valuez['tradable'];
  2035. if(isTradable == 1)
  2036. {
  2037. if(/(Souvenir)/.exec(valuez['market_hash_name'])) return;
  2038.  
  2039. var id = valuey['assetid'];
  2040.  
  2041. var name = valuez['market_hash_name'];
  2042. var price = pret[valuez['market_hash_name']];
  2043. var img = valuez['icon_url'];
  2044.  
  2045. if(price >= minDep)
  2046. {
  2047. idss.push(id);
  2048. namess.push(name);
  2049. pricess.push(price);
  2050. imgss.push(img);
  2051. }
  2052. }
  2053. }
  2054. });
  2055. });
  2056.  
  2057. Ids = idss.join('/');
  2058. Names = namess.join('/');
  2059. Prices = pricess.join('/');
  2060. Imgs = imgss.join('/');
  2061.  
  2062. socket.emit('message', {
  2063. type: 'getInventory2',
  2064. id: Ids,
  2065. name: Names,
  2066. price: Prices,
  2067. img: Imgs
  2068. });
  2069.  
  2070. inventoryUser[user] = {
  2071. id: Ids,
  2072. name: Names,
  2073. price: Prices,
  2074. img: Imgs
  2075. }
  2076. }
  2077. else
  2078. {
  2079.  
  2080. }
  2081. });
  2082. }
  2083.  
  2084. function loadStatistics(socket)
  2085. {
  2086. var totalAmount = 0;
  2087. var totalItems = 0;
  2088. var activeGames = 0;
  2089.  
  2090. pool.query('SELECT SUM(`ctp`) AS `totalAmount`, SUM(`cskins`) AS `totalItems`, COUNT(`id`) AS `activeGames` FROM games WHERE `winner` = -1', function(error, res) {
  2091. if(error) throw error;
  2092.  
  2093. if(res.length == 0)
  2094. {
  2095. totalAmount = 0;
  2096. totalItems = 0;
  2097. activeGames = 0;
  2098.  
  2099. if(!socket)
  2100. {
  2101. io.sockets.emit('message', {
  2102. type: 'loadStatistics',
  2103. totalAmount: totalAmount,
  2104. totalItems: totalItems,
  2105. activeGames: activeGames
  2106. });
  2107. }
  2108. else
  2109. {
  2110. socket.emit('message', {
  2111. type: 'loadStatistics',
  2112. totalAmount: totalAmount,
  2113. totalItems: totalItems,
  2114. activeGames: activeGames
  2115. });
  2116. }
  2117. }
  2118.  
  2119. if(res.length > 0)
  2120. {
  2121. totalAmount = res[0].totalAmount;
  2122. totalItems = res[0].totalItems;
  2123. activeGames = res[0].activeGames;
  2124.  
  2125. if(totalAmount == null)
  2126. {
  2127. totalAmount = 0;
  2128. }
  2129. if(totalItems == null)
  2130. {
  2131. totalItems = 0;
  2132. }
  2133. if(activeGames == null)
  2134. {
  2135. activeGames = 0;
  2136. }
  2137.  
  2138. if(!socket)
  2139. {
  2140. io.sockets.emit('message', {
  2141. type: 'loadStatistics',
  2142. totalAmount: totalAmount,
  2143. totalItems: totalItems,
  2144. activeGames: activeGames
  2145. });
  2146. }
  2147. else
  2148. {
  2149. socket.emit('message', {
  2150. type: 'loadStatistics',
  2151. totalAmount: totalAmount,
  2152. totalItems: totalItems,
  2153. activeGames: activeGames
  2154. });
  2155. }
  2156. }
  2157. });
  2158. }
  2159.  
  2160. function sendGames(gameID)
  2161. {
  2162. setTimeout(function() {
  2163. for(var i in loadGames)
  2164. {
  2165. if(loadGames[i].id == gameID)
  2166. {
  2167. timerGame[loadGames[i].id] = time()+90;
  2168.  
  2169. io.sockets.emit('message', {
  2170. type: 'editGame',
  2171. games: {
  2172. 'id': loadGames[i].id,
  2173. 'csteamid': loadGames[i].csteamid,
  2174. 'cname': loadGames[i].cname,
  2175. 'cavatar': loadGames[i].cavatar,
  2176. 'cskinsurl': loadGames[i].cskinsurl,
  2177. 'cskinsnames': loadGames[i].cskinsnames,
  2178. 'cskinsprices': loadGames[i].cskinsprices,
  2179. 'cskins': loadGames[i].cskins,
  2180. 'ctp': loadGames[i].ctp,
  2181. 'psteamid': loadGames[i].psteamid,
  2182. 'pname': loadGames[i].pname,
  2183. 'pavatar': loadGames[i].pavatar,
  2184. 'pskinsurl': loadGames[i].pskinsurl,
  2185. 'pskinsnames': loadGames[i].pskinsnames,
  2186. 'pskinsprices': loadGames[i].pskinsprices,
  2187. 'pskins': loadGames[i].pskins,
  2188. 'ptp': loadGames[i].ptp,
  2189. 'hash': loadGames[i].hash,
  2190. 'secret': loadGames[i].secret,
  2191. 'winner': loadGames[i].winner,
  2192. 'timer': timerGame[loadGames[i].id]-time(),
  2193. 'timer11': loadGames[i].timer11,
  2194. 'ttimer11': timer11Game[loadGames[i].id]-time(),
  2195. }
  2196. });
  2197.  
  2198. io.sockets.emit('message', {
  2199. type: 'watchCF',
  2200. id: loadGames[i].id,
  2201. csteamid: loadGames[i].csteamid,
  2202. cname: loadGames[i].cname,
  2203. cavatar: loadGames[i].cavatar,
  2204. cskinsurl: loadGames[i].cskinsurl,
  2205. cskinsnames: loadGames[i].cskinsnames,
  2206. cskinsprices: loadGames[i].cskinsprices,
  2207. cskins: loadGames[i].cskins,
  2208. ctp: loadGames[i].ctp,
  2209. psteamid: loadGames[i].psteamid,
  2210. pname: loadGames[i].pname,
  2211. pavatar: loadGames[i].pavatar,
  2212. pskinsurl: loadGames[i].pskinsurl,
  2213. pskinsnames: loadGames[i].pskinsnames,
  2214. pskinsprices: loadGames[i].pskinsprices,
  2215. pskins: loadGames[i].pskins,
  2216. ptp: loadGames[i].ptp,
  2217. hash: loadGames[i].hash,
  2218. secret: loadGames[i].secret,
  2219. winner: loadGames[i].winner,
  2220. timer: timerGame[loadGames[i].id]-time(),
  2221. timer11: loadGames[i].timer11,
  2222. ttimer11: timer11Game[loadGames[i].id]-time(),
  2223. gameNumber: loadGames[i].id
  2224. });
  2225. }
  2226. }
  2227. }, 1000);
  2228. }
  2229.  
  2230. function LevelCalculate(user)
  2231. {
  2232. pool.query('SELECT xp,level FROM users WHERE steamid = ' + pool.escape(user), function(err, row) {
  2233. if(err) throw err;
  2234. if(row.length == 0) return;
  2235.  
  2236. var currentLevel = row[0].level;
  2237.  
  2238. var currentXp = row[0].xp;
  2239. var xpNeeded = 0;
  2240. var xpMinus = 0;
  2241.  
  2242. for(var i = 1; i < 500; i++)
  2243. {
  2244. xpNeeded += 40 * i;
  2245. xpMinus = xpNeeded - (40 * i-1);
  2246. if(currentXp >= xpMinus && currentXp <= xpNeeded)
  2247. {
  2248. pool.query('UPDATE users SET level = ' + pool.escape(i) + ' WHERE steamid = ' + pool.escape(user));
  2249. }
  2250. }
  2251. });
  2252. }
  2253.  
  2254. function getRandomFloat(min, max) {
  2255. return (Math.random() * (max - min) + min).toFixed(10);
  2256. }
  2257.  
  2258. function handleDisconnect() {
  2259. pool = mysql.createConnection(db_config);
  2260.  
  2261. pool.connect(function(err) {
  2262. if(err) {
  2263. //logger.trace('Error: Connecting to database: ', err);
  2264. setTimeout(handleDisconnect, 2000);
  2265. }
  2266. });
  2267.  
  2268. pool.on('error', function(err) {
  2269. //logger.trace('Error: Database error: ', err);
  2270. if(err.code === 'PROTOCOL_CONNECTION_LOST') {
  2271. handleDisconnect();
  2272. } else {
  2273. throw err;
  2274. }
  2275. });
  2276. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement