Advertisement
Guest User

Untitled

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