Advertisement
Guest User

[TW] server

a guest
Dec 23rd, 2016
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.                 ///////////////////////////////
  2.                 //          NODE JS          //
  3.                 ///////////////////////////////
  4.  
  5. var debug = true;
  6.  
  7. var stdin = process.openStdin();
  8.  
  9. stdin.addListener("data", function(d)
  10. {
  11.     if(d.toString().trim() == "debug")
  12.     {
  13.         debug = !debug;
  14.         console.log("debug = " + debug);
  15.     }
  16. });
  17.  
  18. var colors = require('colors');
  19. var crypto = require('crypto');
  20. var mysql = require('mysql');
  21. var express = require('express'); // Para HTTP
  22. var cors = require('cors'); // Para HTTP com EXPRESS
  23. var chance = require('chance'); // Gerar salts
  24.  
  25. var event = express();
  26. event.use(cors());
  27.  
  28. var bodyParser = require('body-parser'); // Ler body do post
  29. event.use(bodyParser.json());
  30. event.use(bodyParser.urlencoded({extended: true}));
  31.  
  32. // Mysql info
  33. var connection = mysql.createConnection(
  34. {
  35.     host     : 'localhost', // MySQL Host
  36.     user     : 'up201405219', // MySQL User
  37.     password : '36Grupo', // MySQL Password
  38.     database : 'up201405219' // MySQL Databse
  39. });
  40.  
  41. // Mysql errors
  42. connection.connect(function(err)
  43. {
  44.     if(err)
  45.     {
  46.         console.log(colors.cyan("[DATABASE]") + " Error connecting: " + colors.red(err.stack));
  47.         return;
  48.     }
  49.  
  50.     console.log(colors.cyan("[DATABASE]") + " Connected as id: " + colors.green(connection.threadId));
  51. });
  52.  
  53. var salts = new chance();
  54. var WaitList = []; // splice(index, i) <- i == 1, remove no index
  55. var game = 0; // GameID
  56. var gameList = [];
  57. var connections = [];
  58.  
  59. function opponent(level, group)
  60. {
  61.     if(WaitList.length == 0)
  62.     {
  63.         return null;
  64.     }
  65.  
  66.     for(var i = 0; i < WaitList.length; i++)
  67.     {
  68.         if(WaitList[i].level == level && WaitList[i].group == group)
  69.         {
  70.             var temp = WaitList[i];
  71.             WaitList.splice(i, 1);
  72.             return temp;
  73.         }
  74.     }
  75.    
  76.     return null;
  77. }
  78.  
  79. var levelSize =
  80. {
  81.     beginner     : { linhas: 5, colunas: 7 },
  82.     intermediate : { linhas: 9, colunas: 11 },
  83.     advanced     : { linhas: 13, colunas: 17 },
  84.     expert       : { linhas: 19, colunas: 23 }
  85. };
  86.  
  87. function gameStarted(gameID)
  88. {
  89.     var users = [];
  90.     var count = 0;
  91.    
  92.     if(gameList[gameID] === undefined)
  93.     {
  94.         return false;
  95.     }
  96.    
  97.     else
  98.     {
  99.         for(var i = 0; i < connections.length; i++)
  100.         {
  101.             if(connections[i].gameID == gameID)
  102.             {
  103.                 users[count] = connections[i].username;
  104.                 count ++;
  105.             }
  106.         }
  107.  
  108.         if(count != 2)
  109.         {
  110.             return false;
  111.         }
  112.  
  113.         if(users[0] == gameList[gameID].user1.username && users[1] == gameList[gameID].user2.username)
  114.         {
  115.             return true;
  116.         }
  117.  
  118.         else if(users[0] == gameList[gameID].user2.username && users[1] == gameList[gameID].user1.username)
  119.         {
  120.             return true;
  121.         }
  122.     }
  123.  
  124.     return false;
  125. }
  126.  
  127. function newGame(user1, user2, gameID, userKey1, userKey2, level)
  128. {
  129.     var data =
  130.     {
  131.         board :
  132.             {
  133.                 table   : null,
  134.                 level   : level,
  135.                 line    : levelSize[level].linhas,
  136.                 column  : levelSize[level].colunas
  137.             },
  138.  
  139.         user1 :
  140.             {
  141.                 username  : user1,
  142.                 key       : userKey1,
  143.                 points    : 0,
  144.                 time      : 0,
  145.                 timeStart : 0
  146.             },
  147.  
  148.         user2 :
  149.             {
  150.                 username  : user2,
  151.                 key       : userKey2,
  152.                 points    : 0,
  153.                 time      : 0,
  154.                 timeStart : 0
  155.             },
  156.  
  157.         game  :
  158.             {
  159.                 turn    : user1,
  160.                 gameID  : gameID
  161.             }
  162.     };
  163.    
  164.     data.board.table = [];
  165.     data.board.table.length = data.board.line;
  166.        
  167.     for(var i = 0; i < data.board.line; i++)
  168.     {
  169.         data.board.table[i] = [];
  170.         data.board.table[i].length = data.board.column;
  171.        
  172.         for(var j = 0; j < data.board.column; j++)
  173.         {
  174.             data.board.table[i][j] = 0;
  175.         }
  176.     }
  177.  
  178.     gameList[gameID] = data;
  179. }
  180.  
  181. function checkUserNameKey(func, username, key, gameID)
  182. {
  183.     var nameRegex = /^[a-zA-Z0-9\_]+$/;
  184.    
  185.     if(!nameRegex.test(username))
  186.     {
  187.         if(debug)
  188.         {
  189.             console.log(colors.cyan(func) + " Invalid username: " + colors.red(username));
  190.         }
  191.  
  192.         return  false;
  193.     }
  194.    
  195.     if(key != null)
  196.     {
  197.         for(var i = 0; i < WaitList.length; i++)
  198.         {
  199.             if(WaitList[i].username == username && WaitList[i].key == key)
  200.             {
  201.                 return true
  202.             }
  203.         }
  204.  
  205.         // notify && update
  206.         if(gameList[gameID] == undefined)
  207.         {
  208.             if(debug)
  209.             {
  210.                 console.log(colors.cyan(func) + " This game isn't exist: " + colors.red(gameID));
  211.             }
  212.  
  213.             return false;
  214.         }  
  215.        
  216.         else if(gameList[gameID].user1.username == username && gameList[gameID].user1.key)
  217.         {
  218.             return true;
  219.         }
  220.        
  221.         else if(gameList[gameID].user2.username == username && gameList[gameID].user2.key)
  222.         {
  223.             return true;
  224.         }
  225.        
  226.         if(debug)
  227.         {
  228.             console.log(colors.cyan(func) + " " + colors.yellow(username) + " can't play on this game " + colors.yellow(gameID));
  229.         }
  230.  
  231.         return false;
  232.     }
  233.  
  234.     return true;
  235. }
  236.  
  237. function addWinnerToDataBase(winner, gameID)
  238. {
  239.     if(gameList[gameID].user1.username == winner)
  240.     {
  241.         connection.query('INSERT INTO `Rankings` (`name`,`level`,`boxes`,`time`) VALUES (\'' + gameList[gameID].user1.username + '\',\'' + gameList[gameID].board.level + '\',\'' + gameList[gameID].user1.points + '\',\'' + Math.round(gameList[gameID].user1.time) + '\');', function(err, row, fields) {});
  242.     }
  243.    
  244.     else
  245.     {
  246.         connection.query('INSERT INTO `Rankings` (`name`,`level`,`boxes`,`time`) VALUES (\'' + gameList[gameID].user2.username + '\',\'' + gameList[gameID].board.level + '\',\'' + gameList[gameID].user2.points + '\',\'' + Math.round(gameList[gameID].user2.time) + '\');', function(err, row, fields) {});
  247.     }
  248. }
  249.  
  250. function closeConnections(gameID)
  251. {
  252.     for(var i = 0; i < connections.length; i++)
  253.     {
  254.         if(connections[i].gameID == gameID)
  255.         {
  256.             connections.splice(i, 1);
  257.  
  258.             if(i > 0)
  259.             {
  260.                 i -= 1;
  261.             }
  262.         }
  263.     }
  264. }
  265.  
  266. function ServerSentEvents(gameID, func, change, l, c)
  267. {
  268.     //var date = new Date();
  269.  
  270.     if(func != "start")
  271.     {
  272.         if(gameList[gameID].game.turn == gameList[gameID].user1.username)
  273.         {
  274.             gameList[gameID].user1.time += (Date.now() - gameList[gameID].user1.timeStart) / 1000;
  275.         }
  276.         else
  277.         {
  278.             gameList[gameID].user2.time += (Date.now() - gameList[gameID].user2.timeStart) / 1000;
  279.         }
  280.     }
  281.  
  282.     var lastTurn = gameList[gameID].game.turn;
  283.  
  284.     if(change != null && !change)
  285.     {
  286.         if(lastTurn == gameList[gameID].user1.username)
  287.         {
  288.             gameList[gameID].game.turn = gameList[gameID].user2.username;
  289.             lastTurn = gameList[gameID].user1.username;
  290.         }
  291.  
  292.         else
  293.         {
  294.             gameList[gameID].game.turn = gameList[gameID].user1.username;
  295.             lastTurn = gameList[gameID].user2.username;
  296.         }
  297.     }
  298.  
  299.     for(var i = 0; i < connections.length; i++)
  300.     {
  301.         if(connections[i].gameID == gameID)
  302.         {  
  303.             if(debug)
  304.             {
  305.                 console.log("\n" + colors.cyan("[UPDATE]") + " User: " + colors.green(connections[i].username));
  306.             }
  307.            
  308.             var object = {};
  309.  
  310.             if(func == "start")
  311.             {
  312.                 if(connections[i].username == gameList[gameID].user1.username)
  313.                 {
  314.                     object =
  315.                     {
  316.                         opponent : gameList[gameID].user2.username,
  317.                         turn     : gameList[gameID].game.turn
  318.                     };
  319.                 }
  320.                
  321.                 else
  322.                 {
  323.                     object =
  324.                     {
  325.                         opponent : gameList[gameID].user1.username,
  326.                         turn     : gameList[gameID].game.turn
  327.                     };
  328.                 }
  329.  
  330.                 connections[i].response.write("data: " + JSON.stringify(object) + "\n\n");
  331.                
  332.                 if(debug)
  333.                 {
  334.                     console.log("New game started! \n\t Opponent = " + colors.magenta(object.opponent) + " \n\t turn \t  = " + colors.magenta(object.turn) + "\n");
  335.                 }
  336.             }
  337.            
  338.             else if(func == "move")
  339.             {
  340.                 var struct = calculatePositionForWebsite(l, c);
  341.  
  342.                 if(lastTurn == gameList[gameID].user1.username)
  343.                 {
  344.                     object =
  345.                     {
  346.                         move :
  347.                             {
  348.                                 name    : gameList[gameID].user1.username,
  349.                                 orient  : struct.o,
  350.                                 row     : struct.l,
  351.                                 col     : struct.c,
  352.                                 time    : gameList[gameID].user1.time
  353.                             },
  354.  
  355.                         turn : gameList[gameID].game.turn
  356.                     };
  357.                 }
  358.  
  359.                 else
  360.                 {
  361.                     object =
  362.                     {
  363.                         move :
  364.                             {
  365.                                 name    : gameList[gameID].user2.username,
  366.                                 orient  : struct.o,
  367.                                 row     : struct.l,
  368.                                 col     : struct.c,
  369.                                 time    : gameList[gameID].user2.time
  370.                             },
  371.  
  372.                         turn : gameList[gameID].game.turn
  373.                     };
  374.                 }
  375.                
  376.                 connections[i].response.write("data: " + JSON.stringify(object) + "\n\n");
  377.                
  378.                 if(debug)
  379.                 {
  380.                     console.log("Play on " + object.move.row + " " + object.move.col + "\n\t name \t = " + colors.magenta(object.move.name) + " \n\t turn \t  = " + colors.magenta(object.turn) + "\n");
  381.                 }      
  382.             }
  383.  
  384.             else if(func == "winner")
  385.             {
  386.                 var winner = userWinner(gameID);
  387.  
  388.                 var struct = calculatePositionForWebsite(l, c);
  389.  
  390.                 if(gameList[gameID].game.turn == gameList[gameID].user1.username)
  391.                 {
  392.                     object =
  393.                     {
  394.                         move :
  395.                             {
  396.                                 name    : gameList[gameID].user1.username,
  397.                                 orient  : struct.o,
  398.                                 row     : struct.l,
  399.                                 col     : struct.c,
  400.                                 time    : gameList[gameID].user1.time
  401.                             },
  402.  
  403.                         winner : winner
  404.                     };
  405.                 }
  406.                
  407.                 else
  408.                 {
  409.                     object =
  410.                     {
  411.                         move :
  412.                             {
  413.                                 name    : gameList[gameID].user2.username,
  414.                                 orient  : struct.o,
  415.                                 row     : struct.l,
  416.                                 col     : struct.c,
  417.                                 time    : gameList[gameID].user2.time
  418.                             },
  419.  
  420.                         winner : winner
  421.                     };
  422.                 }
  423.  
  424.                 connections[i].response.write("data: " + JSON.stringify(object) + "\n\n");
  425.                 if(debug)
  426.                 {
  427.                     console.log("Winner " + colors.red("->") + " " + colors.green(object.winner));
  428.                 }
  429.             }
  430.         }
  431.     }
  432.  
  433.     console.log("\tuser1:\n\t\ttempo: " + gameList[gameID].user1.time + "\n\tuser2:\n\t\ttempo: " + gameList[gameID].user2.time + "\n agora: " + Date.now());
  434.  
  435.     gameList[gameID].user1.timeStart = Date.now();
  436.     gameList[gameID].user2.timeStart = Date.now();
  437.  
  438.     if(func == "winner")
  439.     {
  440.         closeConnections(gameID);
  441.  
  442.         addWinnerToDataBase(winner, gameID);
  443.     }
  444. }
  445.  
  446.  
  447. function calculatePositionForWebsite(l, c)
  448. {
  449.     var struct = {};
  450.    
  451.     if(l%2 == 0 && c%2 != 0)
  452.     {
  453.         struct.o = "h";
  454.         struct.l = 1 + (l / 2);
  455.         struct.c = (c + 1) / 2;
  456.     }
  457.  
  458.     else if(l%2 != 0 && c%2 == 0)
  459.     {
  460.         struct.o = "v";
  461.         struct.l = (l + 1) / 2;
  462.         struct.c = 1 + (c / 2);
  463.     }
  464.    
  465.     return struct;    
  466. }
  467.  
  468. function calculatePositionForHere(o, l, c)
  469. {
  470.     var struct = {};
  471.    
  472.     if(o === "h")
  473.     {
  474.         struct.l = 2 * (l - 1);
  475.         struct.c = (2 * c) - 1;
  476.     }
  477.    
  478.     else
  479.     {
  480.         struct.l = (2 * l) - 1;
  481.         struct.c = 2 * (c - 1);
  482.     }
  483.    
  484.     return struct;    
  485. }
  486.  
  487. function userWinner(gameID)
  488. {
  489.  
  490.     var winner;
  491.    
  492.     if(gameList[gameID].user1.points > gameList[gameID].user2.points)
  493.     {
  494.         winner = gameList[gameID].user1.username;
  495.     }
  496.    
  497.     else if(gameList[gameID].user2.points > gameList[gameID].user1.points)
  498.     {
  499.         winner = gameList[gameID].user2.username;
  500.     }  
  501.    
  502.     else
  503.     {        
  504.         if(gameList[gameID].user2.time > gameList[gameID].user1.time)
  505.         {
  506.             winner = gameList[gameID].user1.username;
  507.         }
  508.        
  509.         else
  510.         {
  511.             winner = winner = gameList[gameID].user2.username;
  512.         }
  513.     }
  514.    
  515.     return winner;
  516. }
  517.  
  518. /* WHO DO SQUARE */
  519. function square(gameID, who)
  520. {
  521.     if(who == gameList[gameID].user1.username)    
  522.     {
  523.         gameList[gameID].user1.points++;
  524.     }
  525.    
  526.     else
  527.     {
  528.         gameList[gameID].user2.points++;
  529.     }
  530. }
  531.  
  532. function someonePlay(gameID, who, l, c)
  533. {
  534.     var vertical;
  535.     var change = false;
  536.  
  537.     gameList[gameID].board.table[l][c] = -2;
  538.  
  539.     if(l%2 === 0)
  540.     {
  541.         vertical = true;      
  542.     }
  543.    
  544.     else
  545.     {
  546.         vertical = false;
  547.     }
  548.    
  549.     if(vertical)
  550.     {
  551.         if(l > 0) // Possivel quadrado de cima
  552.         {
  553.             if(gameList[gameID].board.table[l-2][c] !== 0 && gameList[gameID].board.table[l-1][c-1] !== 0 && gameList[gameID].board.table[l-1][c+1] !== 0)
  554.             {
  555.                 change = true;
  556.                 square(gameID, who, l-1, c);
  557.             }
  558.         }
  559.  
  560.         if(l < gameList[gameID].board.line-1) // Possivel quadrado de baixo
  561.         {
  562.             if(gameList[gameID].board.table[l+2][c] !== 0 && gameList[gameID].board.table[l+1][c-1] !== 0 && gameList[gameID].board.table[l+1][c+1] !== 0)
  563.             {
  564.                 change = true;
  565.                 square(gameID, who, l+1, c);
  566.             }
  567.         }
  568.     }
  569.  
  570.     else
  571.     {
  572.         if(c > 0) // Possivel quadrado da esquerda
  573.         {
  574.             if(gameList[gameID].board.table[l][c-2] !== 0 && gameList[gameID].board.table[l-1][c-1] !== 0 && gameList[gameID].board.table[l+1][c-1] !== 0)
  575.             {
  576.                 change = true;
  577.                 square(gameID, who, l, c-1);
  578.             }
  579.         }
  580.  
  581.         if(c < gameList[gameID].board.column-1) // Possivel quadrado da direita
  582.         {
  583.             if(gameList[gameID].board.table[l][c+2] !== 0 && gameList[gameID].board.table[l-1][c+1] !== 0 && gameList[gameID].board.table[l+1][c+1] !== 0)
  584.             {
  585.                 change = true;
  586.                 square(gameID, who, l, c+1);
  587.             }
  588.         }
  589.     }
  590.  
  591.     if(change)
  592.     {
  593.         /* End game? */
  594.         if(gameList[gameID].user1.points + gameList[gameID].user2.points == ((gameList[gameID].board.line-1)/2) * ((gameList[gameID].board.column-1)/2))
  595.         {
  596.             ServerSentEvents(gameID, "winner", null, l, c);
  597.             return;
  598.         }
  599.        
  600.         /* To know if change something */
  601.         ServerSentEvents(gameID, "move", true, l, c);
  602.         return;
  603.     }
  604.     /* Or not have changes */
  605.  
  606.     ServerSentEvents(gameID, "move", false, l, c);
  607.     return;
  608. }
  609.  
  610.  
  611.                 ///////////////////////////////
  612.                 //         EVENTS POST       //
  613.                 ///////////////////////////////
  614.  
  615. // Register
  616. event.post('/register', function(request, response)
  617. {
  618.     var username = request.body.name;
  619.     var password = request.body.pass;
  620.    
  621.     console.log(colors.cyan("[REGISTER]") + " User: " + colors.yellow(username));
  622.  
  623.     if(checkUserNameKey("[REGISTER]", username, null, null))
  624.     {
  625.         connection.query('SELECT * FROM `Users` WHERE `name`=\'' + username + '\'', function(err,result)
  626.         {
  627.             if(err)
  628.             {
  629.                 if(debug)
  630.                 {
  631.                     console.log(colors.cyan("[REGISTER]") + " Error: " + colors.red(err));
  632.                 }
  633.  
  634.                 response.json(
  635.                 {
  636.                     error : "Something wrong with DataBase!"
  637.                 });
  638.             }
  639.        
  640.             if(result.length > 0)
  641.             {
  642.                 var client = result[0];
  643.                
  644.                 var hash = crypto.createHash('md5').update(client.salt + password).digest('hex')
  645.  
  646.                 if(hash != client.pass)
  647.                 {
  648.                     if(debug)
  649.                     {
  650.                         console.log(colors.cyan("[REGISTER]") + " Incorrect Password! User: " + colors.yellow(username));
  651.                     }
  652.  
  653.                     response.json(
  654.                     {
  655.                         error : "Incorrect password!"
  656.                     });
  657.                 }
  658.                 else
  659.                 {
  660.                     if(debug)
  661.                     {
  662.                         console.log(colors.cyan("[REGISTER]") + " Correct Password! User: " + colors.yellow(username));
  663.                     }
  664.  
  665.                     response.json( {} );
  666.                 }
  667.             }
  668.             else
  669.             {
  670.                 var salt = salts.string( {length: 4} );
  671.                 var pass = crypto.createHash('md5').update(salt + password).digest('hex')
  672.                
  673.                 connection.query('INSERT INTO `Users` (`name`, `pass`, `salt`) VALUES (\'' + username + '\', \'' + pass + '\', \'' + salt + '\')', function(err, result)
  674.                 {
  675.                     if(err)
  676.                     {
  677.                         if(debug)
  678.                         {
  679.                             console.log(colors.cyan("[REGISTER]") + " Error: " + colors.red(err));
  680.                         }
  681.                     }
  682.                     else
  683.                     {  
  684.                         if(debug)
  685.                         {
  686.                             console.log(colors.cyan("[REGISTER]") + " User created successful! User: " + colors.yellow(username));
  687.                         }
  688.  
  689.                         response.json( {} );
  690.                     }
  691.                 });
  692.             }
  693.         });
  694.     }
  695.  
  696.     else
  697.     {
  698.         response.json(
  699.         {
  700.             error : "Your username is wrong! Please logout and login!"
  701.         });
  702.     }
  703. });
  704.  
  705. // Ranking
  706. event.post('/ranking', function(request, response)
  707. {
  708.     var level = request.body.level;
  709.  
  710.     connection.query('SELECT * FROM `Rankings` WHERE `level` = \'' + level + '\' ORDER BY boxes DESC, time ASC LIMIT 10;', function(err, result)
  711.     {
  712.         if(err)
  713.         {
  714.             if(debug)
  715.             {
  716.                 console.log(colors.cyan("[RANKING]") + " Error: " + colors.red(err));
  717.             }
  718.            
  719.             response.json(
  720.             {
  721.                 error : "Something wrong with DataBase!"
  722.             });
  723.         }
  724.         else
  725.         {
  726.             if(debug)
  727.             {
  728.                 console.log(colors.cyan("[RANKING]") + " Rank send successful! Level: " + colors.yellow(level));
  729.             }
  730.  
  731.             response.json(
  732.             {
  733.                 ranking : result
  734.             });
  735.         }
  736.     });
  737. });
  738.  
  739. // Join
  740. event.post('/join', function(request, response)
  741. {
  742.     var username = request.body.name;
  743.     request.body.username = username;
  744.     var hash = request.body.pass; // Na bd, está guardada uma hash
  745.  
  746.     var level = request.body.level;
  747.     var group = request.body.group;
  748.  
  749.     if(checkUserNameKey("[JOIN]", username, null, null))
  750.     {
  751.         connection.query('SELECT * FROM `Users` WHERE `name` = \'' + username + '\';', function(err, result)
  752.         {
  753.             if(err)
  754.             {
  755.                 if(debug)
  756.                 {
  757.                     console.log(colors.cyan("[JOIN]") + " Error: " + colors.red(err));
  758.                 }
  759.  
  760.                 response.json(
  761.                 {
  762.                     error : "Something wrong with DataBase!"
  763.                 });
  764.             }
  765.  
  766.             if(result.length > 0)
  767.             {
  768.                 var user = result[0];          
  769.                 var password = crypto.createHash('md5').update(user.salt + hash).digest('hex');
  770.                
  771.                 if(password == user.pass) // Possiveis ataques
  772.                 {
  773.                     for(var i = 0; i < WaitList.length; i++) // Se já está na lista de espera
  774.                     {
  775.                         if(WaitList[i].username == username)
  776.                         {
  777.                             if(debug)
  778.                             {
  779.                                 console.log(colors.cyan("[JOIN]") + " " + colors.red(username) + " yet are on WaitList!");
  780.                             }  
  781.  
  782.                             response.json({"error" : "You are in another side trying play!"});
  783.  
  784.                             return;
  785.                         }
  786.                     }
  787.  
  788.                     for(var i = 0; i < connections.length; i++) // Se já está a jogar
  789.                     {
  790.                         if(connections[i].username == username)
  791.                         {
  792.                             if(debug)
  793.                             {
  794.                                 console.log(colors.cyan("[JOIN]") + " " + colors.red(username) + " yet are playing in gameID " + colors.red(connections[i].gameID));
  795.                             }  
  796.  
  797.                             response.json(
  798.                             {
  799.                                 error : "You are in another side playing!"
  800.                             });
  801.  
  802.                             return;
  803.                         }
  804.                     }
  805.  
  806.                     var gameID;
  807.                    
  808.                     var key = crypto.createHash('md5').update(salts.string( {length: 8} )).digest('hex');
  809.                     var op = opponent(level, group);
  810.  
  811.                     if(op === null)
  812.                     {
  813.                         gameID = game++;
  814.                         request.body.game = gameID;
  815.                         request.body.key = key;
  816.                         WaitList.splice(0, 0, request.body);
  817.  
  818.                         if(debug)
  819.                         {
  820.                             console.log(colors.cyan("[JOIN]") + " " + colors.yellow(username) + " added to WaitList! gameID = " + colors.yellow(gameID));
  821.                         }
  822.                     }
  823.                     else
  824.                     {
  825.                         gameID = op.game;
  826.                         request.body.key = key;
  827.                         newGame(username, op.username, gameID, key, op.key, level);
  828.                        
  829.                         if(debug)
  830.                         {
  831.                             console.log(colors.cyan("[JOIN]") + " New game (gameID = " + colors.green(gameID) + "): " + colors.green(username) + " vs " + colors.green(op.username));
  832.                         }
  833.                     }
  834.  
  835.                     response.json(
  836.                     {
  837.                         key  : key,
  838.                         game : gameID
  839.                     });
  840.                 }
  841.                 else
  842.                 {
  843.                     if(debug)
  844.                     {
  845.                         console.log(colors.cyan("[JOIN]") + " " + colors.red(username) + " have a wrong password!");
  846.                     }  
  847.  
  848.                     response.json(
  849.                     {
  850.                         error : "Your password are wrong!"
  851.                     });
  852.                 }
  853.             }
  854.  
  855.             else
  856.             {
  857.                 if(debug)
  858.                 {
  859.                     console.log(colors.cyan("[JOIN]") + " " + colors.red("User name isn't valid!"));
  860.                 }  
  861.  
  862.                 response.json(
  863.                 {
  864.                     error : "User name isn't valid!"
  865.                 });
  866.             }
  867.         });
  868.     }
  869.  
  870.     else
  871.     {
  872.         response.json(
  873.         {
  874.             error : "You aren't logged correctly! Please login again!"
  875.         });
  876.     }
  877. });
  878.  
  879. // Leave
  880. event.post('/leave', function(request, response)
  881. {
  882.     var username = request.body.name;
  883.     var key = request.body.key;
  884.     var gameID = request.body.game;
  885.  
  886.     if(checkUserNameKey("[LEAVE]", username, key, gameID))
  887.     {
  888.         if(gameList[gameID] == undefined) // À espera
  889.         {
  890.             for(var i = 0; i < WaitList.length; i++)
  891.             {
  892.                 if(WaitList[i].username == username && WaitList[i].key == key)
  893.                 {
  894.                     WaitList.splice(i, 1);
  895.                    
  896.                     if(debug)
  897.                     {
  898.                         console.log(colors.cyan("[LEAVE]") + " " + colors.green(username) + " left WaitList! gameID = " + colors.green(gameID));
  899.                     }
  900.  
  901.                     if(i > 0)
  902.                     {
  903.                         i -= 1;
  904.                     }
  905.                 }                  
  906.             }
  907.  
  908.             for(var i = 0; i < connections.length; i++)
  909.             {
  910.                 if(connections[i].gameID == gameID && connections[i].key == key && connections[i].username == username)
  911.                 {
  912.                     connections.splice(i, 1);
  913.  
  914.                     if(i > 0)
  915.                     {
  916.                         i -= 1;
  917.                     }
  918.                 }
  919.             }
  920.         }
  921.         response.json( {} );
  922.     }
  923.  
  924.     else
  925.     {
  926.         response.json(
  927.         {
  928.             error : "You aren't logged correctly! Please login again!"
  929.         });
  930.     }
  931. });
  932.  
  933. // Notify
  934. event.post('/notify', function(request, response)
  935. {
  936.     var username = request.body.name;
  937.     var gameID = request.body.game;
  938.     var key = request.body.key;
  939.    
  940.     var orient = request.body.orient;
  941.     var l = request.body.row;
  942.     var c = request.body.col;
  943.  
  944.     var struct = calculatePositionForHere(orient, l ,c);
  945.  
  946.     if(checkUserNameKey("[NOTIFY]", username, key, gameID))
  947.     {
  948.         if(gameList[gameID].game.turn == username)
  949.         {
  950.             if(struct.l >= 0 && struct.l < gameList[gameID].board.line && struct.c >= 0 && struct.c < gameList[gameID].board.column)
  951.             {
  952.                 if(gameList[gameID].board.table[struct.l][struct.c] == 0)
  953.                 {
  954.                     if(debug)
  955.                     {
  956.                         console.log(colors.cyan("[Notify]") + " Move " + colors.green(struct.l) + " " + colors.green(struct.c) + " accepted!");
  957.                     }
  958.  
  959.                     response.json( {} );
  960.                     someonePlay(gameID, username, struct.l, struct.c);
  961.                 }
  962.                
  963.                 else
  964.                 {
  965.                     if(debug)
  966.                     {
  967.                         console.log(colors.cyan("[Notify]") + " " + colors.red(struct.l) + " " + colors.red(struct.c) + " yet played!");
  968.                     }
  969.  
  970.                     response.json(
  971.                     {
  972.                         error : "Edge already drawn!"
  973.                     });
  974.                 }
  975.             }
  976.            
  977.             else
  978.             {
  979.                 if(debug)
  980.                 {
  981.                     console.log(colors.cyan("[Notify]") + " " + colors.red(struct.l) + " " + colors.red(struct.c) + " isn't exist!");
  982.                 }
  983.  
  984.                 response.json(
  985.                 {
  986.                     error : "Edge isn't exist!"
  987.                 });
  988.             }
  989.         }
  990.  
  991.         else
  992.         {
  993.             if(debug)
  994.             {
  995.                 console.log(colors.cyan("[Notify]") + " " + colors.red(username) + " isn't him turn!");
  996.             }
  997.  
  998.             response.json(
  999.             {
  1000.                 error : "Isn't your turn!"
  1001.             });
  1002.         }
  1003.     }
  1004.  
  1005.     else
  1006.     {
  1007.         response.json(
  1008.         {
  1009.             error : "You aren't logged correctly! Please login again!"
  1010.         });
  1011.     }
  1012. });
  1013.  
  1014.  
  1015.                 ///////////////////////////////
  1016.                 //         EVENTS GET        //
  1017.                 ///////////////////////////////
  1018.  
  1019.  
  1020. event.get('/update', function(request, response)
  1021. {
  1022.     var username = request.query.name;
  1023.     var gameID = request.query.game;
  1024.     var key = request.query.key;
  1025.  
  1026.     if(checkUserNameKey("[UPDATE]", username, key, gameID))
  1027.     {
  1028.         console.log(colors.cyan("[UPDATE]") + " " + colors.green(username) + " updating! gameID = " + colors.green(gameID));
  1029.        
  1030.         request.socket.setTimeout(6000000);
  1031.  
  1032.         response.writeHead(200,
  1033.         {
  1034.             'Content-Type' : 'text/event-stream',
  1035.             'Cache-Control': 'no-cache',
  1036.             'Connection'   : 'keep-alive'
  1037.         });
  1038.  
  1039.         response.write('\n');
  1040.        
  1041.         var connection_temp =
  1042.         {
  1043.             response: response,
  1044.             username: username,
  1045.             key     : key,
  1046.             gameID  : gameID
  1047.         };
  1048.        
  1049.         connections.push(connection_temp);
  1050.  
  1051.         if(gameStarted(gameID))
  1052.         {
  1053.             ServerSentEvents(gameID, "start", null, null, null);
  1054.         }
  1055.     }
  1056.  
  1057.     else
  1058.     {
  1059.         if(debug)
  1060.         {
  1061.             console.log(colors.cyan("[UPDATE]") + " Game not found!");
  1062.         }  
  1063.  
  1064.         response.write("data: " + JSON.stringify(
  1065.                                     {
  1066.                                         error : "Game not found!"
  1067.                                     }) + "\n\n");
  1068.     }
  1069.  
  1070.     request.on("close", function()
  1071.     {
  1072.         for(var i = 0; i < connections.length; i++)
  1073.         {
  1074.             if(connections[i].gameID == gameID && connections[i].key == key && connections[i].username == username)
  1075.             {
  1076.                 connections.splice(i, 1);
  1077.  
  1078.                 if(i > 0)
  1079.                 {
  1080.                     i -= 1;
  1081.                 }
  1082.             }
  1083.         }
  1084.  
  1085.         for(var i = 0; i < WaitList.length; i++)
  1086.         {
  1087.             if(WaitList[i].username == username && WaitList[i].key == key)
  1088.             {
  1089.                 WaitList.splice(i, 1);
  1090.                
  1091.                 if(i > 0)
  1092.                 {
  1093.                     i -= 1;
  1094.                 }
  1095.             }
  1096.         }
  1097.  
  1098.  
  1099.     });
  1100. });
  1101.  
  1102. var server = event.listen(8036);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement