-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.js
715 lines (615 loc) · 23 KB
/
web.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
var express = require('express'),
mongoskin = require('mongoskin'),
bodyParser = require('body-parser')
var logfmt = require("logfmt");
var mongo = require('mongodb');
var apn = require('apn');
var yelp = require("yelp").createClient({
consumer_key: "XPHL16m1XKlQsm4JJM8ZLw",
consumer_secret: "dRSDF7CtQIbRV-WAEGd_Yg8jUzo",
token: "PMSIKP0XrmmaqoCzHjwRB9K3DM4oIDOf",
token_secret: "KRSvWPtiHBp-NLmfz8xeArwKDZ0"
});
var request = require('request');
var cheerio = require('cheerio');
var async = require('async')
var GooglePlaces = require("googleplaces");
var googlePlaces = new GooglePlaces("AIzaSyC5p7KH-SOmf2dgYFMqFm9H1vYAXX0jcMs", "json");
var options = { };
var apnConnection = new apn.Connection(options);
var app = express()
app.use(bodyParser())
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
var db = mongoskin.db(mongoUri, {safe:true})
app.param('collectionName', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
// ===================================================================
// Post Methods
// ===================================================================
/*
* Not being used? Look into....
*/
app.post('/ppl/:friend', function(req, res) {
var collection = db.collection(req.params.friend)
collection.insert(req.body, {}, function(e, results){
if (e) res.status(500).send()
res.send(results)
})
})
/*
* Network Communication - linkDeviceToken
* Gets called after we receive device token. Connects token with friend database
*/
app.post('/token/:friend', function(req, res) {
var collection = db.collection(req.params.friend)
collection.count({}, function(error, numOfDocs) {
if(numOfDocs<1)
{
collection.insert(req.body, {}, function(e, results){
if (e) res.status(500).send()
res.send(results)
})
}
else
{
collection.find().toArray(function(err, docs) {
res.send(docs);
});
}
})
})
/*
* FriendViewController - createGroup
* 1 - gets information from yelp
* 2 - gets device tokens
* 3 - creates a new group object
* 4 - inserts group code into all of the friend's arrays
* 5 - sends push notification to friends
*/
app.post('/yelp/:lat/:longi/:search/:mynum/:myId', function(req, res) {
// async.parallel([
// function(callback) {
// db.get('users', userId, function(err, user) {
// if (err) return callback(err);
// callback();
// });
// },
// function(callback) {
// db.query('posts', {userId: userId}, function(err, posts) {
// if (err) return callback(err);
// callback();
// });
// }
// ], function(err) { //This function gets called after the two tasks have called their "task callbacks"
// if (err) return next(err); //If an error occured, we let express/connect handle it by calling the "next" function
// });
// var newTokenArray = []
// async.parallel([
// function(callback){
// yelp.search({limit: req.params.mynum,ll:fixed, term:req.params.search}, function(yelpError, yelpData){
// if(yelpError)
// {
// console.log("yelp failed")
// res.status(500).send()//YelpFailedLetThemKnow
// }
// var info = yelpData["businesses"]
// var decisionObjects = []
// var tempReplies = []
// for(var i = 0; i<info.length; i++)
// {
// var infoDictionary = info[i]
// tempReplies.push(0)
// var temp = {}
// temp["Name"] = infoDictionary["name"]
// if(("image_url" in info[i]))
// {
// temp["ImageURL"] = infoDictionary["image_url"]
// }
// if(("categories" in info[i]))
// {
// var categoryArray = infoDictionary["categories"]
// var fixedCategoryArray = []
// for(var m = 0; m < categoryArray.length; m++)
// {
// var specificarray = categoryArray[m]
// fixedCategoryArray.push(specificarray[0]);
// }
// temp["Category"] = fixedCategoryArray
// }
// if(("distance" in info[i]))
// {
// temp["distance"] = infoDictionary["distance"]
// }
// if(("rating" in info[i]))
// {
// temp["rating"] = infoDictionary["rating"]
// }
// decisionObjects.push(temp)
// }
// var sendDictionary = {}
// sendDictionary["Done"] = -1;
// sendDictionary["Number"] = info.length
// sendDictionary["Replies"] = tempReplies
// sendDictionary["Objects"] = decisionObjects
// sendDictionary["Tokens"] = newTokenArray//want to add later
// var groupCollection = db.collection('groups')
// groupCollection.insert(sendDictionary, {}, function(groupError, groupResults){
// if (groupError)
// {
// console.log("group creation failed")
// res.status(500).send()
// }
// callback(null)
// }
// }
// },
// function(callback){
// var counter = 0
// var tokenArray = req.body.friends
// for(var j = 0;j<tokenArray.length;j++)
// {
// var dbString = tokenArray[j] + "token"
// var tokenCollection = db.collection(dbString)
// tokenCollection.find({} ,{}).toArray(function(tokenError, tokenResults){
// if (tokenError)
// {
// console.log("token failed")
// res.status(500).send()
// }
// newTokenArray.push(tokenResults[0].token)
// counter++
// if(counter==tokenArray.length)
// {
// callback(null)
// }
// }
// }
// }
// ], function(err) { //This function gets called after the two tasks have called their "task callbacks"
// if (err) return next(err);
// for(var i = 0; i < tokenArray.length; i++)
// {
// var personalDictionary = {}
// personalDictionary["groupID"] = groupResults[0]._id;
// personalDictionary["number"] = tokenArray.length
// personalDictionary["currentIndex"] = 0
// personalDictionary["owner"] = req.body.myName
// personalDictionary["ownerID"] = req.params.myId
// personalDictionary["friendID"] = req.body.friends
// var dbString2 = tokenArray[i] + "groups"
// var friendCollection = db.collection(dbString2)
// var counter2 = 0;
// friendCollection.insert(personalDictionary, {}, function(friendError, friendResults){
// if (friendError)
// {
// console.log("creation friend side failed")
// res.status(500).send()
// }
// console.log("creation friend side good")
// var myDevice = new apn.Device(newTokenArray[counter2]);
// counter2++
// var note = new apn.Notification();
// note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
// note.badge = 0;
// note.sound = "ping.aiff";
// note.alert = "\uD83D\uDCE7 \u2709 You have a new group invite";
// note.payload = {'messageFrom': req.body.myName, 'type': "message"};
// apnConnection.pushNotification(note, myDevice);
// if(counter2==newTokenArray.length)
// {
// console.log("everything good")
// res.send("FASHOOOO")
// }
// })
// }
// });
var fixed = req.params.lat + ',' + req.params.longi
yelp.search({sort: 1, limit: req.params.mynum,ll:fixed, term:req.params.search}, function(yelpError, yelpData) {
if(yelpError)
{
console.log("yelp failed")
res.status(500).send()//YelpFailedLetThemKnow
}
var tokenArray = req.body.friends//
var newTokenArray = []//
var counter = 0//
for(var j = 0;j<tokenArray.length;j++)
{
var dbString = tokenArray[j] + "token"
var tokenCollection = db.collection(dbString)
tokenCollection.find({} ,{}).toArray(function(tokenError, tokenResults){
if (tokenError)
{
console.log("token failed")
res.status(500).send()
}
console.log("token good")
newTokenArray.push(tokenResults[0].token)
counter++
//completion handler
if(counter==tokenArray.length)
{
var info = yelpData["businesses"]
console.log(info)
var decisionObjects = []
var tempReplies = []
for(var i = 0; i<info.length; i++)
{
var infoDictionary = info[i]
console.log(infoDictionary["categories"])
tempReplies.push(0)
var temp = {}
temp["Name"] = infoDictionary["name"]
if(("image_url" in info[i]))
{
temp["ImageURL"] = infoDictionary["image_url"]
}
if(("categories" in info[i]))
{
var categoryArray = infoDictionary["categories"]
var fixedCategoryArray = []
for(var m = 0; m < categoryArray.length; m++)
{
var specificarray = categoryArray[m]
fixedCategoryArray.push(specificarray[0]);
}
temp["Category"] = fixedCategoryArray
}
if(("distance" in info[i]))
{
temp["distance"] = infoDictionary["distance"]
}
if(("rating" in info[i]))
{
temp["rating"] = infoDictionary["rating"]
}
decisionObjects.push(temp)
}
var sendDictionary = {}
sendDictionary["Done"] = -1;
sendDictionary["Number"] = info.length
sendDictionary["Replies"] = tempReplies
sendDictionary["Objects"] = decisionObjects
sendDictionary["Tokens"] = newTokenArray
var groupCollection = db.collection('groups')
groupCollection.insert(sendDictionary, {}, function(groupError, groupResults){
if (groupError)
{
console.log("group creation failed")
res.status(500).send()
}
console.log("group creation good")
for(var i = 0; i < tokenArray.length; i++)
{
var personalDictionary = {}
personalDictionary["groupID"] = groupResults[0]._id;
personalDictionary["number"] = tokenArray.length
personalDictionary["currentIndex"] = 0
personalDictionary["owner"] = req.body.myName
personalDictionary["ownerID"] = req.params.myId
personalDictionary["friendID"] = req.body.friends
var dbString2 = tokenArray[i] + "groups"
var friendCollection = db.collection(dbString2)
var counter2 = 0;
friendCollection.insert(personalDictionary, {}, function(friendError, friendResults){
if (friendError)
{
console.log("creation friend side failed")
res.status(500).send()
}
console.log("creation friend side good")
var myDevice = new apn.Device(newTokenArray[counter2]);
counter2++
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 0;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new group invite";
note.payload = {'messageFrom': req.body.myName, 'type': "message"};
apnConnection.pushNotification(note, myDevice);
if(counter2==newTokenArray.length)
{
console.log("everything good")
res.send("FASHOOOO")
}
})
}
})
}
})
}
});
})
// ===================================================================
// Get Methods
// ===================================================================
app.get('/yelp/:lat/:longi/:search/:offset', function(req, res) {
console.log("started")
var fixed = req.params.lat + ',' + req.params.longi
yelp.search({sort:0, offset: req.params.offset,limit: 20,ll:fixed, term:req.params.search}, function(error, data) {
if(error) res.status(500).send()//YelpFailedLetThemKnow
var info = data["businesses"]
var decisionObjects = []
for(var i = 0; i<info.length; i++)
{
var infoDictionary = info[i]
var temp = {}
temp["Name"] = infoDictionary["name"]
temp["id"] = infoDictionary["id"]
if(("image_url" in info[i]))
{
temp["ImageURL"] = infoDictionary["image_url"]
}
if(("categories" in info[i]))
{
var categoryArray = infoDictionary["categories"]
var fixedCategoryArray = []
for(var m = 0; m < categoryArray.length; m++)
{
var specificarray = categoryArray[m]
fixedCategoryArray.push(specificarray[0]);
}
temp["Category"] = fixedCategoryArray
}
if(("distance" in info[i]))
{
temp["distance"] = infoDictionary["distance"]
}
if(("rating" in info[i]))
{
temp["rating"] = infoDictionary["rating"]
}
if(("rating" in info[i]))
{
temp["url"] = infoDictionary["url"]
}
decisionObjects.push(temp)
url = infoDictionary["url"];
var methCounter = 0
// function createfunc(index) {
// return function() {
// request(url, function(error, response, html){
// if(!error){
// var $ = cheerio.load(html);
// var title, release, rating;
// var json = { title : "", release : "", rating : ""};
// // We'll use the unique header class as a starting point.
// $('span.hour-range').filter(function(){
// // Let's store the data we filter into a variable so we can easily see what's going on.
// methCounter++
// var data = $(this);
// console.log(data.children().text())
// console.log(index)
// var myDictionary = decisionObjects[index]
// myDictionary["hours"] = data.children().text()
// if(methCounter===(info.length))
// {
// res.send(decisionObjects)
// }
// // Once we have our title, we'll store it to the our json object.
// // json.title = title;
// })
// $('dd.nowrap.price-description').filter(function(){
// // Let's store the data we filter into a variable so we can easily see what's going on.
// methCounter++
// var data = $(this);
// console.log(data.text());
// var myDictionary = decisionObjects[index]
// myDictionary["price"] = data.text()
// if(methCounter===(info.length))
// {
// res.send(decisionObjects)
// }
// // Once we have our title, we'll store it to the our json object.
// // json.title = title;
// })
// }
// })
// };
// }
//var myfunc = []
//myfunc[0] = createfunc(i)
//myfunc[0]();
}
res.send(decisionObjects)
});
})
/*
Scrape
*/
app.post('/scrape', function(req, res) {
console.log("scraping started")
request(req.body.url, function(error, response, html){
if(!error){
console.log("scraping html started")
var $ = cheerio.load(html);
var title, release, rating;
var json = { title : "", release : "", rating : ""};
// We'll use the unique header class as a starting point.
var methCounter = 0
var sendDict = {}
$('span.hour-range').filter(function(){
console.log("hour")
// Let's store the data we filter into a variable so we can easily see what's going on.
methCounter++
var data = $(this);
console.log(data.children().text())
sendDict["hour"] = data.children().text()
if(methCounter===2)
{
res.send(sendDict)
}
// Once we have our title, we'll store it to the our json object.
// json.title = title;
})
$('dd.nowrap.price-description').filter(function(){
console.log("price")
// Let's store the data we filter into a variable so we can easily see what's going on.
methCounter++
var data = $(this);
console.log(data.text());
sendDict["price"] = data.text()
if(methCounter===2)
{
res.send(sendDict)
}
// Once we have our title, we'll store it to the our json object.
// json.title = title;
})
}
})
})
/*
* GroupTableViewController - resetPeople
* When reset everything is pressed, this method is called and deletes the
group data of the persons that are passed into it as parameters
*/
app.get('/ppl/:friend', function(req, res) {
var collection = db.collection(req.params.friend)
collection.find({} ,{}).toArray(function(e, results){
if (e) res.status(500).send()
res.send(results)
})
})
/*
* GroupTableViewController - getGoogle
* ****CURRENTLY UNUSED*****
*/
app.get('/google/:search', function(req, res) {
/**
* Place search - https://developers.google.com/places/documentation/#PlaceSearchRequests
*/
var parameters;
parameters = {
location:[40.67, -73.94],
types: req.params.search
};
googlePlaces.placeSearch(parameters, function (response) {
googlePlaces.placeDetailsRequest({reference:response.results[0].reference}, function (response) {
res.send(response.result)
});
});
})
/*
* Currently Unused - (For Debugging)
* Fetches all of the group data from every user
*/
app.get('/groups', function(req, res) {
var collection = db.collection('groups')
collection.find({} ,{}).toArray(function(e, results){
if (e) res.status(500).send()
res.send(results)
})
})
/*
* GroupTableViewController - tableView:didSelectRowAtIndexPath
* Gets information for a single group (the one that the user selected)
*/
app.get('/groups/:id', function(req, res) {
var collection = db.collection('groups')
collection.findById(req.params.id, function(e, result){
if (e) res.status(500).send()
res.send(result)
})
})
// ===================================================================
// Delete Methods
// ===================================================================
/*
* GroupTableViewController - deleteGroup
* Deletes a group from the group database
*/
app.delete('/groups/:id', function(req, res, next) {
var collection = db.collection('groups')
collection.removeById(req.params.id, function(e, result){
console.log(result)
if (e) return next(e)
res.send((result === 1)?{msg: 'success'} : {msg: 'error'})
})
})
/*
* GroupTableViewController - deleteGroup
* Deletes a group from the array of groups that an individual person has
*/
app.delete('/ppl/:friend/:id', function(req, res) {
var collection = db.collection(req.params.friend)
collection.removeById(req.params.id, function(e, result){
console.log(result)
if (e) return next(e)
res.send((result === 1)?{msg: 'success'} : {msg: 'error'})
})
})
// ===================================================================
// Put Methods
// ===================================================================
/*
* DraggableBackground - yesWith:index:andUrl
* Increment the number of yesses for one card and if number of yesses equals number of
people in the group also send push notification with info of the match
*/
app.put('/groups/:id/:number/:selfID/:friend/:numppl', function(req, res, next) {
var collection = db.collection('groups')
var collection2 = db.collection(req.params.friend);
var str1 = "Replies.";
var str2 = req.params.number;
var variable = str1.concat(str2);
var action = {};
action[variable] = 1;
collection.updateById(req.params.id, {$inc:action}, {safe: true, multi: false}, function(e, result){
if (e) res.status(500).send()
collection.findById(req.params.id, function(e2, result2){
if (e2) res.status(500).send()
collection2.updateById(req.params.selfID,{$inc:{"currentIndex": 1}},{safe: true, multi: false}, function(e3, result3){
if(e3) res.status(500).send()
if(result2.Replies[req.params.number]==req.params.numppl){
console.log(result2.Replies[req.params.number])
console.log(req.params.numppl)
console.log("yes")
for (var i = 0; i < result2.Tokens.length; i++) {
console.log(i)
var myDevice = new apn.Device(result2.Tokens[i]);
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new group invite";
note.payload = result2.Objects[req.params.number];
apnConnection.pushNotification(note, myDevice);
}
}
else{
console.log(result2.Replies[req.params.number])
console.log(req.params.numppl)
}
res.send({NumberOfReplies:result2.Replies[req.params.number]})
})
})
})
})
/*
* *****CURRENTLY UNUSED******
*/
app.put('/groups/:id/:number/finished', function(req, res, next) {
var collection = db.collection('groups')
var str1 = "Done";
var action = {};
action[variable] = req.params.number;
collection.updateById(req.params.id, {$set:
action
}, {safe: true, multi: false}, function(e, result){
if (e) res.status(500).send()
collection.findById(req.params.id, function(e2, result2){
if (e2) res.status(500).send()
console.log(result2.Replies[req.params.number]);
res.send({
NumberOfReplies:result2.Replies[req.params.number] }
)
})
})
})
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {});