Advertisement
Guest User

XDSTEAMBOT

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