Advertisement
Guest User

Untitled

a guest
Jan 8th, 2018
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 61.65 KB | None | 0 0
  1. var config = require('./config.js');
  2.  
  3. var colors = require('colors');
  4. var mysql = require('mysql2');
  5.  
  6. var fs = require('fs');
  7. var SteamUser = require('steam-user');
  8. var Steamcommunity = require('steamcommunity');
  9. var SteamTotp = require('steam-totp');
  10. var TradeOfferManager = require('steam-tradeoffer-manager');
  11. var request = require('request');
  12. var crypto = require('crypto');
  13.  
  14. var connection = mysql.createConnection({
  15. host: config.db.host,
  16. user: config.db.user,
  17. password: config.db.password,
  18. database: config.db.database
  19. });
  20.  
  21.  
  22. var account = {
  23. accountName: config.bot.accountName,
  24. password: config.bot.password,
  25. shared_secret: config.bot.shared_secret,
  26. identity_secret: config.bot.identity_secret
  27. };
  28.  
  29. var steamapiio_key = '1bb8233e5582b18a1b831215d2fe4e9d';
  30. var steamapis_key = config.steamapis_key;
  31.  
  32. var adminIds = config.admins;
  33. var allowedAppids = [252490]; //CSGO: 730 | RUST: 252490
  34.  
  35. var minPrice = 0.01;
  36.  
  37.  
  38. var settings = {
  39. jackpotPaused: false,
  40. chatPaused: false
  41. };
  42.  
  43.  
  44. var announcement = '<span class="redText"> RELEASE SOON </span>';
  45.  
  46. var playerInfo = {};
  47.  
  48. var io;
  49. var socket_port = config.socket_port;
  50.  
  51. var currentChat = [];
  52. var maxChatLength = 20;
  53.  
  54. var roundNumber = 1;
  55. var gameloopInterval;
  56.  
  57. var itemsInPot = 0;
  58. var potPlayers = [];
  59. var dataItemsInPot = [];
  60. var itemQueue = [];
  61.  
  62. var roundTotal = 0;
  63.  
  64. var currentHash = 'f10d97ddfad20146fdaf8b4b7f915f9ced3896d0';
  65. var currentSalt = '0wbw5djl';
  66.  
  67.  
  68. var waitTime = config.waitTime;
  69. var timeLeft = waitTime;
  70.  
  71. var isPotRunning = false;
  72. var isRolling = false;
  73.  
  74. var lastWinner = { roundid: 0, name: 'Cristal', amount: '1337.88', percentage: '0.69', img: 'cykablyat.png', ticket: 0.691337, steamid: '12314', hash: '132141323NOSCAM', salt: '3123Kappa'};
  75. var historyGames = [];
  76.  
  77. var userTotalBanned = [];
  78. var userChatBanned = [];
  79.  
  80.  
  81. function setup(){
  82. io = require('socket.io')(socket_port);
  83. ioSetup();
  84. }
  85.  
  86. function clearConsole() {
  87. process.stdout.write("\u001b[2J\u001b[0;0H");
  88. console.log(colors.red('RustyPot.com')+ colors.yellow(' by') + colors.green(' CRISTAL | FABSCH'));
  89. }
  90.  
  91. function ioSetup(){
  92. logInfo('Socket running on port '+socket_port);
  93. io.on('connection', function (socket) {
  94. initSocket(socket);
  95. socket.on('userConnection', function(user_connection_data){
  96. connection.query('SELECT * FROM user WHERE userHash = ?', user_connection_data.userHash, function(error, results){
  97. if(!error){
  98. if(results.length == 1){
  99. if(userTotalBanned.indexOf(results[0].steamid) != -1){
  100. notifySocket(socket, 'error', 'You are banned from the Site! ');
  101. notifySocket(socket, 'info', 'Please contact support if you want to appeal this ban');
  102. } else {
  103. socket.join(results[0].steamid+'');
  104. initLoggedInSocket(socket, results[0].steamid, results[0].steamname, results[0].avatar, results[0].avatar_small, results[0].tradelink, results[0].rank, Math.round(results[0].deposited / 5));
  105. if(results[0].rank == 100){
  106. socket.join('admin');
  107. initAdminSocket(socket, results[0].steamid, results[0].steamname);
  108. } else {
  109. socket.join('normal');
  110. }
  111. }
  112. } else {
  113. notifySocket(socket, 'error', 'Failed to find your Userdata.');
  114. }
  115. } else {
  116. notifySocket(socket, 'error', 'Error while loading your Userdata.');
  117. }
  118. });
  119. });
  120. });
  121. }
  122.  
  123. function initSocket(socket){
  124. emitJackpotData(socket);
  125.  
  126. emitChatMessages(socket);
  127.  
  128. emitGameHistoryAll(socket);
  129.  
  130. emitItemsInPotAll(socket);
  131.  
  132. emitAnnouncement(socket);
  133. }
  134.  
  135. function initLoggedInSocket(socket, steamid, name, avatar, avatar_small, tradelink, rank, level){
  136. notifySocket(socket, 'info', 'Authenticated as '+steamid);
  137.  
  138. socket.on('chatMessage', function(data){
  139. if(typeof(data.message) == 'string'){
  140. if(isTimeout(steamid, 'chat')){
  141. notifySocket(socket, 'error', 'You are only allowed to send a chat message once every 5 Seconds!');
  142. return;
  143. } else {
  144. timeoutAction(steamid, 'chat', 20);
  145. }
  146. if(!settings.chatPaused){
  147. if(userChatBanned.indexOf(steamid) != -1){
  148. notifySocket(socket, 'error', 'Failed to send your message! You have been banned from participating in the Chat!');
  149. } else {
  150. logInfo('[CHAT]: '+name+' --> '+data.message);
  151. data.message = safeText(data.message);
  152. if(data.message != false){
  153. newChatMessage({ name: name, avatar: avatar, message: data.message, steamid: steamid, rank: rank, level: 0});
  154. }
  155. }
  156. } else {
  157. notifySocket(socket, 'error', 'Failed to send your message! Chat is currently deactivated!');
  158. }
  159. }
  160. });
  161.  
  162. socket.on('tradelink', function(data){
  163. if(typeof(data.url) == 'string'){
  164. if(isTimeout(steamid, 'tradelink')){
  165. notifySocket(socket, 'error', 'You are only allowed to update your Tradelink once every 5 Seconds!');
  166. return;
  167. } else {
  168. timeoutAction(steamid, 'tradelink', 12);
  169. }
  170. logInfo('[TRADELINK]: '+name+' --> '+data.url);
  171.  
  172. connection.query('UPDATE user SET `tradelink` = ? WHERE `steamid` = "'+steamid+'"', data.url, function(err){
  173. if(err){
  174. logError('Error saving the tradelink of '+name+'. Error: '+err);
  175. notifySocket(socket, 'error', 'Error saving your Tradelink "'+data.url+'"');
  176. } else {
  177. notifySocket(socket, 'success', 'Your tradelink was saved!');
  178. }
  179. });
  180. } else {
  181. notifySocket(socket, 'error', 'Error saving your Tradelink "'+data.url+'"');
  182. }
  183. });
  184.  
  185. socket.on('loadInventory', function(data){
  186. if(isTimeout(steamid, 'loadInventory')){
  187. notifySocket(socket, 'error','You are only allowed to load your Inventory once every 5 Seconds!');
  188. return;
  189. } else {
  190. timeoutAction(steamid, 'loadInventory', 12);
  191. }
  192. loadDepositInventory(steamid, function(err, inventory){
  193. var html = 'Error while loading your Inventory.. Please verify that your Inventory is set to public!';
  194. if(!err){
  195. html = '';
  196.  
  197. for(var i in inventory){
  198. var item = inventory[i];
  199.  
  200. if(item.price > 0){
  201. html += "<div class='itemChoose text-center' id='assetid_"+item.assetid+"' data-price='"+item.price+"' data-name='"+item.name+"' data-assetid='"+item.assetid+"' onclick='invSelect(\""+item.assetid+"\")' data-toggle='tooltip' title='"+item.name+"'>";
  202. html += "<div id='assetid_"+item.assetid+"_bg'></div>";
  203. html += "<img src='"+item.img+"'></img>";
  204. html += "<p class='itemPrice'>$"+item.price+"</p>";
  205. html += "</div>";
  206. } else {
  207. html += "<div class='itemChoose unavailibleItemChoose' data-price='0' data-name='"+item.name+"' data-toggle='tooltip' title='"+item.name+"'>";
  208. html += "<img src='"+item.img+"'></img>";
  209. html += "<p class='itemPrice'>Unavailible</p>";
  210. html += "</div>";
  211. }
  212. }
  213.  
  214. if(inventory.length == 0){
  215. html = 'Your inventory is empty!';
  216. }
  217.  
  218. socket.emit('depositInventory', { success: true, inventoryHtml: html });
  219. } else {
  220. socket.emit('depositInventory', { success: false, inventoryHtml: html });
  221. }
  222. });
  223. });
  224.  
  225. socket.on('deposit', function(data){
  226. if(isTimeout(steamid, 'deposit')){
  227. notifySocket(socket, 'error', 'You are only allowed to deposit once every 3 Seconds!');
  228. return;
  229. } else {
  230. timeoutAction(steamid, 'deposit', 20);
  231. }
  232. var niceTry = false;
  233. if(data.hasOwnProperty('assetids')){
  234. if(Object.prototype.toString.call(data.assetids) === '[object Array]'){
  235.  
  236. if(tradelink == 'null'){
  237. notifySocket(socket, 'error', 'You need to set your tradelink at first.');
  238. return;
  239. }
  240.  
  241. if(data.assetids.length == 0){
  242. notifySocket(socket, 'error', 'You need to select Items.');
  243. return;
  244. }
  245.  
  246. if(settings.jackpotPaused){
  247. notifySocket(socket, 'error', 'Jackpot is currently paused. Try again later please.');
  248. return;
  249. }
  250.  
  251. var itemArray = [];
  252. for(var i in data.assetids){
  253. var assetid = data.assetids[i];
  254. itemArray.push(rustItem(assetid));
  255. }
  256.  
  257. if(itemArray.length <= 20){
  258. logInfo('User '+name+' is trying to deposit...');
  259.  
  260. playerInfo[steamid] = {
  261. name: name,
  262. avatar: avatar_small,
  263. tradelink: tradelink
  264. };
  265.  
  266. sendDepositTrade(itemArray, steamid, tradelink);
  267. } else {
  268. notifySocket(socket, 'error', 'Too many Items.');
  269. return;
  270. }
  271.  
  272. } else {
  273. niceTry = true;
  274. }
  275. } else {
  276. niceTry = true;
  277. }
  278.  
  279. if(niceTry){
  280. notifySocket('info', 'Atleast you tried!');
  281. }
  282. });
  283.  
  284. socket.emit('authenticated', {});
  285. }
  286.  
  287. function initAdminSocket(socket, steamid, name){
  288. socket.on('jackpotPauseOn', function(data){
  289. if(!settings.jackpotPaused){
  290. changeSettings('jackpotPaused', true);
  291.  
  292. logInfo('--> DEACTIVATED THE JACKPOT DEPOSITS <--');
  293.  
  294. notifySocket(socket, 'success', 'Jackpot deposits deactivated.');
  295. } else {
  296. notifySocket(socket, 'error', 'Jackpot deposits are already deactivated.');
  297. }
  298. });
  299.  
  300. socket.on('jackpotPauseOff', function(data){
  301. if(settings.jackpotPaused){
  302. changeSettings('jackpotPaused', false);
  303.  
  304. logInfo('--> ACTIVATED THE JACKPOT DEPOSITS <--');
  305.  
  306. notifySocket(socket, 'success', 'Jackpot deposits activated.');
  307. } else {
  308. notifySocket(socket, 'error', 'Jackpot deposits are already activated.');
  309. }
  310. });
  311.  
  312. socket.on('chatPauseOn', function(data){
  313. if(!settings.chatPaused){
  314. changeSettings('chatPaused', true);
  315.  
  316. logInfo('--> DEACTIVATED THE CHAT <--');
  317.  
  318. notifySocket(socket, 'success', 'Chat deactivated.');
  319. } else {
  320. notifySocket(socket, 'error', 'Chat is already deactivated.');
  321. }
  322. });
  323.  
  324. socket.on('chatPauseOff', function(data){
  325. if(settings.chatPaused){
  326. changeSettings('chatPaused', false);
  327.  
  328. logInfo('--> ACTIVATED THE CHAT <--');
  329.  
  330. notifySocket(socket, 'success', 'Chat activated.');
  331. } else {
  332. notifySocket(socket, 'error', 'Chat is already activated.');
  333. }
  334. });
  335.  
  336. socket.on('changeAnnouncement', function(data){
  337. announcement = data.html;
  338.  
  339. logInfo(announcement);
  340.  
  341. var array = {
  342. html: announcement
  343. };
  344.  
  345. connection.query('INSERT INTO announcements SET ?', array, function(err){
  346. if(err){
  347. logError('Failed to set Announcement. Error: '+err);
  348.  
  349. notifySteamid(steamid, 'error', 'Failed to set Announcement. Error: '+err);
  350. } else {
  351. logSuccess('Saved announcement');
  352.  
  353. notifySteamid(steamid, 'success', 'Changed & Saved the new Announcement!');
  354. }
  355. });
  356.  
  357. emitToAll('announcement', { html: announcement });
  358. });
  359.  
  360. socket.on('userSearch', function(data){
  361. if(data.userid){
  362. connection.query('SELECT steamid, steamname, won, deposited, tradelink, rank, chatBan, totalBan FROM user WHERE `steamid` = ? OR `steamname` = ?', [data.userid, data.userid], function(err, results){
  363. if(err){
  364. notifySocket(socket, 'error', 'Error performing the User Search. Error: '+err);
  365. } else if(results.length == 0){
  366. notifySocket(socket, 'info', '0 Results found.');
  367. } else {
  368. socket.emit('userSearchResult', results[0]);
  369. }
  370. });
  371. }
  372. });
  373.  
  374. socket.on('userBan', function(data){
  375. var type = data.type;
  376. var userid = data.steamid;
  377.  
  378. var proceed = true;
  379. if(type.toLowerCase().indexOf('total') != -1){
  380. if(userTotalBanned.indexOf(userid) != -1){
  381. proceed == false;
  382. notifySocket(socket, 'info', 'User '+userid+' is already banned');
  383. } else {
  384. userTotalBanned.push(userid);
  385. }
  386. } else if(type.toLowerCase().indexOf('chat') != -1){
  387. if(userChatBanned.indexOf(userid) != -1){
  388. proceed == false;
  389. notifySocket(socket, 'info', 'User '+userid+' is already banned');
  390. } else {
  391. userChatBanned.push(userid);
  392. }
  393. }
  394.  
  395. if(proceed == true){
  396. connection.query('UPDATE user SET '+type+' = "1" WHERE steamid = ?', userid, function(err){
  397. if(err){
  398. notifySocket(socket, 'error', 'Error while performing the '+type+' Ban to '+userid+'. Error: '+err);
  399. } else{
  400. notifySocket(socket, 'success', 'User '+userid+' got '+type+' banned!');
  401. logSuccess('User '+userid+' got '+type+' banned!');
  402.  
  403. if(type.toLowerCase().indexOf('total') != -1){
  404. emitToSteamid(userid, 'refresh', {});
  405. }
  406. }
  407. });
  408. }
  409. });
  410.  
  411. socket.on('userUnban', function(data){
  412. var type = data.type;
  413. var userid = data.steamid+'';
  414.  
  415.  
  416. var proceed = true;
  417. if(type.toLowerCase().indexOf('total') != -1){
  418. if(userTotalBanned.indexOf(userid) == -1){
  419. proceed == false;
  420. notifySocket(socket, 'info', 'User '+userid+' is already unbanned');
  421. } else {
  422. userTotalBanned.splice(userTotalBanned.indexOf(userid), 1);
  423. }
  424. } else if(type.toLowerCase().indexOf('chat') != -1){
  425. if(userChatBanned.indexOf(userid) == -1){
  426. proceed == false;
  427. notifySocket(socket, 'info', 'User '+userid+' is already unbanned');
  428. } else {
  429. userChatBanned.splice(userChatBanned.indexOf(userid), 1);
  430. }
  431. }
  432. if(proceed == true){
  433. connection.query('UPDATE user SET '+type+' = "0" WHERE steamid = ?', userid, function(err){
  434. if(err){
  435. notifySocket(socket, 'error', 'Error while performing the '+type+' Ban to '+userid+'. Error: '+err);
  436. } else{
  437. notifySocket(socket, 'success', 'User '+userid+' got '+type+' unbanned!');
  438.  
  439. logSuccess('User '+userid+' got '+type+' unbanned!');
  440.  
  441. if(type.toLowerCase().indexOf('total') != -1){
  442. emitToSteamid(userid, 'refresh', {});
  443. }
  444. }
  445. });
  446. }
  447.  
  448. });
  449.  
  450. socket.on('chatClear', function(data){
  451. currentChat = [];
  452.  
  453. emitToAll('clearChat', {});
  454.  
  455. notifySocket(socket, 'success', 'Chat got cleared!');
  456. });
  457. }
  458.  
  459.  
  460. function gameLoopStart(){
  461. isPotRunning = true;
  462. emitToAll('timeLeft', { value: timeLeft, isPotRunning: isPotRunning });
  463. timeLeft++;
  464. var gameloop = function(){
  465. logInfo('Gameloop: '+colors.magenta(timeLeft)+'/'+waitTime);
  466.  
  467. timeLeft--;
  468. if(timeLeft <= 0){
  469. clearInterval(gameloopInterval);
  470. gameRoll();
  471. }
  472. }
  473. gameloopInterval = setInterval(gameloop, 1000);
  474. }
  475.  
  476.  
  477. function gameLoopReset(winnerdata, items, rN){
  478. saveToDB(winnerdata, items);
  479. setTimeout(function(){
  480. logInfo('Gameloop reset');
  481.  
  482.  
  483.  
  484. isRolling = false;
  485.  
  486. timeLeft = waitTime;
  487.  
  488. lastWinner = { roundid: rN, name: winnerdata.name, steamid: winnerdata.steamid, img: winnerdata.img, amount: winnerdata.amount, percentage: winnerdata.percentage, ticket: winnerdata.ticket, hash: winnerdata.hash, salt: winnerdata.salt, entries: winnerdata.entries };
  489.  
  490. historyGames.push(lastWinner);
  491.  
  492. if(historyGames.length > 5){
  493. historyGames.shift();
  494. }
  495.  
  496. dataItemsInPot = [];
  497. itemsInPot = 0;
  498. roundTotal = 0;
  499. potPlayers = [];
  500.  
  501. generateSalt();
  502. generateHash();
  503.  
  504. emitJackpotDataAll();
  505.  
  506. setTimeout(function(){
  507. handleQueue();
  508. }, 1000);
  509. }, 12000);
  510. }
  511.  
  512.  
  513. function gameRoll(){
  514. isPotRunning = false;
  515. isRolling = true;
  516. logInfo('GameRoll');
  517.  
  518. var entries = [];
  519.  
  520. for(var itemsInPot in dataItemsInPot){
  521. var found = false;
  522. var position;
  523. for(var i in entries){
  524. if(entries[i].steamid == dataItemsInPot[itemsInPot].ownerid){
  525. found = true;
  526. position = i;
  527.  
  528. break; //USELESS but faster
  529. }
  530. }
  531.  
  532. if(!found){
  533. var arr = {
  534. steamid: dataItemsInPot[itemsInPot].ownerid,
  535. total: dataItemsInPot[itemsInPot].price,
  536. img: dataItemsInPot[itemsInPot].owneravatar,
  537. name: dataItemsInPot[itemsInPot].ownername
  538. };
  539. entries.push(arr);
  540. } else {
  541. entries[i].total += dataItemsInPot[itemsInPot].price;
  542. }
  543. }
  544.  
  545. roundTotal = round(roundTotal, 2);
  546. //CHANCE CALCULATOR
  547. for(var entry in entries){
  548. entries[entry].total = round(entries[entry].total, 2);
  549. logInfo('Total: '+entries[entry].total+', RoundTotal: '+roundTotal);
  550.  
  551. var chance = parseFloat((entries[entry].total / roundTotal).toFixed(2));
  552. logInfo('Chance: '+chance+' for: '+entries[entry].name);
  553. entries[entry].chance = chance;
  554. }
  555.  
  556. /* entries = [
  557. {
  558. chance: 0.2,
  559. img: 'http://cdn.edgecast.steamstatic.com/steamcommunity/public/images/avatars/3c/3c6908ff39a0cbc630905216caf347e4acfa053e_medium.jpg'
  560. },
  561. {
  562. chance: 0.8,
  563. img: 'http://cdn.edgecast.steamstatic.com/steamcommunity/public/images/avatars/7a/7ad598022f21263d6be2f05ab9bce7eaca2b8b01_medium.jpg'
  564. }]; */
  565.  
  566. //PICK WINNER
  567.  
  568. //var random = Math.random();
  569.  
  570. var random = getWinnerTicket(Number(roundTotal).toFixed(2));
  571.  
  572. var winningAmountAt = parseFloat((roundTotal * random).toFixed(2));
  573.  
  574. logInfo('Random: '+random+', WinningAmountAt: '+winningAmountAt);
  575.  
  576. var winner = {};
  577. var counter = 0;
  578. for(var e in entries){
  579. var entry = entries[e];
  580. if(round(counter, 2) + round(entry.total, 2) >= winningAmountAt){
  581. winner = entry;
  582.  
  583. winner.chance = round(winner.chance, 2);
  584.  
  585. winner.total = round(winner.total, 2);
  586.  
  587. logInfo('Winner found: '+winner.name+', Total: '+winner.total+', Chance: '+winner.chance*100+'%');
  588.  
  589. break;
  590. } else {
  591. counter += entry.total;
  592. }
  593. }
  594.  
  595. /* var winner = {
  596. img: 'http://cdn.edgecast.steamstatic.com/steamcommunity/public/images/avatars/3c/3c6908ff39a0cbc630905216caf347e4acfa053e_medium.jpg',
  597. name: 'DankMemeLord'
  598. }; */
  599.  
  600. var html = '';
  601. var rollEntries = [];
  602.  
  603. var tmpTotal = 0;
  604.  
  605. logInfo(entries.length+' Entries');
  606. for(var entry in entries){
  607.  
  608. var persChance = 100 * entries[entry].chance;
  609. persChance = round(persChance, 2);
  610.  
  611. logInfo(persChance+' Images for this person');
  612.  
  613. for(var i = 0; i < persChance; i++){
  614. rollEntries.push('<div class="rollImg"><img src="'+entries[entry].img+'"></img></div>');
  615. }
  616.  
  617. tmpTotal += persChance;
  618. }
  619.  
  620.  
  621. shuffle(rollEntries);
  622. for(var entry in rollEntries){
  623. html += rollEntries[entry];
  624. }
  625.  
  626. html += '<div class="rollImg"><img src="'+winner.img+'"></img></div>';
  627.  
  628. for(var entry in rollEntries){
  629. html += rollEntries[entry];
  630. }
  631.  
  632. emitToAll('gameRoll',
  633. {
  634. html: html,
  635. winner: winner,
  636. position: tmpTotal * 64,
  637. wobble: Math.random() * 32
  638. });
  639.  
  640. var winnerdata = {
  641. name: winner.name,
  642. steamid: winner.steamid,
  643. img: winner.img,
  644. amount: roundTotal,
  645. percentage: winner.chance * 100,
  646. ticket: random.toFixed(7),
  647. salt: currentSalt,
  648. hash: currentHash,
  649. entries: dataItemsInPot
  650. };
  651.  
  652. var rN = roundNumber;
  653. roundNumber++;
  654. calculateItems(roundTotal, dataItemsInPot, (winner.name.indexOf('RustyPot.com') == -1 )? 10 : 5,function(items){
  655. //winnerdata.amount = items.amountWon;
  656. gameLoopReset(winnerdata, items, rN);
  657.  
  658. sendWinnings(items.nonFee, winnerdata.steamid, rN);
  659. });
  660. }
  661.  
  662. function addItem(item, fromQueue){
  663. if(isRolling){
  664. if(fromQueue){
  665. return 'isRolling';
  666. }
  667. addToQueue(item);
  668. } else {
  669. dataItemsInPot.push(item);
  670.  
  671. if(potPlayers.indexOf(item.ownerid) == -1){
  672. potPlayers.push(item.ownerid);
  673. }
  674.  
  675.  
  676. itemsInPot++;
  677.  
  678. addToRoundTotal(item.price);
  679.  
  680. emitToAll('newItem', item);
  681. emitToAll('itemsInPot', { value: itemsInPot });
  682. emitToAll('roundTotal', { value: roundTotal });
  683.  
  684. connection.query('UPDATE user SET `deposited` = `deposited` + ? WHERE steamid = ?', [item.price, item.ownerid], function(err){
  685. if(err){
  686. logError('FATAL ERROR -> FAILED TO SAVE THE AMOUNT TO THE DB.');
  687. }
  688. });
  689.  
  690. if(fromQueue){
  691. logInfo('[QUEUE] Item added');
  692. } else {
  693. logInfo('Item added');
  694. }
  695.  
  696.  
  697. if(potPlayers.length == 2 && !isPotRunning){
  698. gameLoopStart();
  699. } else if(itemsInPot == 200){
  700. if(fromQueue){
  701. return 'isFull';
  702. }
  703. gameRoll();
  704. }
  705. }
  706. }
  707.  
  708. function addToQueue(item){
  709. itemQueue.push(item);
  710. logInfo('Item added to queue');
  711. }
  712.  
  713. function handleQueue(){
  714. var rollIt = false;
  715. var success = [];
  716. for(var qI in itemQueue){
  717. var queueItem = itemQueue[qI];
  718.  
  719. var stopHandlingQueue = addItem(queueItem, true);
  720. if(stopHandlingQueue == 'isFull'){
  721. logInfo('PotFull stopping handling the Queue');
  722. rollIt = true;
  723. break;
  724. } else if(stopHandlingQueue == 'isRolling'){
  725. logInfo('PotFull stopping handling the Queue');
  726. break;
  727. } else {
  728. success.push(qI);
  729. }
  730. }
  731.  
  732. for(var i in success){
  733. itemQueue.splice(itemQueue.indexOf(success[i]), 1);
  734. }
  735.  
  736. if(rollIt){
  737. gameRoll();
  738. }
  739. }
  740.  
  741. function saveToDB(winnerdata, itemdata){
  742. logInfo('Saving to DB.');
  743.  
  744. var array = {
  745. total: roundTotal,
  746. won: winnerdata.amount,
  747. winnersteamid: winnerdata.steamid,
  748. winnername: winnerdata.name,
  749. winnerchance: winnerdata.percentage.toFixed(4),
  750. winneravatar: winnerdata.img,
  751. potPlayers: JSON.stringify(potPlayers),
  752. offersent: 0,
  753. sendbackItems: JSON.stringify(itemdata.nonFeeNames),
  754. feeItems: JSON.stringify(itemdata.feeNames),
  755. salt: winnerdata.salt,
  756. hash: winnerdata.hash,
  757. ticket: winnerdata.ticket,
  758. rawEntries: JSON.stringify(winnerdata.entries)
  759. };
  760.  
  761. connection.query('INSERT INTO jackpotHistory SET ?', array, function(err){
  762. if(err){
  763. logError('FATAL ERROR -> FAILED TO SAVE THE JACKPOT TO THE DB. Error: '+err);
  764. }
  765. });
  766.  
  767. connection.query('UPDATE user SET `won` = `won` + ? WHERE steamid = ?', [array.won, array.winnersteamid], function(err){
  768. if(err){
  769. logError('FATAL ERROR -> FAILED TO SAVE THE AMOUNT TO THE DB.');
  770. }
  771. });
  772.  
  773. }
  774.  
  775. function loadFromDb(callback){
  776. logInfo('Trying to load from DB');
  777.  
  778. var loadAnnouncement = function(){
  779. connection.query('SELECT * FROM `announcements` ORDER BY `id` DESC LIMIT 1', function(err2, results2){
  780. if(!err2){
  781. if(results2.length == 0){
  782. logInfo('No announcementdata found.');
  783.  
  784. loadSettings();
  785. } else {
  786. announcement = results2[0].html;
  787. loadSettings();
  788. }
  789. } else {
  790. logError('FATAL ERROR -> FAILED TO LOAD THE ANNOUNCEMENTDATA FROM THE DB.');
  791. process.exit(1);
  792. }
  793. });
  794. };
  795.  
  796. var loadSettings = function(){
  797. connection.query('SELECT * FROM `settings`', function(err, results){
  798. if(!err){
  799. if(results.length == 0){
  800. logInfo('No settings found.');
  801.  
  802. loadBannedPeople();
  803. } else {
  804. logInfo('Loading '+results.length+' Settings.');
  805. for(var r in results){
  806. settings[results[r].name] = (results[r].value == '1')? true : false;
  807. }
  808.  
  809. loadBannedPeople();
  810. }
  811. } else {
  812. logError('FATAL ERROR -> FAILED TO LOAD THE SETTINGS FROM THE DB.');
  813. process.exit(1);
  814. }
  815. });
  816. };
  817.  
  818. var loadBannedPeople = function(){
  819. connection.query('SELECT * FROM `user` WHERE totalBan = "1" OR chatBan = "1"', function(err, results){
  820. if(!err){
  821. if(results.length == 0){
  822. logInfo('No banned People found.');
  823.  
  824. callback();
  825. } else {
  826. logInfo('Loaded '+results.length+' banned People.');
  827.  
  828. for(var r in results){
  829. var p = results[r];
  830. logInfo(p.steamname);
  831.  
  832. if(p.chatBan == '1'){
  833. userChatBanned.push(p.steamid)
  834. logInfo('Chatban' + p.Chatban);
  835. }
  836.  
  837.  
  838. if(p.totalBan == '1'){
  839. userTotalBanned.push(p.steamid);
  840. logInfo('Totalban' + p.totalBan);
  841.  
  842. }
  843. }
  844.  
  845. callback();
  846. }
  847. } else {
  848. logError('FATAL ERROR -> FAILED TO LOAD THE BANNED PEOPLE.');
  849. process.exit(1);
  850. }
  851. });
  852. };
  853.  
  854.  
  855. connection.query('SELECT * FROM `jackpotHistory` ORDER BY `id` DESC LIMIT 5', function(err, results){
  856. if(!err){
  857. if(results.length == 0){
  858. logInfo('No JackpotData found. Congratz for the first Round in the History of RUSTYPOT.com. ---> Using crappy data');
  859. loadAnnouncement();
  860. } else {
  861. var i = 0;
  862. roundNumber = results[0].id + 1;
  863. lastWinner = {
  864. roundid: results[i].id,
  865. name: results[i].winnername,
  866. steamid: results[i].winnersteamid,
  867. img: results[i].winneravatar,
  868. amount: results[i].total,
  869. percentage: results[i].winnerchance,
  870. ticket: results[i].ticket,
  871. salt: results[i].salt,
  872. hash: results[i].hash,
  873. entries: JSON.parse(results[i].rawEntries)
  874. };
  875.  
  876. for(var r in results){
  877. historyGames.unshift({
  878. roundid: r,
  879. name: results[r].winnername,
  880. steamid: results[r].winnersteamid,
  881. img: results[r].winneravatar,
  882. amount: results[r].total,
  883. percentage: results[r].winnerchance,
  884. ticket: results[r].ticket,
  885. salt: results[r].salt,
  886. hash: results[r].hash,
  887. entries: JSON.parse(results[r].rawEntries)
  888. });
  889. }
  890.  
  891. generateSalt();
  892. generateHash();
  893.  
  894. loadAnnouncement();
  895. }
  896. } else {
  897. logError('FATAL ERROR -> FAILED TO LOAD THE JACKPOTDATA FROM THE DB.');
  898. process.exit(1);
  899. }
  900. });
  901.  
  902. }
  903.  
  904.  
  905. function newChatMessage(mes){
  906. currentChat.push(mes);
  907.  
  908. if(currentChat.length > maxChatLength){
  909. currentChat.shift();
  910. }
  911.  
  912. var steamid = mes.steamid;
  913. //mes.steamid = '1234';
  914.  
  915. emitToNormal('chatMessage', mes);
  916.  
  917. //mes.steamid = steamid;
  918. emitToAdmin('chatMessage', mes);
  919.  
  920.  
  921. var array = {
  922. message: mes.message,
  923. steamid: mes.steamid
  924. };
  925.  
  926. connection.query('INSERT INTO chatHistory SET ?', array, function(err){
  927. if(err){
  928. logError('Error while saving the Message '+array.message+' by '+mes.name+'('+mes.steamid+'). Error: '+err);
  929. }
  930. })
  931. }
  932.  
  933. function emitJackpotData(socket){
  934. socket.emit('lastWinner', lastWinner);
  935.  
  936. socket.emit('itemsInPot', { value: itemsInPot });
  937. socket.emit('roundNumber', { value: roundNumber });
  938. socket.emit('roundTotal', { value: roundTotal });
  939.  
  940. socket.emit('timeLeft', { value: timeLeft, isPotRunning: isPotRunning });
  941.  
  942. socket.emit('roundHash', { value: currentHash });
  943. }
  944.  
  945. function emitJackpotDataAll(){
  946. emitToAll('gameHistory', historyGames[historyGames.length - 1]);
  947.  
  948. emitToAll('lastWinner', lastWinner);
  949.  
  950. emitToAll('itemsInPot', { value: 0 });
  951. emitToAll('roundNumber', { value: roundNumber });
  952. emitToAll('roundTotal', { value: 0 });
  953.  
  954. emitToAll('timeLeft', { value: timeLeft });
  955.  
  956. emitToAll('roundHash', { value: currentHash });
  957. }
  958.  
  959.  
  960. function emitChatMessages(socket, rank){
  961. for(var c in currentChat){
  962. var mes = currentChat[c];
  963. //mes.steamid = '1234';
  964. mes.noAnimation = true;
  965. socket.emit('chatMessage', mes);
  966. }
  967. }
  968.  
  969. function emitGameHistoryAll(socket){
  970. for(var h in historyGames){
  971. var his = historyGames[h];
  972. socket.emit('gameHistory', his);
  973. }
  974. }
  975.  
  976. function emitItemsInPotAll(socket){
  977. for(var i in dataItemsInPot){
  978. var item = dataItemsInPot[i];
  979. item.noAnimation = true;
  980. socket.emit('newItem', item);
  981. }
  982. }
  983.  
  984. function emitAnnouncement(socket){
  985. socket.emit('announcement', { html: announcement });
  986. }
  987.  
  988. function notifySocket(socket, type, message){
  989. socket.emit('notification', { type: type, message: message });
  990. }
  991.  
  992. function notifySteamid(steamid, type, message){
  993. try{ //idk if it will throw an error :D, too lazy to find out
  994. io.to(steamid+'').emit('notification', { type: type, message: message });
  995. } catch(err){
  996.  
  997. }
  998. }
  999.  
  1000. function emitToSteamid(steamid, type, message){
  1001. try{ //idk if it will throw an error :D, too lazy to find out
  1002. io.to(steamid+'').emit(type, message);
  1003. } catch(err){
  1004.  
  1005. }
  1006. }
  1007.  
  1008. function emitToAll(type, data){
  1009. io.sockets.emit(type, data);
  1010. }
  1011.  
  1012. function emitToNormal(type, data){
  1013. io.to('normal').emit(type, data);
  1014. }
  1015.  
  1016. function emitToAdmin(type, data){
  1017. io.to('admin').emit(type, data);
  1018. }
  1019.  
  1020.  
  1021. function safeText(text){
  1022. text = text.substr(0, 199);
  1023.  
  1024. for(var i = 0; i < text.length; i++){
  1025. text = text.replace('<', '');
  1026. text = text.replace('>', '');
  1027. }
  1028.  
  1029. for(var i = 0; i < text.length; i++){
  1030. text = text.replace('<', '');
  1031. text = text.replace('>', '');
  1032. } //just to make sure :D
  1033.  
  1034. if (text.replace(/\s/g, '').length == 0 || text == '') {
  1035. return false;
  1036. }
  1037.  
  1038. return text;
  1039. }
  1040.  
  1041. function addToRoundTotal(value){
  1042. roundTotal = roundTotal + value;
  1043. roundTotal = parseFloat(parseFloat(roundTotal).toFixed(2));
  1044. }
  1045.  
  1046. function changeSettings(name, newValue){
  1047. settings[name] = newValue;
  1048.  
  1049. connection.query('UPDATE settings SET value = ? WHERE name = ?', [newValue, name], function(err){
  1050. if(err){
  1051. logError('Error while saving the setting '+name+' to '+newValue+'. Error: '+err);
  1052. }
  1053. });
  1054. }
  1055.  
  1056.  
  1057. function logInfo(message){
  1058. log(colors.yellow(message));
  1059. }
  1060.  
  1061. function logSuccess(message){
  1062. log(colors.green(message));
  1063. }
  1064.  
  1065. function logError(message){
  1066. log(colors.red(message));
  1067. }
  1068.  
  1069. function log(message){
  1070. console.log(message);
  1071. var d = new Date();
  1072. var time = ("00" + (d.getMonth() + 1)).slice(-2) + "/" +
  1073. ("00" + d.getDate()).slice(-2) + "/" +
  1074. d.getFullYear() + " " +
  1075. ("00" + d.getHours()).slice(-2) + ":" +
  1076. ("00" + d.getMinutes()).slice(-2) + ":" +
  1077. ("00" + d.getSeconds()).slice(-2);
  1078.  
  1079. fs.appendFile('log.txt', '['+time+']'+' '+message+'\n', function(err){
  1080. if(err)
  1081. console.log('Error while appending to log.txt');
  1082. })
  1083. }
  1084.  
  1085. function shuffle(array) {
  1086. var currentIndex = array.length, temporaryValue, randomIndex;
  1087.  
  1088. // While there remain elements to shuffle...
  1089. while (0 !== currentIndex) {
  1090.  
  1091. // Pick a remaining element...
  1092. randomIndex = Math.floor(Math.random() * currentIndex);
  1093. currentIndex -= 1;
  1094.  
  1095. // And swap it with the current element.
  1096. temporaryValue = array[currentIndex];
  1097. array[currentIndex] = array[randomIndex];
  1098. array[randomIndex] = temporaryValue;
  1099. }
  1100.  
  1101. return array;
  1102. }
  1103.  
  1104. function round(num, scale) {
  1105. if(!("" + num).includes("e")) {
  1106. return +(Math.round(num + "e+" + scale) + "e-" + scale);
  1107. } else {
  1108. var arr = ("" + num).split("e");
  1109. var sig = ""
  1110. if(+arr[1] + scale > 0) {
  1111. sig = "+";
  1112. }
  1113. return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  1114. }
  1115. }
  1116.  
  1117. function generateSalt(){
  1118. currentSalt = generateRandomString(8);
  1119.  
  1120. logInfo('Salt generated!: '+currentSalt);
  1121. }
  1122.  
  1123. function generateHash(){
  1124. currentHash = crypto.createHash('sha1').update(currentSalt).digest('hex');
  1125.  
  1126. logInfo('Hash generated!: '+currentHash);
  1127. }
  1128.  
  1129. function getWinnerTicket(total){
  1130. var hash = crypto.createHash('md5').update(total+'-'+currentSalt).digest('hex');
  1131. hash = hash.slice(0, 8);
  1132.  
  1133. var ticket = parseInt(hash, 16);
  1134. ticket = ticket / 4294967296;
  1135.  
  1136. return ticket;
  1137. }
  1138.  
  1139.  
  1140. var timeoutActions = {};
  1141. function timeoutAction(steamid, name, perMin){
  1142. if(!timeoutActions.hasOwnProperty(steamid)){
  1143. timeoutActions[steamid] = [];
  1144. }
  1145.  
  1146. timeoutActions[steamid].push(name);
  1147.  
  1148. setTimeout(function(){
  1149. timeoutActions[steamid].splice(timeoutActions[steamid].indexOf(name), 1);
  1150. }, 60000 / perMin);
  1151. }
  1152.  
  1153. function isTimeout(steamid, name){
  1154. if(timeoutActions.hasOwnProperty(steamid)){
  1155. if(timeoutActions[steamid].indexOf(name) != -1){
  1156. return true;
  1157. } else {
  1158. return false;
  1159. }
  1160. } else {
  1161. return false;
  1162. }
  1163. }
  1164.  
  1165.  
  1166.  
  1167.  
  1168.  
  1169. clearConsole();
  1170. botLogin();
  1171.  
  1172. var firstTime = true;
  1173. function botLoggedIn(){
  1174. if(firstTime){
  1175. firstTime = false;
  1176. setup();
  1177. loadFromDb(function(){
  1178. logSuccess('Loaded from DB.');
  1179. /* logInfo('Starting demo in 5 seconds');
  1180.  
  1181. setTimeout(function(){
  1182. start();
  1183. }, 5000); */
  1184. });
  1185. }
  1186. }
  1187.  
  1188.  
  1189. function start(){
  1190. setInterval(function(){
  1191. var item = {
  1192. owneravatar: 'http://cdn.edgecast.steamstatic.com/steamcommunity/public/images/avatars/3c/3c6908ff39a0cbc630905216caf347e4acfa053e_medium.jpg',
  1193. ownername: 'NahuiBlyat',
  1194. ownerid: '76561198143176360',
  1195. img: 'https://steamcommunity-a.akamaihd.net/economy/image/rtOnLXYSD-u65eusOk-nO4hCpUCJo2NbCxc2U4Y51MLNQ5Hz3URG1UJcBu0sv2Ko-M1Zj0mvYmKzVOblhE_kZDiDqzUUnSAYyUNwwYoNBWPspc_WGyySVEc98w/62fx62f',
  1196. market_hash_name: 'ItemName',
  1197. price: parseFloat((100 * Math.random()).toFixed(2))
  1198. };
  1199.  
  1200. addItem(item, false);
  1201.  
  1202. setTimeout(function(){
  1203. var item = {
  1204. owneravatar: 'http://cdn.edgecast.steamstatic.com/steamcommunity/public/images/avatars/7a/7ad598022f21263d6be2f05ab9bce7eaca2b8b01_medium.jpg',
  1205. ownername: 'Cristal',
  1206. ownerid: '123',
  1207. img: 'https://steamcommunity-a.akamaihd.net/economy/image/rtOnLXYSD-u65eusOk-nO4hCpUCJo2NbCxc2U4Y51MLNQ5Hz3URG1UJcBu0sv2Ko-M1Zj0mvYmKzVOblhE_kZDiDqzUUnSAYyUNwwYoNBWPspc_WGyySVEc98w/62fx62f',
  1208. market_hash_name: 'ItemName',
  1209. price: parseFloat((100 * Math.random()).toFixed(2))
  1210. };
  1211.  
  1212. addItem(item, false);
  1213. }, 1000);
  1214.  
  1215. }, 4000);
  1216. }
  1217.  
  1218. /*
  1219. * STEAM-BOT
  1220. */
  1221. /*
  1222. * Init of the node steam modules
  1223. */
  1224. var client = new SteamUser();
  1225. var community = new Steamcommunity();
  1226.  
  1227. var manager = new TradeOfferManager({
  1228. "steam": client,
  1229. "language": "en",
  1230. "pollInterval": -1
  1231. });
  1232.  
  1233. //Array to prevent double handling of offers
  1234. var tmpOffers = []; //offer.ids are stored here
  1235.  
  1236. //twoFactorCodeGeneration to start logging in
  1237. account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
  1238.  
  1239. var usedAssetids = [];
  1240. var prices = {};
  1241.  
  1242. function botLogin(){
  1243. logInfo('Launching the Bot!');
  1244.  
  1245. loadUsedAssetids(function(){
  1246. loadPrices(function(){
  1247. client.logOn(account); //Tries to log in
  1248.  
  1249. setBotEvents();
  1250. });
  1251. });
  1252. }
  1253.  
  1254. function loadUsedAssetids(callback){
  1255. fs.readFile('./cache/usedAssetids.json', function(err, data) {
  1256. if (!err){
  1257. usedAssetids = JSON.parse(data);
  1258. logSuccess('Successfully loaded usedAssetids');
  1259.  
  1260. callback();
  1261. } else {
  1262. logError('FATAL ERROR -> BOT: FAILED TO LOAD "/cache/usedAssetids.json" -> I need this file.');
  1263. process.exit(1);
  1264. }
  1265. });
  1266. }
  1267.  
  1268. function loadPrices(callback){
  1269. var read = function(){
  1270. fs.readFile('./cache/prices.json', function(err, data) {
  1271. if (!err){
  1272. prices = JSON.parse(data);
  1273. logSuccess('Successfully loaded the Prices');
  1274.  
  1275. startInterval();
  1276. callback();
  1277. } else {
  1278. logInfo('Error while loading the Prices. Redownloading...');
  1279. download();
  1280.  
  1281. startInterval();
  1282. callback();
  1283. }
  1284. });
  1285. };
  1286.  
  1287.  
  1288. var download = function(){
  1289. request({
  1290. url: 'https://api.steamapis.com/market/items/252490?api_key='+steamapis_key+'&format=compact',
  1291. json: true
  1292. }, function (err, response, body) {
  1293. if (err){
  1294. logError('Failed to download steamapis.com prices.');
  1295. return;
  1296. } else if(response.statusCode != 200){
  1297. logError('Unexpected response statusCode. '+response.statusCode);
  1298. return;
  1299. } else {
  1300. prices = body;
  1301.  
  1302. request({
  1303. url: 'https://opskins.com/pricelist/252490.json',
  1304. json: true
  1305. }, function (err, response, body) {
  1306. if (err){
  1307. logError('Failed to download steamapis.com prices.');
  1308. return;
  1309. } else if(response.statusCode != 200){
  1310. logError('Unexpected response statusCode. '+response.statusCode);
  1311. return;
  1312. } else {
  1313. var toSave = {};
  1314. var items = body;
  1315. for (var item in items) {
  1316. if (items.hasOwnProperty(item)) {
  1317. var lastDate = null;
  1318. for(var key in items[item]){
  1319. lastDate = key;
  1320. }
  1321. toSave[item] = parseFloat(items[item][lastDate].price / 100);
  1322. }
  1323. }
  1324.  
  1325. for(var tS in toSave){
  1326. if(!prices.hasOwnProperty(tS)){
  1327. prices[tS] = toSave[tS];
  1328. }
  1329. }
  1330.  
  1331. fs.writeFile('./cache/prices.json', JSON.stringify(prices), function(err){
  1332. if(err){
  1333. logError('FATAL ERROR --> FAILED TO SAVE PRICES. ABORTING.');
  1334. process.exit(1);
  1335. } else {
  1336. logSuccess('Successfully downloaded the Prices');
  1337. }
  1338. });
  1339. }
  1340. });
  1341. }
  1342. });
  1343. };
  1344.  
  1345. var startInterval = function(){
  1346. setInterval(download, 1000 * 60 * 60 * 3); //Every 3 hours
  1347. };
  1348.  
  1349. read();
  1350. }
  1351.  
  1352. function setBotEvents(){
  1353. // Event:
  1354. // Kinda useless here but shows a successful login attempt
  1355. client.on('loggedOn', function(data) {
  1356. logInfo('Logged in');
  1357. client.setPersona(SteamUser.EPersonaState.Online);
  1358.  
  1359. });
  1360.  
  1361. //Loads existing polldata for the tradeoffermanager
  1362. if (fs.existsSync('./cache/polldata_' + account.accountName + '.json')) {
  1363. manager.pollData = JSON.parse(fs.readFileSync('./cache/polldata_' + account.accountName + '.json'));
  1364. }
  1365. //Saves polldata by the tradeoffermanager
  1366. manager.on('pollData', function(pollData) {
  1367. fs.writeFile('./cache/polldata_' + account.accountName + '.json', JSON.stringify(pollData));
  1368. });
  1369.  
  1370. //Simple ClientError Event | Never saw it btw :)
  1371. client.on('error', function(err) {
  1372. logError('Error ' + err);
  1373. });
  1374.  
  1375. //Once the client recieves the cookies of the current login-session it inits steamtradeoffermanager and steamcommunity
  1376. client.on('webSession', function(sessionID, cookies) {
  1377. manager.setCookies(cookies, function(err) { //manager cookies
  1378. if (err) {
  1379. logError('Cookie Error: ' + err);
  1380.  
  1381. if (err != 'Access Denied') {
  1382. logError('Failed to set TradeOfferManagerCookies. Aborting...');
  1383. process.exit(1);
  1384. } else {
  1385. logError('Account is currently locked. Aborting...');
  1386. process.exit(1);
  1387. }
  1388. } else {
  1389. logInfo('Cookies set');
  1390. botLoggedIn();
  1391. }
  1392. });
  1393.  
  1394. community.setCookies(cookies); //community cookies
  1395. community.chatLogon(); //community login
  1396. community.startConfirmationChecker(10000, account.identity_secret); //confirmation checker for mobile confirmations
  1397. });
  1398.  
  1399. //Once the community session expires it tries to relogin
  1400. community.on('sessionExpired', function(err) {
  1401. logInfo('Session expired.');
  1402. if (err) {
  1403. if (err.message == 'Not Logged In') {
  1404. logError('Not Logged In');
  1405.  
  1406. var tryLoginClient = function(){
  1407. try{
  1408. client.webLogOn();
  1409. } catch(err){
  1410. logError('Failed to login client, retrying...');
  1411. setTimeout(function(){
  1412. tryLoginClient();
  1413. }, 1000);
  1414. }
  1415. }
  1416.  
  1417. tryLoginClient();
  1418. } else {
  1419. logError('Error :' + err.message);
  1420. }
  1421. } else {
  1422. logInfo('Relogin.');
  1423. client.webLogOn();
  1424. }
  1425. });
  1426.  
  1427. //Event that gets triggered once a new offer is received
  1428. manager.on('newOffer', function(offer) {
  1429. logInfo('Received a new offer...');
  1430. handleOffer(offer);
  1431. });
  1432.  
  1433. //Used to log the received items, once an incoming trade has been successfully accepted
  1434. manager.on('sentOfferChanged', function(offer, oldState) {
  1435. if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) { //Checks if the offer got accepted
  1436. offer.getReceivedItems(function(err, items) { //Loads the receivedItems from the offer
  1437. if (err) {
  1438. logInfo("Couldnt load received items " + err); //IF error
  1439. } else {
  1440. if (items.length > 0) { //If items got received |
  1441. var func = function(){
  1442. for(var i in offer.itemsToReceive){
  1443. var offerItem = offer.itemsToReceive[i];
  1444. var item = {
  1445. owneravatar: playerInfo[offer.partner].avatar,
  1446. ownername: playerInfo[offer.partner].name,
  1447. ownerid: offer.partner+'',
  1448. img: offerItem.getImageURL() +'62fx62f',
  1449. market_hash_name: offerItem.market_hash_name,
  1450. price: prices[offerItem.market_hash_name]
  1451. };
  1452. addItem(item);
  1453. }
  1454. }
  1455. if(playerInfo.hasOwnProperty(offer.partner)){
  1456. func();
  1457. } else {
  1458. logError('ERROR -> NO USER DETAILS FOR '+offer.partner);
  1459. connection.query('SELECT * FROM user WHERE steamid = '+offer.partner, function(playerInfoErr, playerInfoResults){
  1460. if(playerInfoErr){
  1461. logError('FATAL ERROR -> FAILED TO LOAD USER DETAILS FOR '+offer.partner+'. WE ALREADY GOT THE ITEMS THOUGH.');
  1462. } else {
  1463. if(playerInfoResults[0].tradelink != 'null'){
  1464. playerInfo[offer.partner] = {
  1465. name: playerInfoResults[0].steamname,
  1466. avatar: playerInfoResults[0].avatar_small,
  1467. tradelink: playerInfoResults[0].tradelink
  1468. };
  1469.  
  1470. func();
  1471. }
  1472. }
  1473. });
  1474. }
  1475. }
  1476. }
  1477. });
  1478. }
  1479. });
  1480. }
  1481.  
  1482. //Handles offers
  1483. function handleOffer(offer) { // Prevents offers being handled more than once
  1484. if (tmpOffers.indexOf(offer.id) != -1) { // the offer.id is already in the list -> returns
  1485. return; // the offer.id is not in the list -> proceeds
  1486. } else { // & adds the offer.id to the list
  1487. tmpOffers.push(offer.id);
  1488. }
  1489. offer.getUserDetails(function(error, me, them) { //Loads the userdetails of the offer to prevents escrow trades
  1490. if (error) {
  1491. if (offer.state == TradeOfferManager.ETradeOfferState.Active) { //Error loading the details but the offer is still avaiblible, so we will wait for 10secs before trying again
  1492. logError('New Offer #' + offer.id + ', but there was an Error while loading the partner details. \n Error: ' + colors.magenta(error));
  1493. setTimeout(function() {
  1494. tmpOffers.splice(tmpOffers.indexOf(offer.id), 1); //makes it possible to handle it again
  1495. handleOffer(offer);
  1496. }, 10000);
  1497. } else {
  1498. logInfo('Offer #' + offer.id + ' not availible anymore..'); //The trade is not active anymore
  1499. }
  1500. } else {
  1501. if (them.escrowDays > 0) {
  1502. notifySteamid(offer.partner+'', 'error', 'Please note that we only accept trades without Tradehold. Declining your offer!');
  1503. manageOffer(offer, 'decline', them); //declines Escrowtrades
  1504. } else {
  1505. if (adminIds.indexOf(offer.partner + '') != -1) { //If offer.partner is admin
  1506. logSuccess('Received request for Admin trade. Trying to accept...');
  1507. notifySteamid(offer.partner+'', 'success', 'Admintrade received. Trying to accept your offer!');
  1508.  
  1509. manageOffer(offer, 'accept', them); //accepts admin trades
  1510. } else {
  1511. if(settings.jackpotPaused){
  1512. notifySteamid(offer.partner+'', 'error', 'Jackpot is paused right now. Declining your offer!');
  1513. manageOffer(offer, 'decline', them); //declines if jackpot is paused.
  1514. return;
  1515. }
  1516. if(false){//if (offer.itemsToGive.length == 0 && offer.itemsToReceive.length > 0 && offer.itemsToReceive.length <= 10) { //if it is a donation | only items on their side
  1517. connection.query('SELECT * FROM user WHERE steamid = '+offer.partner, function(playerInfoErr, playerInfoResults){
  1518. if(playerInfoErr){
  1519. logInfo('Received bad offer from ' + them.personaName + ' -> No details found. Trying to decline...');
  1520.  
  1521. notifySteamid(offer.partner+'', 'error', 'Internal Error. Declining your offer!');
  1522. manageOffer(offer, 'decline', them); //not a donation
  1523. } else {
  1524. if(playerInfoResults[0].tradelink != 'null'){
  1525. playerInfo[offer.partner] = {
  1526. name: playerInfoResults[0].steamname,
  1527. avatar: playerInfoResults[0].avatar_small,
  1528. tradelink: playerInfoResults[0].tradelink
  1529. };
  1530.  
  1531. var appidsValid = true;
  1532. var badPrice = false;
  1533. for (var i in offer.itemsToReceive) { //checks all items
  1534. var appid = offer.itemsToReceive[i].appid;
  1535.  
  1536. if (allowedAppids.indexOf(appid) == -1) { //for invalid appids
  1537. appidsValid = false;
  1538. }
  1539.  
  1540. if(prices.hasOwnProperty(offer.itemsToReceive[i].market_hash_name)){
  1541. if(prices[offer.itemsToReceive[i].market_hash_name] < minPrice){
  1542. badPrice = true;
  1543. logInfo('Price of '+offer.itemsToReceive[i].market_hash_name+' is too low.');
  1544. }
  1545. } else {
  1546. badPrice = true;
  1547. logError('Failed to find price for '+offer.itemsToReceive[i].market_hash_name);
  1548. }
  1549. }
  1550. if (appidsValid && !badPrice) { //but if we wanna accept all items anyways its not a problem if we find invalid ones
  1551. logSuccess('Received valid Offer from ' + them.personaName + '. Trying to accept the trade...');
  1552. notifySteamid(offer.partner+'', 'success', 'Offer received. Accepting your offer...');
  1553. manageOffer(offer, 'accept', them); //accepts, because its a donation.
  1554. } else {
  1555. notifySteamid(offer.partner+'', 'error', 'Some of the items you sent were invalid. Declining your offer!');
  1556. logInfo('Received bad offer from ' + them.personaName + '. Trying to decline...');
  1557.  
  1558. manageOffer(offer, 'decline', them); //declines, because its a donation but we dont want it.
  1559. }
  1560. } else {
  1561. notifySteamid(offer.partner+'', 'error', 'Please enter your Tradelink!. Declining your offer!');
  1562. logInfo('Received bad offer from ' + them.personaName + ' -> no Tradelink found. Trying to decline...');
  1563.  
  1564. manageOffer(offer, 'decline', them); //no tradelink
  1565. }
  1566. }
  1567. });
  1568. } else {
  1569. logInfo('Received bad offer from ' + them.personaName + '. Trying to decline...');
  1570.  
  1571. manageOffer(offer, 'decline', them); //not a donation
  1572. }
  1573. }
  1574. }
  1575. }
  1576. });
  1577. }
  1578.  
  1579. /*
  1580. * Used to accept decline offers
  1581. * offer is the trade offer we wanna work with
  1582. * action is what we are trying to do accept|decline
  1583. * them is the userdetails of the offer.partner
  1584. */
  1585. function manageOffer(offer, action, them) {
  1586. var counter = 0;
  1587. var maxTries = 10;
  1588. var retryInterval = 1000;
  1589. var alreadyUpdating = false; //prevents offer.update spam
  1590.  
  1591. var offerFunc = function() { //extra function to sort Everything
  1592. if (counter < maxTries) { //dont retry forever
  1593. if (offer.isGlitched() == true && !alreadyUpdating) { //if glitched
  1594. alreadyUpdating = true; //prevents offer.update spam
  1595. offer.update(function(err) {
  1596. if (err) {
  1597. alreadyUpdating = false; //prevents offer.update spam
  1598. } else {
  1599. accept(); //tries to accept
  1600. }
  1601. });
  1602. } else {
  1603. accept(); //tries to accept
  1604. }
  1605. } else {
  1606. logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') cancelled. Accepting/Declining failed.'); //limit of retries reached
  1607. clearInterval(interval); //stops the retry interval
  1608. }
  1609. };
  1610.  
  1611. var accept = function() {
  1612. if (offer.state == TradeOfferManager.ETradeOfferState.Active) { //if the trade is active -> acceptable|declineable
  1613. if (action == 'accept') {
  1614. offer.accept(function(err) {
  1615. if (err) { //accepting failed
  1616. logError('Accepting the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);
  1617. counter++; //used for the limit of retries
  1618. } else {
  1619. logSuccess('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully accepted.');
  1620. clearInterval(interval); //stops the retry interval because of success
  1621. }
  1622. });
  1623. } else {
  1624. offer.decline(function(err) {
  1625. if (err) { //declining failed
  1626. logError('Declining the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);
  1627. counter++; //used for the limit of retries
  1628. } else {
  1629. logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully declined.');
  1630. clearInterval(interval); //stops the retry interval because of success
  1631. }
  1632. });
  1633. }
  1634. } else {
  1635. clearInterval(interval); //stops the retry interval because its not active anymore
  1636. }
  1637. };
  1638.  
  1639. offerFunc(); //instantly runs the Function
  1640. var interval = setInterval(offerFunc, retryInterval); // & runs it in an interval
  1641. }
  1642.  
  1643.  
  1644. function calculateItems(total, entries, pFee, callback){
  1645. var array = {
  1646. nonFee: [],
  1647. fee: [],
  1648. nonFeeNames: [],
  1649. feeNames: [],
  1650. amountWon: 0
  1651. };
  1652.  
  1653. var fee = pFee;
  1654. fee = fee / 100;
  1655. var approxFee = total * fee;
  1656. approxFee = round(approxFee, 2);
  1657. logInfo('Calculating Items. Approx. '+approxFee+'$ Fee');
  1658.  
  1659.  
  1660. var allItems = [];
  1661.  
  1662.  
  1663. for(var e in entries){
  1664. allItems.push(entries[e]);
  1665. }
  1666.  
  1667.  
  1668. allItems = sortItems(allItems);
  1669.  
  1670. var feeTaken = 0;
  1671. for(var i in allItems){
  1672. var item = allItems[i];
  1673.  
  1674. item.price = round(item.price, 2);
  1675.  
  1676. if(approxFee >= item.price){
  1677. array.fee.push(item);
  1678. array.feeNames.push(item.market_hash_name);
  1679.  
  1680. approxFee -= item.price;
  1681. feeTaken += item.price;
  1682. } else {
  1683. array.nonFee.push(item);
  1684. array.nonFeeNames.push(item.market_hash_name);
  1685. array.amountWon += item.price;
  1686. }
  1687. }
  1688. feeTaken = round(feeTaken, 2);
  1689.  
  1690. logInfo('Took '+feeTaken+' Fee');
  1691.  
  1692. callback(array);
  1693. }
  1694.  
  1695.  
  1696. function sendWinnings(items, steamid, roundid){
  1697. logInfo('Trying to send winnings to '+steamid);
  1698. logInfo('Creating Steamitems');
  1699.  
  1700. var tradelink = playerInfo[steamid].tradelink;
  1701.  
  1702. var nameArray = [];
  1703.  
  1704. for(var i in items){
  1705. nameArray.push(items[i].market_hash_name);
  1706. }
  1707.  
  1708. var itemArray = [];
  1709.  
  1710. var load = function(){
  1711. manager.loadInventory(252490, 2, true, function(err, inventory){
  1712. if(err){
  1713. logError('Failed to load Inventory. Retrying in 5 Seconds.');
  1714.  
  1715. setTimeout(load, 5000);
  1716. } else {
  1717. handle(inventory);
  1718. }
  1719. });
  1720. };
  1721.  
  1722. var assetids = [];
  1723.  
  1724. var handle = function(inv){
  1725. for(var nA in nameArray){
  1726. var name = nameArray[nA];
  1727.  
  1728. var itemInInv = false;
  1729. for(var i in inv){
  1730. var item = inv[i];
  1731.  
  1732. if(item.market_hash_name == name){
  1733. if(usedAssetids.indexOf(item.assetid) != -1){
  1734. continue;
  1735. } else {
  1736. itemArray.push(rustItem(item.assetid));
  1737. assetids.push(item.assetid);
  1738. usedAssetids.push(item.assetid);
  1739. itemInInv = true;
  1740. break;
  1741. }
  1742. }
  1743. }
  1744. if(!itemInInv){
  1745. logError('Fatal Error -> Item '+name+' not existing in Inventory.');
  1746. }
  1747. }
  1748.  
  1749. send();
  1750. };
  1751.  
  1752. var send = function(){
  1753. try{
  1754. var offer = manager.createOffer(tradelink);
  1755. } catch(err){
  1756. logError('FATAL ERROR --> FAILED TO CREATE OFFER. Reason: probably wrong Tradelink');
  1757. return;
  1758. }
  1759.  
  1760. offer.addMyItems(itemArray);
  1761. offer.setMessage('Congratiulations on your Win! Dont decline or counter with an Offer -> NO REFUNDS');
  1762.  
  1763. offer.send(function(err, state) {
  1764. if (err) {
  1765. logError('Error while sending Trade #' + offer.id);
  1766. removeAssetidsInUse(assetids);
  1767. } else {
  1768. saveAssetidsInUse();
  1769. connection.query('UPDATE jackpotHistory SET offersent = "1" WHERE id = '+roundid, function(err){
  1770. if(err){
  1771. logError('FATAL ERROR -> FAILED TO SAVE OFFER SENT.');
  1772. }
  1773. });
  1774.  
  1775. setTimeout(function() {
  1776. confirmOffer(offer, function(err) {
  1777.  
  1778. });
  1779. }, 3000);
  1780. }
  1781. });
  1782. };
  1783.  
  1784. load();
  1785. }
  1786.  
  1787. function sendDepositTrade(items, steamid, tradelink){
  1788. logInfo('Trying to send deposit trade to '+steamid);
  1789.  
  1790. try{
  1791. var offer = manager.createOffer(tradelink);
  1792. } catch(err){
  1793. logError('FATAL ERROR --> FAILED TO CREATE OFFER. Reason: probably wrong Tradelink');
  1794. notifySteamid(steamid, 'error', 'Your Trade has been sent. Code: '+code);
  1795. return;
  1796. }
  1797. var code = generateCode();
  1798.  
  1799. offer.addTheirItems(items);
  1800. offer.setMessage(code);
  1801.  
  1802. offer.send(function(err, state) {
  1803. if (err) {
  1804. logError('Error while sending Trade #' + offer.id);
  1805. } else {
  1806. notifySteamid(steamid, 'success', 'Your Trade has been sent. Code: '+code);
  1807. }
  1808. });
  1809. }
  1810.  
  1811. function loadDepositInventory(steamid, callback){
  1812. /*
  1813. request({
  1814. url: 'https://api.steamapi.io/user/inventory/'+steamid+'/252490/2?key='+steamapiio_key
  1815. }, function (err, response, body) {
  1816. if(!err){
  1817. if(response.statusCode == 200){
  1818. var inv = [];
  1819.  
  1820. try{
  1821. body = JSON.parse(body);
  1822. } catch(err){
  1823. logError('Failed to load UserInventory of '+steamid+'. Invalid response body.');
  1824. callback(true, null);
  1825. return;
  1826. }
  1827.  
  1828. var inventory = body;
  1829.  
  1830.  
  1831. for(var i in inventory){
  1832. var item = inventory[i];
  1833.  
  1834. if(!item.tradable){
  1835. continue;
  1836. }
  1837.  
  1838. item.icon_url = 'http://steamcommunity-a.akamaihd.net/economy/image/'+item.icon_url+'/128x128';
  1839. var arr = {
  1840. img: item.icon_url,
  1841. name: item.market_hash_name,
  1842. assetid: item.assetid,
  1843. price: (!prices.hasOwnProperty(item.market_hash_name)) ? 0 : prices[item.market_hash_name]
  1844. };
  1845.  
  1846. inv.push(arr);
  1847. }
  1848.  
  1849. logSuccess('Loaded the Inventory of '+steamid+' successfully. '+inv.length+' Items are tradeable.');
  1850. callback(false, inv);
  1851. } else if(response.statusCode == 429){
  1852. logError('FATAL ERROR --> Failed to load UserInventory of '+steamid+'. Limit reached.');
  1853. callback(true, null);
  1854. } else {
  1855. logError('Failed to load UserInventory of '+steamid+'. Invalid response. '+response.statusCode+' | '+'https://api.steamapi.io/user/inventory/'+steamid+'/252490/2?key='+steamapiio_key);
  1856. callback(true, null);
  1857. }
  1858. } else {
  1859. logError('Failed to load UserInventory of '+steamid+'. Error response.');
  1860. callback(true, null);
  1861. }
  1862. });*/
  1863.  
  1864. request({
  1865. url: 'http://api.steamapis.com/steam/inventory/'+steamid+'/252490/2?api_key='+steamapis_key
  1866. }, function (err, response, body) {
  1867. if(!err){
  1868. if(response.statusCode == 200){
  1869. var inv = [];
  1870.  
  1871. try{
  1872. body = JSON.parse(body);
  1873. } catch(err){
  1874. logError('Failed to load UserInventory of '+steamid+'. Invalid response body.');
  1875. callback(true, null);
  1876. return;
  1877. }
  1878.  
  1879. var assets = body.assets;
  1880. var descriptions = body.descriptions;
  1881.  
  1882. for(var i in assets){
  1883. var classid = assets[i].classid;
  1884. var assetid = assets[i].assetid;
  1885.  
  1886. for(var y in descriptions){
  1887. if(descriptions[y].classid == classid){
  1888. var item = descriptions[y];
  1889.  
  1890. if(!item.tradable){
  1891. continue;
  1892. }
  1893.  
  1894. var arr = {
  1895. img: 'http://steamcommunity-a.akamaihd.net/economy/image/'+item.icon_url+'/128x128',
  1896. name: item.market_hash_name,
  1897. assetid: assetid,
  1898. price: (!prices.hasOwnProperty(item.market_hash_name)) ? 0 : prices[item.market_hash_name]
  1899. };
  1900.  
  1901. inv.push(arr);
  1902. }
  1903. }
  1904. }
  1905.  
  1906. logSuccess('Loaded the Inventory of '+steamid+' successfully. '+inv.length+' Items are tradeable.');
  1907. callback(false, inv);
  1908. } else if(response.statusCode == 429){
  1909. logError('FATAL ERROR --> Failed to load UserInventory of '+steamid+'. Limit reached.');
  1910. callback(true, null);
  1911. } else {
  1912. logError('Failed to load UserInventory of '+steamid+'. Invalid response. '+response.statusCode+' | '+'https://api.steamapi.io/user/inventory/'+steamid+'/252490/2?key='+steamapiio_key);
  1913. callback(true, null);
  1914. }
  1915. } else {
  1916. logError('Failed to load UserInventory of '+steamid+'. Error response.');
  1917. callback(true, null);
  1918. }
  1919. });
  1920.  
  1921. /*
  1922. manager.loadUserInventory(steamid, 252490, 2, true, function(err, inventory){
  1923. if(err){
  1924. logError('Failed to load UserInventory of '+steamid+'.');
  1925.  
  1926. callback(true, null);
  1927. } else {
  1928. var inv = [];
  1929.  
  1930. for(var i in inventory){
  1931. var item = inventory[i];
  1932.  
  1933. var arr = {
  1934. img: item.getImageURL() + '128x128',
  1935. name: item.market_hash_name,
  1936. assetid: item.assetid,
  1937. price: (!prices.hasOwnProperty(item.market_hash_name)) ? 0 : prices[item.market_hash_name]
  1938. };
  1939.  
  1940. inv.push(arr);
  1941. }
  1942.  
  1943. logSuccess('Loaded the Inventory of '+steamid+' successfully');
  1944. callback(false, inv);
  1945. }
  1946. });
  1947. */
  1948. }
  1949.  
  1950. function sortItems(arr){
  1951. var swapped;
  1952. do {
  1953. swapped = false;
  1954. for (var i=0; i < arr.length-1; i++) {
  1955. if (arr[i].price > arr[i+1].price) {
  1956. var temp = arr[i];
  1957. arr[i] = arr[i+1];
  1958. arr[i+1] = temp;
  1959. swapped = true;
  1960. }
  1961. }
  1962. } while (swapped);
  1963.  
  1964. return arr;
  1965. }
  1966.  
  1967. function rustItem(assetid){
  1968. var item = {};
  1969. item.appid = 252490;
  1970. item.assetid = assetid;
  1971. item.contextid = 2;
  1972. item.amount = 1;
  1973. return item;
  1974. }
  1975.  
  1976. function confirmOffer(offer, callback){
  1977.  
  1978. community.acceptConfirmationForObject(account.identity_secret, offer.id, function(err) {
  1979. if (err) {
  1980. logError('Trade #' + offer.id + ': Error while confirming: ' + err);
  1981. }
  1982. if (callback != null) {
  1983. callback(err);
  1984. }
  1985. });
  1986. }
  1987.  
  1988. function removeAssetidsInUse(assetids){
  1989. for(var a in assetids){
  1990. usedAssetids.splice(usedAssetids.indexOf(assetids[a]), 1);
  1991. }
  1992. }
  1993.  
  1994. function saveAssetidsInUse(){
  1995. var assetidsInUse_string = JSON.stringify(usedAssetids);
  1996.  
  1997. fs.writeFile('./cache/usedAssetids.json', assetidsInUse_string, function(err) {
  1998. if(err) {
  1999. logError('FATAL ERROR -> Error saving the usedAssetids');
  2000. } else {
  2001. logInfo('The usedAssetids have been saved');
  2002. }
  2003. });
  2004. }
  2005.  
  2006. function generateCode(){
  2007. return generateRandomString(5);
  2008. }
  2009.  
  2010. function generateRandomString(length){
  2011. var random = '';
  2012. var possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
  2013.  
  2014. for (var i = 0; i < length; i++){
  2015. random += possible.charAt(Math.floor(Math.random() * possible.length));
  2016. }
  2017.  
  2018. return random;
  2019. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement