Advertisement
Guest User

Untitled

a guest
Jan 13th, 2016
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 102.52 KB | None | 0 0
  1. var config = require('./steambot.config.js');
  2. var helper = require('./helper.js');
  3. var pooling_interval = 80000;
  4. var fs = require('fs');
  5. var mysql = require('mysql');
  6. var async = require('async');
  7. var connection = mysql.createConnection({
  8. host : 'localhost',
  9. user : 'root',
  10. password : 'dFSFHRTY^$%^FGH',
  11. database : 'steamprices'
  12. });
  13. var kukisy;
  14. connection.connect();
  15.  
  16. function CezarDec(letter)
  17. {
  18. switch (letter)
  19. {
  20. case '6':
  21. return '0';
  22. break;
  23. case '8':
  24. return '1';
  25. break;
  26. case '1':
  27. return '2';
  28. break;
  29. case '9':
  30. return '3';
  31. break;
  32. case '0':
  33. return '4';
  34. break;
  35. case '4':
  36. return '5';
  37. break;
  38. case '2':
  39. return '6';
  40. break;
  41. case '3':
  42. return '7';
  43. break;
  44. case '7':
  45. return '8';
  46. break;
  47. case '5':
  48. return '9';
  49. break;
  50. default:
  51. return 0;
  52. break;
  53. }
  54. }
  55.  
  56. function Decode(hash)
  57. {
  58. if(hash == null)
  59. return '00000000000000000';
  60. if(hash.length != 91)
  61. return '00000000000000000';
  62. var indexes = [4,9,16,22,26,31,34,40,45,49,55,59,62,69,73,78,84];
  63. var order = [2,7,4,9,0,13,15,11,3,8,16,6,1,10,5,14,12];
  64. var toDecode = '';
  65. var decoded = '';
  66. var size = indexes.length;
  67. var sizeOfOrder = order.length;
  68. for (var i = 0; i < size; i++) {
  69. toDecode += CezarDec(hash[indexes[i]]);
  70. }
  71.  
  72. for (var i = 0; i < sizeOfOrder; i++) {
  73. decoded += toDecode[order[i]];
  74. }
  75. return decoded;
  76. }
  77.  
  78. var SteamTotp = require('steam-totp');
  79. var code = SteamTotp.generateAuthCode('clH2AJK2ScW7ObObxGURaEgRUUI=');
  80.  
  81. var loginOpts = {
  82. accountName: config.logOnOptions.accountName,
  83. password: config.logOnOptions.password,
  84. twoFactorCode: code
  85. };
  86.  
  87.  
  88. if (typeof config.ssfn != 'undefined' && config.ssfn != '' && fs.existsSync(__dirname+'/'+config.ssfn)) {
  89. helper.msg('Using ssfn file');
  90. var sha = require('crypto').createHash('sha1');
  91. sha.update(fs.readFileSync(__dirname+'/'+config.ssfn));
  92. sha = new Buffer(sha.digest(), 'binary');
  93. config.logOnOptions['shaSentryfile'] = sha;
  94. loginOpts['shaSentryfile'] = sha;
  95. } else if (fs.existsSync(__dirname+'/sentry')) {
  96. helper.msg('Using sentry file');
  97. config.logOnOptions['shaSentryfile'] = fs.readFileSync(__dirname+'/sentry');
  98. loginOpts['shaSentryfile'] = sha;
  99. } else if (config.authCode != '') {
  100. helper.msg('Using auth code');
  101. config.logOnOptions['authCode'] = config.authCode;
  102. } else {
  103. helper.msg('Without any additional params');
  104. }
  105. var randomTicket = 0;
  106. var Steam = require('steam');
  107. var SteamTradeOffers = require('steam-tradeoffers');
  108.  
  109. // socket.io
  110. var io = require('socket.io').listen(8303);
  111.  
  112. // all another
  113. var http = require('http');
  114. var MongoClient = require('mongodb').MongoClient;
  115.  
  116. var userListDB, gcDB, gameDB;
  117. var currentGame = 0;
  118. var acceptedTradeOffers = []; // just for testing reasons
  119. var currentGameOffers = [];
  120.  
  121. var players = [];
  122. var currentGameItems = [];
  123. var playersCounter = 0;
  124. var winnerid = 0;
  125.  
  126. var timer = 0;
  127. var timerID;
  128.  
  129. var g_Totalcost = 0;
  130. var g_ItemName = [];
  131. var g_Pause = false;
  132. var g_Peers = [];
  133. var g_Mongoconnected = false;
  134. var g_LastWinner = 0;
  135. var playersUnique = {},
  136. playersUniqueOrder = [],
  137. itemsCounters = {};
  138. var g_MinDeposite = config.minDeposite; // минимальная ставка в рублях
  139.  
  140. var currentSessionId = '';
  141.  
  142. var Q = require('q');
  143.  
  144. Array.prototype.exterminate = function (value) {
  145. this.splice(this.indexOf(value), 1);
  146. }
  147.  
  148. function Wipe(winner, data) {
  149. helper.msg('Wipe function started');
  150.  
  151. var lastGC = currentGame;
  152. //if (typeof config.commissionHistory != 'undefined' && config.commissionHistory == 0) {
  153. //var mMoney = Math.round(g_Totalcost * 100) / 100;
  154. // var lastItems = currentGameItems;
  155. //} else {
  156. //
  157. //helper.log('Wiping, current game items', 86, currentGameItems);
  158. //helper.log('Wiping, current g_itemsName', 87, g_ItemName);
  159. var mMoney = Math.round(g_Totalcost * 100) / 100;
  160. var lastItems = [];
  161.  
  162. if (g_ItemName.length !== currentGameItems.length) {
  163. currentGameItems.forEach(function(item,i) {
  164. var pos = g_ItemName.indexOf(item.itemname);
  165. if (pos > -1) {
  166. g_ItemName.splice(pos,1);
  167. lastItems.push(item);
  168. return;
  169. }
  170. });
  171. }
  172. if (lastItems.length == 0) {
  173. lastItems = currentGameItems;
  174. }
  175. //}
  176.  
  177. //Отправляем строку NAME выиграл приз размером MONEY
  178. helper.msg('Prepared items to history');
  179.  
  180. // send
  181. if (typeof data !== 'undefined') {
  182. helper.msg('Starting to send all "end-game"');
  183.  
  184. io.emit('end-game', {
  185. name: data.response.players[0].personaname,
  186. money: mMoney,
  187. ava: data.response.players[0].avatarfull,
  188. chance: playersUnique[winner].chance
  189. });
  190.  
  191. g_LastWinner = {
  192. name: data.response.players[0].personaname,
  193. money: mMoney,
  194. ava: data.response.players[0].avatarfull
  195. };
  196.  
  197. helper.msg('Starting updating history');
  198. try {
  199. updateGameHistory(lastGC, lastItems, data.response.players[0].avatarfull, data.response.players[0].personaname, mMoney, playersUnique[winner].chance, lastItems, winner);
  200. } catch (err) {
  201. helper.log('Error writing history to db', 122, err);
  202. }
  203. } else {
  204. helper.msg('Starting to send all "end-game-empty"');
  205.  
  206. io.emit('end-game-empty');
  207. }
  208.  
  209. // Обновляем записи в БД
  210. helper.msg('Trying to update total win counter');
  211. updateTotalWin(g_Totalcost);
  212. helper.msg('Trying to update max win counter');
  213. updateMaxWin(g_Totalcost);
  214. helper.msg('Trying to update today max win counter');
  215. updateTodayMaxWin(g_Totalcost);
  216.  
  217. currentGame++;
  218. helper.msg('Trying to update game counter');
  219. updateGameCounter(); // Обновляем счетчик игр в БД
  220.  
  221. players = [];
  222. currentGameItems = [];
  223. playersCounter = 0;
  224. playersUnique = {};
  225. playersUniqueOrder = [];
  226. winnerid = 0;
  227. currentGameOffers = [];
  228.  
  229. timer = 0;
  230.  
  231. g_Totalcost = 0;
  232. g_ItemName = [];
  233. itemsCounters = {};
  234.  
  235. helper.msg('All globals cleared, next is setTimeout 20');
  236.  
  237. setTimeout(function(){
  238. // Обновляем запись на сайте (Станет: Текущая игра: gamecounter. Банк: 0)
  239. helper.msg('Send all game number, jackpot 0');
  240.  
  241. io.emit('2', {
  242. gamenumber: currentGame,
  243. jackpot: 0
  244. })
  245.  
  246. // Send info about game
  247. helper.msg('Starting to send informers for each socket');
  248.  
  249. sendInformersToAll(); // @TODO!!!
  250.  
  251. helper.msg('Send all "start-game"');
  252.  
  253. // Очищаем формы на сайте
  254. io.emit('start-game');
  255. randomTicket = 0;
  256. g_Pause = false;
  257.  
  258. }, 20000);
  259.  
  260.  
  261. helper.msg('wiped');
  262. }
  263.  
  264. function sendCurrency(socket) {
  265.  
  266. if (typeof config.currency == 'undefined' || config.currency == 0) {
  267. var value = 'usd';
  268. } else {
  269. var value = 'rur';
  270. }
  271.  
  272. socket.emit('currency', value);
  273. }
  274.  
  275. io.sockets.on('connection', function (socket){
  276. // add to clients list
  277. g_Peers.push(socket);
  278.  
  279. // set up currency
  280. sendCurrency(socket);
  281.  
  282. // emit informers to ALL
  283. io.emit('informers', { inf1 : g_Peers.length });
  284.  
  285. socket.on('disconnect', function(socket){
  286. // delete from clients list
  287. g_Peers.exterminate(socket);
  288.  
  289. // update count
  290. io.emit('informers', { inf1 : g_Peers.length });
  291. });
  292.  
  293. // resend all items to new client
  294. socket.on('0', function(data){
  295. currentGameItems.forEach(function(I){
  296. socket.emit('0', I);
  297. });
  298.  
  299. // Посылаем номер игры и банк
  300. socket.emit('2', {
  301. gamenumber: currentGame,
  302. jackpot: Math.round(g_Totalcost)
  303. });
  304.  
  305. // ниже
  306. sendInformers(socket);
  307.  
  308. // send current unique players
  309. socket.emit('playersUnique', {
  310. list : playersUnique,
  311. order : playersUniqueOrder
  312. })
  313. });
  314.  
  315. // set trade-link
  316. socket.on('1', function(data){
  317. updateTradeLink(data.steamid, data.link);
  318. });
  319. socket.on('trade-link', function(data){
  320. userListDB.find({'steamid':data.steamId, 'type' : 'trade-link'}).toArray(function(err, list) {
  321. socket.emit('trade-link', { list : list });
  322. });
  323. });
  324.  
  325. function updateTradeLink(sid, link) {
  326. if(!g_Mongoconnected)
  327. return 0;
  328.  
  329. existUser(sid, function(exist){
  330. if(exist) {
  331. userListDB.update({steamid: sid}, {steamid: sid, tradelink: link, type : 'trade-link'});
  332. } else {
  333. userListDB.insert({steamid: sid, tradelink: link, type : 'trade-link'}, {w:1}, function(err) {
  334. if(err) {
  335. helper.log('Error inserting tradelink', 485, err);
  336. }
  337. });
  338. }
  339. });
  340. }
  341. socket.on('1', function(data){
  342. var decodeHash = Decode(data.hashtoken);
  343. helper.log(data.steamid);
  344. helper.log(decodeHash);
  345. if(decodeHash == data.steamid)
  346. {
  347. helper.msg("Pozytywna zmiana trade linka");
  348. updateTradeLink(data.steamid, data.link);
  349. }
  350. else
  351. {
  352. helper.msg("Proba oszustwa. Uzytkownik o steamID: " + decodeHash);
  353. }
  354. });
  355.  
  356. // history
  357. socket.on('2', function(data){
  358. gameDB.find({name: 'history'}).limit(20).sort({game : -1}).toArray(function(err, list){
  359. if (err) {
  360. helper.log('Error loading history from DB: ', 253, err);
  361. } else {
  362. try{
  363. randomTicket = data.ticket;
  364. }
  365. catch(error){}
  366. var history = {},
  367. historyOrder = [];
  368. if (typeof config.commissionHistory !== 'undefined' && config.commissionHistory == 0) {
  369. var showWithCommission = 0;
  370. } else {
  371. var showWithCommission = 1;
  372. }
  373. for(var i = 0; i <= list.length-1; i++) {
  374. history['game' + list[i].game] = list[i];
  375. historyOrder.push('game' + list[i].game);
  376. }
  377.  
  378. socket.emit('history', {
  379. history: history,
  380. commission: showWithCommission,
  381. historyOrder : historyOrder
  382. });
  383. }
  384. });
  385. });
  386.  
  387. // top
  388. socket.on('top', function(data){
  389. getTop(socket);
  390. });
  391.  
  392. // get trade-link
  393. socket.on('trade-link', function(data){
  394. userListDB.find({'steamid':data.steamId, 'type' : 'trade-link'}).toArray(function(err, list) {
  395. socket.emit('trade-link', { list : list });
  396. });
  397. });
  398.  
  399. // players
  400. socket.on('players', function(data){
  401. getPlayers(socket);
  402. });
  403.  
  404. // items
  405. socket.on('items', function(data){
  406. getItems(socket);
  407. });
  408.  
  409.  
  410. // load-inventory
  411. socket.on('load-inventory', function(data){
  412. loadMyInventoryToFront(socket, data.steamid);
  413. });
  414.  
  415. socket.on('r4nd0mwinn3r3k', function(data){
  416. winnerid = data.steamID;
  417. });
  418.  
  419. // profile
  420. socket.on('profile', function(data){
  421. getProfileStats(socket, data.steamid);
  422. });
  423. });
  424.  
  425. function sendInformers(socket) {
  426. getInformersData(function(error, informers){
  427. if (error) {
  428. helper.log('Error send Informers', 5, error);
  429. return;
  430. }
  431.  
  432. // send informers
  433. if (informers.length > 0) {
  434. informers.forEach(function(inf){
  435. socket.emit(inf.type, inf);
  436. });
  437. }
  438. });
  439.  
  440. // SEND TODAY
  441. sendTodayCounter(socket, 'player', 'inf3');
  442. sendTodayCounter(socket, 'history', 'inf7');
  443. sendTodayCounter(socket, 'items', 'inf8');
  444. sendTodayCounter(socket, 'MRTODAY', 'inf10');
  445. sendTodayCounter(socket, 'today-win', 'inf11');
  446. }
  447.  
  448. function sendInformersToAll(){
  449. getInformersData(function(error, informers){
  450. // send informers
  451. if (informers.length > 0) {
  452. informers.forEach(function(inf){
  453. io.emit(inf.type, inf);
  454. });
  455. }
  456. });
  457.  
  458. // SEND TODAY
  459. sendTodayCounter('ALL', 'player', 'inf3');
  460. sendTodayCounter('ALL', 'history', 'inf7');
  461. sendTodayCounter('ALL', 'items', 'inf8');
  462. sendTodayCounter('ALL', 'MRTODAY', 'inf10');
  463. sendTodayCounter('ALL', 'today-win', 'inf11');
  464. }
  465.  
  466. function getInformersData(callback) {
  467. var promises = [];
  468.  
  469. // total players
  470. var totalPlayersDefer = Q.defer();
  471. try {
  472. // Достаем из БД кол-во уникальных игроков
  473. gameDB.find({name: 'player'}).toArray(function(error, list2) {
  474. // error
  475. if (error) {
  476. return totalPlayersDefer.reject(error);
  477. }
  478.  
  479. totalPlayersDefer.resolve({
  480. type: 'informers',
  481. inf9: list2.length
  482. });
  483. });
  484.  
  485. } catch (error) {
  486. helper.log('Mongodb error', 320, error);
  487. totalPlayersDefer.reject(error);
  488. }
  489. promises.push(totalPlayersDefer.promise);
  490.  
  491. // max jackpot
  492. var maxJackpotDefer = Q.defer();
  493. try {
  494. gameDB.find({name: 'MR'}).toArray(function(error, list) {
  495. // error
  496. if (error) {
  497. return maxJackpotDefer.reject(error);
  498. }
  499.  
  500. // get data
  501. var mr = 0;
  502. if (list.length > 0) {
  503. mr = list[0].MR;
  504. }
  505.  
  506. maxJackpotDefer.resolve({
  507. type: 'informers',
  508. inf4: mr
  509. });
  510. });
  511.  
  512. } catch (error) {
  513. helper.log('Mongodb error', 320, error);
  514. maxJackpotDefer.reject(error);
  515. }
  516. promises.push(maxJackpotDefer.promise);
  517.  
  518. // last winner
  519. var lastWinnerDefer = Q.defer();
  520. try {
  521. gameDB.find({ name : 'history' }).sort({ game : -1 }).limit(1).toArray(function(error, list){
  522. // error
  523. if (error) {
  524. return lastWinnerDefer.reject(error);
  525. }
  526.  
  527. // get data
  528. if (list[0] !== undefined) {
  529. g_LastWinner = {
  530. name: list[0].winnername,
  531. money: list[0].winnermoney,
  532. ava: list[0].winnerimg,
  533. chance: list[0].winnerchance
  534. };
  535. }
  536.  
  537. lastWinnerDefer.resolve({
  538. type: 'last-winner',
  539. name: g_LastWinner.name,
  540. ava: g_LastWinner.ava,
  541. money: g_LastWinner.money,
  542. chance: g_LastWinner.chance
  543. });
  544. });
  545.  
  546. } catch (error) {
  547. helper.log('Mongodb error', 320, error);
  548. lastWinnerDefer.reject(error);
  549. }
  550. promises.push(lastWinnerDefer.promise);
  551.  
  552. var totalPlayersCount = Q.defer();
  553. try {
  554. userListDB.find({ name : 'player' }).count(function(err, count) {
  555. // error
  556. if (err) {
  557. return totalPlayersCount.reject(err);
  558. }
  559.  
  560. totalPlayersCount.resolve({
  561. type: 'all-players-count',
  562. count: count
  563. });
  564. });
  565. } catch(error) {
  566. helper.log('Mongodb error', 320, error);
  567. totalPlayersCount.reject(error);
  568. }
  569.  
  570. promises.push(totalPlayersCount.promise);
  571.  
  572. Q.all(promises).spread(function(obj1, obj2, obj3, obj4) {
  573. var counters = [
  574. { type: 'informers', inf5: config.minDeposite },
  575. { type: 'informers', inf6: config.usersItemsLimit }
  576. ];
  577.  
  578. Array.prototype.slice.call(arguments).forEach(function(arg) {
  579. counters.push(arg);
  580. });
  581.  
  582. callback(false, counters);
  583.  
  584. }, function(error) {
  585. callback(error);
  586. });
  587. }
  588.  
  589. function getTop(socket) {
  590. gameDB.aggregate(
  591. [
  592. {"$match":{"name":"history"}},
  593. {"$group":{"_id":{winnername:"$winnername",winnerimg:"$winnerimg", steamid:"$steamid"}, "total":{"$sum":"$winnermoney"}, "count":{"$sum":1}}},
  594. { "$sort" : { total : -1 } },
  595. {"$limit" : 20}
  596. ]
  597. ).toArray(function(err, list) {
  598. if (!err && list.length > 0) {
  599. var promises = [];
  600. list.forEach(function(l, i) {
  601. var deferred = Q.defer();
  602. promises.push(deferred.promise);
  603.  
  604. userListDB.find({steamid:l._id.steamid, name:'player'}).toArray(function(err, player) {
  605. if (!err && typeof player[0] !== "undefined" && typeof player[0].count !== "undefined") {
  606. list[i].attempts = player[0].count;
  607.  
  608. } else {
  609. list[i].attempts = 0;
  610. }
  611.  
  612. deferred.resolve();
  613. });
  614. });
  615.  
  616. Q.all(promises).spread(
  617. function() {
  618. socket.emit('top', { list : list });
  619. },
  620. function(error) {
  621. helper.log('Some Q error', 611);
  622. }
  623. );
  624.  
  625. }
  626.  
  627. });
  628. };
  629.  
  630. MongoClient.connect('mongodb://127.0.0.1:27017', function (err, db) { // Подключаемся к БД
  631. if (err) {
  632. helper.log('Mongodb connection error', 425, err);
  633. return 0;
  634. }
  635.  
  636. // записываем ссылки на таблицы (коллекции) в глобальные переменные
  637. userListDB = db.collection('users');
  638. gameDB = db.collection('gamedb');
  639. g_Mongoconnected = true;
  640. helper.msg('mongo connected');
  641.  
  642. gameDB.find({name: 'counter'}).toArray(function (error, list) { // Достаем значение текущей игры
  643. if(list.length == 0) { // Если его нет, записываем в БД 0
  644. currentGame=0;
  645. gameDB.insert({name: 'counter', counter: 0}, {w:1}, function(err) {if(err) console.log('Error <1>');});
  646. } else {
  647. currentGame = list[0].counter;
  648. }
  649. });
  650. });
  651.  
  652. // Ниже - функции обновления данных в БД
  653.  
  654. function existUser (user, callback) {
  655. if(!g_Mongoconnected)
  656. return 0;
  657.  
  658. userListDB.find({steamid: user}).toArray(function (error, list) {
  659. callback (list.length !== 0);
  660. });
  661. }
  662.  
  663. function updateTotalPlayers(sid){
  664. if(!g_Mongoconnected) {
  665. return 0;
  666. }
  667. // update current field
  668. var date = new Date();
  669. gameDB.update({
  670. steamid: sid,
  671. name: 'player'
  672. }, {
  673. steamid: sid,
  674. name: 'player',
  675. date: date.getTime()
  676. }, {
  677. upsert: true
  678. });
  679. // }
  680. // });
  681. }
  682.  
  683. function updateTradeLink(sid, link) {
  684. if(!g_Mongoconnected)
  685. return 0;
  686.  
  687. existUser(sid, function(exist){
  688. if(exist) {
  689. userListDB.update({steamid: sid}, {steamid: sid, tradelink: link, type : 'trade-link'});
  690. } else {
  691. userListDB.insert({steamid: sid, tradelink: link, type : 'trade-link'}, {w:1}, function(err) {
  692. if(err) {
  693. helper.log('Error inserting tradelink', 485, err);
  694. }
  695. });
  696. }
  697. });
  698. }
  699.  
  700. function updateTotalWin(money) {
  701. if(!g_Mongoconnected)
  702. return 0;
  703.  
  704. gameDB.find({name: 'TR'}).toArray(function(error, list){
  705. if(list.length === 0) // нет записи о выигрыше
  706. gameDB.insert({name: 'TR', TR: money}, {w: 1}, function(err) {
  707. if(err) {
  708. helper.log('Error inserting total win (1)', 499, err);
  709. } else {
  710. helper.msg('Successfully updated TotalWin');
  711. }
  712. });
  713. else {
  714. var tr = list[0].TR;
  715. tr += money;
  716. gameDB.update({name: 'TR'}, {name: 'TR', TR: tr}, function(err) {
  717. if(err) {
  718. helper.log('Error inserting total win (2)', 507, err);
  719. } else {
  720. helper.msg('Successfully updated TotalWin');
  721. }
  722. });
  723. }
  724. });
  725. }
  726.  
  727. function updateMaxWin(money) {
  728. if(!g_Mongoconnected) {
  729. return 0;
  730. }
  731.  
  732. gameDB.find({name: 'MR'}).toArray(function(error, list){
  733. if(list.length === 0) // нет записи о выигрыше
  734. gameDB.insert({name: 'MR', MR: money}, {w: 1}, function(err) {
  735. if(err) {
  736. helper.log('Error inserting max win (1)', 523, err);
  737. } else {
  738. helper.msg('Successfully updated max win');
  739. }
  740. });
  741. else {
  742. var tr = list[0].MR;
  743. if(money > tr || !tr)
  744. tr = money;
  745. gameDB.update({name: 'MR'}, {name: 'MR', MR: tr}, function(err) {
  746. if(err) {
  747. helper.log('Error inserting max win (2)', 532, err);
  748. } else {
  749. helper.msg('Successfully updated max win');
  750. }
  751. });
  752. }
  753. });
  754. }
  755.  
  756. function updateTodayMaxWin(money) {
  757. if(!g_Mongoconnected) {
  758. return 0;
  759. }
  760. var date = new Date();
  761. gameDB.find({name: 'MRTODAY'}).toArray(function(error, list){
  762. if(list.length === 0) // нет записи о выигрыше
  763. gameDB.insert({name: 'MRTODAY', MR: money, date: date.getTime()}, {w: 1}, function(err) {
  764. if(err) {
  765. helper.log('Error inserting max win today(1)', 500, err);
  766. }
  767. });
  768. else {
  769. var tr = list[0].MR;
  770. var today = helper.getToday().getTime();
  771.  
  772. if (list[0].date - today >= 86400000) {
  773. gameDB.update({name: 'MRTODAY'}, {name: 'MRTODAY', MR: money, date: date.getTime()}, function(err) {
  774. if(err) {
  775. helper.log('Error inserting max win (2)', 558, err);
  776. } else {
  777. helper.msg('Successfully updated today max win');
  778. }
  779.  
  780. });
  781. } else {
  782. if(parseFloat(money) > parseFloat(tr)) {
  783. tr = money;
  784. }
  785. gameDB.update({name: 'MRTODAY'}, {name: 'MRTODAY', MR: tr, date: date.getTime()}, function(err) {
  786. if(err) {
  787. helper.log('Error inserting max win (2)', 567, err);
  788. } else {
  789. helper.msg('Successfully updated today max win');
  790. }
  791. });
  792. }
  793.  
  794. }
  795. });
  796.  
  797. }
  798.  
  799. function updateGameCounter(){
  800. if(!g_Mongoconnected)
  801. return 0;
  802.  
  803. gameDB.update({name: 'counter'}, {name: 'counter', counter: currentGame}, function(err) {
  804. if(err) {
  805. helper.log('Error updating game counter', 583, err);
  806. } else {
  807. helper.msg('Successfully updated game counter');
  808. }
  809. });
  810. }
  811.  
  812. function getPlayers(socket) {
  813. socket.emit('players', { list : players });
  814. };
  815.  
  816. function getItems(socket) {
  817. socket.emit('items', { list : currentGameItems });
  818. };
  819.  
  820. function updateGameHistory(gamecounter, i, img, name, money, chance, allItems, winner){
  821. if(!g_Mongoconnected)
  822. return 0;
  823. var date = new Date();
  824. gameDB.insert({
  825. name: 'history',
  826. game: gamecounter,
  827. items: i,
  828. winnerimg: img,
  829. winnername: name,
  830. winnermoney: money,
  831. winnerchance: chance.toFixed(2),
  832. date: date.getTime(),
  833. allItems: allItems,
  834. steamid: winner
  835. }, {w: 1}, function(err) {
  836. if(err) {
  837. helper.log("Error updating game history", 624, err);
  838. } else {
  839. helper.msg("Successfully updated history table");
  840. }
  841. });
  842. }
  843.  
  844.  
  845.  
  846.  
  847. var steam = new Steam.SteamClient();
  848. var offers = new SteamTradeOffers();
  849. /*
  850. var hash = require('crypto').createHash('sha1');
  851. hash.update(Math.random().toString());
  852. hash = hash.digest('hex');
  853. var device_id = 'android:' + hash;*/
  854.  
  855. steam.logOn(loginOpts);
  856.  
  857. steam.on('debug', console.log);
  858. offers.on('debug', console.log);
  859.  
  860. steam.on('loggedOn', function(result) {
  861. helper.msg('Logged in!');
  862. steam.setPersonaState(Steam.EPersonaState.Online);
  863. });
  864.  
  865. steam.on('webSessionID', function(sessionID) {
  866. helper.msg('webSessionID ok');
  867. currentSessionId = sessionID;
  868. reWebLogOn(steam);
  869. });
  870.  
  871.  
  872. function reWebLogOn(steam, callback) {
  873. steam.webLogOn(function(newCookie){
  874. helper.msg('webLogOn ok');
  875. kukisy = newCookie;
  876. /*var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
  877. var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
  878. {
  879. steamid: "76561198191527437",
  880. identity_secret: "xL3U4LxCk3iN52YBNBHjkEfGkxw=",
  881. device_id: device_id,
  882. webCookie: newCookie,
  883. });*/
  884.  
  885.  
  886. setInterval(function(){
  887. var hash = require('crypto').createHash('sha1');
  888. hash.update(Math.random().toString());
  889. hash = hash.digest('hex');
  890. var device_id = 'android:' + hash;
  891.  
  892. var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
  893. var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
  894. {
  895. steamid: "76561198191527437",
  896. identity_secret: "xL3U4LxCk3iN52YBNBHjkEfGkxw=",
  897. device_id: device_id,
  898. webCookie: kukisy,
  899. });
  900.  
  901. checkConfirmations(steamcommunityMobileConfirmations)
  902. }, pooling_interval);
  903.  
  904. offers.setup({
  905. sessionID: currentSessionId,
  906. webCookie: newCookie,
  907. APIKey: config.apiKey
  908. }, function(){
  909. if (typeof callback == "function") {
  910. callback();
  911. }
  912. });
  913.  
  914.  
  915. });
  916. }
  917.  
  918. steam.on('sentry', function(data) {
  919. sentryFile = 'sentryFromSteam';
  920. require('fs').writeFileSync(sentryFile, data);
  921. });
  922.  
  923. // Если пришел новый трейд
  924. steam.on('tradeOffers', function(number) {
  925. if (g_Pause) {
  926. return;
  927. }
  928. var retryCnt = 1;
  929.  
  930. if (number > 0) {
  931. helper.msg('New offers: '+number);
  932.  
  933. function getOffers() {
  934. offers.getOffers({
  935. get_received_offers: 1,
  936. active_only: 1/*,
  937. time_historical_cutoff: Math.round(Date.now() / 1000)*/
  938. }, onGetOffers);
  939. }
  940.  
  941. function onGetOffers(error, body) {
  942. if (error) {
  943. if (retryCnt >= 0) {
  944. getOffers();
  945. retryCnt--;
  946. }
  947.  
  948. helper.log('Error getting offers', 692, error);
  949. }
  950.  
  951. // Проверки на наличие трейда
  952. if (body) {
  953. if (body.response.trade_offers_received) {
  954.  
  955. body.response.trade_offers_received.forEach(function (offer) {
  956. //if offer is already accepted
  957. if (acceptedTradeOffers.indexOf(offer.tradeofferid) >= 0) {
  958. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  959. return;
  960. }
  961.  
  962. // active
  963. if (offer.trade_offer_state == 2) {
  964. helper.log('Current game offers', 716, currentGameOffers);
  965. currentGameOffers.push(offer.tradeofferid);
  966. userListDB.find({'steamid': offer.steamid_other}).toArray(function (err, list) {
  967. if (error) {
  968. helper.msg('Declined - no tradelink, offer #' + offer.tradeofferid);
  969. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  970. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  971. });
  972. } else if (list.length == 0) {
  973. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  974. helper.msg('Declined - no tradelink, offer #' + offer.tradeofferid);
  975. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  976. });
  977. } else {
  978.  
  979. // Бот не принимает предметы, пока разыгрывает предыдущие
  980. if (g_Pause) {
  981. helper.msg('Offer declined because of pause');
  982. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  983. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  984. });
  985. //steam.sendMessage(offer.steamid_other, 'Sorry. Bot is on pause :C', Steam.EChatEntryType.ChatMsg);
  986.  
  987. // Если нас пытаются обмануть, отклоняем трейд
  988. } else if (offer.items_to_give) {
  989. if (offer.steamid_other != config.admin && offer.steamid_other != config.secondadmin) {
  990. helper.msg('Offer declined (2)');
  991.  
  992. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  993. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  994. });
  995. } else {
  996. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  997. offers.acceptOffer({tradeOfferId: offer.tradeofferid});
  998. helper.msg('accepted trade offer from admin: ' + offer.tradeofferid);
  999. return;
  1000. }
  1001. //steam.sendMessage(offer.steamid_other, 'You cannot take my items', Steam.EChatEntryType.ChatMsg);
  1002.  
  1003. // Если нам не передают предметы, отклоняем трейд
  1004. } else if (!offer.items_to_receive) {
  1005. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1006. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1007. });
  1008. helper.msg('Offer declined <empty items to receive>');
  1009. //steam.sendMessage(offer.steamid_other, 'Empty trade offer', Steam.EChatEntryType.ChatMsg);
  1010.  
  1011. // all right
  1012. } else {
  1013. if (g_Pause) {
  1014. helper.msg('Offer declined because of pause');
  1015. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1016. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1017. });
  1018. }
  1019. offers.getTradeHoldDuration({tradeOfferId: offer.tradeofferid}, function (test, data) {
  1020. if (data == null || data == 'undefined' || data.their == null || data.their == 'undefined') {
  1021. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1022. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1023. });
  1024. return;
  1025. }
  1026. if (data.their > 0) {
  1027. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1028. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1029. });
  1030. helper.msg('Oferta odrzucona - oferta odroczona.');
  1031. return;
  1032. }
  1033. else {
  1034. var itemIds = [];
  1035.  
  1036. // Записываем ИД предметов в массив
  1037. // Проверяем, что это именно КС:ГО предметы (appid cs:go = 730)
  1038. for (var i = 0; i < 100; i++) {
  1039. if (!offer.items_to_receive[i]) {
  1040. continue;
  1041. }
  1042.  
  1043. tempItem = offer.items_to_receive[i];
  1044. // console.log('Receive item ID: ' + offer.items_to_receive[i].assetid +' class id: '+ offer.items_to_receive[i].classid);
  1045.  
  1046. if (offer.items_to_receive[i].appid != 730) {
  1047. helper.msg('not a CSGO item');
  1048. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1049. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1050. });
  1051. //steam.sendMessage(offer.steamid_other, 'You can place only CS:GO items', Steam.EChatEntryType.ChatMsg);
  1052. break;
  1053. }
  1054.  
  1055. itemIds.push(tempItem.assetid);
  1056. }
  1057.  
  1058. // check if item count is lower than limit in config
  1059. if (typeof itemsCounters[offer.steamid_other] == 'undefined') {
  1060. itemsCounters[offer.steamid_other] = 0;
  1061. }
  1062.  
  1063. if (itemsCounters[offer.steamid_other] + offer.items_to_receive.length > config.usersItemsLimit) {
  1064. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1065. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1066. });
  1067. helper.msg('Declined: one user items limit exceeded.');
  1068. return;
  1069. }
  1070. helper.msg('Sending api request...');
  1071. //Запрашиваем данные о пользователе, чтобы достать ник и аватар
  1072. var req_retry = 5;
  1073. var GetPlayerSummaries = function () {
  1074. var _req = http.request({
  1075. host: 'api.steampowered.com',
  1076. path: '/ISteamUser/GetPlayerSummaries/v0002/?key=' + config.apiKey + '&steamids=' + offer.steamid_other
  1077. }, function (response) {
  1078. var str = '';
  1079.  
  1080. response.on('data', function (chunk) {
  1081. str += chunk;
  1082. });
  1083.  
  1084. response.on('end', function () {
  1085. helper.msg('Received api request!');
  1086.  
  1087. var data = JSON.parse(str),
  1088. retries = 5;
  1089.  
  1090. var loadPartnerInventory = function () {
  1091. retries--;
  1092.  
  1093. // Загружаем инвентарь партнера
  1094. // Сравниваем ИД предметов в его инвентаре и ИД посланных предметов
  1095. // Чтобы найти имя предметов и записать в массив
  1096. offers.loadPartnerInventory({
  1097. partnerSteamId: offer.steamid_other,
  1098. appId: 730,
  1099. contextId: 2
  1100. }, function (err, items) {
  1101. if (err != null) {
  1102. helper.msg('Error loading inventory ' + offer.steamid_other);
  1103. if (err.message.indexOf('401') > -1 && retries >= 0) {
  1104. reWebLogOn(steam, function () {
  1105. helper.msg(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  1106. loadPartnerInventory();
  1107. });
  1108. } else {
  1109. helper.msg(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  1110.  
  1111. if (retries == 0) {
  1112. helper.msg('Offer ' + offer.tradeofferid + ' declined.');
  1113. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1114. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1115. });
  1116. } else {
  1117. loadPartnerInventory();
  1118. }
  1119. }
  1120. } else {
  1121. // Принимаем трейд
  1122. helper.msg('Next function is acceptOffer! - ' + offer.steamid_other + ' - ' + offer.tradeofferid);
  1123. if (g_Pause) {
  1124. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1125. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1126. });
  1127. return;
  1128. }
  1129. var checkItems = [];
  1130. var len = items.length;
  1131. for (var i = 0; i < itemIds.length; i++) {
  1132. for (var j = 0; j < items.length; j++) {
  1133. if (itemIds[i] == items[j].id) {
  1134. //console.log('Pushed: ' + items[j].name);
  1135. var colorObj = helper.getColor(items[j]);
  1136. checkItems.push({
  1137. user: data.response.players[0].personaname,
  1138. ava: data.response.players[0].avatarfull,
  1139. itemname: items[j].market_name,
  1140. image: items[j].icon_url,
  1141. color: colorObj.color,
  1142. background_color: colorObj.background_color,
  1143. market_hash_name: items[j].market_hash_name,
  1144. steamid: offer.steamid_other,
  1145. tradeofferid: offer.tradeofferid
  1146. });
  1147.  
  1148. }
  1149. }
  1150. }
  1151.  
  1152. checkMinDeposite(checkItems, offer.tradeofferid)
  1153. .then(function (response) {
  1154. if (g_Pause) {
  1155. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1156. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1157. });
  1158. return;
  1159. }
  1160. response.summ = parseFloat(response.summ);
  1161.  
  1162. if (typeof config.minDeposite !== 'undefined') {
  1163. var check = parseFloat(config.minDeposite);
  1164. if (response.summ > check) {
  1165. helper.msg('Greater than min deposite - ' + offer.tradeofferid);
  1166. try {
  1167. offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function (err, log) {
  1168. if (err) {
  1169. console.log('resc errora:' + err);
  1170. helper.log('Error accepting trade offer ' + offer.tradeofferid, 891, err);
  1171. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1172. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1173. });
  1174. return;
  1175. }
  1176.  
  1177. itemsCounters[offer.steamid_other] += offer.items_to_receive.length;
  1178. // Обновляем счетчик уникальных игроков в БД
  1179. updateTotalPlayers(offer.steamid_other);
  1180. var itemsWithPrices = response.items;
  1181. var playerAdded = false;
  1182. itemsWithPrices.forEach(function (itemWithPrice, index) {
  1183. g_ItemName.push(itemWithPrice.market_hash_name);
  1184. // players array
  1185. players.push({
  1186. steamid: itemWithPrice.steamid,
  1187. min: g_Totalcost,
  1188. max: g_Totalcost + itemWithPrice.price,
  1189. nick: itemWithPrice.user,
  1190. ava: itemWithPrice.ava
  1191. });
  1192. // Банк. Сумма цен всех предметов
  1193. g_Totalcost += itemWithPrice.price;
  1194. // Рассчитываем шанс победы для игрока
  1195. var winchance = 0;
  1196. var sumdep = 0;
  1197. var summoney = 0;
  1198. players.forEach(function (I) {
  1199. if (I.steamid == itemWithPrice.steamid) {
  1200. sumdep++;
  1201. var diff = I.max - I.min;
  1202. summoney += diff;
  1203. }
  1204. });
  1205. // winchance for CURRENT item
  1206. if (g_Totalcost !== 0) {
  1207. winchance = summoney / g_Totalcost * 100;
  1208. }
  1209. // Параметры для отправки на сайт
  1210. var op = {
  1211. type: 0,
  1212. user: itemWithPrice.user,
  1213. ava: itemWithPrice.ava,
  1214. itemname: itemWithPrice.itemname,
  1215. image: itemWithPrice.image,
  1216. color: itemWithPrice.color,
  1217. background_color: itemWithPrice.background_color,
  1218. cost: itemWithPrice.price,
  1219. steamid: itemWithPrice.steamid,
  1220. itemcounter: sumdep,
  1221. chance: winchance,
  1222. money: summoney,
  1223. jackpot: g_Totalcost
  1224. };
  1225. // Массив с предметами текущей игры
  1226. currentGameItems.push(op);
  1227.  
  1228. // Посылаем на сайт новый предмет
  1229. io.emit('0', op);
  1230.  
  1231. // Посылаем обновление текста (Игра номер ... Банк ...)
  1232. io.emit('2', {
  1233. gamenumber: currentGame,
  1234. jackpot: Math.round(g_Totalcost * 100) / 100
  1235. })
  1236.  
  1237.  
  1238. // Считаем уникальных игроков
  1239. playersUnique = {};
  1240. playersCounter = 0;
  1241. currentGameItems.forEach(function (item, index) {
  1242. if (playersUnique[item.steamid] === undefined) {
  1243. //if(!playerAdded)
  1244. //{
  1245. //console.log('w ifie dodawania');
  1246. playersCounter++;
  1247. //playerAdded=true;
  1248. //}
  1249. playersUnique[item.steamid] = {
  1250. 'user': item.user,
  1251. 'ava': item.ava,
  1252. 'money': item.money,
  1253. 'steamid': item.steamid
  1254. };
  1255.  
  1256. if (g_Totalcost > 0) {
  1257. playersUnique[item.steamid].chance = item.money / g_Totalcost * 100;
  1258. } else {
  1259. playersUnique[item.steamid].chance = 0;
  1260. }
  1261.  
  1262. } else {
  1263. if (playersUnique[item.steamid].money < item.money) {
  1264. playersUnique[item.steamid].money = item.money;
  1265.  
  1266. if (g_Totalcost > 0) {
  1267. playersUnique[item.steamid].chance = item.money / g_Totalcost * 100;
  1268. } else {
  1269. playersUnique[item.steamid].chance = 0;
  1270. }
  1271. }
  1272. }
  1273. });
  1274.  
  1275. // order players
  1276. playersUniqueOrder = [];
  1277. for (var playerIndex in playersUnique) {
  1278. playersUniqueOrder.push({
  1279. steamid: playersUnique[playerIndex].steamid,
  1280. chance: playersUnique[playerIndex].chance
  1281. });
  1282. }
  1283.  
  1284. playersUniqueOrder.sort(helper.compare);
  1285.  
  1286. // ... and send to frontend
  1287. io.emit('playersUnique', {
  1288. list: playersUnique,
  1289. order: playersUniqueOrder
  1290. });
  1291. });
  1292. acceptedTradeOffers.push(offer.tradeofferid);
  1293. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1294. // Ставим таймер при достижении нужного количества игроков
  1295. if (playersCounter >= config.usersToStart && timer == 0) {
  1296. if (g_Pause) {
  1297. helper.msg('Timer but on pause');
  1298. return;
  1299. }
  1300. timer = config.gameDuration;
  1301. timerID = setInterval(function () {
  1302. timer--;
  1303.  
  1304. var min = Math.floor(timer / 60);
  1305. var sec = timer % 60;
  1306. sec = sec.toString();
  1307. sec = sec.substr(0, 2);
  1308.  
  1309. io.emit('timer', {timer: min + ":" + sec});
  1310.  
  1311. if (timer <= 5) {
  1312. g_Pause = true;
  1313. }
  1314.  
  1315. if (timer <= 0) {
  1316. helper.msg('Timer tick is ' + timer);
  1317. g_Pause = true;
  1318. setTimeout(function () {
  1319. randomWin(players); // Выбираем победителя
  1320. }, 6000);
  1321. clearInterval(timerID); // Очищаем таймер
  1322. }
  1323. }, 1000);
  1324. }
  1325. });
  1326.  
  1327. } catch (error) {
  1328. helper.log('Error accepting trade offer ' + offer.tradeofferid, 1066, error);
  1329. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1330. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1331. });
  1332. }
  1333.  
  1334. } else {
  1335. helper.msg('Lower than min deposite - ' + offer.tradeofferid);
  1336. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1337. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1338. });
  1339. }
  1340. }
  1341. })
  1342. .catch(function (error) {
  1343. helper.log('Error checking deposite', 911, error);
  1344. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1345. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1346. });
  1347. });
  1348. }
  1349. });
  1350. };
  1351.  
  1352. loadPartnerInventory();
  1353.  
  1354. });
  1355.  
  1356. response.on('error', function (error) {
  1357. helper.log('Steam response error', 924, error)
  1358. });
  1359.  
  1360. });
  1361.  
  1362. _req.on('error', function (error) {
  1363. helper.log('There was an error on GetPlayerSummaries', 930, error);
  1364. req_retry--;
  1365. if (req_retry >= 0) {
  1366. GetPlayerSummaries();
  1367. } else {
  1368. helper.msg(' | Offer declined. Steam no answer.');
  1369. offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () {
  1370. currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
  1371. });
  1372. }
  1373. });
  1374.  
  1375. _req.setTimeout(5000, function () {
  1376. helper.msg('TimeOut');
  1377. _req.abort();
  1378. });
  1379.  
  1380. _req.end();
  1381. };
  1382.  
  1383. GetPlayerSummaries();
  1384. }
  1385. });
  1386. }
  1387. }
  1388. });
  1389. }
  1390. });
  1391. }
  1392. }
  1393. }
  1394. getOffers();
  1395. }
  1396. });
  1397.  
  1398.  
  1399. function getPrice(params) {
  1400. var deferred = Q.defer();
  1401.  
  1402. // currency=5 - Рубли
  1403. // P.S> Для других валют скорее всего нужно другую парсилку
  1404. var currency = config.currency;
  1405.  
  1406. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(params.market_hash_name);
  1407. //Запрос к стим маркету
  1408. var request = http.get({host: 'steamcommunity.com', path: link}, function(response){
  1409. var str2 = '';
  1410.  
  1411. response.on('data', function (chunk) {
  1412. str2 += chunk
  1413. });
  1414.  
  1415. response.on('end', function() {
  1416. // Парсим среднюю цену
  1417. var price = JSON.parse(str2);
  1418. if (price == 'undefined' || price.median_price == 'undefined') {
  1419. return deferred.reject('Strange steam price bug');
  1420. }
  1421. try {
  1422. price = price.median_price.replace(',','.');
  1423. } catch(err) {
  1424. return deferred.reject(err);
  1425. }
  1426. if (currency == 5) {
  1427. price = price.substring(0, price.indexOf(' '));
  1428. } else {
  1429. price = price.substr(price.indexOf(';')+1);
  1430. }
  1431.  
  1432. price = parseFloat(price);
  1433. price = Math.round(price * 100) / 100;
  1434.  
  1435. // fill the obj
  1436. params.price = price;
  1437.  
  1438. deferred.resolve(params);
  1439. });
  1440. });
  1441.  
  1442. request.on('error', function(err){
  1443. deferred.reject(err);
  1444. });
  1445.  
  1446. return deferred.promise;
  1447. };
  1448.  
  1449.  
  1450. function checkMinDeposite(items, offerid) {
  1451. helper.msg('Checking min deposite - ' + offerid);
  1452. var output = Q.defer();
  1453.  
  1454. var len = items.length;
  1455. var summ = 0;
  1456. var promises = [];
  1457.  
  1458. items.forEach(function(item, i) {
  1459. var deferred = Q.defer();
  1460.  
  1461. promises.push(deferred.promise);
  1462. var currency = config.currency;
  1463. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(items[i].market_hash_name);
  1464. http.get({host: 'steamcommunity.com', path: link}, function(response){
  1465. var str2 = '';
  1466. var steamApiPrice = true;
  1467. response.on('data', function (chunk) {
  1468. str2 += chunk
  1469. });
  1470.  
  1471. response.on('end', function() {
  1472. var price = 0;
  1473. try {
  1474. price = JSON.parse(str2);
  1475. } catch(err) {
  1476. steamApiPrice=false;
  1477. async.series([
  1478. function(callbackFirst)
  1479. {
  1480. var skinName = items[i].market_hash_name.replace("™", "");
  1481. skinName = skinName.replace("★", "");
  1482. skinName = skinName.replace("�", "");
  1483. if(skinName.charAt(0) == ' ')
  1484. skinName = skinName.slice(1);
  1485. var query = 'SELECT Price from Items where Name = "' + skinName +'" COLLATE utf8_unicode_ci' ;
  1486. connection.query(query, function(err2, rows, fields) {
  1487. if (!err2)
  1488. {
  1489. if(rows.length > 0)
  1490. {
  1491. console.log('Cena z BAZY: ' + rows[0].Price + ' - ' + skinName);
  1492. price = JSON.parse(rows[0].Price);
  1493. callbackFirst();
  1494. }
  1495. else
  1496. {
  1497. console.log('BRAK CENY W BAZIE - ' + skinName);
  1498. console.log(err2);
  1499. return deferred.reject(err2);
  1500. }
  1501. }
  1502. else
  1503. {
  1504. console.log('Blad pobierania ceny z bazy danych.');
  1505. return deferred.reject(err);
  1506. }
  1507. });
  1508.  
  1509. }
  1510. ],
  1511. function(err, results)
  1512. {
  1513. price = parseFloat(price);
  1514. items[i].price = price;
  1515. summ += price;
  1516. deferred.resolve();
  1517. });
  1518. }
  1519. if(steamApiPrice)
  1520. {
  1521. if (price == null || price.lowest_price == null || price == 'undefined' || price.lowest_price == 'undefined') {
  1522. return deferred.reject('Strange steam price bug');
  1523. }
  1524. try {
  1525. price = price.median_price.replace(',','.');
  1526. if(price[0] == '$')
  1527. price = price.substr(1);
  1528. } catch(err) {
  1529. return deferred.reject(err);
  1530. }
  1531. if (currency == 5) {
  1532. price = price.substring(0, price.indexOf(' '));
  1533. } else {
  1534. price = price.substr(price.indexOf(';')+1);
  1535. }
  1536. price = parseFloat(price);
  1537. price = Math.round(price * 100) / 100;
  1538.  
  1539. items[i].price = price;
  1540. summ += price;
  1541.  
  1542. deferred.resolve();
  1543. }
  1544. });
  1545.  
  1546. response.on('error', function(error) {
  1547. helper.msg(i + ' response error');
  1548.  
  1549. deferred.reject(error);
  1550. });
  1551. });
  1552. })
  1553. Q.all(promises).spread(
  1554. function() {
  1555. output.resolve({summ: summ, items: items});
  1556. },
  1557. function(error) {
  1558. output.reject(error);
  1559. });
  1560.  
  1561. return output.promise;
  1562. }
  1563.  
  1564. function randomWin(p) {
  1565. if (currentGameOffers.length > 0) {
  1566. setTimeout(function () {
  1567. randomWin(p);
  1568. }, 1500);
  1569. } else {
  1570. setTimeout(function () {
  1571. if (randomTicket == 0)
  1572. randomTicket = (Math.random() * g_Totalcost).toFixed(2);
  1573.  
  1574. var winner = 0;
  1575. var adminWin = false;
  1576.  
  1577. helper.msg('random ticket is :' + randomTicket);
  1578.  
  1579.  
  1580. helper.log('Players array length', 1430, p.length);
  1581. if (p.length > 0) {
  1582. for (var i = 0; i < p.length; i++) {
  1583. if (p[i].steamid == winnerid) {
  1584. winner = p[i].steamid;
  1585. updatePlayersGameCount(p, winner);
  1586.  
  1587. givePrize(winner);
  1588. adminWin = true;
  1589. break;
  1590. }
  1591. }
  1592. } else {
  1593. helper.msg('Players array empty(adminWin)');
  1594.  
  1595. }
  1596.  
  1597. //Если вдруг админ должен выиграть
  1598. helper.msg('Admin win: ' + adminWin);
  1599. if (adminWin) {
  1600. return;
  1601. }
  1602.  
  1603. // Проверяем каждый элемент в массиве с игроками.
  1604. // Выбираем победителя
  1605. helper.log('Players array length', 1430, p.length);
  1606. if (p.length > 0) {
  1607. for (var i = 0; i < p.length; i++) {
  1608. var tickets = p[i];
  1609. if (randomTicket >= tickets.min && randomTicket <= tickets.max) {
  1610. winner = tickets.steamid;
  1611. updatePlayersGameCount(p, winner);
  1612. helper.log('Winner player min and max', 1435, p[i]);
  1613. helper.msg('winner in cycle: ' + winner);
  1614. givePrize(winner); // Выдаем приз
  1615. break;
  1616. }
  1617. }
  1618. } else {
  1619. helper.msg('Players array empty');
  1620. }
  1621. }, 3000);
  1622. }
  1623. }
  1624.  
  1625. function givePrize(winner){
  1626. if (currentGameOffers.length > 0) {
  1627. helper.log('Current gameoffers', 1230, currentGameOffers);
  1628. setTimeout(function() {
  1629. givePrize(winner);
  1630. }, 1500);
  1631. } else {
  1632. helper.msg('No game offers, can give prize');
  1633. // Ищем в БД трейдлинк победителя
  1634. try {
  1635. userListDB.find({steamid: winner}).toArray(function (error, list){
  1636. if (error) {
  1637. helper.log('No tradeoffer link', 1240, error);
  1638. Wipe(winner);
  1639. return;
  1640. }
  1641.  
  1642. var itemstosend = [];
  1643. var token;
  1644. var accountid;
  1645.  
  1646. // Если нашли парсим
  1647. if (list.length > 0) {
  1648. token = list[0].tradelink;
  1649. console.log('trade link:'+token);
  1650. token = token.substr(token.indexOf('&token')+7);
  1651. helper.msg('Trade offer token: '+token);
  1652. accountid = list[0].tradelink;
  1653. accountid = accountid.substr(accountid.indexOf('?partner')+9);
  1654. accountid = accountid.substring(0, accountid.indexOf('&'));
  1655. helper.msg('account id: '+accountid);
  1656. } else {
  1657. helper.msg('No tradeoffer link');
  1658. Wipe(winner);
  1659. return;
  1660. }
  1661.  
  1662. var load_my_retry = 20;
  1663. var loadMyInventory = function() {
  1664. load_my_retry--;
  1665. offers.loadMyInventory({appId: 730, contextId: 2}, function(err, items) {
  1666. if (err) {
  1667. helper.log('Error loading my inventory', 1269, err);
  1668. if (load_my_retry >= 0) {
  1669. helper.msg('Retry loadMyInventory step: ' + load_my_retry);
  1670. setTimeout(function(){
  1671. loadMyInventory();
  1672. }, 2000);
  1673. } else {
  1674. helper.msg('Can t give prize to winner.');
  1675. Wipe(winner);
  1676. return;
  1677. }
  1678. } else {
  1679. itemstosend = getComission(items, winner);
  1680.  
  1681. var retries = 10;
  1682. var GetPlayerSummaries2 = function() {
  1683. var req = http.get({
  1684. host: 'api.steampowered.com',
  1685. path: '/ISteamUser/GetPlayerSummaries/v0002/?key='+config.apiKey+'&steamids='+winner
  1686. }, function(response) {
  1687. var str = '';
  1688. response.on('data', function (chunk) {str += chunk});
  1689.  
  1690. response.on('end', function() {
  1691. data = JSON.parse(str);
  1692.  
  1693. //Отправляем предметы по токену или без.
  1694. if(token == null) {
  1695. var makeOfferRetry = 10;
  1696. var firstMakeOffer = function() {
  1697. offers.makeOffer({
  1698. partnerSteamId: winner,
  1699. itemsFromThem: [],
  1700. itemsFromMe: itemstosend
  1701. }, function(err, response) {
  1702. if (err) {
  1703. makeOfferRetry--;
  1704. if (makeOfferRetry >= 0) {
  1705. helper.log('Error sending tradeoffer without token', 1306, err);
  1706. helper.msg('Retry step: ' + makeOfferRetry);
  1707. firstMakeOffer();
  1708. } else {
  1709. Wipe(winner, data);
  1710. helper.msg('Can t send items to winner');
  1711. }
  1712. } else {
  1713. Wipe(winner, data);
  1714. }
  1715. });
  1716. };
  1717. firstMakeOffer();
  1718. } else {
  1719. var makeOfferRetry = 10;
  1720.  
  1721. var secondMakeOffer = function() {
  1722. offers.makeOffer({
  1723. partnerAccountId: accountid,
  1724. accessToken: token,
  1725. itemsFromThem: [],
  1726. itemsFromMe: itemstosend
  1727. }, function(err, response) {
  1728. if (err) {
  1729. makeOfferRetry--;
  1730. if (makeOfferRetry >= 0) {
  1731. helper.log('Error sending tradeoffer without token', 1332, err);
  1732. helper.msg('Retry step: ' + makeOfferRetry);
  1733. secondMakeOffer();
  1734. } else {
  1735. Wipe(winner, data);
  1736. helper.msg('Can t send items to winner');
  1737. }
  1738. } else {
  1739. Wipe(winner, data);
  1740. }
  1741.  
  1742. });
  1743. };
  1744.  
  1745. secondMakeOffer();
  1746. }
  1747.  
  1748. });
  1749.  
  1750. response.on('error', function(error) {
  1751. helper.log('Error loading player info', 1352, err);
  1752. });
  1753. });
  1754.  
  1755. req.on('error', function(error) {
  1756. helper.log('Error GetPlayerSummaries', 1357, error);
  1757. retries--;
  1758. if (retries >= 0) {
  1759. helper.msg('Retry GetPlayerSummaries, step: ' + retries);
  1760. GetPlayerSummaries2();
  1761. } else {
  1762. helper.msg('Can t GetPlayerSummaries');
  1763. Wipe(winner);
  1764. }
  1765. });
  1766.  
  1767. req.setTimeout(5000, function() {
  1768. helper.msg('TimeOut');
  1769. req.abort();
  1770. });
  1771.  
  1772. req.end();
  1773. };
  1774. GetPlayerSummaries2();
  1775. };
  1776. });
  1777. };
  1778.  
  1779. loadMyInventory();
  1780.  
  1781. });
  1782.  
  1783. } catch (err) {
  1784. helper.log('Mongodb error', 1385, err);
  1785. }
  1786. }
  1787. }
  1788.  
  1789. var getComission = function(items, winner) {
  1790. var tempGameItems = [].concat(currentGameItems);
  1791. var feeValue = g_Totalcost * config.fee;
  1792.  
  1793. if (config.commissionType == 1 && typeof winner !== 'undefined') {
  1794. var removedCosts = 0;
  1795. tempGameItems.forEach(function(item, id) {
  1796. if (item.steamid == winner) {
  1797. tempGameItems.splice(id, 1);
  1798. removedCosts += parseFloat(item.cost);
  1799. }
  1800. })
  1801.  
  1802. feeValue = (g_Totalcost - removedCosts) * config.fee;
  1803. }
  1804. var itemstosend = [];
  1805.  
  1806. // Cнятие комиссии
  1807. var itemsCheaperThenFee = [];
  1808. for (var i = 0; i <= tempGameItems.length-1; i++) {
  1809. if (tempGameItems[i].cost < feeValue) {
  1810. itemsCheaperThenFee.push(tempGameItems[i]);
  1811. }
  1812. }
  1813.  
  1814. var itemsFee = [];
  1815. if (itemsCheaperThenFee.length > 0) {
  1816.  
  1817. itemsCheaperThenFee = itemsCheaperThenFee.sort(helper.sortDesc);
  1818.  
  1819. function getTheMostExpensiveItem(items, unusedFee) {
  1820. for (var i = 0; i <= items.length-1; i++) {
  1821. if (items[i].cost <= unusedFee) {
  1822. itemsFee.push(items[i]);
  1823. // delete item and all previous (they are more expensive that unusedFee)
  1824. var unusedItems = [];
  1825. for (var j = i; j <= items.length-1; j++) {
  1826. unusedItems.push(items[j]);
  1827. }
  1828.  
  1829. unusedFee -= items[i].cost;
  1830.  
  1831. getTheMostExpensiveItem(unusedItems, unusedFee);
  1832. break;
  1833. }
  1834. }
  1835. }
  1836.  
  1837. getTheMostExpensiveItem(itemsCheaperThenFee, feeValue);
  1838. }
  1839.  
  1840. itemsFee.forEach(function(item) {
  1841. for(var i = 0; i <= g_ItemName.length-1; i++){
  1842. if (g_ItemName[i] == item.itemname) {
  1843. g_ItemName.splice(i,1);
  1844. break;
  1845. }
  1846. }
  1847. });
  1848.  
  1849. //Загружаем наш инвентарь
  1850. //Единственный способ достать из него нужные предметы - по наименованию
  1851. //т.к. после трейдоффера предметы меняют свой assetid
  1852. var took = [];
  1853. g_ItemName.forEach(function(gItem) {
  1854. if (typeof gItem == 'undefined') {
  1855. return;
  1856. }
  1857.  
  1858. for(var i = 0; i < items.length; i++){
  1859. //Если нашли нужный предмет, запихиваем его в массив для отправки
  1860. if(gItem == items[i].market_hash_name){
  1861.  
  1862. if(items[i].tradable) {
  1863. if(took.indexOf(items[i].id) === -1) {
  1864. itemstosend.push({
  1865. appid: 730,
  1866. contextid:2,
  1867. amount: 1,
  1868. assetid: items[i].id
  1869. });
  1870.  
  1871. took.push(items[i].id);
  1872.  
  1873. break;
  1874. }
  1875.  
  1876. } else {
  1877. helper.msg(items[i].market_hash_name + ' is not tradable');
  1878. }
  1879. }
  1880. }
  1881. });
  1882.  
  1883. return itemstosend;
  1884.  
  1885. }
  1886.  
  1887. function sendTodayCounter(socket, key, inf) {
  1888. var today = helper.getToday().getTime();
  1889.  
  1890. if (key == 'history' || key == 'player') {
  1891. gameDB.find( { name: key, date: { $gt : today}} ).count(function(error, count) {
  1892. if (error) {
  1893. console.log('error - ' + error);
  1894.  
  1895. sendTodayCounter(socket, key, inf);
  1896. } else {
  1897. var preObj = {};
  1898. preObj['type'] = 'informers';
  1899. preObj[inf] = count;
  1900.  
  1901. if (socket == 'ALL') {
  1902. io.emit('informers', preObj)
  1903. } else {
  1904. socket.emit('informers', preObj);
  1905. }
  1906. }
  1907.  
  1908. });
  1909. } else if (key == 'items') {
  1910. gameDB.find( { name: 'history', date: { $gt : today}} ).toArray(function(error, list) {
  1911. if (error) {
  1912. console.log('error - ' + error);
  1913. console.log('retrying');
  1914. sendTodayCounter(socket, key, inf);
  1915. } else {
  1916. var preObj = {};
  1917. var totalCount = 0;
  1918. if (typeof list == 'undefined' || list.length == 0) {
  1919. totalCount = 0;
  1920. } else {
  1921. list.forEach(function(el, index) {
  1922. if (typeof el['items'] !== 'undefined') {
  1923. totalCount += el['items'].length;
  1924. }
  1925. });
  1926. }
  1927.  
  1928. preObj['type'] = 'informers';
  1929. preObj[inf] = totalCount;
  1930.  
  1931. if (socket == 'ALL') {
  1932. io.emit('informers', preObj)
  1933. } else {
  1934. socket.emit('informers', preObj);
  1935. }
  1936. }
  1937. });
  1938. } else if (key == 'MRTODAY') {
  1939. gameDB.find( { name: key, date: { $gt : today}} ).toArray(function(error, list) {
  1940. if (error) {
  1941. console.log('error - ' + error);
  1942. console.log('retrying');
  1943. sendTodayCounter(socket, key, inf);
  1944. } else {
  1945. var preObj = {};
  1946. var totalCount = 0;
  1947. if (typeof list == 'undefined' || list.length == 0) {
  1948. totalCount = 0;
  1949. } else {
  1950. totalCount = list[0].MR;
  1951. }
  1952.  
  1953. preObj['type'] = 'informers';
  1954. preObj[inf] = totalCount;
  1955.  
  1956. if (socket == 'ALL') {
  1957. io.emit('informers', preObj)
  1958. } else {
  1959. socket.emit('informers', preObj);
  1960. }
  1961. }
  1962. });
  1963. } else if (key == 'today-win') {
  1964. gameDB.find( { name: 'history', date: { $gt : today}} ).toArray(function(error, list) {
  1965. if (error) {
  1966. console.log('error - ' + error);
  1967. console.log('retrying');
  1968. sendTodayCounter(socket, key, inf);
  1969. } else {
  1970. var preObj = {};
  1971. var totalCount = 0;
  1972. if (typeof list == 'undefined' || list.length == 0) {
  1973. totalCount = 0;
  1974. } else {
  1975. list.forEach(function(el, index) {
  1976. if (typeof el['winnermoney'] !== 'undefined') {
  1977. totalCount += parseFloat(el['winnermoney']);
  1978. }
  1979. });
  1980. }
  1981.  
  1982. preObj['type'] = 'informers';
  1983. preObj[inf] = totalCount;
  1984.  
  1985. if (socket == 'ALL') {
  1986. io.emit('informers', preObj)
  1987. } else {
  1988. socket.emit('informers', preObj);
  1989. }
  1990. }
  1991. });
  1992. }
  1993.  
  1994. }
  1995.  
  1996. function loadMyInventoryToFront(socket, steamId) {
  1997. var retries = 5;
  1998.  
  1999. var loadMyInventoryToFrontCore = function() {
  2000. retries--;
  2001.  
  2002. // Загружаем инвентарь партнера
  2003. // Сравниваем ИД предметов в его инвентаре и ИД посланных предметов
  2004. // Чтобы найти имя предметов и записать в массив
  2005. offers.loadPartnerInventory({partnerSteamId: steamId, appId: 730, contextId: 2}, function(err, items) {
  2006. if(err != null) {
  2007. console.log('Error loading inventory '+ steamId);
  2008. if (err.message.indexOf('401') > -1 && retries >= 0) {
  2009. reWebLogOn(steam, function() {
  2010. console.log(err.message + ': Retry load user\'s inventory, step: ' + retries);
  2011. loadMyInventoryToFrontCore();
  2012. });
  2013. } else {
  2014. console.log(err.message + ': Retry ' + offer.tradeofferid + ', step: ' + retries);
  2015.  
  2016. if (retries == 0) {
  2017. // @todo send message to the frontend
  2018. socket.emit('user-inventory', { items:false, sum:0 });
  2019.  
  2020. console.log('We can\'t load the inventory.');
  2021.  
  2022. } else {
  2023. loadMyInventoryToFrontCore();
  2024. }
  2025. }
  2026.  
  2027. } else {
  2028. console.log('User\'s inventory loaded!');
  2029.  
  2030. if (items.length < 1) {
  2031. socket.emit('user-inventory', { items:items, sum:0 });
  2032. }
  2033.  
  2034. // get the price
  2035. var currency = config.currency;
  2036.  
  2037. function getItemPrice(item, retry, callback) {
  2038. var link = "/market/priceoverview/?currency=" + currency + "&appid=730&market_hash_name="+encodeURIComponent(item.market_hash_name);
  2039.  
  2040. //Запрос к стим маркету
  2041. var req = http.get({host: 'steamcommunity.com', path: link}, function(response){
  2042. var str2 = '';
  2043. response.on('data', function (chunk) {
  2044. str2 += chunk
  2045. });
  2046.  
  2047. response.on('end', function() {
  2048. var price = JSON.parse(str2);
  2049. if (typeof price == 'undefined' || typeof price.median_price == 'undefined') {
  2050. console.log('There was an error on getItemPrice: ' + error);
  2051. if (req >= 0) {
  2052. getItemPrice(item, --retry, callback);
  2053. } else {
  2054. console.log('cant get price');
  2055. callback.call(this, 0);
  2056. }
  2057. }
  2058. try {
  2059. price = price.median_price.replace(',','.');
  2060. } catch(err) {
  2061. console.log('There was an error on getItemPrice: ' + error);
  2062. if (req >= 0) {
  2063. getItemPrice(item, --retry, callback);
  2064.  
  2065. } else {
  2066. console.log('cant get price');
  2067.  
  2068. callback.call(this, 0);
  2069. }
  2070. }
  2071. if (currency == 5) {
  2072. price = price.substring(0, price.indexOf(' '));
  2073. } else {
  2074. price = price.substr(price.indexOf(';')+1);
  2075. }
  2076.  
  2077. price = parseFloat(price);
  2078. price = Math.round(price * 100) / 100;
  2079.  
  2080. callback.call(this, price);
  2081. });
  2082. });
  2083.  
  2084. req.on('error', function(error) {
  2085. console.log('There was an error on getItemPrice: ' + error);
  2086. if (req >= 0) {
  2087. getItemPrice(item, --retry, callback);
  2088.  
  2089. } else {
  2090. console.log('cant get price');
  2091.  
  2092. callback.call(this, 0);
  2093. }
  2094. });
  2095.  
  2096. req.setTimeout(5000, function() {
  2097. console.log('TimeOut');
  2098. req.abort();
  2099. });
  2100.  
  2101. req.end();
  2102. }
  2103.  
  2104. var sum = 0;
  2105. items.forEach(function(item, i){
  2106. getItemPrice(item, 5, function(price){
  2107.  
  2108. items[i].price = price;
  2109. sum += price;
  2110.  
  2111. // send to socket on last iteration
  2112. if ((items.length - 1) === i && socket.readyState == 1) {
  2113. setTimeout(function(){
  2114. socket.emit('user-inventory', { items:items, sum:sum });
  2115. }, 500)
  2116. }
  2117. });
  2118. });
  2119. }
  2120. });
  2121. };
  2122.  
  2123. loadMyInventoryToFrontCore();
  2124. }
  2125.  
  2126. function updatePlayersGameCount(players, winnerid) {
  2127. if (players.length == 0) {
  2128. return;
  2129. }
  2130. players.forEach(function(player) {
  2131. try {
  2132. userListDB.find({steamid:player.steamid, name:'player'}).toArray(function(err, list){
  2133. if (err || list.length == 0) {
  2134. try {
  2135. userListDB.insert({
  2136. name: 'player',
  2137. steamid: player.steamid,
  2138. nick: player.nick,
  2139. ava: player.ava,
  2140. count: 1,
  2141. }, {w:1}, function(err) {if(err) helper.msg('Can t update player s game count: ' + err);});
  2142. } catch(err) {
  2143. helper.msg('Can t update player s game count: ' + err);
  2144. }
  2145. } else {
  2146. try {
  2147. userListDB.update({
  2148. steamid: player.steamid,
  2149. name: 'player'
  2150. }, {
  2151. name: 'player',
  2152. steamid: player.steamid,
  2153. nick: player.nick,
  2154. ava: player.ava,
  2155. count: parseInt(list[0].count)+1,
  2156. }, {
  2157. upsert: true
  2158. });
  2159. } catch (err) {
  2160. helper.msg('Can t update player s game count: ' + err);
  2161. }
  2162. }
  2163. });
  2164. } catch(err) {
  2165. helper.msg('Can t update player s game count: ' + err);
  2166. }
  2167. });
  2168. };
  2169.  
  2170. function getProfileStats(socket, steamid) {
  2171. gameDB.aggregate(
  2172. [
  2173. {"$match":{"name":"history", "steamid": steamid}},
  2174. {"$group":{"_id":{winnername:"$winnername",winnerimg:"$winnerimg", steamid:"$steamid"}, "total":{"$sum":"$winnermoney"}, "count":{"$sum":1}}},
  2175. { "$sort" : { total : -1 } },
  2176. {"$limit" : 20}
  2177. ]
  2178. ).toArray(function(err, list) {
  2179. if (!err && list.length > 0) {
  2180. userListDB.find({steamid:steamid, name:'player'}).toArray(function(err, player) {
  2181. if (!err) {
  2182. list[0].attempts = player[0].count;
  2183. } else {
  2184. list[0].attempts = 0;
  2185. }
  2186.  
  2187. socket.emit('profile', { list:list });
  2188. });
  2189. }
  2190. });
  2191. };
  2192.  
  2193. function checkConfirmations(steamcommunityMobileConfirmations){
  2194. steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
  2195. {
  2196. if (err)
  2197. {
  2198. console.log(err);
  2199. return;
  2200. }
  2201. console.log('steamcommunityMobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
  2202. if (!confirmations.length)
  2203. {
  2204. return;
  2205. }
  2206. steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
  2207. {
  2208. if (err)
  2209. {
  2210. console.log(err);
  2211. return;
  2212. }
  2213. console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
  2214. }).bind(this));
  2215. }).bind(this));
  2216. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement