forked from XboxYan/material-ui-webpack-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
356 lines (322 loc) · 11 KB
/
Copy pathserver.js
File metadata and controls
356 lines (322 loc) · 11 KB
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
/**
* Created by Neil on 9/13/2016.
*/
var path = require('path');
var express =require('express');
var bodyParser = require('body-parser')
var stormpath = require('express-stormpath');
var twilio = require('twilio');
var http = require('http').Server(app);
var Curl = require( 'node-libcurl' ).Curl;
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//use stormpath
app.use(stormpath.init(app, {
web: {
spa: {
enabled: true,
view: path.resolve(__dirname, '/build/index.html')
},
register: {
enabled: false
}
}
}));
//TWILIO
//require the Twilio module and create a REST client
var TWILIO_ACCOUNT_SID=process.env.TWILIO_ACCOUNT_SID;
var TWILIO_AUTH_TOKEN=process.env.TWILIO_AUTH_TOKEN;
var TWILIO_PHONE_NUMBER=process.env.TWILIO_PHONE_NUMBER;
var client = new twilio.RestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
var sendTwilioMessage=function(recipient,message){
client.messages.create({
to: recipient,
from: TWILIO_PHONE_NUMBER,
body: message,
}, function(err, message) {
console.log(message.sid);
});
};
//END TWILIO
app.use(express.static('build'));
app.post('/api/messages',stormpath.loginRequired,function(req,res){
var recipients = req.body.recipients;
var message = req.body.message;
for (var recipient in recipients){
//console.log('User wants to message: '+recipients[recipient]);
//console.log('with message: '+message);
sendTwilioMessage(recipients[recipient],message);
}
res.sendStatus(200);
});
var cleanNextURI=function(nextPageURI){
var str = nextPageURI,
delimiter = '/',
start = 2;
try {
var tokens = str.split(delimiter).slice(start);
}
catch(err) {
return null;
}
var result = tokens.join(delimiter);
return "/"+result;
};
var setupCurl=function(messagesURI){
var curl = new Curl();
curl.setOpt( Curl.option.URL, messagesURI );
curl.setOpt( Curl.option.USERNAME, TWILIO_ACCOUNT_SID );
curl.setOpt( Curl.option.PASSWORD, TWILIO_AUTH_TOKEN );
curl.setOpt( Curl.option.SSL_VERIFYPEER, 0 );
return curl;
};
var getMessages=function(numberOfMessages,res){
var messagesURI='https://api.twilio.com/2010-04-01/Accounts/'+String(TWILIO_ACCOUNT_SID)+"/Messages.json?PageSize="+String(numberOfMessages)+"&Page=0";
var conversations = [];
console.log("The URI for curling is: "+messagesURI);
//SETUP CURL STUFF
var curl = new setupCurl(messagesURI);
curl.on( 'end', function( statusCode, body, headers ) {
//work with response data
var data = JSON.parse(body);
data.messages.forEach(function (message) {
//check if convo exists, create it if necessary
checkConversationExists(conversations, message);
//add message to a conversation
addMessageToConversation(conversations, message)
});
var nextPageURI = cleanNextURI(data.next_page_uri);
nextPageURI = 'https://api.twilio.com/2010-04-01'+nextPageURI;
getMessagesAtNextURI(conversations,nextPageURI,res);
this.close();
});
curl.on( 'error', function(){
console.log("There was an error while cURLing");
curl.close.bind( curl );
} );
curl.perform();
};
var getMessagesAtNextURI=function(conversations, nextPageURI,res) {
var curl = setupCurl(nextPageURI);
curl.on( 'end', function( statusCode, body, headers ) {
//work with response data
try {
var data = JSON.parse(body);
}
catch(err){
console.log('We have hit the end of the pages, proof: '+body);
conversations.forEach(function(conversation){
conversation.messages.reverse();
});
this.close();
res.send(conversations);
return;
}
data.messages.forEach(function (message) {
//check if convo exists, create it if necessary
checkConversationExists(conversations, message);
//add message to a conversation
addMessageToConversation(conversations, message)
});
var nextNextPageURI = data.next_page_uri;
if (typeof nextNextPageURI !== null){
console.log("GOING TO THE NEXT PAGE!");
nextNextPageURI = cleanNextURI(nextNextPageURI);
nextNextPageURI = "https://api.twilio.com/2010-04-01"+nextNextPageURI;
getMessagesAtNextURI(conversations, nextNextPageURI,res);
}
else{
console.log("NO MORE PAGES LEFT!");
//Reverse conversations in the end
conversations.forEach(function(conversation){
conversation.messages.reverse();
});
//remove all conversations with no in them
//conversations=getPositiveConversations(conversations);
res.send(conversations);
}
this.close();
});
curl.on( 'error', function(){
console.log("There was an error while cURLing");
curl.close.bind( curl );
} );
curl.perform();
};
var getPositiveConversations=function(conversations){
positiveConversations = [];
conversations.forEach(function(conversation){
if ((conversation.messages.length==2)&&(conversation.messages[1].body.toLowerCase()!=="no")){
positiveConversations.push(conversation)
}
if ((conversation.messages.length>2)){
positiveConversations.push(conversation)
}
});
return positiveConversations;
};
var getNewestMessage=function(callback){
var messagesURI='/Accounts/'+String(TWILIO_ACCOUNT_SID)+"/Messages.json?PageSize=1&Page=0";
var requestPromise=client.request({
url: messagesURI,
method: 'GET'
});
requestPromise.then(function(data){
var conversations = [];
//work with response data
data.messages.forEach(function (message) {
nextPageURI = message.next_page_uri;
//check if convo exists, create it if necessary
checkConversationExists(conversations, message);
//add message to a conversation
addMessageToConversation(conversations, message)
});
conversations.forEach(function(conversation){
conversation.messages.reverse();
});
console.log('Calling callback...')
callback(conversations);
},function(err){
console.log('There was an error'+JSON.stringify(err));
});
}
app.get('/api/messages',stormpath.loginRequired,function(req,res){
var numberOfMessages=500;
getMessages(numberOfMessages,res);
});
//see if we have a place to put this message
var checkConversationExists=function(conversations,message){
recipient=getRecipient(message);
var conversationExists = false;
conversations.forEach(function(conversation){
if (conversation.recipient===recipient){
conversationExists=true;
}
});
if (conversationExists===false){
conversations.push(createConversation(message));
}
};
//if conversation does not exist create it
var createConversation=function(message){
return({
recipient:getRecipient(message),
messages:[]
});
};
//returns who the recipient is in the conversation
var getRecipient=function(message){
if (message.from===TWILIO_PHONE_NUMBER){
return message.to;
}
else{
return message.from;
}
};
//add message to a conversation
var addMessageToConversation=function(conversations,message){
var recipient=getRecipient(message);
conversations.forEach(function(conversation){
if (conversation.recipient===recipient){
//console.log('The message is: ');
//console.log(message);
var themOrUs='';
if (message.from===TWILIO_PHONE_NUMBER){
themOrUs='us'
}
else{
themOrUs='them'
}
conversation.messages.push({body: message.body, from: themOrUs, date:message.date_sent, them:recipient});
}
});
};
//Required Stompath path
app.post('/me', bodyParser.json(), stormpath.loginRequired, function (req, res) {
function writeError(message) {
res.status(400);
res.json({ message: message, status: 400 });
res.end();
}
function saveAccount() {
req.user.givenName = req.body.givenName;
req.user.surname = req.body.surname;
req.user.email = req.body.email;
req.user.save(function (err) {
if (err) {
return writeError(err.userMessage || err.message);
}
res.end();
});
}
if (req.body.password) {
var application = req.app.get('stormpathApplication');
application.authenticateAccount({
username: req.user.username,
password: req.body.existingPassword
}, function (err) {
if (err) {
return writeError('The existing password that you entered was incorrect.');
}
req.user.password = req.body.password();
saveAccount();
});
} else {
saveAccount();
}
});
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, './build', 'index.html'));
});
var getIncomingRecipient=function(bodyObject){
if (bodyObject.From===TWILIO_PHONE_NUMBER){
return bodyObject.To;
}
else{
return bodyObject.From;
}
};
var getIncomingThemOrUs=function(bodyObject){
var themOrUs='';
if (bodyObject.From===TWILIO_PHONE_NUMBER){
themOrUs='us';
}
else{
themOrUs='them';
}
return themOrUs;
};
var startServer = function(){
var port = 3000;
console.log('The server is listening...');
var server = app.listen(process.env.PORT || port);
var io = require('socket.io').listen(server);
//use socket.io
io.on('connection', function(socket){
console.log('a user connected');
});
//twilio will notify us that we are recieving a message
//conversation.messages.push({body: message.body, from: themOrUs, date:message.date_sent, them:recipient});
app.post('/api/incoming', function(req,res){
//console.log('The request body appears to be...');
//console.log(req.body);
var thisRecipient = getIncomingRecipient(req.body);
var themOrUs = getIncomingThemOrUs(req.body);
var nowDate = new Date();
var conversation = [{recipient:thisRecipient,messages:[{body:req.body.Body,from:themOrUs,date:nowDate,them:thisRecipient}]}];
//console.log('Got newest message!');
//console.log(JSON.stringify(conversation));
io.emit('new message', conversation);
var twiml = new twilio.TwimlResponse();
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
};
//wait for stormpath, then start server
app.on('stormpath.ready', function () {
console.log('Stormpath is ready');
startServer();
});