aboutsummaryrefslogtreecommitdiff
path: root/chatserver.js
blob: 11443d89d560926f9d40ac203d5b5e9f24716b1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env node
var fs=require("fs"),
    http=require("http"),
    util=require("util"),
    WebSocketServer=require("ws").Server,
    CircularBuffer=require("circular-buffer"),
    Persist=require("node-persist"),
    Naampje=require("naampje").name;
var HTTPPORT=81,WSPORT=8000;


var nickdeleteregex=/[\x00-\x20\x7F\x80-\xFF]/g;


////////// WEBSOCKETS //////////

function uniqid(){
	if(!uniqid.$)uniqid.$=1;
	return uniqid.$++;
}

function lobby_create(lname){
	lobbies.push({id:uniqid(),name:lname,users:[],history:new CircularBuffer(40)});
}

var __do_persist_lobbies_timeout=null;
function do_persist_lobbies(){
	if(__do_persist_lobbies_timeout)return;
	__do_persist_lobbies_timeout=setTimeout(function(){
		__do_persist_lobbies_timeout=null;
		Persist.setItem("lobbies",lobbies,function(err,res){
			if(err)console.log("persist lobbies error: "+err);
			else console.log("persist lobbies: "+res);
		});
	},10*1000);
}

var users=[],lobbies;

Persist.initSync({});
lobbies=Persist.getItemSync("lobbies");
if(!lobbies){
	lobbies=[];
	["lobby_1","lobby_2"].forEach(lobby_create);
} else {
	lobbies.forEach(function(l){
		l.users=[];
		l.history=new CircularBuffer(l.history);
	});
}


