Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var chatConnections = [];
  2. var myMessages = [];
  3. var bannedIPs = {};
  4. var sessionid = 0;
  5. var sessions = {};
  6. var userbank = {};
  7. var globalTransmit = [];
  8. function User ( a, pass ) {
  9.     // Users to be attached to sessions.
  10.     if (!a || !(a.match(/^[a-zA-Z]\w{4,17}$/)) || a.length > 18 ) {
  11.         // Check for legal username.
  12.         throw new Error('User must have a valid name'); }
  13.     var u = userbank[a.toLowerCase()];
  14.     // Look in the user database for the name
  15.     if (u) {
  16.     // If the database has the user
  17.         if ( u.pass && u.pass !== pass ) {
  18.             // Make sure the user has a valid password.
  19.             throw new Error('Log In failed, the username has a password assigned and it did not match the password you provided. Reapeated login failures will have your IP banned.'); }
  20.         else if ( pass && !u.pass ) {
  21.             // If a password was provided, but the account doesn't have one, set a password on the accound.
  22.             u.pass = pass; }
  23.         u.name = a;
  24.         // Set the case of the name.
  25.         u.online = true;
  26.         // They are online at this point.
  27.         return u; }
  28.     else {
  29.         this.name = a;
  30.         this.online = true;
  31.         this.pass = pass;
  32.         userbank[a.toLowerCase()] = this;
  33.         return this; }
  34.     }
  35. function Connection ( key, name, pass ) {
  36.     this.key = key;
  37.     // Key is a randomly generated number provided by the client on the first connection to prevent impersonation.
  38.     // Follow up connections will provide a session id provided by the server, and the connection key they first generated.
  39.     // The session id will relate to the index the reference to this structure is stored at.
  40.     this.user = new User ( name, pass );
  41.     this.comet = [];
  42.     // Comet connection, used to stream data once the user logs in. Used as a buffer to catch data while the user isn't connected.
  43.     this.connection = null;
  44.     // Stores the connection, if the comet buffer is empty(this is often) the http connection info will be stored in here, ready to be responded to when new information is pushed.
  45.     // Also used to respond with a TCP keep-alive
  46.     this.lastAction = +new Date;
  47.     // Time outs, this is not managed by TCP
  48.     }
  49. function format (thi) {
  50.     /* Formats (escaped) text for display in a chat box, adds <a> to links, etc. */
  51.     function atag (s) {
  52.         return '<a href="'+s+'" target="_blank">'+s+'</a>'; }
  53.     function heart(s) {
  54.         return '<font color=red>'+s+'</font>'; }
  55.     function tag(s) {
  56.         var mytag = s.replace(/\[(b|s|i|u)\].*/,'$1')
  57.         return '<'+mytag+'>' + s.replace(/\[(b|s|i|u)\](.*?)\[\/(\1)\]/,'$2') +'</'+mytag+'>'; }
  58.     function color(s) {
  59.         var mycolor = s.replace(/\[(red|green|blue|gray)\].*/,'$1')
  60.         return '<font color='+mycolor+'>' + s.replace(/\[\/?(red|green|blue|gray)\]/gi,'') +'</font>'; }
  61.     var str = thi.replace(/[a-z]{3,}:\/\/[^ '"\\]+/ig,atag).replace(/\u2665/g,heart);
  62.     while (str != (str = str.
  63.         replace(/\[(b|s|i|u)\](.*?)\[\/(\1)\]/gi, '<$1>$2</$1>'/*tag*/).
  64.         replace(/\[(red|green|blue)\](.*?)\[\/(\1)\]/gi, '<font color="$1">$2</font>'/*color*/) )) {};
  65.     return str; }
  66. function colorOf(ip) {
  67.     var c = ip.split('.');
  68.     var n = 0;
  69.     for (var x in c) {
  70.         n ^= +c[x]; }
  71.     var clist =['#5811b1','#399bcd','#0474bb','#f8760d','#a00c9e','#0d762b','#5f4c00','#9a4f6d','#d0990f','#1b1390','#028678','#0324b1'];
  72.     return clist[n % clist.length]; }
  73. (function (port) {
  74.     var cmd = require('sys'),
  75.         http = require('http'),
  76.         querystring = require('querystring'),
  77.         url = require("url"),
  78.         fs = require('fs');
  79.         self = this;
  80. function updateUsers () {
  81.     cmd.puts('supposedly updating');
  82.     var s = '\n\t\t\t'+myMessages.join('\n\t\t\t<br />') + '\n\t\t';
  83.     cmd.puts('Users online: ' + chatConnections.length);
  84.     for (var x in chatConnections) {
  85.         if (!chatConnections[x]) {
  86.             continue; }
  87.         var response = chatConnections[x];
  88.         response.writeHead(200, {"Content-Type": "text/plain"});
  89.         response.write(s);
  90.         response.end(); }
  91.     chatConnections = []; }
  92. http.createServer(function (request, response) {
  93.     var uri = url.parse(request.url).pathname;
  94.     // find the page the user is trying to get.
  95.     request.connection.setNoDelay();
  96.     // This is annoying.
  97.     response.connection.setNoDelay();
  98.     // This is annoying.
  99.     if ( request.connection.remoteAddress in bannedIPs ) {
  100.         // Sometimes we ban users, meh.
  101.         response.writeHead(403, {"Content-Type": "text/plain"});
  102.         // Forbidden error.
  103.         response.end("You are banned from the server.");
  104.         // Be rude.
  105.         return;
  106.         // Stop wasting breath
  107.         }
  108.     if (request.method === "POST" && uri == '/login.node') {
  109.         // User is trying to log into our chat.
  110.         var myPOST;
  111.         request.addListener('data', function (POST) {
  112.         // Wait for the information.
  113.         myPOST = querystring.parse(POST);
  114.         // Parsing the post into an object
  115.         }).addListener('end', function () {
  116.         // This code runs when the stream is finnished.
  117.         if (myPOST.name && myPOST.session) {
  118.         // Make sure the user provided nessecary information.
  119.             try {
  120.                 sessions[++sessionid] = new Connection ( myPOST.session, myPOST.name, myPOST.pass );
  121.                 // A new session should be pushed to the sessions object, increment the counter for new session ids.
  122.                 response.writeHead(200, {"Content-Type": "text/plain"});
  123.                 // Tell the browser this page loaded correctly.
  124.                 response.end(JSON.stringify({script: 'alert("1")'}));
  125.                 // End the stream with a JSON responce.
  126.                 }
  127.             catch (e) {
  128.                 // When intialization of a new connection fails for some reason.
  129.                 // Usually a bad password or illegal name.
  130.                 response.writeHead(400,{"Content-Type": "text/plain"});
  131.                 // 400 error.
  132.                 response.end(e.toString());
  133.                 // Send the client the error
  134.                 }
  135.             }
  136.         else {
  137.             response.writeHead(400,{"Content-Type": "text/plain"});
  138.             // When something like myPOST.name isn't provided.
  139.             response.end('Missing POST arguments.'); }
  140.         });
  141.         }
  142.     else if (request.method === "POST" && uri == '/message.node') {
  143.         // This means the user is trying to post a message to the chatbox.
  144.         var myPOST;
  145.         request.addListener('data', function (POST) {
  146.         // Wait for the information.
  147.         myPOST = querystring.parse(POST);
  148.         // Parsing the post into an object
  149.         }).addListener('end', function () {
  150.         if ( !myPOST.key || !myPOST.session || !myPOST.msg ) {
  151.         // When a value is missing
  152.             } // Add error code here soon.
  153.         if ( sessions[myPOST.key].key != session ) {
  154.         // If the key is invalid (impersonation attempt?)
  155.             } // Error code here, may want to change the variable names on server and client to be less confusing
  156.         globalTransmit.push(JSON.stringyfy({newmsg:('<font color="'+colorOf(request.connection.remoteAddress)+'"><b>'+ (sessions[myPOST.key].user.name).replace(/&/g,'&').replace(/\>/g,'>').replace(/\</g,'<') + ':</b></font> ' + format((myPOST.msg || '<nothing>').replace(/&/g,'&').replace(/\>/g,'>').replace(/\</g,'<')))}));
  157.         // Might, just might, need to clean this up.
  158.         // No, really?
  159.         }  
  160.         }
  161.     else if (request.method === "POST" && uri == '/get.node') {
  162.         request.addListener('data', function (POST) {
  163.         myPOST = querystring.parse(POST);
  164.         }).addListener('end', function () {
  165.         if (!myPOST.key || !myPOST.id || sessions[myPOST.id].key != myPOST.key) {
  166.             } // Error, authentication failed
  167.         if (sessions[myPOST.id].conection !== null) {
  168.             } // Error, multiple connnecetions, maybe drop old connection with an error?
  169.         sessions[myPOST.id].connection = response;a
  170.         // This allows us to respond later when nessecary.
  171.         }
  172.     }
  173.  
  174.     else if (request.method === "POST" && uri == '/post.node') {
  175.         request.addListener('data', function (POST) {
  176.         self.myPOST = querystring.parse(POST);
  177.         }).addListener('end', function () {
  178.             myMessages.push('<font color="'+colorOf(request.connection.remoteAddress)+'"><b>'+ (self.myPOST.name || 'annon').replace(/&/g,'&').replace(/\>/g,'>').replace(/\</g,'<') + ':</b></font> ' + format((self.myPOST.msg || '<nothing>').replace(/&/g,'&').replace(/\>/g,'>').replace(/\</g,'<')));
  179.             response.writeHead(200, {"Content-Type": "text/html"});
  180.             myMessages.splice(0,myMessages.length - 20);
  181.             response.end('<!DOCTYPE html>\n<html language="en">\n\t<head>\n\t\t<title>AJAX Node.js Chat</title>\n\t</head>\n\t<body>\n\t\t<h1>AJAX Node.js Chat</h1>\n\t\t<form method="POST" action="/post.node">\n\t\t\tName: <input type="text" name="name" value="'+(self.myPOST.name || 'annon')+'" /><br />\n\t\t\tMessage: <input type="text" name="msg" id="box"/><br />\n\t\t\t<input type="submit" value="submit" /></form>\n\t\t<p id="chat">%m</p>\n\t</body>\n\t<script>\n\t\tfunction $(a) {\n\t\t\treturn document.getElementById(a); }\n\t\tvar synchronize = (function(url,callBack) {\n\t\t\tvar myRequest;\n\t\t\tvar responder;\n\t\t\tvar synchronize_inner = (function() {\n\t\t\t\tmyRequest = new XMLHttpRequest;\n\t\t\t\tmyRequest.onreadystatechange = responder;\n\t\t\t\tmyRequest.open("GET",url,true);\n\t\t\t\tmyRequest.send(); });\n\t\t\tresponder = (function() {\n\t\t\t\tif (myRequest.readyState == 4 && (myRequest.status == 200)) {\n\t\t\t\t\tcallBack(myRequest.responseText);\n\t\t\t\t\tsynchronize_inner(); }\n\t\t\t\t});\n\t\t\tsynchronize_inner(); });\n\t\tvar theText = $("chat");\n\t\tvar theBox = $("box");\n\t\twindow.onload = function () {\n\t\t\tsynchronize("/chat.node",\n\t\t\t\tfunction (resp) {\n\t\t\t\t\tif (resp == "x") {\n\t\t\t\t\t\treturn; }\n\t\t\t\t\ttheText.innerHTML = resp; \n\t\t\t\t\treturn; }\n\t\t\t\t);\n\t\t\ttheBox.focus(); }\n\t</script>\n</html>'.replace('%m','\n\t\t\t'+myMessages.join('\n\t\t\t<br />') + '\n\t\t'));
  182.            
  183.             updateUsers();
  184.             });
  185.         }
  186.     else if (request.method === "GET" && uri == '/chat.node') {
  187.         cmd.puts('new /chat.node');
  188.         chatConnections.push(response); }
  189.     else if (request.method === "GET" && uri == '/') {
  190.         response.writeHead(200, {"Content-Type": "text/html"});
  191.         response.write('<!DOCTYPE html>\n<html language="en">\n\t<head>\n\t\t<title>AJAX Node.js Chat</title>\n\t</head>\n\t<body>\n\t\t<h1>AJAX Node.js Chat</h1>\n\t\t<form method="POST" action="/post.node">\n\t\t\tName: <input type="text" name="name" value="'+('annon')+'" /><br />\n\t\t\tMessage: <input type="text" name="msg" id="box"/><br />\n\t\t\t<input type="submit" value="submit" /></form>\n\t\t<p id="chat">%m</p>\n\t</body>\n\t<script>\n\t\tfunction $(a) {\n\t\t\treturn document.getElementById(a); }\n\t\tvar synchronize = (function(url,callBack) {\n\t\t\tvar myRequest;\n\t\t\tvar responder;\n\t\t\tvar synchronize_inner = (function() {\n\t\t\t\tmyRequest = new XMLHttpRequest;\n\t\t\t\tmyRequest.onreadystatechange = responder;\n\t\t\t\tmyRequest.open("GET",url,true);\n\t\t\t\tmyRequest.send(); });\n\t\t\tresponder = (function() {\n\t\t\t\tif (myRequest.readyState == 4 && (myRequest.status == 200)) {\n\t\t\t\t\tcallBack(myRequest.responseText);\n\t\t\t\t\tsynchronize_inner(); }\n\t\t\t\t});\n\t\t\tsynchronize_inner(); });\n\t\tvar theText = $("chat");\n\t\tvar theBox = $("box");\n\t\twindow.onload = function () {\n\t\t\tsynchronize("/chat.node",\n\t\t\t\tfunction (resp) {\n\t\t\t\t\tif (resp == "x") {\n\t\t\t\t\t\treturn; }\n\t\t\t\t\ttheText.innerHTML = resp; \n\t\t\t\t\treturn; }\n\t\t\t\t);\n\t\t\ttheBox.focus(); }\n\t</script>\n</html>'.replace('%m','\n\t\t\t'+myMessages.join('\n\t\t\t<br />') + '\n\t\t')); }
  192.     else if (request.method === "GET" && uri == '/blip.wav') {
  193.         response.writeHead(200, {"Content-Type": "audio/x-wav"});
  194.         response.end(blip); }
  195.     else if (request.method === "GET" && uri == '/i.gif') {
  196.         response.writeHead(200, {"Content-Type": "image/gif"});
  197.         response.end(inv); }
  198.     else if (request.method === "GET" && uri == '/audio.class') {
  199.         response.writeHead(200, {"Content-Type": "text/plain"});
  200.         response.end(blip); }
  201.     else {
  202.         response.writeHead(404, {"Content-Type": "application/octet-stream"});
  203.         response.end('404: Epic Fail.'); }
  204.     }).listen(port);
  205.     setInterval(updateUsers, 50000); // keep alive
  206.     cmd.puts("Running on port:" + port + " with process id: " + process.pid);
  207. })(5082);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement