forked from heroku/facebook-template-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb.js
571 lines (498 loc) · 19.2 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
var async = require('async');
var express = require('express');
var util = require('util');
var gm = require('googlemaps'); //https://github.com/moshen/node-googlemaps/blob/master/lib/googlemaps.js
var _ = require('underscore')._;
/*
var geohash = require("geohash").GeoHash;
var _ = require('underscore')._;
*/
///////////////////////////////////////////////////////////////////
// Database
////////////////////////////////////////////////////////////////
// app.js
var databaseUrl = process.env.MONGOHQ_URL; //""; // "username:[email protected]/mydb"
var collections = ["users", "events"]
var db = require("mongojs").connect(databaseUrl, collections);
db.users.ensureIndex({
id: 1
}); //info: http://www.mongodb.org/display/DOCS/Indexes
//geo loc indexes
db.users.ensureIndex({
'home.loc': '2d'
});
db.users.ensureIndex({
'work.loc': '2d'
});
///////////////////////////////////////////////////////////////////
// Express server setup
////////////////////////////////////////////////////////////////
// create an express webserver
var app = express.createServer(
express.logger(), express.static(__dirname + '/public'), express.bodyParser(),
//express.bodyDecoder(), //for stripe??
express.cookieParser(),
// set this to a secret value to encrypt session cookies
express.session({
secret: process.env.SESSION_SECRET || 'topsecret55887456'
}), require('faceplate').middleware({
app_id: process.env.FACEBOOK_APP_ID,
secret: process.env.FACEBOOK_SECRET,
scope: 'user_likes,user_photos,user_photo_video_tags,email,user_work_history,location,friends,languages,user_website'
//NOTE: SCOPE is set on CLIENT SIDE TOKEN!
}));
app.debug = true; // a silly attempt to centralized that...
var port = process.env.PORT || 3000; // listen to the PORT given to us in the environment
app.listen(port, function () {
console.log("Listening on " + port);
});
app.dynamicHelpers({
'host': function (req, res) {
return req.headers['host'];
},
'scheme': function (req, res) {
req.headers['x-forwarded-proto'] || 'http'
},
'url': function (req, res) {
return function (path) {
return app.dynamicViewHelpers.scheme(req, res) + app.dynamicViewHelpers.url_no_scheme(path);
}
},
'url_no_scheme': function (req, res) {
return function (path) {
return '://' + app.dynamicViewHelpers.host(req, res) + path;
}
},
});
function render_page(req, res) {
req.facebook.app(function (app) {
req.facebook.me(function (user) {
res.render('fb_test.ejs', {
layout: false,
req: req,
app: app,
user: user
});
});
});
}
function index(req, res){ //TODO: MAKE the delivery 100% static, no node processing.
res.render('index.ejs', {
layout: false,
req: req,
app: app
});
}
///////////////////////////////////////////////////////////////////
// email server
////////////////////////////////////////////////////////////////
var SendGrid = require('sendgrid').SendGrid;
var sendgrid = new SendGrid(
process.env.SENDGRID_USERNAME, process.env.SENDGRID_PASSWORD);
app.get('/emailme', function (req, res) { //testing route - should work locally as well once .env is populated with credential
sendgrid.send({
to: '[email protected]',
from: '[email protected]',
subject: 'test',
text: 'Sending email with NodeJS through SendGrid!'
}, function () {
res.send('email sent!'); //handle error callback??
});
});
///////////////////////////////////////////////////////////////////
// Payment Provider //tut: http://www.catonmat.net/blog/stripe-payments-with-node/
////////////////////////////////////////////////////////////////
var stripe_secret = process.env.STRIPE_SECRET;
var stripe_secret_dev = process.env.STRIPE_SECRET_DEV;
var stripe = require('stripe')(stripe_secret_dev); //maybe publi key goes here??
app.post("/plans/browserling_developer", function (req, res) {
stripe.customers.create({
card: req.body.stripeToken,
email: req.session.email,
// // customer's email (get it from db or session)"...",
plan: "test" // this value has to be created on stripe.com as well...
}, function (err, customer) {
if (err) {
var msg = customer.error.message || "unknown";
res.send("Error while processing your payment: " + msg);
} else {
var id = customer.id;
console.log('Success! Customer with Stripe ID ' + id + ' just signed up!');
// save this customer to your database here!
res.send('ok');
}
});
});
app.get('/pay', function (req, res) {
res.render('pay_form.ejs', {
title: 'New Template Page',
layout: true
});
});
///////////////////////////////////////////////////////////////////
// FB Demo Fetch (garbage) -loooong //http://howtonode.org/facebook-connect
////////////////////////////////////////////////////////////////
function handle_facebook_request(req, res) { // default facebook example, Do some fetches on facebook graph asyncrounously
// if the user is logged in
if (req.facebook.token) {
async.parallel([
function (cb) {
// query 4 friends and send them to the socket for this socket id
req.facebook.get('/me/friends', {
limit: 20
}, function (friends) {
req.friends = friends;
cb();
});
}, function (cb) {
// query 16 photos and send them to the socket for this socket id
req.facebook.get('/me/photos', {
limit: 16
}, function (photos) {
req.photos = photos;
cb();
});
}, function (cb) {
// query 4 likes and send them to the socket for this socket id
req.facebook.get('/me/likes', {
limit: 20
}, function (likes) {
req.likes = likes;
cb();
});
}, function (cb) {
// use fql to get a list of my friends that are using this app
req.facebook.fql('SELECT uid, name, is_app_user, pic_square FROM user WHERE uid in (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1', function (result) {
req.friends_using_app = result;
cb();
});
}], function () {
render_page(req, res);
});
} else {
render_page(req, res);
}
}
///////////////////////////////////////////////////////////////////
// Facebook user data fetch tries
////////////////////////////////////////////////////////////////
app.get('/', index);
app.post('/', handle_facebook_request); //required??
app.get('/location', index);
app.get('/commute', index);
app.get('/promo', index);
app.get('/driver', index);
app.get('/passenger', index);
app.get('/driver/:user_id', index);
app.get('/passenger/:user_id', index);
app.get('/dashboard', index);
app.get('/home', index);
app.get('/settings', index);
app.get('/fb', handle_facebook_request);
app.get('/echo', function (req, res) {
echo = req.param("echo", "no param")
res.send('ECHO: ' + echo);
});
app.get('/template', function (req, res) {
res.render('test.ejs', {
title: 'New Template Page',
layout: true
});
});
app.post('/posttest', function (req, res) {
res.send(req.body);
});
app.get('/friends', function (req, res) {
req.facebook.get('/me/friends', {
limit: 5000
}, function (friends) {
res.send(friends); //plain json
});
});
app.get('/me', function (req, res) {
req.facebook.get('/me', {
fields: 'email, name, locale, work, languages, education, location, website,friends'
}, function (data) {
res.send(data); //plain json
});
});
///////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////
app.get('/api/constant', function (req, res) {
var c={
FACEBOOK_APP_ID: process.env.FACEBOOK_APP_ID,
STRIPE_PUBLIC_DEV: process.env.STRIPE_PUBLIC_DEV,
STRIPE_PUBLIC: process.env.STRIPE_PUBLIC,
BASE_PRICE: 1900
}
res.send(c);
});
///////////////////////////////////////////////////////////////////
// USER data, and facebook fetching
////////////////////////////////////////////////////////////////
app.get('/api/user', function (req, res) { // fetch data on facebook for our user, saves it to the database.
ensureSession(req, res, function () {
db.users.find({
id: req.session.uid
}, function (err, users) { // check if user exist... (poll mongo...)
if (err || !users || (users.length ==0)) { //the dude's note on file
console.log("No user found...");
fetchFbUserDate(req, res, function () {
console.log("FB2 callback!");
res.send(req.user); //the user will have been populated by FB.
}); //eo fb fetch
} else {
console.log("FOUND THE GUY ON FILE!!!" + users.length);
res.send(users[0]); //the matching record from MOngo
}
}); //eo db search
}); //eo ensure session
console.log('Session ID : ' + req.session.uid);
}); //eo route
app.get('/ensuresession', function (req, res) { // sets session ID according to FB id
console.log('ensuresession! + ' + req.session.uid);
ensureSession(req, res, function () {
console.log('CALL BAKC ENSURED! + ' + req.session.uid);
res.send(req.session.uid);
});
});
function ensureFacebook(req, res, callback) {
// if no facebook token, return error, ask to login...
if (req.facebook.token) { //if logged on facebook...
callback(req, res);
} else {
console.log('FB IS NOT SET, user should proceed to login on client side first');
//no callback/
// TODO: redirect to home??
}
}
function ensureSession(req, res, callback) { // make sure that user is connected, and session are set
// TODO, make sure the FB token exists as well, if not, redirect to homepage, don't call the callback...
// BUG, if not FB logged, crashes!!
ensureFacebook(req, res, function () {
if ((!req.session.uid) || (req.session.uid == undefined)) {
req.facebook.get('/me', {
fields: 'id'
}, function (data) {
var id = data.id; //plain str
req.session.uid = id;
console.log('uid (FB just setted) = ' + id + data);
callback(req, res);
});
} else {
console.log('uid = ' + ' (session...)' + req.session.uid);
callback(req, res);
}
});
}
function outputUser(req, res) { //set the sessions value according to FB data or FB, and output the thing to client
// set sessions
var id = req.user.me.id
req.session.uid = id;
req.session.email = req.me.email;
res.send(req.user);
}
function fetchFbUserDate(req, res, callback) { //Only for the first time, or when we feel it's time to update user data from FB
console.log('fetchFbUserDate()');
async.parallel([
function (cb) {
// query 4 friends and send them to the socket for this socket id
req.facebook.get('/me/friends', {
limit: 2000
}, function (friends) {
req.friends = friends;
cb();
});
}, function (cb) {
// query 16 photos and send them to the socket for this socket id
req.facebook.get('/me', {
fields: 'email, name, locale, work, languages, education, location, website, picture, gender, about, birthday' //add more fields as required, just make sure scope match...
}, function (me) {
req.me = me;
cb();
});
}, function (cb) {
// query 4 likes and send them to the socket for this socket id
req.facebook.get('/me/likes', {
limit: 20
}, function (likes) {
req.likes = likes;
cb();
});
}, function (cb) {
// use fql to get a list of my friends that are using this app
req.facebook.fql('SELECT uid, name, is_app_user, pic_square FROM user WHERE uid in (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1', function (result) {
req.friends_using_app = result;
cb();
});
}], function () { //Once we received all data from FB...
console.log('ASYNC CALLS finished');
console.log(req.me.email + '1');
var user = { //create user object to be inserted
id: req.session.uid,
email: req.me.email,
sex: req.me.gender,
birthday: req.me.birthday,
photo: "http://graph.facebook.com/" + req.session.uid + "/picture?type=large",
photo_square: "http://graph.facebook.com/" + req.session.uid + "/picture?type=square",
friends: req.friends,
me: req.me
}
console.log(req.me.email);
console.log(user.id);
req.user = user; //so it's accessible down the line
console.log(req.user);
callback(req, res);
// save the fb fetches in the database
db.users.save(user, function (err, saved) {
if (err || !saved) console.log("User not saved");
else console.log("User saved");
});
}); //eo async fb callback
} //eo function
///////////////////////////////////////////////////////////////////
// USER SET LOCATION Location API V1
////////////////////////////////////////////////////////////////
// /api/setlocation/?home=laval&work=montreal
app.get('/setlocation', function (req, res) { // fetch data on facebook for our user, saves it to the database.
// TODO: ENsure user is logged!
ensureSession(req, res, function(){
async.parallel([ // call google-maps for both addresses async
function (cb) {
gm.geocode(req.param("home") || 'Oakland', function (err, data) {//return the geometry of the top matching location...
req.home = data.results[0];
req.home['loc'] = [req.home.geometry.location.lng, req.home.geometry.location.lat]; //for geospatial indexing
cb();
});
}, function (cb) {
gm.geocode(req.param("work") || 'San Francisco', function (err, data) {
req.work = data.results[0];
req.work['loc'] = [req.work.geometry.location.lng, req.work.geometry.location.lat]; //for geospatial indexing
cb();
});
}, function (cb) {
gm.distance(req.param("home") || 'montreal', req.param("work") || 'toronto', function (err, data) {
req.commute = data.rows[0].elements[0]; //only keep distance + duration.
cb();
});
}], function () { //Once we received all data from FB...
var loc = {
home: req.home,
work: req.work,
commute: req.commute,
updated: new Date()
}
var uid = req.session.uid;
db.users.update({id: uid}, { $set: { loc: loc }}, function (err, updated) {
if (err || !updated) console.log("User not updated: " + req.session.uid);
else console.log("User updated");
});
res.send(loc);
}); //eo parrallel calls
});//eo ensure-session
});
///////////////////////////////////////////////////////////////////
// USER SET schedule
////////////////////////////////////////////////////////////////
// /api/setlocation/?home=laval&work=montreal
app.get('/setschedule', function (req, res) { // fetch data on facebook for our user, saves it to the database.
// TODO: ENsure user is logged!
ensureSession(req, res, function(){
var schedule = {
starthour: req.params['starthour'],
finishhour: req.params['finishhour'],
days: req.params['days'],
flex: req.params['flex'],
car: req.params['car'],
updated: new Date()
}
var uid = req.session.uid;
db.users.update({id: uid}, { $set: { schedule: schedule }}, function (err, updated) {
if (err || !updated) console.log("User schedule not updated: " + req.session.uid);
else console.log("User updated with new schedule");
});
res.send(schedule); // on production, we can just return the DB success handler...
}); //eo parrallel calls
});
///////////////////////////////////////////////////////////////////
// Geo Location API V1
////////////////////////////////////////////////////////////////
app.get('/geohash/:id', function (req, res) {
var latlon = geohash.decodeGeoHash(req.params['id']);
lat = latlon.latitude[2];
lon = latlon.longitude[2];
zoom = req.params["id"].length + 2;
res.render('geohash.ejs', {
layout: false,
lat: lat,
lon: lon,
zoom: zoom,
geohash: req.params['id']
});
});
app.get('/reverseGeo/:lat/:long', function (req, res) {
gm.reverseGeocode('41.850033,-87.6500523', function (err, data) {
util.puts(JSON.stringify(data));
res.send(data);
});
});
app.get('/getCoord/:address', function (req, res) {
// var address = '520 rue fortune, montreal';
var address = req.param("address", "montreal")
gm.geocode(address, function (err, data) {
util.puts(JSON.stringify(data));
var coords = data.results[0].geometry.location; //return the geometry of the top matching location...
res.send(coords);
});
});
function getElevation(lat, lng, callback) {
var options = {
host: 'maps.googleapis.com',
port: 80,
path: '/maps/api/elevation/json?locations=' + lat + ',' + lng + '&sensor=true'
};
http.get(options, function (res) {
data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function (chunk) {
el_response = JSON.parse(data);
callback(el_response.results[0].elevation);
});
});
};
///////////////////////////////////////////////////////////////////
// DB EXAMPLES
////////////////////////////////////////////////////////////////
// examples.... (http://howtonode.org/node-js-and-mongodb-getting-started-with-mongojs)
/*
db.users.find({sex: "female"}, function(err, users) {
if( err || !users) console.log("No female users found");
else users.forEach( function(femaleUser) {
console.log(femaleUser);
} );
});
db.users.save({email: "[email protected]", password: "iLoveMongo", sex: "male"}, function(err, saved) {
if( err || !saved ) console.log("User not saved");
else console.log("User saved");
});
db.users.update({email: "[email protected]"}, {$set: {password: "iReallyLoveMongo"}}, function(err, updated) {
if( err || !updated ) console.log("User not updated");
else console.log("User updated");
});
*/
///////////////////////////////////////////////////////////////////
// FINI
////////////////////////////////////////////////////////////////
/*
function get_distance(points) { //return the computed driving distance from google maps API
getElevation(40.714728,-73.998672, function(elevation){
elevations.push(elevation);
elevations.push(elevation);
console.log("Elevations: "+elevations); });
var elevations= []
};
*/
//})