Advertisement
Tretlenz

app.js

Mar 13th, 2018
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var auth = require('http-auth'),
  2.     scribe = require('scribe-js')(),
  3.     console = process.console,
  4.     config  = require('./config.js'),
  5.     app     = require('express')(),
  6.     server  = require('http').Server(app),
  7.     io      = require('socket.io')(server),
  8.     redis   = require('redis'),
  9.     requestify   = require('requestify'),
  10.     bot     = require('./bot.js');
  11.     shop    = require('./shop.js');
  12.  
  13. var redisClient = redis.createClient(),
  14.     client = redis.createClient();
  15.  
  16. bot.init(redis, io, requestify);
  17. shop.init(redis, requestify);
  18.  
  19. server.listen(config.serverPort);
  20.  
  21. console.tag('SOCKET', logTime()).log('Сервер запущен на ' + config.domain + ':' + config.serverPort);
  22.  
  23. var basicAuth = auth.basic({
  24.     realm: "WebPanel",
  25.     file: __dirname + "/users.htpasswd"
  26. });
  27. app.use('/logs', auth.connect(basicAuth), scribe.webPanel());
  28.  
  29. redisClient.subscribe('ioMessage');
  30. redisClient.subscribe('show.winners');
  31. redisClient.subscribe('queue');
  32. redisClient.subscribe('newDeposit');
  33. redisClient.subscribe('msgChannel');
  34. redisClient.subscribe('MessageShop');
  35. redisClient.subscribe('depositDecline');
  36. redisClient.subscribe('withdraw_message');
  37. redisClient.subscribe('withdraw_message_close');
  38. redisClient.setMaxListeners(0);
  39. redisClient.on("message", function(channel, message) {
  40.     if(channel == 'ioMessage') {
  41.         message = JSON.parse(message);
  42.         io.sockets.emit(message.io, message.message);
  43.     }
  44.     if(channel == 'withdraw_message') io.sockets.emit(channel, JSON.parse(message));
  45.     if(channel == 'withdraw_message_close') io.sockets.emit(channel, JSON.parse(message));
  46.     if(channel == 'depositDecline' || channel == 'queue' || channel == 'msgChannel'){
  47.         io.sockets.emit(channel, message);
  48.     }
  49.     if(channel == 'show.winners'){
  50.         clearInterval(timer);
  51.         timerStatus = false;
  52.         console.log('Принудительная остановка!');
  53.         game.status = 3;
  54.         showSliderWinners();
  55.     }
  56.     if(channel == 'newDeposit'){
  57.         io.sockets.emit(channel, message);
  58.          message = JSON.parse(message);
  59.          if(!timerStatus && message.gameStatus == 1){
  60.          game.status = 1;
  61.          startTimer(io.sockets);
  62.          }
  63.  
  64.     }
  65. });
  66.  
  67. /* CHAT MESSGAGE */
  68.  
  69. redisClient.subscribe('chat.message');
  70. redisClient.subscribe('new.msg');
  71. redisClient.subscribe('del.msg');
  72. redisClient.on("message", function (channel, message) {
  73.     if (channel == 'new.msg')
  74.     {
  75.         updateChat();
  76.     }
  77.     if (channel == 'del.msg')
  78.     {
  79.         io.sockets.emit('DMessage', message);
  80.         console.tag('CHAT', logTime()).log('Сообщение удалено!');
  81.     }
  82. });
  83.  
  84. /* CHAT MESSGAGE END */
  85.  
  86. io.sockets.on('connection', function (socket) {
  87.     updateOnline();
  88.     socket.on('disconnect', function () {
  89.         setTimeout(function () {
  90.             updateOnline();
  91.         }, 1500)
  92.     })
  93. });
  94.  
  95. function updateOnline() {
  96.     io.sockets.emit('online', Object.keys(io.sockets.adapter.rooms).length);
  97.     online = Object.keys(io.sockets.adapter.rooms).length;
  98.     setTimeout(function () {
  99.         if (online != Object.keys(io.sockets.adapter.rooms).length) {
  100.             console.tag('SOCKET','ONLINE', logTime()).info('Подключено ' + Object.keys(io.sockets.adapter.rooms).length + ' пользователей');
  101.         }
  102.     }, 5000)
  103. }
  104.  
  105. var steamStatus = [],
  106.     game,
  107.     timer,
  108.     ngtimer,
  109.     timerStatus = false,
  110.     timerTime = config.gameTime,
  111.     preFinishingTime = 2;
  112.     online = 0;
  113.    
  114. getCurrentGame();
  115. checkSteamInventoryStatus();
  116.  
  117.  
  118. // Chat & Stats & Winners Functions Start
  119.  
  120. function updateMaxPrice() {
  121.         requestify.post('http://' + config.domain + '/api/maxprice', {
  122.         secretKey: config.secretKey
  123.     })
  124.         .then(function (response) {
  125.             console.tag('Статистика', logTime()).log('Макс. Выигрыш - Обновлено');
  126.                 data = JSON.parse(response.body);
  127.                 io.sockets.emit('updateMaxPrice', data);
  128.             }
  129.         );
  130. }
  131. function updateUsersToday() {
  132.         requestify.post('http://' + config.domain + '/api/userstoday', {
  133.         secretKey: config.secretKey
  134.     })
  135.         .then(function (response) {
  136.             console.tag('Статистика', logTime()).log('Игроков Сегодня - Обновлено');
  137.                 data = JSON.parse(response.body);
  138.                 io.sockets.emit('updateUsersToday', data);
  139.             }
  140.         );
  141. }
  142. function updateGamesToday() {
  143.         requestify.post('http://' + config.domain + '/api/gamestoday', {
  144.         secretKey: config.secretKey
  145.     })
  146.         .then(function (response) {
  147.             console.tag('Статистика', logTime()).log('Игр Сегодня - Обновлено');
  148.                 data = JSON.parse(response.body);
  149.                 io.sockets.emit('updateGamesToday', data);
  150.             }
  151.         );
  152. }
  153.  
  154. function updateChat() {
  155.     requestify.post('http://' + config.domain + '/api/chat', {
  156.         secretKey: config.secretKey
  157.     })
  158.         .then(function(response) {
  159.             chat_messages = JSON.parse(response.body);
  160.             io.sockets.emit('CMessages', chat_messages);
  161.             console.tag('CHAT', logTime()).log('Новое сообщение!');
  162.         }, function(response) {
  163.             console.tag('CHAT', logTime()).log('Что-то не так [getChatMessages]');
  164.         });
  165. }
  166.  
  167. function lastwinner() {
  168.     requestify.get('http://' + config.domain + '/api/lastwinner', {
  169.         secretKey: config.secretKey
  170.     })
  171.         .then(function(response) {
  172.             data = JSON.parse(response.body);
  173.             console.tag('Last Winner', logTime()).log('Updating...');
  174.             console.tag('Last Winner', logTime()).log('Success!');
  175.             io.sockets.emit('LastWinner', data);
  176.         },function(err){
  177.             console.tag('Last Winner', logTime()).error(err);
  178.             setTimeout(lastwinner, 1000);
  179.         });
  180. }
  181.  
  182. function happywinner() {
  183.     requestify.get('http://' + config.domain + '/api/happywinner', {
  184.         secretKey: config.secretKey
  185.     })
  186.         .then(function(response) {
  187.            data = JSON.parse(response.body);
  188.             console.tag('Happy Winner', logTime()).log('Updating...');
  189.             console.tag('Happy Winner', logTime()).log('Success!');
  190.             io.sockets.emit('HappyWinner', data);
  191.         },function(err){
  192.             console.tag('Happy Winner', logTime()).error(err);
  193.             setTimeout(happywinner, 1000);
  194.         });
  195. }
  196.  
  197.  
  198. function ChatBot() {
  199.     requestify.post('http://' + config.domain + '/api/ChatBot', {
  200.         secretKey: config.secretKey
  201.     })
  202.         .then(function (response) {
  203.             updateChat();
  204.         }, function (err) {
  205.             console.tag('Игра').error(err);
  206.             setTimeout(ChatBot, 1000);
  207.         });
  208. }
  209.  
  210. // Chat & Stats & Winners Functions End
  211.  
  212.  
  213. // Game Functions Start
  214.  
  215. function logTime() {
  216.  
  217.     var date = new Date();
  218.     var hour = date.getHours();
  219.     var min  = date.getMinutes();
  220.     var sec  = date.getSeconds();
  221.  
  222.     var year = date.getFullYear();
  223.     var month = date.getMonth() + 1;
  224.     var day  = date.getDate();
  225.  
  226.     hour = (hour < 10 ? "0" : "") + hour;
  227.     min = (min < 10 ? "0" : "") + min;
  228.     sec = (sec < 10 ? "0" : "") + sec;
  229.     month = (month < 10 ? "0" : "") + month;
  230.     day = (day < 10 ? "0" : "") + day;
  231.  
  232.     return hour + ":" + min + ":" + sec;
  233. }
  234.  
  235. function updatePrices(){
  236.     requestify.post('http://' + config.domain + '/api/updatePrices', {
  237.         secretKey: config.secretKey
  238.     })
  239.         .then(function (response) {
  240.             console.tag('updatePrices', logTime()).log('Updating...');
  241.             console.tag('updatePrices', logTime()).log('Success!');
  242.         }, function (response) {
  243.             console.tag('updatePrices', logTime()).log('Что-то не так [updatePrices]');
  244.         });
  245. }
  246.  
  247. function getRandomArbitary(min, max)
  248. {
  249.     return Math.random() * (max - min) + min;
  250. }
  251.  
  252. function offers() {
  253.     io.sockets.emit('lastOffers');
  254.     console.tag('LastBets', logTime()).log('Принимаем последние ставки...');
  255.         preFinish = true;
  256.         timerStatus = true;
  257.         setTimeout(function(){
  258.             setGameStatus(2);
  259.             showSliderWinners();
  260.         }, Math.round(getRandomArbitary(10000,15000)));
  261. }
  262.  
  263.  
  264. var preFinish = false;
  265. function startTimer(){
  266.     var time = timerTime;
  267.     timerStatus = true;
  268.     clearInterval(timer);
  269.     console.tag('Игра').log('Игра началась.');
  270.     timer = setInterval(function(){
  271.         console.tag('Игра', logTime()).log('Таймер: ' + time);
  272.         io.sockets.emit('Time', time--);
  273.         if(time <= 0){
  274.             clearInterval(timer);
  275.             console.tag('Игра', logTime()).log('Игра завершена.');
  276.             offers();
  277.         }
  278.     }, 1000);
  279. }
  280.  
  281. function startNGTimer(winners){
  282.     var time = 22;
  283.     data = JSON.parse(winners);
  284.     data.showSlider = true;
  285.     clearInterval(ngtimer);
  286.     ngtimer = setInterval(function(){
  287.         if(time <= 14) data.showSlider = false;
  288.         console.tag('Игра', logTime()).log('Новая игра через: ' + time);
  289.         if(time == 5) {
  290.         lastwinner();
  291.         happywinner();
  292.         ChatBot();
  293.         data.time = time--;
  294.         }
  295.         data.time = time--;
  296.         io.sockets.emit('Roulette', data);
  297.         if(time <= 0){
  298.             clearInterval(ngtimer);
  299.             newGame();
  300.         }
  301.     }, 1000);
  302. }
  303.  
  304. function getCurrentGame(){
  305.     requestify.post('http://'+config.domain+'/api/getCurrentGame', {
  306.         secretKey: config.secretKey
  307.     })
  308.         .then(function(response) {
  309.             game = JSON.parse(response.body);
  310.             console.tag('Игра', logTime()).log('Текущая Игра #' + game.id);
  311.             if(game.status == 1) startTimer();
  312.             if(game.status == 2) startTimer();
  313.             if(game.status == 3) newGame();
  314.         },function(err){
  315.             console.tag('Игра', logTime()).log(err);
  316.             setTimeout(getCurrentGame, 1000);
  317.         });
  318. }
  319.  
  320. function newGame(){
  321.     requestify.post('http://'+config.domain+'/api/newGame', {
  322.         secretKey: config.secretKey
  323.     })
  324.         .then(function(response) {
  325.             preFinish = false;
  326.             game = JSON.parse(response.body);
  327.             console.tag('Игра', logTime()).log('Новая игра, успешно создалась! #' + game.id);
  328.             io.sockets.emit('newRound', game);
  329.             bot.handleOffers();
  330.             updateMaxPrice();
  331.             updateUsersToday();
  332.             updateGamesToday();
  333.         },function(err){
  334.             console.tag('Игра', logTime()).error(err);
  335.             setTimeout(newGame, 1000);
  336.         });
  337. }
  338.  
  339.  
  340. function showSliderWinners(){
  341.     requestify.post('http://'+config.domain+'/api/getWinners', {
  342.         secretKey: config.secretKey
  343.     })
  344.         .then(function(response) {
  345.             var winners = response.body;
  346.             timerStatus = false;
  347.             console.tag('Игра', logTime()).log('Показываем слайдер!');
  348.             startNGTimer(winners);
  349.             setGameStatus(3);
  350.         },function(err){
  351.             console.tag('Игра', logTime()).error(err);
  352.             setTimeout(showSliderWinners, 5000);
  353.         });
  354. }
  355.  
  356. function setGameStatus(status){
  357.     requestify.post('http://'+config.domain+'/api/setGameStatus', {
  358.         status: status,
  359.         secretKey: config.secretKey
  360.     })
  361.         .then(function(response) {
  362.             game = JSON.parse(response.body);
  363.             console.tag('Игра', logTime()).log('Закрываем игру. Ставки будут перенаправлены на новую игру.');
  364.         },function(response){
  365.             console.tag('Игра', logTime()).error('Что-то не так [setGameStatus]');
  366.             setTimeout(setGameStatus, 1000);
  367.         });
  368. }
  369.  
  370. function checkSteamInventoryStatus(){
  371.     requestify.get('https://api.steampowered.com/ICSGOServers_730/GetGameServersStatus/v1/?key=' + config.apiKey)
  372.         .then(function(response) {
  373.             var answer = JSON.parse(response.body);
  374.             steamStatus = answer.result.services;
  375.             console.tag('SteamStatus', logTime()).info(steamStatus);
  376.             client.set('steam.community.status', steamStatus.SteamCommunity);
  377.             client.set('steam.inventory.status', steamStatus.IEconItems);
  378.             if(steamStatus.SteamCommunity == 'normal') io.sockets.emit('SteamStatus', 'normal');
  379.             if(steamStatus.SteamCommunity == 'delayed') io.sockets.emit('SteamStatus', 'delayed');
  380.             if(steamStatus.SteamCommunity == 'critical') io.sockets.emit('SteamStatus', 'critical');
  381.         },function(response){
  382.             console.log('Something wrong [5]');
  383.             console.log(response.body);
  384.         });
  385. }
  386.  
  387.  
  388. // Game Functions End
  389.  
  390. setInterval(checkSteamInventoryStatus, 120000);
  391. setInterval(updatePrices, 10800000); // 86400000 24 hours
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement