-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
246 lines (180 loc) · 6.63 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
var config = require("./config.json")
var path = require("path")
var express = require("express")
var app = express()
var cors = require("cors")
require("dotenv").config()
app.use(cors());
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 4000))
const TWILIO_ACCOUNT_SID = config.TWILIO_ACCOUNT_SID;
const TWILIO_AUTH_TOKEN = config.TWILIO_AUTH_TOKEN;
const TWILIO_NUMBER = config.TWILIO_NUMBER
var twilioClient = require('twilio')(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
//mongodb stuff
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var mongoose = require('mongoose');
if (process.env.NODE_ENV === 'production') {
mongoose.connect("mongodb://gnak:hejsan@ds127982.mlab.com:27982/heroku_j0kd36jk")
app.use(express.static('crime_front_end/build'));
} else {
mongoose.connect('mongodb://localhost:27017/db');
}
var db = mongoose.connection;
var CrimeLocation = require('./models/crimelocation');
var Contact = require('./models/contact');
//Contact.collection.drop();
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('mongoose up and running')
});
//set up socket
const server = app.listen(app.get('port'), function () {
console.log("Listening on" + app.get('port') )
})
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
//these are OUTGOING chat messages from the app
socket.on('chat message', function(messageObj){
console.log(messageObj);
//io.emit('chat message', "hello world from server!");
let body = messageObj.body;
let phoneNumber = messageObj.phone_number
//send the outgoing message to twilio
twilioClient.messages.create(
{to: phoneNumber, from: TWILIO_NUMBER, body: body},
(error, message) => {
if (!error) {
console.log('success sending text')
} else {
console.log('error sending text')
}
}
)
io.emit('chat message', messageObj)
});
});
// chat end points
app.get('/contacts', (req, res) => {
Contact.find((err, contacts) => {
res.json({contacts: contacts})
})
})
app.post('/contacts/new', (req,res) => {
let contactHash = {phone_number: req.body.phone_number};
let contact = new Contact(contactHash);
contact.save((err, contact) => {
if (err) {
console.log(err)
} else {
console.log("saved contact:", contact)
res.json(contact)
}
})
})
app.post('/contacts/messages/new', (req, res) => {
let phoneNumber = req.body.phone_number;
let messageBody = req.body.body;
Contact.findOne({"phone_number": phoneNumber}, (err, foundContact) => {
foundContact.messages.push({"body": messageBody});
foundContact.save((err, foundContact) => {
if (err) {
console.log(err)
} else {
console.log("saved message")
}
})
res.json({message: "created message in db"})
})
})
app.get("/contacts", (req,res) => {
Contact.find((err, contacts) => {
res.json({contacts: contacts})
})
})
app.post("/sms", (req, res) => {
let phoneNumber = req.body.From;
let body = req.body.Body;
let messageObj = {"phone_number": phoneNumber, "body": body, "incoming_message": true}
Contact.findOne({"phone_number": phoneNumber}, (err, foundContact) => {
foundContact.messages.push(messageObj)
foundContact.save((err, foundContact) => {
if (err) {
console.log(err)
} else {
console.log("saved message")
}
})
})
io.emit("chat message", messageObj)
res.json({message: "created message in db"})
})
//end chat end points
app.get("/crime", function (req, res) {
res.set('Content-Type', 'application/json');
CrimeLocation.find(function (err, crimelocations) {
if (err) return console.error(err);
res.json({crimelocations : crimelocations.slice(1,100)})
})
})
app.get("/crime_aggregated", function (req, res) {
res.set('Content-Type', 'application/json');
CrimeLocation.find(function (err, crimelocations) {
if (err) return console.error(err);
res.json({crimelocations : crimelocations.slice(1,100)})
})
})
app.get("/crime_yearly/", function(req, res) {
res.set('Content-Type', 'application/json')
console.log(req.query)
CrimeLocation.find(function(err, crimelocations) {
//here goes the function that takes input req.query.year and spits out the yearly dataset
//memoize this later
crimelocationsYearlyFilter = function(crimelocations, filterYear) {
let filteredData = []
crimelocations.forEach( (crimelocation) => {
let hundred_block = crimelocation.hundred_block
let hundred_block_geocoded = crimelocation.hundred_block_geocoded
let geometry = crimelocation.geometry
let crimesFiltered = crimelocation.crimes.filter((crime) => {
let date = new Date(crime.date)
let year = date.getFullYear().toString()
return year === filterYear;
})
let crimelocationHash = {hundred_block: hundred_block, hundred_block_geocoded: hundred_block_geocoded, geometry: geometry , crimes: crimesFiltered }
filteredData.push(crimelocationHash)
})
return filteredData
}
crimelocationsAggregate = function(crimelocations) {
//this function was previously on serverside.
let dataArr = []
crimelocations.forEach((crimelocation) =>{
let hundred_block = crimelocation.hundred_block
let hundred_block_geocoded = crimelocation.hundred_block_geocoded
let geometry = crimelocation.geometry
let aggregatedHash = {hundred_block: hundred_block, hundred_block_geocoded: hundred_block_geocoded, geometry: geometry , crime:{baeb:0, baer:0, shoplifting:0, tfmv:0, tomv:0,total_crime:0} }
crimelocation.crimes.forEach((crime) => {
aggregatedHash.crime.baeb += crime.baeb
aggregatedHash.crime.baer += crime.baer
aggregatedHash.crime.shoplifting += crime.shoplifting
aggregatedHash.crime.tfmv += crime.tfmv
aggregatedHash.crime.tomv += crime.tomv
aggregatedHash.crime.total_crime += crime['total_crime']
})
dataArr.push(aggregatedHash)
});
return dataArr
}
const crimelocationsYearlyFiltered = crimelocationsYearlyFilter(crimelocations, req.query.year)
const crimelocationsYearlyFilteredAggregated = crimelocationsAggregate(crimelocationsYearlyFiltered)
res.json({year: req.query, crimelocations : crimelocationsYearlyFilteredAggregated})
})
})