Advertisement
Guest User

Untitled

a guest
May 17th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 31.25 KB | None | 0 0
  1. var config = require('./config.js'),
  2. fs = require('fs'),
  3. crypto = require('crypto');
  4.  
  5. /**
  6. * configure express
  7. */
  8. var expressApp = require('express')();
  9.  
  10. /**
  11. * configure http server
  12. */
  13. var http = require('http').Server(expressApp);
  14. http.listen(8080);
  15. /**
  16. * configure request-json
  17. */
  18. var reqJSON = require('request-json'),
  19. requestJSON = reqJSON.createClient(currentWorkingSite);
  20. /**
  21. * configure socket.io
  22. */
  23. var io = require('socket.io')(http);
  24.  
  25. /**
  26. * ssfn config
  27. */
  28. config.logOnOptions.sha_sentryfile = getSHA1(fs.readFileSync(__dirname + '/' + config.ssfn));
  29.  
  30. /**
  31. * configure steam npm package
  32. * configure steam-trade-offers package;
  33. */
  34. var Steam = require('steam'),
  35. SteamTradeOffers = require('steam-tradeoffers'),
  36. SteamWebLogOn = require('steam-weblogon'),
  37. getSteamAPIKey = require('steam-web-api-key');
  38.  
  39. // if we've saved a server list, use it
  40. if (fs.existsSync('servers')) {
  41. Steam.servers = JSON.parse(fs.readFileSync('servers'));
  42. }
  43.  
  44. var steamClient = new Steam.SteamClient(),
  45. steamUser = new Steam.SteamUser(steamClient),
  46. steamOffers = new SteamTradeOffers(),
  47. steamFriends = new Steam.SteamFriends(steamClient),
  48. steamWebLogOn = new SteamWebLogOn(steamClient, steamUser);
  49.  
  50. steamClient.connect();
  51.  
  52. steamClient.on('connected', function() {
  53. steamUser.logOn(config.logOnOptions);
  54. });
  55.  
  56. steamClient.on('error', function() {
  57. steamUser.logOn(config.logOnOptions);
  58. });
  59.  
  60. steamClient.on('logOnResponse', function(logonResp) {
  61. if (logonResp.eresult == Steam.EResult.OK) {
  62.  
  63. console.log('Steam client connected');
  64.  
  65. steamFriends.setPersonaState(Steam.EPersonaState.Online); // to display your bot's status as "Online"
  66.  
  67. steamWebLogOn.webLogOn(function(sessionID, newCookie) {
  68. getSteamAPIKey({
  69. sessionID: sessionID,
  70. webCookie: newCookie
  71. }, function(err, APIKey) {
  72. steamOffers.setup({
  73. sessionID: sessionID,
  74. webCookie: newCookie,
  75. APIKey: APIKey
  76. }, function() {
  77.  
  78. console.log('Steam webLogon is fine');
  79. console.log('Initializing trade-offers/winning-tradeoffers request every X seconds');
  80. var intervalForOffers = executeIntervalForOffers(),
  81. intervalForPendingWinningOffers = executeIntervalForPendingWinningOffers();
  82. });
  83. });
  84. });
  85.  
  86. }
  87.  
  88. });
  89. /*steam.on('webSessionID', function(sessionID) {
  90. helper.msg('webSessionID ok');
  91. currentSessionId = sessionID;
  92. reWebLogOn(steam);
  93. });
  94.  
  95.  
  96. function reWebLogOn(steam, callback) {
  97. steam.webLogOn(function(newCookie) {
  98. helper.msg('webLogOn ok');
  99.  
  100. offers.setup({
  101. sessionID: currentSessionId,
  102. webCookie: newCookie
  103. }, function() {
  104. if (typeof callback == "function") {
  105. callback();
  106. }
  107. });
  108. });
  109. }*/
  110. steamClient.on('servers', function(servers) {
  111. fs.writeFile('servers', JSON.stringify(servers));
  112. });
  113.  
  114. steamUser.on('updateMachineAuth', function(sentry, callback) {
  115. fs.writeFileSync('sentry', sentry.bytes);
  116. callback({
  117. sha_file: getSHA1(sentry.bytes)
  118. });
  119. });
  120.  
  121. steamOffers.on('debug', function(el) {
  122. console.log(el);
  123. });
  124.  
  125.  
  126. /**
  127. * new round initialization;
  128. */
  129.  
  130. //check if there is a new round already active;
  131. requestJSON.get('api/activeRoundGoingOn', function(err, res, json) {
  132. if (res.statusCode === 200) {
  133. if (json.success === true) {
  134. WinningPercentage = json.game.ticket;
  135. HashOfGame = json.game.game_hash;
  136. SaltOfGame = json.game.game_salt;
  137. currentGameID = json.game.id;
  138. console.log('Found new active round with id #' + json.game.id + '. Setting it up');
  139. //emit new round;
  140. io.emit('newGameRound', {
  141. gameID: currentGameID,
  142. gameHash: HashOfGame
  143. });
  144. requestJSON.post('api/getRoundPot', {
  145. gameid: currentGameID
  146. }, function(err, res, json) {
  147. if (res.statusCode === 200 && json.success) {
  148. io.emit('roundPot', {
  149. potplayers: json.html,
  150. potitems: json.potitems,
  151. timerisactive: (!timerID ? false : true)
  152. });
  153. } else {
  154. console.log('Error getting round pot');
  155. }
  156. });
  157. //get current pot items;
  158. requestJSON.get('api/getTotalPotItems/' + currentGameID, function(err, res, json_) {
  159. if (res.statusCode === 200 && json_.success) {
  160. currentTotalPotItems = json_.potItems;
  161. if (currentTotalPotItems >= config.itemsToStart) {
  162. startTimerForRound();
  163. }
  164. } else {
  165. console.log('Error api/getTotalPotItems');
  166. }
  167. });
  168. respondToConsole();
  169. } else {
  170. initiateNewRound();
  171. }
  172. }
  173. });
  174.  
  175. function startTimerForRound() {
  176. //comes from request json activeRoundGoingOn;
  177. //not only;
  178. if (!timerID) {
  179. timerToTick = config.gameDuration;
  180. timerID = setInterval(function() {
  181. timerToTick--;
  182.  
  183. var minute = Math.floor(timerToTick / 60),
  184. second = timerToTick % 60;
  185.  
  186. second = second.toString();
  187. second = second.substr(0, 2);
  188. io.emit('timerTick', {
  189. timerToTick: minute + ":" + second
  190. });
  191.  
  192. if (timerToTick <= 0) {
  193. console.log('Time is over');
  194. pickAWinner(currentGameID);
  195. clearInterval(timerID);
  196. timerID = false;
  197. }
  198. }, 1000);
  199. } else {
  200. console.log('timerID is defined already');
  201. }
  202. }
  203. var SaltOfGame = null,
  204. WinningPercentage = null,
  205. HashOfGame = null,
  206. currentGameID = null,
  207. currentTotalPotItems = 0,
  208. pendingWinningTradeoffers = [],
  209. timerID = null;
  210.  
  211. function respondToConsole() {
  212. console.log('Current Game Salt: ' + SaltOfGame);
  213. console.log('Next Winner percentage is: ' + WinningPercentage + '%');
  214. console.log('Current Game Hash is: ' + HashOfGame);
  215. }
  216.  
  217. function initiateNewRound() {
  218. if (gameIsPaused) {
  219. gameIsPaused = false;
  220. }
  221. WinningPercentage = randomInRange(0, 100);
  222. SaltOfGame = makeid();
  223. HashOfGame = crypto.createHash('md5').update(SaltOfGame + ':' + WinningPercentage).digest('hex');
  224. currentGameID = null;
  225. //add new game to sql;
  226. addNewGameToDB();
  227. }
  228.  
  229. var peers = [],
  230. pendingSentOffers = [],
  231. timerInterval = null,
  232. gameIsPaused = false,
  233. timerToTick = 0,
  234. pendingUserToGetOffered = [],
  235. chatMessages = [],
  236. pendingChatMessageForUserApiKey = [],
  237. userIDPendingOffer = [];
  238.  
  239. io.on('connection', function(socket) {
  240. //push client
  241. peers.push(socket);
  242. //emit peers
  243. socket.emit('peers', {
  244. totalPeers: peers.length
  245. });
  246.  
  247. requestJSON.get('api/getChatMessages', function(err, res, json) {
  248. if (typeof res === 'undefined') return;
  249.  
  250. if (res.statusCode === 200 && json.success) {
  251. io.emit('sendChatData', json.html);
  252. }
  253. });
  254.  
  255. socket.on('ez', function() {
  256. requestJSON.post('api/getRoundPot', {
  257. gameid: (currentGameID ? currentGameID : 0)
  258. }, function(err, res, json) {
  259.  
  260. if (typeof res === 'undefined') return;
  261.  
  262. if (res.statusCode === 200 && json.success) {
  263. if (typeof io.sockets.connected === 'undefined' || typeof socket.id === 'undefined' || typeof io.sockets.connected[socket.id] === 'undefined') {
  264. return;
  265. }
  266. io.sockets.connected[socket.id].emit('roundPot', {
  267. potplayers: json.html,
  268. potitems: json.potitems,
  269. timerisactive: (!timerID ? false : true)
  270. });
  271. }
  272. });
  273. });
  274.  
  275. //on disconnect
  276. socket.on('disconnect', function(socket) {
  277. //delete from peers list
  278. peers.splice(peers.indexOf(socket), 1);
  279. //update count
  280. io.emit('peers', {
  281. totalPeers: peers.length
  282. });
  283. });
  284.  
  285. //requestOffer
  286. socket.on('requestOffer', function(data) {
  287. //rewrote;
  288. requestJSON.get('api/userExists/' + data.apikey, function(err, res, user) {
  289. //returns
  290. //**user.userid
  291. //**user.tradeurl
  292. //**user.steamid
  293. //**user.avatar
  294. if (res.statusCode === 200 && user.success) {
  295.  
  296. if (userIDPendingOffer.indexOf(user.userid) > -1) {
  297. console.log('Cant offer him. Still awaiting for another offer to be accepted/declined of user: ' + user.userid);
  298. socket.emit('playerError', {
  299. apikey: data.apikey,
  300. html: "There is already a pending offer for you. Please either accept or decline it to be able to make a new trade. <div class='modal-close'>close</div>"
  301. });
  302. return;
  303. }
  304.  
  305. if (pendingUserToGetOffered.indexOf(user.userid) > -1) {
  306. //there is a pending getOffer request; return;
  307. console.log('Cant offer him. Still awaiting for steam to respond for another trade offer of ' + user.userid);
  308. socket.emit('playerError', {
  309. apikey: data.apikey,
  310. html: "There is already a pending offer for you and we're afraid that steam is delayed :( <div class='modal-close'>close</div>"
  311. });
  312. return;
  313. }
  314.  
  315. pendingUserToGetOffered.push(user.userid);
  316. userIDPendingOffer.push(user.userid);
  317.  
  318. requestJSON.get('api/playerTotalPot/' + currentGameID + '/' + user.userid, function(err, res, json_) {
  319.  
  320. if (res.statusCode === 200 && json_.success) {
  321. if (json_.total >= config.usersItemsLimit || ((data.items.length + json_.total) > config.usersItemsLimit)) {
  322. console.log('User ' + user.steamid + ' reached maximum skins deposited');
  323. socket.emit('playerError', {
  324. apikey: data.apikey,
  325. html: "You can't deposit more than 10 skins <div class='modal-close'>close</div>"
  326. });
  327. pendingUserToGetOffered.splice(pendingUserToGetOffered.indexOf(user.userid), 1);
  328. userIDPendingOffer.splice(userIDPendingOffer.indexOf(user.userid), 1);
  329. return;
  330. } else {
  331. var partnerInventoryRetry = 5;
  332.  
  333. var token = user.tradeurl;
  334. token = token.substr(token.indexOf('&token') + 7);
  335.  
  336. var accountid = user.tradeurl;
  337. accountid = accountid.substr(accountid.indexOf('?partner') + 9);
  338. accountid = accountid.substring(0, accountid.indexOf('&'));
  339.  
  340. var loadPartnerInventory = function() {
  341. partnerInventoryRetry--;
  342. steamOffers.loadPartnerInventory({
  343. appId: 730,
  344. contextId: 2,
  345. partnerAccountId: accountid
  346. }, function(err, items) {
  347. if (err) {
  348. console.log('Error loadPartnerInventory ' + err);
  349. if (partnerInventoryRetry >= 0) {
  350. console.log('Retry loadPartnerInventory step: ' + partnerInventoryRetry);
  351. setTimeout(function() {
  352. loadPartnerInventory();
  353. }, 2000);
  354. } else {
  355. userIDPendingOffer.splice(userIDPendingOffer.indexOf(user.userid), 1);
  356. }
  357. } else {
  358. var lengthToCheck = data.items.length,
  359. itemsExist = 0,
  360. itemsInfo = [];
  361.  
  362. for (var i = 0; i < items.length; i++) {
  363. for (var z in data.items) {
  364. if (items[i].id === data.items[z] && items[i].tradable) {
  365. itemsInfo.push({
  366. name: items[i].market_hash_name
  367. });
  368. itemsExist += 1;
  369. continue;
  370. }
  371. if (itemsExist === lengthToCheck) break;
  372. }
  373. }
  374. //after loading inventory
  375. if (itemsExist === lengthToCheck) {
  376. //all items proposed from site exists
  377. //move on and make him an offer;
  378.  
  379. var itemsToRequest = buildItemsArrayToRequest(data.items);
  380.  
  381. console.log('Trying to make ' + user.steamid + ' an offer');
  382. //check if he has alreayd a pending offer with same assetid;
  383. if (pendingSentOffers.length > 0) {
  384.  
  385. var newArray_ = [];
  386. for (var z in itemsToRequest) {
  387. newArray_.push(itemsToRequest[z].assetid);
  388. }
  389.  
  390. for (var z in pendingSentOffers) {
  391. if (pendingSentOffers[z].userid == user.userid) {
  392. for (var ex in pendingSentOffers[z].assetids) {
  393. if (newArray_.indexOf(pendingSentOffers[z].assetids[ex]) > -1) {
  394. socket.emit('playerError', {
  395. apikey: data.apikey,
  396. html: "You tried to deposit an already pending item. <div class='modal-close'>close</div>"
  397. });
  398. pendingUserToGetOffered.splice(pendingUserToGetOffered.indexOf(user.userid), 1);
  399. userIDPendingOffer.splice(userIDPendingOffer.indexOf(user.userid), 1);
  400. return;
  401. }
  402. }
  403. }
  404. }
  405.  
  406. }
  407.  
  408. var makeHimAnOfferTries = 5;
  409. var makeHimAnOffer = function() {
  410. steamOffers.makeOffer({
  411. partnerAccountId: accountid,
  412. accessToken: token,
  413. itemsFromMe: [],
  414. itemsFromThem: itemsToRequest,
  415. message: 'Deposit for Game # ' + currentGameID + '. Thanks for gambling.'
  416. }, function(err, response) {
  417.  
  418. if (err) {
  419. console.log('Error making an offer: Retry ' + makeHimAnOfferTries);
  420. makeHimAnOfferTries--;
  421. if (makeHimAnOfferTries > 0) {
  422. setTimeout(function() {
  423. makeHimAnOffer();
  424. }, 3000);
  425. } else {
  426. socket.emit('playerError', {
  427. apikey: data.apikey,
  428. html: "Couldn't reach steam. Please try again. <div class='modal-close'>close</div>"
  429. });
  430. pendingUserToGetOffered.splice(pendingUserToGetOffered.indexOf(user.userid), 1);
  431. userIDPendingOffer.splice(userIDPendingOffer.indexOf(user.userid), 1);
  432. }
  433. return;
  434. }
  435.  
  436. requestJSON.post('api/getItemInfo', {
  437. items: itemsInfo
  438. }, function(err, res, json) {
  439. if (json.success === true) {
  440. var assetidsMotherfucker = [];
  441. for (var z in itemsToRequest) {
  442. assetidsMotherfucker.push(itemsToRequest[z].assetid);
  443. }
  444. pendingSentOffers.push({
  445. tradeofferid: response.tradeofferid,
  446. steamid: user.steamid,
  447. userid: user.userid,
  448. items: json.items,
  449. assetids: assetidsMotherfucker
  450. });
  451. socket.emit('playerDeposited', {
  452. apikey: data.apikey,
  453. html: "Your deposit has been successful <a href='https://steamcommunity.com/tradeoffer/" + response.tradeofferid + "' class='link' target='_blank'>Click here to view the trade offer</a><div class='modal-close'>close</div>",
  454. });
  455. console.log('Offer with id ' + response.tradeofferid + ' of user with steam id ' + user.steamid + ' has been pushed');
  456. }
  457. pendingUserToGetOffered.splice(pendingUserToGetOffered.indexOf(user.userid), 1);
  458. });
  459.  
  460. });
  461. }
  462. makeHimAnOffer();
  463.  
  464. } else {
  465. socket.emit('playerError', {
  466. apikey: data.apikey,
  467. html: "Couldn't find deposited items in your inventory. Please try again. <div class='modal-close'>close</div>"
  468. });
  469. pendingUserToGetOffered.splice(pendingUserToGetOffered.indexOf(user.userid), 1);
  470. }
  471. }
  472. });
  473.  
  474. };
  475. loadPartnerInventory();
  476. }
  477. }
  478. });
  479. }
  480. });
  481. });
  482.  
  483. socket.on('sendChatMessage', function(data) {
  484.  
  485. if (pendingChatMessageForUserApiKey.indexOf(data.apikey) > -1) {
  486. console.log('Didnt push his previous message. Returning');
  487. return;
  488. }
  489.  
  490. pendingChatMessageForUserApiKey.push(data.apikey);
  491.  
  492. requestJSON.post('api/saveChatMessage', {
  493. apikey: data.apikey,
  494. message: data.message
  495. }, function(err, res, json) {
  496. if (res.statusCode === 200 && json.success) {
  497. io.emit('sendChatData', json.html);
  498. } else {
  499. console.log('Error api/saveChatMessage');
  500. }
  501. pendingChatMessageForUserApiKey.splice(pendingChatMessageForUserApiKey.indexOf(data.apikey), 1);
  502. });
  503.  
  504. });
  505.  
  506. /**
  507. * admin emits
  508. */
  509. socket.on('deletedMessages', function() {
  510. requestJSON.get('api/getChatMessages', function(err, res, json) {
  511. if (res.statusCode === 200 && json.success) {
  512. io.emit('sendChatData', json.html);
  513. }
  514. });
  515. });
  516.  
  517. if (currentGameID) {
  518. socket.emit('newGameRound', {
  519. gameID: currentGameID,
  520. gameHash: HashOfGame
  521. });
  522. }
  523. });
  524.  
  525.  
  526. var buildItemsArrayToRequest = function(items) {
  527. var itemsToSend = [];
  528.  
  529. for (var z in items) {
  530. //z key
  531. //items[0] item.id;
  532. itemsToSend.push({
  533. appid: 730,
  534. contextid: 2,
  535. amount: 1,
  536. assetid: items[z]
  537. });
  538. }
  539. return itemsToSend;
  540. }
  541.  
  542. /**
  543. * functions;
  544. */
  545. var pendingHoldTradeOfferIds = [],
  546. pendingHoldWinnerTradeOfferIds = [];
  547.  
  548. var timesCheckedAnID = [];
  549.  
  550. function executeIntervalForOffers() {
  551. setInterval(function() {
  552. if (pendingSentOffers.length > 0 && !gameIsPaused) {
  553. pendingSentOffers.forEach(function(offer, i) {
  554.  
  555. console.log('Checking ' + offer.tradeofferid);
  556.  
  557. if (typeof offer === 'undefined') {
  558. return;
  559. }
  560.  
  561. if (pendingHoldTradeOfferIds.indexOf(offer.tradeofferid) > -1) {
  562. //there is a pending getOffer request; return;
  563. console.log(timesCheckedAnID[offer.tradeofferid]);
  564. if (timesCheckedAnID[offer.tradeofferid] >= 20) {
  565. console.log('Checked him 5 times. Dodge');
  566. timesCheckedAnID.splice(timesCheckedAnID.indexOf(timesCheckedAnID[offer.tradeofferid]), 1);
  567. pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  568. return;
  569. } else {
  570. timesCheckedAnID[offer.tradeofferid] = timesCheckedAnID[offer.tradeofferid] + 1;
  571. console.log('Returning. Awaiting for steam response');
  572. return;
  573. }
  574. }
  575.  
  576. timesCheckedAnID[offer.tradeofferid] = 1;
  577.  
  578. pendingHoldTradeOfferIds.push(offer.tradeofferid);
  579.  
  580. steamOffers.getOffer({
  581. tradeofferid: offer.tradeofferid
  582. }, function(error, body) {
  583. if (body && body.response && body.response.offer && body.response.offer.trade_offer_state) {
  584.  
  585. switch (body.response.offer.trade_offer_state) {
  586. case 1:
  587. case 4:
  588. case 5:
  589. case 6:
  590. case 7:
  591. case 8:
  592. case 9:
  593. case 10:
  594. console.log('Tradeofferid ' + body.response.offer.tradeofferid + ' has either declined/expired/unavailabe. Return');
  595. console.log('Should remove ' + body.response.offer.tradeofferid);
  596. //removing user from being pending so he can make an offer again;
  597. userIDPendingOffer.splice(userIDPendingOffer.indexOf(offer.userid), 1);
  598. //removing pending tradeofferid;
  599. pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  600. //removing pending sent offer;
  601. pendingSentOffers = removeFromArray(pendingSentOffers, offer.tradeofferid);
  602. break;
  603. case 2: //still active
  604. console.log('Offer with id ' + body.response.offer.tradeofferid + ' still active. Return.')
  605. //console.log(body.response.descriptions);
  606. pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  607. break;
  608. case 3: //accepted
  609. console.log('Recipient ' + body.response.offer.steamid_other + ' has accepted the offer with id ' + body.response.offer.tradeofferid + '. Pushing the guy into pot');
  610. if (typeof offer === 'undefined' || !offer.userid) {
  611. return false;
  612. }
  613. requestJSON.post('api/addPotItems', {
  614. gameid: currentGameID,
  615. userid: offer.userid,
  616. items: offer.items
  617. }, function(err, res, json) {
  618. if (typeof res !== 'undefined' && res.statusCode === 200) {
  619. if (json.success) {
  620. //json.total_items
  621. console.log('All good with ' + body.response.offer.tradeofferid + '. Emitting');
  622. currentTotalPotItems += json.total_items;
  623. requestJSON.post('api/getRoundPot', {
  624. gameid: currentGameID
  625. }, function(err, res, json) {
  626. if (res.statusCode === 200 && json.success) {
  627. io.emit('roundPot', {
  628. potplayers: json.html,
  629. potitems: json.potitems,
  630. timerisactive: (!timerID ? false : true)
  631. });
  632. }
  633. });
  634. io.emit('enterPot', {
  635. gameid: currentGameID,
  636. steamid: body.response.offer.steamid_other,
  637. html: "You entered Game Round # " + currentGameID + ". You can view more stats on the Current Pot Players sidebar. <div class='modal-close'>close</div>"
  638. });
  639.  
  640. requestJSON.get('api/getTotalPotItems/' + currentGameID, function(err, res, json_) {
  641. if (res.statusCode === 200 && json_.success) {
  642. currentTotalPotItems = json_.potItems;
  643. if (currentTotalPotItems >= config.itemsToStart) {
  644. if (wheelStillSpinning) {
  645. setTimeout(function() {
  646. startTimerForRound();
  647. }, 10000);
  648. } else {
  649. startTimerForRound();
  650. }
  651. }
  652. pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  653. }
  654. });
  655. }
  656. } else {
  657. console.log('Error api/addPotItems');
  658. console.log(json);
  659. }
  660. });
  661.  
  662. //removing user from being pending so he can make an offer again;
  663. userIDPendingOffer.splice(userIDPendingOffer.indexOf(offer.userid), 1);
  664.  
  665. pendingSentOffers = removeFromArray(pendingSentOffers, offer.tradeofferid);
  666. break;
  667. }
  668.  
  669. } else {
  670. console.log('No body or error occured');
  671. pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  672. return false;
  673. }
  674. });
  675. //offer.tradeofferid;
  676. //offer.steamid;
  677. //offer.userid;
  678. //offer.items[z].id//name//price;
  679. });
  680. }
  681. }, 10000);
  682. }
  683.  
  684. function executeIntervalForPendingWinningOffers() {
  685. //comes from weblogon
  686. setInterval(function() {
  687. /*pendingWinningTradeoffers.push({
  688. gameRound: gameID,
  689. tradeofferid: response.tradeofferid
  690. assetids: []
  691. });*/
  692. if (pendingWinningTradeoffers.length > 0) {
  693. pendingWinningTradeoffers.forEach(function(winningoffer, i) {
  694. if (typeof winningoffer === 'undefined') {
  695. console.log('Undefined what the fuck');
  696. return;
  697. }
  698.  
  699. if (pendingHoldWinnerTradeOfferIds.indexOf(winningoffer.tradeofferid) > -1) {
  700. console.log('Returning. Awaiting for steam response. Winnings');
  701. return;
  702. }
  703.  
  704. pendingHoldWinnerTradeOfferIds.push(winningoffer.tradeofferid);
  705.  
  706. steamOffers.getOffer({
  707. tradeofferid: winningoffer.tradeofferid
  708. }, function(error, body) {
  709. if (body && body.response && body.response.offer && body.response.offer.trade_offer_state) {
  710.  
  711. switch (body.response.offer.trade_offer_state) {
  712. case 2:
  713. console.log('Winner tradeofferid ' + body.response.offer.tradeofferid + ' is still active');
  714. pendingHoldWinnerTradeOfferIds.splice(pendingHoldWinnerTradeOfferIds.indexOf(body.response.offer.tradeofferid), 1);
  715. break;
  716. case 3:
  717. console.log('Winner tradeofferid ' + body.response.offer.tradeofferid + ' got accepted. Remove items from being held.');
  718. requestJSON.post('api/updateGame', {
  719. state: 'completed',
  720. gameid: winningoffer.gameRound
  721. }, function(err, res, json) {
  722. if (res.statusCode === 200 && json.success) {
  723. console.log('Game updated to completed');
  724. }
  725. });
  726. //remove body.response.offer.tradeofferid from pendingwinningtradeofferids;
  727. //pendingHoldTradeOfferIds.splice(pendingHoldTradeOfferIds.indexOf(offer.tradeofferid), 1);
  728. //pendingSentOffers = removeFromArray(pendingSentOffers, body.response.offer.tradeofferid);
  729. pendingHoldWinnerTradeOfferIds.splice(pendingHoldWinnerTradeOfferIds.indexOf(body.response.offer.tradeofferid), 1);
  730. pendingWinningTradeoffers = removeFromArray(pendingWinningTradeoffers, body.response.offer.tradeofferid);
  731. break;
  732. case 7:
  733. console.log('Winner tradeofferid ' + body.response.offer.tradeofferid + ' is retarded and he declined winnings. Remove items from being held.');
  734. pendingHoldWinnerTradeOfferIds.splice(pendingHoldWinnerTradeOfferIds.indexOf(body.response.offer.tradeofferid), 1);
  735. pendingWinningTradeoffers = removeFromArray(pendingWinningTradeoffers, body.response.offer.tradeofferid);
  736. break;
  737. }
  738. } else {
  739. console.log('No body or error occured');
  740. pendingHoldWinnerTradeOfferIds.splice(pendingHoldWinnerTradeOfferIds.indexOf(winningoffer.tradeofferid), 1);
  741. return false;
  742. }
  743. });
  744.  
  745. });
  746. }
  747. }, 20000);
  748. }
  749.  
  750. function makeid() {
  751. var text = "";
  752. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  753.  
  754. for (var i = 0; i < 16; i++)
  755. text += possible.charAt(Math.floor(Math.random() * possible.length));
  756.  
  757. return text;
  758. }
  759.  
  760. function randomInRange(min, max) {
  761. return Math.random() < 0.5 ? ((1 - Math.random()) * (max - min) + min) : (Math.random() * (max - min) + min);
  762. }
  763.  
  764. function getSHA1(bytes) {
  765. var shasum = crypto.createHash('sha1');
  766. shasum.end(bytes);
  767. return shasum.read();
  768. }
  769.  
  770. function removeFromArray(array, itemToRemove) {
  771. var newArray = array.filter(function(el) {
  772. return el.tradeofferid !== itemToRemove
  773. });
  774. return newArray;
  775. }
  776.  
  777. function addNewGameToDB(callback) {
  778. requestJSON.post('api/addNewGame/', {
  779. hash: HashOfGame,
  780. salt: SaltOfGame,
  781. ticket: WinningPercentage.toString(),
  782. pass: superPassword
  783. }, function(err, res, json) {
  784. if (res.statusCode === 200) {
  785. if (json.success) {
  786. if (callback && typeof callback === 'function') {
  787. callback();
  788. }
  789. currentGameID = json.game_id;
  790. io.emit('newGameRound', {
  791. gameID: currentGameID,
  792. gameHash: HashOfGame
  793. });
  794. console.log('Current game saved with Game Number #' + json.game_id);
  795. respondToConsole();
  796. }
  797. } else {
  798. console.log('Error api/addNewGame');
  799. }
  800. });
  801. }
  802.  
  803. var wheelStillSpinning = false;
  804.  
  805. function initiateWheelForGame(currentGameID, userID) {
  806. //comes from pickAWinner;
  807. wheelStillSpinning = true;
  808.  
  809. requestJSON.get('api/potPlayersForGame/' + currentGameID, function(err, res, json) {
  810. if (res.statusCode === 200 && json.success) {
  811. //json.wheelData;
  812. //json.jackpot;
  813. //json.totalDepositedSkins;
  814. io.emit('startWheel', {
  815. players: json.wheelData,
  816. winnerid: userID,
  817. jackpot: json.jackpot,
  818. totalSkins: json.totalDepositedSkins,
  819. });
  820. setTimeout(function() {
  821. wheelStillSpinning = false;
  822. }, 7000);
  823. } else {
  824. console.log('Error api/potPlayersForGame');
  825. }
  826. });
  827. }
  828.  
  829. function completeCurrentGame(gameID, userID) {
  830. //comes from pickAWinner;
  831. requestJSON.post('api/completeCurrentGame', {
  832. gameid: gameID,
  833. userid: userID,
  834. pass: superPassword
  835. }, function(err, res, json) {
  836. if (res.statusCode === 200 && json.success) {
  837. //we got the itemNames to give;
  838. //json.usersteamid
  839. //json.tradeurl,
  840. //json.apikey
  841. var itemNamesToGive = json.itemNames;
  842. console.log('Loading my inventory to give ' + json.itemNames.length + ' items.');
  843. steamOffers.loadMyInventory({
  844. appId: 730,
  845. contextId: 2,
  846. tradableOnly: true
  847. }, function(err, items) {
  848.  
  849. var itemsFound = [],
  850. cachedInventory = items;
  851.  
  852. console.log('Inventory total items: ' + cachedInventory.length);
  853.  
  854. if (pendingWinningTradeoffers.length > 0) {
  855. var assetidsToRemove = [];
  856.  
  857. for (var w in pendingWinningTradeoffers) {
  858. for (var omi in pendingWinningTradeoffers[w].assetids) {
  859. assetidsToRemove.push(pendingWinningTradeoffers[w].assetids[omi]);
  860. }
  861. }
  862.  
  863. for (var q in cachedInventory) {
  864. for (var ez in assetidsToRemove) {
  865. //assetidsToRemove[ez] == assetid
  866. if (assetidsToRemove[ez] === cachedInventory[q].id) {
  867. console.log('Removed ' + cachedInventory[q].id + ' from inventory');
  868. cachedInventory.splice(q, 1);
  869. }
  870. }
  871. }
  872. };
  873.  
  874. for (var key in itemNamesToGive) {
  875. //key = name to check
  876. for (var x in cachedInventory) {
  877.  
  878. if (cachedInventory[x].market_hash_name === itemNamesToGive[key]) {
  879.  
  880. itemsFound.push({
  881. name: cachedInventory[x].market_hash_name,
  882. assetid: cachedInventory[x].id
  883. });
  884.  
  885. cachedInventory.splice(x, 1);
  886. break;
  887.  
  888. }
  889.  
  890. }
  891. }
  892.  
  893. /*newly written*/
  894. /*sending to other bot an offer*/
  895. if (cachedInventory.length >= 200) {
  896. console.log('Making an offer to our bot');
  897. makeAnOfferToOurBot(cachedInventory);
  898. }
  899.  
  900. if (itemsFound.length === itemNamesToGive.length) {
  901. console.log('Found all items. Proceeding to give items to winner with userID: ' + userID + ' for gameID: ' + gameID);
  902. } else {
  903. console.log('Didnt found all items');
  904. }
  905.  
  906. var itemsToSend = [],
  907. retriesToSendWinnerItems = 5;
  908.  
  909. for (var wiss in itemsFound) {
  910. itemsToSend.push({
  911. "appid": 730,
  912. "contextid": 2,
  913. "amount": 1,
  914. "assetid": itemsFound[wiss].assetid
  915. });
  916. }
  917.  
  918. var sendWinner = function() {
  919. retriesToSendWinnerItems--;
  920. var token = null,
  921. accountid = null;
  922.  
  923. if (!json.tradeurl) {
  924. //needs a player message error etc;
  925. return console.log('He has not trade url');
  926. }
  927.  
  928. token = json.tradeurl;
  929. token = token.substr(token.indexOf('&token') + 7);
  930. console.log('Winning user token: ' + token);
  931.  
  932. accountid = json.tradeurl;
  933. accountid = accountid.substr(accountid.indexOf('?partner') + 9);
  934. accountid = accountid.substring(0, accountid.indexOf('&'));
  935.  
  936. console.log('Winning user account id: ' + accountid);
  937.  
  938. steamOffers.makeOffer({
  939. partnerAccountId: accountid,
  940. accessToken: token,
  941. itemsFromMe: itemsToSend,
  942. itemsFromThem: [],
  943. message: 'Congratulations ! You won Game Number #' + gameID + '. These are your winnings. Thanks for gambling.'
  944. }, function(err, response) {
  945. if (err) {
  946. console.log('Error sending offer to userID ' + userID + ' for winning game number ' + gameID);
  947. if (retriesToSendWinnerItems >= 0) {
  948. console.log('Retry sending offer: ' + retriesToSendWinnerItems);
  949. setTimeout(function() {
  950. sendWinner();
  951. }, 2000);
  952. } else {
  953. io.emit('playerError', {
  954. apikey: json.apikey,
  955. html: "We tried 5 times to send you your winnings. Our bot will retry shortly. <div class='modal-close'>close</div>"
  956. });
  957. }
  958. return;
  959. }
  960. console.log('Trade offer for winnings of round #' + gameID + ' was successful. Emitting winnerMessage');
  961. requestJSON.post('api/updateGame', {
  962. state: 'semicompleted',
  963. gameid: gameID
  964. }, function(err, res, json) {
  965. if (res.statusCode === 200 && json.success) {
  966. console.log('Round: ' + gameID + ' has been updated to semicompleted');
  967. }
  968. });
  969. io.emit('winnerMessage', {
  970. apikey: json.apikey,
  971. html: "Your winnings has been sent to you. <a href='https://steamcommunity.com/tradeoffer/" + response.tradeofferid + "' class='link' target='_blank'>Click here to accept your winnings.</a><div class='modal-close'>close</div>",
  972. });
  973. //pushing item assetids to be onhold;
  974. var smallArray = [];
  975. for (var o in itemsToSend) {
  976. smallArray.push(itemsToSend[o].assetid);
  977. }
  978. //pushing winning trade offer id for check up every 20s;
  979. pendingWinningTradeoffers.push({
  980. gameRound: gameID,
  981. tradeofferid: response.tradeofferid,
  982. assetids: smallArray
  983. });
  984. //emitting end-game to clear shit;
  985. io.emit('endRound', {
  986. gameid: gameID
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement