-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
368 lines (310 loc) · 10.6 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// AnonyMouse Server 0.0.0.0.1 (lol!)
// By @aashay and @aaronmoy and @ewee
//-------------GLOBAL STUFF-------------
var PORT = process.env.PORT || 3000;
var CURLONLY = false; //for dev
//Twilio stuff.
var ACCOUNT_SID = 'blah';
var AUTH_TOKEN = 'blah';
var MY_HOSTNAME = 'anonymouse.herokuapp.com';
var sandboxNum = '+14155992671';
var masterNumber = 'SOMENUMHERE';
var aaronNumber = 'SOMENUMHERE'
//----------------------------------------
//-------------REQUIRED STUFF-------------
var express = require('express');
var app = express.createServer();
var sys = require('sys'),
rest = require('restler');
MemoryStore = require('connect').session.MemoryStore;
var sessionStore = new MemoryStore(); //TODO: Use something more robust instead of memory JEEEEZUS
var nowjs = require('now');
var db = require('./database.js');
//----------------------------------------
//You dun configuramalate thems middlewares!
app.configure(function(){
//Parse JSON POST request bodies rawr
app.use(express.bodyParser());
//Remove this for production!
app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));
//for any static files (like css and stuff)
app.use(express.static(__dirname + '/public'));
//Templating!
app.set("view engine", "html");
app.set("view options", {layout: false});
app.register(".html", require('ejs'));
//Cookies and sessions. Mmm, cookies.
app.use(express.cookieParser());
app.use(express.session({ store: sessionStore, secret: "anonymouuuuuuuse" }));
});
//-------------CUSTOM FUNCTIONS SO SEXY-------------
var sendSMS = function(from, to, body, callback) {
var accountSid = ACCOUNT_SID,
authToken = AUTH_TOKEN,
apiVersion = '2010-04-01',
uri = '/'+apiVersion+'/Accounts/'+accountSid+'/SMS/Messages',
host = 'api.twilio.com',
fullURL = 'https://'+accountSid+':'+authToken+'@'+host+uri;
if(!CURLONLY){
rest.post(fullURL, {
data: { From:from, To:to, Body:body }
}).on('error', function(data, response) {
callback(data,null);
}).on('complete', function(data, response) {
callback(null,data);
});
}
else{
callback(null,"DEV TEST SUCCESSFUL");
}
}
var login = function(username, password, callback){
if(!username || !password){
callback("Invalid username or password", null);
}
else{
db.getMentor(username, function(err,mentor){
if(!err){
if(mentor.password != password){
callback("Invalid password: " + mentor.password + " vs given " + password, null);
}else{
callback(null,mentor)
}
}else{
callback(err,null);
}
});
}
}
var restricted = function(req, res, callnext){
if (req.session.username) {
callnext();
}
else {
res.redirect('/');
}
}
//--------------------------------------
//-------------PAGE ROUTES-------------
app.get('/', function(req, res){
var localVars = {name:"none"};
if(req.session.mentor){
localVars =
{
name: req.session.mentor.name,
username: req.session.mentor.username
};
}
res.render('index', {
locals:localVars
});
});
app.get('/chat', restricted, function(req, res){
var localVars =
{
name: req.session.mentor.name,
username: req.session.mentor.username
};
res.render('chat', {
locals:localVars
});
});
//--------------------------------------
//-------------APPLICATION API-------------
app.post('/login', function(req, res){
login(req.body.username, req.body.password, function(err,mentor){
if(!err){
req.session.regenerate(function(err,ses){
req.session.username = req.body.username;
req.session.mentor = mentor;
req.session.cookie.maxAge = 7200000;
res.clearCookie('username');
res.cookie('username',req.session.username);
res.cookie('sid', req.sessionID);
req.session.save(function(err){
if(!err){
res.redirect('/chat');
}
else{
console.log("Error writing to session store : "+err);
res.redirect('500.html');
}
});
});
}
else{
console.log("Bad login attempt!" + JSON.stringify(req.body) + " error was " + err);
res.redirect('back');
}
});
});
app.get('/logout', function(req, res){
//destroy session and redirect home.
req.session.destroy(function(){
res.redirect('/');
});
});
app.get('/api/unanswered', function(req, res){
var response = "";
db.getUnanswered(function(err,data){
if(err){
response = err;
}
else{
response = data;
}
res.send(response);
});
});
app.get('/api/mentors/:username', function(req, res){
var response = "";
var username = req.params.username;
db.getMentor(username,function(err,data){
if(err){
response = err;
}
else{
response = data;
}
res.send(response);
});
});
app.get('/api/mentees/:id', function(req, res){
var response = "";
var id = req.params.id;
db.getMenteeById(id,function(err,data){
if(err){
response = err;
}
else{
response = data;
}
res.send(response);
});
});
// app.post('/api/chat/:id', function(req, res){
// var id = req.params.id;
// var message = req.body.Body;
// var username = req.session.mentor || req.body.username;
//
// if(username){
// db.addChat(id, username, message, function(err,data){
// if(err){
// response = err;
// }
// else{
// response = data;
// }
// res.send(response);
// });
// }else{
// res.send("Need to be logged in to use this API");
// }
// });
//--------------------------------------
//----------------POST API FOR TWILIO TO TALK TO--------------------
app.post('/newseed', function(req, res){
var message = req.body.Body;
var menteeNumber = req.body.From;
var reply = "Thanks, a mentor will be connecting with you soon!";
db.createMentee(menteeNumber, message, function(err,data){
if(err){console.log(err)}
else{
sendSMS(masterNumber, menteeNumber, reply, function(err,data){
console.log("WELCOME: " + menteeNumber);
res.send(reply);
});
}
});
});
app.post('/mentor/:username/message', function(req, res){
//1. Add to database.
//2. If this mentor is online, send.
var username = req.params.username;
var message = req.body.Body;
var menteeNumber = req.body.From;
db.getMentor(username, function(err,mentor){
if(err) { console.error("TWILIO IS ATTEMPTING TO POST TO NONEXISTING MENTORS")}
else{
db.getMentee(menteeNumber, function(err,mentee){
if(err) { console.error("Mentor " + username + " got a message from an unknown mentee")}
else{
//add chat to db for persistant logging
//then if the mentor is online send it to them
console.log(JSON.stringify(mentee));
var reply = {
"seed" : mentee.seed,
"message": message,
"menteeId": mentee._id.$oid
};
everyone.now.sendMessage(mentor, reply);
var response = "Mentee texting a mentor; sent: " + JSON.stringify(reply);
res.send(response);
}
});
}
});
});
//--------------------------------------
//----------------NOWJS------------------
var everyone = nowjs.initialize(app);
everyone.connected(function(){
this.user.sid = "";
});
everyone.now.setSid = function(sid){
if(sid){
this.user.sid = sid;
console.log("Set a sid " + sid);
}
}
//Inbound message from Twilio, need to send it to the right mentor.
everyone.now.sendMessage = function(mentor, message, callback){
var self = this;
if(this.user.sid){
sessionStore.get(this.user.sid, function(err,session){
if(session.username == mentor.username){
console.log("Sending to mentor: " + JSON.stringify(message));
self.now.incomingMessage(message);
//callback(null,message);
}
});
}
else{
//callback(null,null);
//console.log("meh");
}
}
//called by client to send a txt to a particular mentee
everyone.now.sendSMS = function(menteeId, smsbody){
var self = this;
if(this.user.sid){
sessionStore.get(this.user.sid, function(err,session){
var yourOwnMessage = {
"menteeId" : menteeId,
"message": smsbody,
"name": session.mentor.name
};
db.getMenteeById(menteeId, function(err,mentee){
if(err){ console.log (err)}
else{
var mentor = session.mentor;
var fromNumber = mentor.phone;
var toNumber = mentee.phone;
sendSMS(fromNumber, toNumber, smsbody, function(err,data){
console.log(smsbody + " -> " + menteeId);
//TODO: If this isn't where we reply back, we need some mechanism for failed SMS-es
//self.now.incomingMessage(yourOwnMessage);
});
} //end else
});
self.now.incomingMessage(yourOwnMessage);
});
}
else{
this.now.incomingError("Invalid sid, please set sid");
}
}
//--------------------------------------
//Go baby go!
app.listen(PORT);
console.log("The AnonyMouse server is running on port " + PORT);