new WebSocketServer({port:WSPORT}).on("connection",function(ws){
	var uobj;
	(function(){
		//var nick="_user"+uniqid();
		var nick=Naampje(),suffix="";
		if(fnick(nick)!=-1)for(suffix=1;fnick(nick+suffix)!=-1;suffix++);
		uobj=new UserObject((nick+suffix).replace(nickdeleteregex,""),ws);
	})();
	users.push(uobj);
	ws.send("#yournick "+uobj.nick);
	ws.on("message",function(msg,flags){
		console.log("("+uobj.id+","+uobj.nick+"): "+msg);
		if(msg.match(/^#lobby /)){
			var which=parseInt(msg.slice(7),10),lobidx=flob(which),oldlobidx;
			if(lobidx==-1){
				ws.send("#error Invalid lobby");
				return;
			}
			ws.send("#lobby "+which);
			if(uobj.lob!=null)leave_lobby(uobj);
			join_lobby(lobidx,uobj);
			send_history(lobidx,uobj);
			do_persist_lobbies();
		} else if(msg.match(/^#mylobby/)){
			if(uobj.lob==null)ws.send("#mylobby");
			else ws.send("#mylobby "+uobj.lob);
		} else if(msg.match(/^#nick /)){
			var choice=msg.slice(6).replace(nickdeleteregex,""); //all shitty characters including space (' ')
			var i;
			if(choice.length==0||choice.length>8){
				ws.send("#error Invalid nick");
				return;
			}
			if(uobj.lob!=null){
				if(fnick(choice)!=-1){
					i=1;
					while(fnick(choice+i)!=-1)i++;
					choice+=i;
				}
				lobbysend(lobbies[flob(uobj.lob)],"#nick "+uobj.nick+" "+choice,[uobj.id]);
			}
			uobj.nick=choice;
			ws.send("#yournick "+uobj.nick);
			do_persist_lobbies();
		} else if(msg.match(/^#lobbylist/)){
			ws.send("#lobbylist "+lobbies.map(function(lob){return lob.id+":"+lob.name;}).join(" "));
		} else if(msg.match(/^#nicklist/)){
			if(this.lob==null){
				ws.send("#error Cannot request nicklist while not in a lobby");
				return;
			}
			ws.send("#nicklist "+lobbies[flob(uobj.lob)].users.map(function(usr){
				return users[fuser(usr)].nick;
			}).join(" "));
		} else if(msg[0]==">"){ //message!
			var lobidx;
			if(uobj.lob==null){
				ws.send("#error Cannot send message while not in a lobby");
				return;
			}
			lobidx=flob(uobj.lob);
			lobbysend(lobbies[lobidx],"<"+uobj.nick+" "+msg.slice(1));
			lobbies[lobidx].history.push([">",uobj.nick,msg.slice(1)]);
			do_persist_lobbies();
		} else {
			ws.send("#error Invalid message starting with \""+msg.slice(0,10)+"\"");
			return;
		}
	});
	ws.on("close",function(){
		var lobidx;
		if(uobj.lob!=null){
			lobidx=flob(uobj.lob);
			lobbysend(lobbies[lobidx],"#part "+uobj.nick,[uobj.id]);
			lobbies[lobidx].history.push(["part",uobj.nick]);
			lobbies[lobidx].users.splice(lobfuser(lobbies[lobidx],uobj.id),1);
		}
		users.splice(fuser(uobj.id),1);
		do_persist_lobbies();
	});
});
console.log("Websocket server started on port "+WSPORT+".");

function UserObject(nick,ws){
	if(!(this instanceof UserObject))return new UserObject(nick,ws);
	this.id=uniqid();
	this.nick=nick;
	this.ws=ws;
	this.lob=null;
}

function lobbysend(lob,msg,exceptids){
	var uidx;
	if(exceptids==undefined)exceptids=[];
	for(var i=0;i<lob.users.length;i++){
		if(exceptids.indexOf(lob.users[i])==-1){
			uidx=fuser(lob.users[i]);
			users[uidx].ws.send(msg);
		}
	}
}

function lobfuser(lob,id){
	for(var i=0;i<lob.users.length;i++)if(users[fuser(lob.users[i])].id==id)return i;
	return -1;
}

function fuser(id){
	for(var i=0;i<users.length;i++)if(users[i].id==id)return i;
	return -1;
}
function fnick(nick){
	for(var i=0;i<users.length;i++)if(users[i].nick==nick)return i;
	return -1;
}

function flob(lobid){
	for(var i=0;i<lobbies.length;i++)if(lobbies[i].id==lobid)return i;
	return -1;
}

function join_lobby(lobidx,uobj){
	var lobid=lobbies[lobidx].id;
	uobj.lob=lobid;
	lobbies[lobidx].users.push(uobj.id);
	lobbysend(lobbies[lobidx],"#join "+uobj.nick);
	lobbies[lobidx].history.push(["join",uobj.nick]);
}
function send_history(lobidx,uobj){
	uobj.ws.send("#historystart");
	lobbies[lobidx].history.toarray().forEach(function(h){
		uobj.ws.send("#history "+h.join(" "));
	});
	uobj.ws.send("#historyend");
}
function leave_lobby(uobj){
	var lobidx=flob(uobj.lob);
	lobbies[lobidx].users.splice(lobfuser(lobbies[lobidx],uobj.id),1);
	lobbysend(lobbies[lobidx],"#part "+uobj.nick);
	lobbies[lobidx].history.push(["part",uobj.nick]);
}


////////// HTTP //////////

var pagehtml;
try{
	pagehtml=fs.readFileSync("chatserver.html").toString();
} catch(e){
	console.log("Could not read file 'chatserver.html'.");
	console.log(e);
	process.exit();
}

http.createServer(function(req,res){
	if(req.url=="/"){
		res.writeHead(200,{"Content-Type":"text/html"});
		res.end(pagehtml);
	} else {
		var url=req.url.slice(1); //strip off the initial '/'
		if(url.indexOf("?")!=-1)url=url.slice(0,url.indexOf("?")); //strip off parameters
		if(!/^theme-[a-z0-9]+\.css$/i.test(url))res.end("not permitted");
		try{res.end(fs.readFileSync(url).toString());}
		catch(e){res.end("error");}
	}
}).listen(HTTPPORT);
console.log("HTTP server started on port "+HTTPPORT+".");