Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var chatConnections = [];
- var myMessages = [];
- var bannedIPs = {};
- var sessionid = 0;
- var sessions = {};
- var userbank = {};
- var globalTransmit = [];
- function User ( a, pass ) {
- // Users to be attached to sessions.
- if (!a || !(a.match(/^[a-zA-Z]\w{4,17}$/)) || a.length > 18 ) {
- // Check for legal username.
- throw new Error('User must have a valid name'); }
- var u = userbank[a.toLowerCase()];
- // Look in the user database for the name
- if (u) {
- // If the database has the user
- if ( u.pass && u.pass !== pass ) {
- // Make sure the user has a valid password.
- 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.'); }
- else if ( pass && !u.pass ) {
- // If a password was provided, but the account doesn't have one, set a password on the accound.
- u.pass = pass; }
- u.name = a;
- // Set the case of the name.
- u.online = true;
- // They are online at this point.
- return u; }
- else {
- this.name = a;
- this.online = true;
- this.pass = pass;
- userbank[a.toLowerCase()] = this;
- return this; }
- }
- function Connection ( key, name, pass ) {
- this.key = key;
- // Key is a randomly generated number provided by the client on the first connection to prevent impersonation.
- // Follow up connections will provide a session id provided by the server, and the connection key they first generated.
- // The session id will relate to the index the reference to this structure is stored at.
- this.user = new User ( name, pass );
- this.comet = [];
- // Comet connection, used to stream data once the user logs in. Used as a buffer to catch data while the user isn't connected.
- this.connection = null;
- // 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.
- // Also used to respond with a TCP keep-alive
- this.lastAction = +new Date;
- // Time outs, this is not managed by TCP
- }
- function format (thi) {
- /* Formats (escaped) text for display in a chat box, adds <a> to links, etc. */
- function atag (s) {
- return '<a href="'+s+'" target="_blank">'+s+'</a>'; }
- function heart(s) {
- return '<font color=red>'+s+'</font>'; }
- function tag(s) {
- var mytag = s.replace(/\[(b|s|i|u)\].*/,'$1')
- return '<'+mytag+'>' + s.replace(/\[(b|s|i|u)\](.*?)\[\/(\1)\]/,'$2') +'</'+mytag+'>'; }
- function color(s) {
- var mycolor = s.replace(/\[(red|green|blue|gray)\].*/,'$1')
- return '<font color='+mycolor+'>' + s.replace(/\[\/?(red|green|blue|gray)\]/gi,'') +'</font>'; }
- var str = thi.replace(/[a-z]{3,}:\/\/[^ '"\\]+/ig,atag).replace(/\u2665/g,heart);
- while (str != (str = str.
- replace(/\[(b|s|i|u)\](.*?)\[\/(\1)\]/gi, '<$1>$2</$1>'/*tag*/).
- replace(/\[(red|green|blue)\](.*?)\[\/(\1)\]/gi, '<font color="$1">$2</font>'/*color*/) )) {};
- return str; }
- function colorOf(ip) {
- var c = ip.split('.');
- var n = 0;
- for (var x in c) {
- n ^= +c[x]; }
- var clist =['#5811b1','#399bcd','#0474bb','#f8760d','#a00c9e','#0d762b','#5f4c00','#9a4f6d','#d0990f','#1b1390','#028678','#0324b1'];
- return clist[n % clist.length]; }
- (function (port) {
- var cmd = require('sys'),
- http = require('http'),
- querystring = require('querystring'),
- url = require("url"),
- fs = require('fs');
- self = this;
- function updateUsers () {
- cmd.puts('supposedly updating');
- var s = '\n\t\t\t'+myMessages.join('\n\t\t\t<br />') + '\n\t\t';
- cmd.puts('Users online: ' + chatConnections.length);
- for (var x in chatConnections) {
- if (!chatConnections[x]) {
- continue; }
- var response = chatConnections[x];
- response.writeHead(200, {"Content-Type": "text/plain"});
- response.write(s);
- response.end(); }
- chatConnections = []; }
- http.createServer(function (request, response) {
- var uri = url.parse(request.url).pathname;
- // find the page the user is trying to get.
- request.connection.setNoDelay();
- // This is annoying.
- response.connection.setNoDelay();
- // This is annoying.
- if ( request.connection.remoteAddress in bannedIPs ) {
- // Sometimes we ban users, meh.
- response.writeHead(403, {"Content-Type": "text/plain"});
- // Forbidden error.
- response.end("You are banned from the server.");
- // Be rude.
- return;
- // Stop wasting breath
- }
- if (request.method === "POST" && uri == '/login.node') {
- // User is trying to log into our chat.
- var myPOST;
- request.addListener('data', function (POST) {
- // Wait for the information.
- myPOST = querystring.parse(POST);
- // Parsing the post into an object
- }).addListener('end', function () {
- // This code runs when the stream is finnished.
- if (myPOST.name && myPOST.session) {
- // Make sure the user provided nessecary information.
- try {
- sessions[++sessionid] = new Connection ( myPOST.session, myPOST.name, myPOST.pass );
- // A new session should be pushed to the sessions object, increment the counter for new session ids.
- response.writeHead(200, {"Content-Type": "text/plain"});
- // Tell the browser this page loaded correctly.
- response.end(JSON.stringify({script: 'alert("1")'}));
- // End the stream with a JSON responce.
- }
- catch (e) {
- // When intialization of a new connection fails for some reason.
- // Usually a bad password or illegal name.
- response.writeHead(400,{"Content-Type": "text/plain"});
- // 400 error.
- response.end(e.toString());
- // Send the client the error
- }
- }
- else {
- response.writeHead(400,{"Content-Type": "text/plain"});
- // When something like myPOST.name isn't provided.
- response.end('Missing POST arguments.'); }
- });
- }
- else if (request.method === "POST" && uri == '/message.node') {
- // This means the user is trying to post a message to the chatbox.
- var myPOST;
- request.addListener('data', function (POST) {
- // Wait for the information.
- myPOST = querystring.parse(POST);
- // Parsing the post into an object
- }).addListener('end', function () {
- if ( !myPOST.key || !myPOST.session || !myPOST.msg ) {
- // When a value is missing
- } // Add error code here soon.
- if ( sessions[myPOST.key].key != session ) {
- // If the key is invalid (impersonation attempt?)
- } // Error code here, may want to change the variable names on server and client to be less confusing
- 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,'<')))}));
- // Might, just might, need to clean this up.
- // No, really?
- }
- }
- else if (request.method === "POST" && uri == '/get.node') {
- request.addListener('data', function (POST) {
- myPOST = querystring.parse(POST);
- }).addListener('end', function () {
- if (!myPOST.key || !myPOST.id || sessions[myPOST.id].key != myPOST.key) {
- } // Error, authentication failed
- if (sessions[myPOST.id].conection !== null) {
- } // Error, multiple connnecetions, maybe drop old connection with an error?
- sessions[myPOST.id].connection = response;a
- // This allows us to respond later when nessecary.
- }
- }
- else if (request.method === "POST" && uri == '/post.node') {
- request.addListener('data', function (POST) {
- self.myPOST = querystring.parse(POST);
- }).addListener('end', function () {
- 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,'<')));
- response.writeHead(200, {"Content-Type": "text/html"});
- myMessages.splice(0,myMessages.length - 20);
- 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'));
- updateUsers();
- });
- }
- else if (request.method === "GET" && uri == '/chat.node') {
- cmd.puts('new /chat.node');
- chatConnections.push(response); }
- else if (request.method === "GET" && uri == '/') {
- response.writeHead(200, {"Content-Type": "text/html"});
- 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')); }
- else if (request.method === "GET" && uri == '/blip.wav') {
- response.writeHead(200, {"Content-Type": "audio/x-wav"});
- response.end(blip); }
- else if (request.method === "GET" && uri == '/i.gif') {
- response.writeHead(200, {"Content-Type": "image/gif"});
- response.end(inv); }
- else if (request.method === "GET" && uri == '/audio.class') {
- response.writeHead(200, {"Content-Type": "text/plain"});
- response.end(blip); }
- else {
- response.writeHead(404, {"Content-Type": "application/octet-stream"});
- response.end('404: Epic Fail.'); }
- }).listen(port);
- setInterval(updateUsers, 50000); // keep alive
- cmd.puts("Running on port:" + port + " with process id: " + process.pid);
- })(5082);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement