Advertisement
Guest User

Untitled

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