forked from reu/express-node-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
196 lines (161 loc) · 5.1 KB
/
server.js
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
var express = require('express'),
app = express.createServer(
express.staticProvider(__dirname + '/public'),
express.cookieDecoder(),
express.session({ secret: 'sb5vlapgl3cc49sh2ohl6vk40jhjnron2c7ru5kkht1e0qm96d' }),
express.bodyDecoder(),
express.logger({ format: ':method :url :status in :response-timems' }),
express.methodOverride()
),
sanitizer = require('sanitizer');
app.set('view engine', 'jade');
Room = function(){
this.id = new Date().getTime(),
this.name = null,
this.messages = [],
this.callbacks = [],
this.users = [],
this.maximum_messages = 200,
this.appendMessage = function(message) {
var message = sanitizer.escape(message);
// Adds the message to the rooms messages collection
this.messages.push(message);
// Now we execute all the remaining callbacks. So, all the
// users connected to the room will receive the update.
while (this.callbacks.length > 0)
this.callbacks.shift()([message]);
// Here we clean up old messages
this.flushMessages();
},
this.query = function(since, callback) {
// The users will constantly query the room for new messages.
// The main point here is that different from the usual implementations,
// node doesn't "block" the process, so the users can remain
// "connected" until the server respond to then.
var pendingMessages = [];
for(var key in this.messages) {
var message = this.messages[key];
if (message.sent_at > since)
pendingMessages.push(message);
}
if (pendingMessages.length > 0) {
// If the user didn`t receive some of the message, then we will
// use the callback to render then
callback(pendingMessages);
} else {
// Otherwise, we will add this to the room's callback collection,
// and we are gonna call it when someone send a new message.
this.callbacks.push(callback);
}
},
this.flushMessages = function() {
while (this.messages.length > this.maximum_messages)
this.messages.shift();
}
}
// Convinience stactic method, used as a room factory
Room.createByName = function(name) {
var room = new Room();
room.name = name;
return room;
}
// The message class. Currently stored in memory.
Message = function(from, text){
this.from = from,
this.text = text,
this.to = null,
this.type = 'message',
this.sent_at = new Date().getTime(),
this.toString = function() {
return this.nick + ' ' + new Date(this.sent_at) + ': ' + this.text;
}
}
User = function(nick){
this.nick = nick
}
// Here we will store all our rooms
var rooms = [];
// Default room
var room = Room.createByName('General room');
room.id = 1;
rooms[1] = room;
// As both "/" and "/rooms" url shares the same behaviour, we needed
// to extract the function for then
var indexHandler = function(req, res){
res.render('rooms/index', { locals: { rooms: rooms } });
};
// Helper filters to avoid duplication
var filters = {
getRoom: function(req, res, next){
var room = rooms[req.params.room_id];
if (room) {
req.room = room;
next();
} else {
res.send('Oops... room not found =/', 404);
}
},
getUser: function(req, res, next) {
var user = req.room.users[req.sessionID];
if (user) {
req.user = user;
next();
} else {
req.flash('error', 'You are not on this room.');
res.redirect('home');
}
}
}
// Index
app.get('/', indexHandler);
app.get('/rooms', indexHandler);
// New
app.get('/rooms/new', function(req, res){
res.render('rooms/new');
});
// Create
app.post('/rooms', function(req, res){
room = Room.createByName(req.body.room.name);
rooms[room.id] = room;
res.redirect('home');
});
// Show
app.get('/rooms/:room_id', filters.getRoom, filters.getUser, function(req, res){
res.render('rooms/room', { locals: { room: req.room } });
});
app.get('/rooms/:room_id/join', filters.getRoom, function(req, res){
if (!req.room.users[req.sessionID]) {
var user = new User(req.query.user.nick);
req.room.users[req.sessionID] = user;
// Alert people that a new user joined the room
var message = new Message(req.room.name, user.nick + ' joined!');
message.type = 'notice';
req.room.appendMessage(message);
}
res.redirect('/rooms/' + req.room.id);
});
app.get('/rooms/:room_id/leave', filters.getRoom, filters.getUser, function(req, res){
if (delete req.room.users[req.sessionID]) {
req.session.destroy();
var message = new Message(req.room.name, req.user.nick + ' left the room.');
message.type = 'notice';
req.room.appendMessage(message);
}
res.writeHead(200);
res.end();
});
// Messages
// List
app.get('/rooms/:room_id/messages', filters.getRoom, function(req, res){
req.room.query(parseInt(req.query.since), function(messages){
res.send(res.partial('message', messages));
res.end();
});
});
app.post('/rooms/:room_id/messages', filters.getRoom, filters.getUser, function(req, res){
var message = new Message(req.user.nick, req.body.message.text);
req.room.appendMessage(message);
res.writeHead(200);
res.end();
});
app.listen(3000);